code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE DeriveAnyClass, PatternSynonyms, ConstraintKinds, FlexibleContexts #-}
module Workflow.OSX.Types
( module Workflow.OSX.Types
, module Workflow.Types
) where
import Workflow.Types
import Workflow.OSX.Extra
import Foreign (Storable(..))
import Foreign.CStorable (CStorable(..))
import Foreign.C.Types
import Data.Word
{-|
relates a Haskell type with a Objective-C type:
* Objective-C defines @typedef unsigned int UInt32;@
* in @MacTypes.h@
-}
type UInt32 = Word32
{-| a UTF-16 encoded unicode character.
TODO i.e. not codepoint like Char?
@
typedef unsigned short unichar;
@
-}
type UniChar = Word16
{- | a virtual key.
relates a Haskell type with a Objective-C type:
* Objective-C defines @typedef unsigned short uint16_t;@
* line 34 of
</System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/Headers/CGRemoteOperation.h>
defines @typedef uint16_t CGKeyCode;@
-}
type CGKeyCode = CUShort
{- | a set of modifiers.
relates a Haskell type with a Objective-C type:
* Objective-C defines @typedef unsigned long long uint64_t;@
* line 98 of
</System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/Headers/CGEventTypes.h>
defines @typedef uint64_t CGEventFlags;@
(@typedef CF_ENUM(uint64_t, CGEventFlags)@).
-}
type CGEventFlags = CULLong
{- | an event (like key/mouse up/down).
relates a Haskell type with a Objective-C type:
* @typedef CF_ENUM(uint32_t, CGEventType) { ... }@
* in
</System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/Headers/CGEventTypes.h>
-}
type CGEventType = Word32
{- | relates a Haskell type with a Objective-C type:
* @typedef CF_ENUM(uint32_t, CGMouseButton) { ... }@
* in
</System/Library/Frameworks/ApplicationServices.framework/Versions/A/Frameworks/CoreGraphics.framework/Versions/A/Headers/CGEventTypes.h>
-}
type CGMouseButton = Word32
{-|
-}
type OSXMouseButton = (CGMouseButton, CGEventType, CGEventType)
{-|
@<CoreGraphics/CGBase.h>@ defines:
@
#if defined(__LP64__) && __LP64__
# define CGFLOAT_TYPE double
# define CGFLOAT_IS_DOUBLE 1
# define CGFLOAT_MIN DBL_MIN
# define CGFLOAT_MAX DBL_MAX
#else
# define CGFLOAT_TYPE float
# define CGFLOAT_IS_DOUBLE 0
# define CGFLOAT_MIN FLT_MIN
# define CGFLOAT_MAX FLT_MAX
#endif
typedef CGFLOAT_TYPE CGFloat;
@
-}
type CGFloat = Double
{-|
@<CoreGraphics/CGGeometry.h>@ defines:
@
struct CGPoint {
CGFloat x;
CGFloat y;
};
typedef struct CGPoint CGPoint;
@
-}
data CGPoint = CGPoint
{ xCGPoint :: CGFloat
, yCGPoint :: CGFloat
} deriving (Show,Read,Eq,Ord,Data,Generic,NFData,Hashable,CStorable)
instance Storable CGPoint where
peek = cPeek
poke = cPoke
alignment = cAlignment
sizeOf = cSizeOf
{-
@
struct CGSize {
CGFloat width;
CGFloat height;
};
typedef struct CGSize CGSize;
@
-}
{-
@
struct CGVector {
CGFloat dx;
CGFloat dy;
};
typedef struct CGVector CGVector;
@
-}
{-
@
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CGRect CGRect;
@
-}
{-|
@
struct ProcessSerialNumber { unsigned long highLongOfPSN; unsigned long lowLongOfPSN; };
@
<https://developer.apple.com/legacy/library/documentation/Carbon/Reference/Process_Manager/index.html#//apple_ref/doc/c_ref/ProcessSerialNumber>
-}
data ProcessSerialNumber = ProcessSerialNumber
{ _highLongOfPSN :: CULong
, _lowLongOfPSN :: CULong
}
{-|
E.G. In Objective-C:
@
// via NSLog(@"%@", ...);
NSDictionary: {
NSApplicationBundleIdentifier = "org.gnu.Emacs";
NSApplicationName = Emacs;
NSApplicationPath = "/Applications/Notes.app";
NSApplicationProcessIdentifier = 40831;
NSApplicationProcessSerialNumberHigh = 0;
NSApplicationProcessSerialNumberLow = 4195328;
NSWorkspaceApplicationKey = "<NSRunningApplication: 0x7fe3c0e08b30 (org.gnu.Emacs - 40831)>";
}
@
-}
data ApplicationInformation = ApplicationInformation
{ nsApplicationName :: String
, nsApplicationPath :: String
, nsApplicationBundleIdentifier :: String
, nsApplicationProcessIdentifier :: Word --TODO
, nsApplicationProcessSerialNumber :: ProcessSerialNumber
, nsWorkspaceApplicationKey :: NSRunningApplication --TODO
}
type NSRunningApplication = () --TODO
--------------------------------------------------------------------------------
-- compat
-- | an (unordered, no-duplicates) sequence of key chords make up a keyboard shortcut
type KeyRiff = KeySequence
type ClipboardText = Clipboard
-- | @CommandModifier = 'MetaModifier'@ (also could be @CommandModifier = 'HyperModifier@)
pattern CommandModifier :: Modifier
pattern CommandModifier = MetaModifier
-- | @CommandKey = 'MetaKey'@ (also could be @CommandKey = 'HyperKey@)
pattern CommandKey :: Key
pattern CommandKey = MetaKey
|
sboosali/workflow-osx
|
workflow-osx/sources/Workflow/OSX/Types.hs
|
mit
| 4,828 | 0 | 8 | 676 | 354 | 227 | 127 | 44 | 0 |
import Data.List
reverseString :: String -> String
reverseString s = if (length s) <= 1 then s else l++r where
r = reverseString(take( (genericLength s) `div` 2) s)
l = reverseString(drop( (genericLength s) `div` 2) s)
|
RAFIRAF/HASKELL
|
reverseString.hs
|
mit
| 225 | 0 | 13 | 42 | 109 | 59 | 50 | 5 | 2 |
module DecToBin (decToBin) where
decToBin':: Int -> [Int] -> [Int]
decToBin' n b
| n `div` 2 == 0 = reverse $ n `mod` 2 : b
| otherwise = n `mod` 2 : decToBin' (n `div` 2) b
decToBin :: Int -> String
decToBin n = concat . map show . reverse $ decToBin' n []
|
harrisi/on-being-better
|
list-expansion/Haskell/DecToBin.hs
|
cc0-1.0
| 264 | 0 | 9 | 63 | 140 | 75 | 65 | 7 | 1 |
{-# OPTIONS -fglasgow-exts #-}
--
-- riot/Riot/BootAPI.hs
--
-- Copyright (c) Tuomo Valkonen 2004-2005.
--
-- 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 is the only module that is linked twice, once statically linked,
-- and once dynamically. It must be done so that the type of the value
-- passed from Boot.main to Main.main is available on both sides of the
-- border. We use the existential to prevent a dependency on ConfigAPI
-- in Boot.hs. It gets unwrapped magically in Main.dynamic_main
--
module Riot.BootAPI where
data ConfigData = forall a. CD a {- has Config type -}
type RiotMainType = (Maybe ConfigData) -> IO ()
|
opqdonut/riot
|
Riot/BootAPI.hs
|
gpl-2.0
| 853 | 0 | 7 | 153 | 60 | 42 | 18 | -1 | -1 |
module IExpr where
import Pretty
import Text.PrettyPrint
data IExpr s = IAtom String s
| IString String s
| IList [IExpr s]
| IBraceList [IExpr s]
| IBracketList [IExpr s]
| IDecor (IExpr s) (IExpr s)
| ITree (IExpr s) [IExpr s]
| ITreeSep (String, s) (IExpr s) [IExpr s]
| IHash (IExpr s) [String]
deriving (Show)
data ParenType = Parens | Brackets | Braces deriving (Show, Eq)
instance Pretty (IExpr s) where
pretty (IAtom cont _) = text cont
pretty (IString cont _) = text $ show cont
pretty (IList exprs) = text "List" <> parens (hsep $ map pretty exprs)
pretty (IBraceList exprs)
= text "List" <> (braces . sep $ map pretty exprs)
pretty (IBracketList exprs)
= text "List" <> (brackets . sep $ map pretty exprs)
pretty (IDecor decorator decorated)
= text "Decor" <+> pretty decorator $+$
nest 2 (pretty decorated)
pretty (ITree rootexpr subexpr)
= text "Tree" <+> pretty rootexpr $+$
nest 2 (vcat $ map pretty subexpr)
pretty (ITreeSep (sep,_) left right)
= text "TreeSep" <+> parens (pretty left) <> text (':' : sep) $+$
nest 2 (vcat $ map pretty right)
pretty (IHash expr substrings)
= text "Hash" <+> parens (pretty expr) $+$
nest 2 (vcat $ map (prepend "|" . text) substrings)
where
prepend str = (text str <>)
postpend str = (<> text str)
surround str = prepend str . postpend str
getPositions :: IExpr pos -> [pos]
getPositions (IAtom _ pos) = [pos]
getPositions (IString _ pos) = [pos]
getPositions (IList elems) = concatMap getPositions elems
getPositions (IBraceList elems) = concatMap getPositions elems
getPositions (IBracketList elems) = concatMap getPositions elems
getPositions (IDecor decorator decorated) = getPositions decorator ++ getPositions decorated
getPositions (ITree root leaves) = getPositions root ++ concatMap getPositions leaves
getPositions (ITreeSep (_, seperatorpos) root leaves)
= getPositions root ++ [seperatorpos] ++ concatMap getPositions leaves
getPositions (IHash root contents) = getPositions root
getPosition :: IExpr pos -> Maybe pos
getPosition expr = case getPositions expr of
firstpos:rest -> Just firstpos
otherwise -> Nothing
|
keenbug/iexpr
|
IExpr.hs
|
gpl-2.0
| 2,417 | 0 | 13 | 673 | 893 | 446 | 447 | 52 | 2 |
{- |
Module : ./OWL2/XMLKeywords.hs
Copyright : (c) Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : portable
Kewyords used for XML conversions
-}
module OWL2.XMLKeywords where
ontologyIRIK :: String
ontologyIRIK = "ontologyIRI"
iriK :: String
iriK = "IRI"
abbreviatedIRI :: String
abbreviatedIRI = "AbbreviatedIRI"
nodeID :: String
nodeID = "nodeID"
prefixK :: String
prefixK = "Prefix"
importK :: String
importK = "Import"
classK :: String
classK = "Class"
datatypeK :: String
datatypeK = "Datatype"
namedIndividualK :: String
namedIndividualK = "NamedIndividual"
objectPropertyK :: String
objectPropertyK = "ObjectProperty"
dataPropertyK :: String
dataPropertyK = "DataProperty"
annotationPropertyK :: String
annotationPropertyK = "AnnotationProperty"
anonymousIndividualK :: String
anonymousIndividualK = "AnonymousIndividual"
facetRestrictionK :: String
facetRestrictionK = "FacetRestriction"
literalK :: String
literalK = "Literal"
declarationK :: String
declarationK = "Declaration"
annotationK :: String
annotationK = "Annotation"
objectInverseOfK :: String
objectInverseOfK = "ObjectInverseOf"
datatypeRestrictionK :: String
datatypeRestrictionK = "DatatypeRestriction"
dataComplementOfK :: String
dataComplementOfK = "DataComplementOf"
dataOneOfK :: String
dataOneOfK = "DataOneOf"
dataIntersectionOfK :: String
dataIntersectionOfK = "DataIntersectionOf"
dataUnionOfK :: String
dataUnionOfK = "DataUnionOf"
objectIntersectionOfK :: String
objectIntersectionOfK = "ObjectIntersectionOf"
objectUnionOfK :: String
objectUnionOfK = "ObjectUnionOf"
objectComplementOfK :: String
objectComplementOfK = "ObjectComplementOf"
objectOneOfK :: String
objectOneOfK = "ObjectOneOf"
objectSomeValuesFromK :: String
objectSomeValuesFromK = "ObjectSomeValuesFrom"
objectAllValuesFromK :: String
objectAllValuesFromK = "ObjectAllValuesFrom"
objectHasValueK :: String
objectHasValueK = "ObjectHasValue"
objectHasSelfK :: String
objectHasSelfK = "ObjectHasSelf"
objectMinCardinalityK :: String
objectMinCardinalityK = "ObjectMinCardinality"
objectMaxCardinalityK :: String
objectMaxCardinalityK = "ObjectMaxCardinality"
objectExactCardinalityK :: String
objectExactCardinalityK = "ObjectExactCardinality"
dataSomeValuesFromK :: String
dataSomeValuesFromK = "DataSomeValuesFrom"
dataAllValuesFromK :: String
dataAllValuesFromK = "DataAllValuesFrom"
dataHasValueK :: String
dataHasValueK = "DataHasValue"
dataMinCardinalityK :: String
dataMinCardinalityK = "DataMinCardinality"
dataMaxCardinalityK :: String
dataMaxCardinalityK = "DataMaxCardinality"
dataExactCardinalityK :: String
dataExactCardinalityK = "DataExactCardinality"
subClassOfK :: String
subClassOfK = "SubClassOf"
equivalentClassesK :: String
equivalentClassesK = "EquivalentClasses"
disjointClassesK :: String
disjointClassesK = "DisjointClasses"
disjointUnionK :: String
disjointUnionK = "DisjointUnion"
datatypeDefinitionK :: String
datatypeDefinitionK = "DatatypeDefinition"
hasKeyK :: String
hasKeyK = "HasKey"
subObjectPropertyOfK :: String
subObjectPropertyOfK = "SubObjectPropertyOf"
objectPropertyChainK :: String
objectPropertyChainK = "ObjectPropertyChain"
equivalentObjectPropertiesK :: String
equivalentObjectPropertiesK = "EquivalentObjectProperties"
disjointObjectPropertiesK :: String
disjointObjectPropertiesK = "DisjointObjectProperties"
objectPropertyDomainK :: String
objectPropertyDomainK = "ObjectPropertyDomain"
objectPropertyRangeK :: String
objectPropertyRangeK = "ObjectPropertyRange"
inverseObjectPropertiesK :: String
inverseObjectPropertiesK = "InverseObjectProperties"
functionalObjectPropertyK :: String
functionalObjectPropertyK = "FunctionalObjectProperty"
inverseFunctionalObjectPropertyK :: String
inverseFunctionalObjectPropertyK = "InverseFunctionalObjectProperty"
reflexiveObjectPropertyK :: String
reflexiveObjectPropertyK = "ReflexiveObjectProperty"
irreflexiveObjectPropertyK :: String
irreflexiveObjectPropertyK = "IrreflexiveObjectProperty"
symmetricObjectPropertyK :: String
symmetricObjectPropertyK = "SymmetricObjectProperty"
asymmetricObjectPropertyK :: String
asymmetricObjectPropertyK = "AsymmetricObjectProperty"
antisymmetricObjectPropertyK :: String
antisymmetricObjectPropertyK = "AntisymmetricObjectProperty"
transitiveObjectPropertyK :: String
transitiveObjectPropertyK = "TransitiveObjectProperty"
subDataPropertyOfK :: String
subDataPropertyOfK = "SubDataPropertyOf"
equivalentDataPropertiesK :: String
equivalentDataPropertiesK = "EquivalentDataProperties"
disjointDataPropertiesK :: String
disjointDataPropertiesK = "DisjointDataProperties"
dataPropertyDomainK :: String
dataPropertyDomainK = "DataPropertyDomain"
dataPropertyRangeK :: String
dataPropertyRangeK = "DataPropertyRange"
functionalDataPropertyK :: String
functionalDataPropertyK = "FunctionalDataProperty"
dataPropertyAssertionK :: String
dataPropertyAssertionK = "DataPropertyAssertion"
negativeDataPropertyAssertionK :: String
negativeDataPropertyAssertionK = "NegativeDataPropertyAssertion"
objectPropertyAssertionK :: String
objectPropertyAssertionK = "ObjectPropertyAssertion"
negativeObjectPropertyAssertionK :: String
negativeObjectPropertyAssertionK = "NegativeObjectPropertyAssertion"
sameIndividualK :: String
sameIndividualK = "SameIndividual"
differentIndividualsK :: String
differentIndividualsK = "DifferentIndividuals"
classAssertionK :: String
classAssertionK = "ClassAssertion"
annotationAssertionK :: String
annotationAssertionK = "AnnotationAssertion"
subAnnotationPropertyOfK :: String
subAnnotationPropertyOfK = "SubAnnotationPropertyOf"
annotationPropertyDomainK :: String
annotationPropertyDomainK = "AnnotationPropertyDomain"
annotationPropertyRangeK :: String
annotationPropertyRangeK = "AnnotationPropertyRange"
entityList :: [String]
entityList = [classK, datatypeK, namedIndividualK,
objectPropertyK, dataPropertyK, annotationPropertyK]
annotationValueList :: [String]
annotationValueList = [literalK, iriK, abbreviatedIRI, anonymousIndividualK]
annotationSubjectList :: [String]
annotationSubjectList = [iriK, abbreviatedIRI, anonymousIndividualK]
individualList :: [String]
individualList = [namedIndividualK, anonymousIndividualK]
objectPropList :: [String]
objectPropList = [objectPropertyK, objectInverseOfK]
dataPropList :: [String]
dataPropList = [dataPropertyK]
dataRangeList :: [String]
dataRangeList = [datatypeK, datatypeRestrictionK, dataComplementOfK,
dataOneOfK, dataIntersectionOfK, dataUnionOfK]
classExpressionList :: [String]
classExpressionList = [classK, objectIntersectionOfK, objectUnionOfK,
objectComplementOfK, objectOneOfK, objectSomeValuesFromK,
objectAllValuesFromK, objectHasValueK, objectHasSelfK,
objectMinCardinalityK, objectMaxCardinalityK, objectExactCardinalityK,
dataSomeValuesFromK, dataAllValuesFromK, dataHasValueK,
dataMinCardinalityK, dataMaxCardinalityK, dataExactCardinalityK]
|
gnn/Hets
|
OWL2/XMLKeywords.hs
|
gpl-2.0
| 7,061 | 0 | 5 | 730 | 1,017 | 621 | 396 | 180 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -funbox-strict-fields #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.UI.Pango
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- This module defines a user interface implemented using gtk2hs and
-- pango for direct text rendering.
module Yi.UI.Pango (start, startGtkHook) where
import Control.Applicative
import Control.Concurrent
import Control.Exception (catch, SomeException)
import Control.Lens hiding (set, Action, from)
import Control.Monad hiding (forM_, mapM_, forM, mapM)
import Data.Foldable
import Data.IORef
import qualified Data.List.PointedList as PL (moveTo)
import qualified Data.List.PointedList.Circular as PL
import qualified Data.Map as M
import Data.Maybe
import Data.Monoid
import Data.Text (unpack, Text)
import qualified Data.Text as T
import Data.Traversable
import qualified Graphics.UI.Gtk as Gtk
import Graphics.UI.Gtk hiding (Region, Window, Action , Point,
Style, Modifier, on)
import qualified Graphics.UI.Gtk.Gdk.EventM as EventM
import qualified Graphics.UI.Gtk.Gdk.GC as Gtk
import Graphics.UI.Gtk.Gdk.GC hiding (foreground)
import Prelude hiding (error, elem, mapM_, foldl, concat, mapM)
import System.Glib.GError
import Yi.Buffer
import Yi.Config
import Yi.Debug
import Yi.Editor
import Yi.Event
import Yi.Keymap
import Yi.Layout(DividerPosition, DividerRef)
import Yi.Monad
import qualified Yi.Rope as R
import Yi.Style
import Yi.Tab
import Yi.Types (fontsizeVariation, attributes)
import qualified Yi.UI.Common as Common
import Yi.UI.Pango.Control (keyTable)
#ifdef GNOME_ENABLED
import Yi.UI.Pango.Gnome(watchSystemFont)
#endif
import Yi.UI.Pango.Layouts
import Yi.UI.Pango.Utils
import Yi.String (showT)
import Yi.UI.TabBar
import Yi.UI.Utils
import Yi.Utils
import Yi.Window
-- We use IORefs in all of these datatypes for all fields which could
-- possibly change over time. This ensures that no 'UI', 'TabInfo',
-- 'WinInfo' will ever go out of date.
data UI = UI
{ uiWindow :: Gtk.Window
, uiNotebook :: SimpleNotebook
, uiStatusbar :: Statusbar
, tabCache :: IORef TabCache
, uiActionCh :: Action -> IO ()
, uiConfig :: UIConfig
, uiFont :: IORef FontDescription
, uiInput :: IMContext
}
type TabCache = PL.PointedList TabInfo
-- We don't need to know the order of the windows (the layout manages
-- that) so we might as well use a map
type WindowCache = M.Map WindowRef WinInfo
data TabInfo = TabInfo
{ coreTabKey :: TabRef
, layoutDisplay :: LayoutDisplay
, miniwindowPage :: MiniwindowDisplay
, tabWidget :: Widget
, windowCache :: IORef WindowCache
, fullTitle :: IORef Text
, abbrevTitle :: IORef Text
}
instance Show TabInfo where
show t = show (coreTabKey t)
data WinInfo = WinInfo
{ coreWinKey :: WindowRef
, coreWin :: IORef Window
, shownTos :: IORef Point
, lButtonPressed :: IORef Bool
, insertingMode :: IORef Bool
, inFocus :: IORef Bool
, winLayoutInfo :: MVar WinLayoutInfo
, winMetrics :: FontMetrics
, textview :: DrawingArea
, modeline :: Label
, winWidget :: Widget -- ^ Top-level widget for this window.
}
data WinLayoutInfo = WinLayoutInfo {
winLayout :: !PangoLayout,
tos :: !Point,
bos :: !Point,
bufEnd :: !Point,
cur :: !Point,
buffer :: !FBuffer,
regex :: !(Maybe SearchExp)
}
instance Show WinInfo where
show w = show (coreWinKey w)
instance Ord EventM.Modifier where
x <= y = fromEnum x <= fromEnum y
mkUI :: UI -> Common.UI Editor
mkUI ui = Common.dummyUI
{ Common.main = main
, Common.end = const end
, Common.suspend = windowIconify (uiWindow ui)
, Common.refresh = refresh ui
, Common.layout = doLayout ui
, Common.reloadProject = const reloadProject
}
updateFont :: UIConfig -> IORef FontDescription -> IORef TabCache -> Statusbar
-> FontDescription -> IO ()
updateFont cfg fontRef tc status font = do
maybe (return ()) (fontDescriptionSetFamily font) (configFontName cfg)
writeIORef fontRef font
widgetModifyFont status (Just font)
tcs <- readIORef tc
forM_ tcs $ \tabinfo -> do
wcs <- readIORef (windowCache tabinfo)
forM_ wcs $ \wininfo -> do
withMVar (winLayoutInfo wininfo) $ \WinLayoutInfo{winLayout} ->
layoutSetFontDescription winLayout (Just font)
-- This will cause the textview to redraw
widgetModifyFont (textview wininfo) (Just font)
widgetModifyFont (modeline wininfo) (Just font)
askBuffer :: Window -> FBuffer -> BufferM a -> a
askBuffer w b f = fst $ runBuffer w b f
-- | Initialise the ui
start :: UIBoot
start = startGtkHook (const $ return ())
-- | Initialise the ui, calling a given function
-- on the Gtk window. This could be used to
-- set additional callbacks, adjusting the window
-- layout, etc.
startGtkHook :: (Gtk.Window -> IO ()) -> UIBoot
startGtkHook userHook cfg ch outCh ed =
catch (startNoMsgGtkHook userHook cfg ch outCh ed)
(\(GError _dom _code msg) -> fail $ unpack msg)
startNoMsgGtkHook :: (Gtk.Window -> IO ()) -> UIBoot
startNoMsgGtkHook userHook cfg ch outCh ed = do
logPutStrLn "startNoMsgGtkHook"
void unsafeInitGUIForThreadedRTS
win <- windowNew
ico <- loadIcon "yi+lambda-fat-32.png"
vb <- vBoxNew False 1 -- Top-level vbox
im <- imMulticontextNew
imContextSetUsePreedit im False -- handler for preedit string not implemented
-- Yi.Buffer.Misc.insertN for atomic input?
let imContextCommitS :: Signal IMContext (String -> IO ())
imContextCommitS = imContextCommit
im `on` imContextCommitS $ mapM_ (\k -> ch [Event (KASCII k) []])
set win [ windowDefaultWidth := 700
, windowDefaultHeight := 900
, windowTitle := ("Yi" :: T.Text)
, windowIcon := Just ico
, containerChild := vb
]
win `on` deleteEvent $ io $ mainQuit >> return True
win `on` keyPressEvent $ handleKeypress ch im
paned <- hPanedNew
tabs <- simpleNotebookNew
panedAdd2 paned (baseWidget tabs)
status <- statusbarNew
-- Allow multiple lines in statusbar, GitHub issue #478
statusbarGetMessageArea status >>= containerGetChildren >>= \case
[w] -> labelSetSingleLineMode (castToLabel w) False
_ -> return ()
-- statusbarGetContextId status "global"
set vb [ containerChild := paned
, containerChild := status
, boxChildPacking status := PackNatural
]
fontRef <- fontDescriptionNew >>= newIORef
let actionCh = outCh . return
tc <- newIORef =<< newCache ed actionCh
#ifdef GNOME_ENABLED
let watchFont = watchSystemFont
#else
let watchFont = (fontDescriptionFromString ("Monospace 10" :: T.Text) >>=)
#endif
watchFont $ updateFont (configUI cfg) fontRef tc status
-- I think this is the correct place to put it...
userHook win
-- use our magic threads thingy
-- http://haskell.org/gtk2hs/archives/2005/07/24/writing-multi-threaded-guis/
void $ timeoutAddFull (yield >> return True) priorityDefaultIdle 50
widgetShowAll win
let ui = UI win tabs status tc actionCh (configUI cfg) fontRef im
-- Keep the current tab focus up to date
let move n pl = fromMaybe pl (PL.moveTo n pl)
runAction = uiActionCh ui . makeAction
-- why does this cause a hang without postGUIAsync?
simpleNotebookOnSwitchPage (uiNotebook ui) $ \n -> postGUIAsync $
runAction ((%=) tabsA (move n) :: EditorM ())
return (mkUI ui)
main :: IO ()
main = logPutStrLn "GTK main loop running" >> mainGUI
-- | Clean up and go home
end :: IO ()
end = mainQuit
-- | Modify GUI and the 'TabCache' to reflect information in 'Editor'.
updateCache :: UI -> Editor -> IO ()
updateCache ui e = do
cache <- readIORef $ tabCache ui
-- convert to a map for convenient lookups
let cacheMap = mapFromFoldable . fmap (\t -> (coreTabKey t, t)) $ cache
-- build the new cache
cache' <- forM (e ^. tabsA) $ \tab ->
case M.lookup (tkey tab) cacheMap of
Just t -> updateTabInfo e ui tab t >> return t
Nothing -> newTab e ui tab
-- store the new cache
writeIORef (tabCache ui) cache'
-- update the GUI
simpleNotebookSet (uiNotebook ui)
=<< forM cache' (\t -> (tabWidget t,) <$> readIORef (abbrevTitle t))
-- | Modify GUI and given 'TabInfo' to reflect information in 'Tab'.
updateTabInfo :: Editor -> UI -> Tab -> TabInfo -> IO ()
updateTabInfo e ui tab tabInfo = do
-- update the window cache
wCacheOld <- readIORef (windowCache tabInfo)
wCacheNew <- mapFromFoldable <$> forM (tab ^. tabWindowsA) (\w ->
case M.lookup (wkey w) wCacheOld of
Just wInfo -> updateWindow e ui w wInfo >> return (wkey w, wInfo)
Nothing -> (wkey w,) <$> newWindow e ui w)
writeIORef (windowCache tabInfo) wCacheNew
-- TODO update renderer, etc?
let lookupWin w = wCacheNew M.! w
-- set layout
layoutDisplaySet (layoutDisplay tabInfo)
. fmap (winWidget . lookupWin) . tabLayout $ tab
-- set minibox
miniwindowDisplaySet (miniwindowPage tabInfo)
. fmap (winWidget . lookupWin . wkey) . tabMiniWindows $ tab
-- set focus
setWindowFocus e ui tabInfo . lookupWin . wkey . tabFocus $ tab
updateWindow :: Editor -> UI -> Window -> WinInfo -> IO ()
updateWindow e _ui win wInfo = do
writeIORef (inFocus wInfo) False -- see also 'setWindowFocus'
writeIORef (coreWin wInfo) win
writeIORef (insertingMode wInfo)
(askBuffer win (findBufferWith (bufkey win) e) $ use insertingA)
setWindowFocus :: Editor -> UI -> TabInfo -> WinInfo -> IO ()
setWindowFocus e ui t w = do
win <- readIORef (coreWin w)
let bufferName = shortIdentString (length $ commonNamePrefix e) $
findBufferWith (bufkey win) e
ml = askBuffer win (findBufferWith (bufkey win) e) $
getModeLine (T.pack <$> commonNamePrefix e)
im = uiInput ui
writeIORef (inFocus w) True -- see also 'updateWindow'
update (textview w) widgetIsFocus True
update (modeline w) labelText ml
writeIORef (fullTitle t) bufferName
writeIORef (abbrevTitle t) (tabAbbrevTitle bufferName)
drawW <- catch (fmap Just $ widgetGetDrawWindow $ textview w)
(\(_ :: SomeException) -> return Nothing)
imContextSetClientWindow im drawW
imContextFocusIn im
getWinInfo :: UI -> WindowRef -> IO WinInfo
getWinInfo ui ref =
let tabLoop [] = error "Yi.UI.Pango.getWinInfo: window not found"
tabLoop (t:ts) = do
wCache <- readIORef (windowCache t)
case M.lookup ref wCache of
Just w -> return w
Nothing -> tabLoop ts
in readIORef (tabCache ui) >>= (tabLoop . toList)
-- | Make the cache from the editor and the action channel
newCache :: Editor -> (Action -> IO ()) -> IO TabCache
newCache e actionCh = mapM (mkDummyTab actionCh) (e ^. tabsA)
-- | Make a new tab, and populate it
newTab :: Editor -> UI -> Tab -> IO TabInfo
newTab e ui tab = do
t <- mkDummyTab (uiActionCh ui) tab
updateTabInfo e ui tab t
return t
-- | Make a minimal new tab, without any windows.
-- This is just for bootstrapping the UI; 'newTab' should normally
-- be called instead.
mkDummyTab :: (Action -> IO ()) -> Tab -> IO TabInfo
mkDummyTab actionCh tab = do
ws <- newIORef M.empty
ld <- layoutDisplayNew
layoutDisplayOnDividerMove ld (handleDividerMove actionCh)
mwp <- miniwindowDisplayNew
tw <- vBoxNew False 0
set tw [containerChild := baseWidget ld,
containerChild := baseWidget mwp,
boxChildPacking (baseWidget ld) := PackGrow,
boxChildPacking (baseWidget mwp) := PackNatural]
ftRef <- newIORef ""
atRef <- newIORef ""
return (TabInfo (tkey tab) ld mwp (toWidget tw) ws ftRef atRef)
-- | Make a new window.
newWindow :: Editor -> UI -> Window -> IO WinInfo
newWindow e ui w = do
let b = findBufferWith (bufkey w) e
f <- readIORef (uiFont ui)
ml <- labelNew (Nothing :: Maybe Text)
widgetModifyFont ml (Just f)
set ml [ miscXalign := 0.01 ] -- so the text is left-justified.
-- allow the modeline to be covered up, horizontally
widgetSetSizeRequest ml 0 (-1)
v <- drawingAreaNew
widgetModifyFont v (Just f)
widgetAddEvents v [Button1MotionMask]
widgetModifyBg v StateNormal . mkCol False . Yi.Style.background
. baseAttributes . configStyle $ uiConfig ui
sw <- scrolledWindowNew Nothing Nothing
scrolledWindowAddWithViewport sw v
scrolledWindowSetPolicy sw PolicyAutomatic PolicyNever
box <- if isMini w
then do
prompt <- labelNew (Just $ miniIdentString b)
widgetModifyFont prompt (Just f)
hb <- hBoxNew False 1
set hb [ containerChild := prompt,
containerChild := sw,
boxChildPacking prompt := PackNatural,
boxChildPacking sw := PackGrow]
return (castToBox hb)
else do
vb <- vBoxNew False 1
set vb [ containerChild := sw,
containerChild := ml,
boxChildPacking ml := PackNatural]
return (castToBox vb)
tosRef <- newIORef (askBuffer w b (use . markPointA
=<< fromMark <$> askMarks))
context <- widgetCreatePangoContext v
layout <- layoutEmpty context
layoutRef <- newMVar (WinLayoutInfo layout 0 0 0 0
(findBufferWith (bufkey w) e) Nothing)
language <- contextGetLanguage context
metrics <- contextGetMetrics context f language
ifLButton <- newIORef False
imode <- newIORef False
focused <- newIORef False
winRef <- newIORef w
layoutSetFontDescription layout (Just f)
-- stops layoutGetText crashing (as of gtk2hs 0.10.1)
layoutSetText layout T.empty
let ref = wkey w
win = WinInfo { coreWinKey = ref
, coreWin = winRef
, winLayoutInfo = layoutRef
, winMetrics = metrics
, textview = v
, modeline = ml
, winWidget = toWidget box
, shownTos = tosRef
, lButtonPressed = ifLButton
, insertingMode = imode
, inFocus = focused
}
updateWindow e ui w win
v `on` buttonPressEvent $ handleButtonClick ui ref
v `on` buttonReleaseEvent $ handleButtonRelease ui win
v `on` scrollEvent $ handleScroll ui win
-- todo: allocate event rather than configure?
v `on` configureEvent $ handleConfigure ui
v `on` motionNotifyEvent $ handleMove ui win
void $ v `onExpose` render ui win
-- also redraw when the window receives/loses focus
uiWindow ui `on` focusInEvent $ io (widgetQueueDraw v) >> return False
uiWindow ui `on` focusOutEvent $ io (widgetQueueDraw v) >> return False
-- todo: consider adding an 'isDirty' flag to WinLayoutInfo,
-- so that we don't have to recompute the Attributes when focus changes.
return win
refresh :: UI -> Editor -> IO ()
refresh ui e = do
postGUIAsync $ do
contextId <- statusbarGetContextId (uiStatusbar ui) ("global" :: T.Text)
statusbarPop (uiStatusbar ui) contextId
void $ statusbarPush (uiStatusbar ui) contextId $ T.intercalate " " $
statusLine e
updateCache ui e -- The cursor may have changed since doLayout
cache <- readIORef $ tabCache ui
forM_ cache $ \t -> do
wCache <- readIORef (windowCache t)
forM_ wCache $ \w -> do
updateWinInfoForRendering e ui w
widgetQueueDraw (textview w)
-- | Record all the information we need for rendering.
--
-- This information is kept in an MVar so that the PangoLayout and
-- tos/bos/buffer are in sync.
updateWinInfoForRendering :: Editor -> UI -> WinInfo -> IO ()
updateWinInfoForRendering e _ui w = modifyMVar_ (winLayoutInfo w) $ \wli -> do
win <- readIORef (coreWin w)
return $! wli{buffer=findBufferWith (bufkey win) e,regex=currentRegex e}
-- | Tell the 'PangoLayout' what colours to draw, and draw the 'PangoLayout'
-- and the cursor onto the screen
render :: UI -> WinInfo -> t -> IO Bool
render ui w _event =
withMVar (winLayoutInfo w) $
\WinLayoutInfo{winLayout=layout,tos,bos,cur,buffer=b,regex} -> do
-- read the information
win <- readIORef (coreWin w)
-- add color attributes.
let picture = askBuffer win b $ attributesPictureAndSelB sty regex
(mkRegion tos bos)
sty = configStyle $ uiConfig ui
picZip = zip picture $ drop 1 (fst <$> picture) <> [bos]
strokes = [ (start',s,end') | ((start', s), end') <- picZip
, s /= emptyAttributes ]
rel p = fromIntegral (p - tos)
allAttrs = concat $ do
(p1, Attributes fg bg _rv bd itlc udrl, p2) <- strokes
let atr x = x (rel p1) (rel p2)
if' p x y = if p then x else y
return [ atr AttrForeground $ mkCol True fg
, atr AttrBackground $ mkCol False bg
, atr AttrStyle $ if' itlc StyleItalic StyleNormal
, atr AttrUnderline $ if' udrl UnderlineSingle UnderlineNone
, atr AttrWeight $ if' bd WeightBold WeightNormal
]
layoutSetAttributes layout allAttrs
drawWindow <- widgetGetDrawWindow $ textview w
gc <- gcNew drawWindow
-- see Note [PangoLayout width]
-- draw the layout
drawLayout drawWindow gc 1 0 layout
-- calculate the cursor position
im <- readIORef (insertingMode w)
-- check focus, and decide whether we want a wide cursor
bufferFocused <- readIORef (inFocus w)
uiFocused <- Gtk.windowHasToplevelFocus (uiWindow ui)
let focused = bufferFocused && uiFocused
wideCursor =
case configCursorStyle (uiConfig ui) of
AlwaysFat -> True
NeverFat -> False
FatWhenFocused -> focused
FatWhenFocusedAndInserting -> focused && im
(PangoRectangle (succ -> curX) curY curW curH, _) <-
layoutGetCursorPos layout (rel cur)
-- tell the input method
imContextSetCursorLocation (uiInput ui) $
Rectangle (round curX) (round curY) (round curW) (round curH)
-- paint the cursor
gcSetValues gc
(newGCValues { Gtk.foreground = mkCol True . Yi.Style.foreground
. baseAttributes . configStyle $
uiConfig ui
, Gtk.lineWidth = if wideCursor then 2 else 1 })
-- tell the renderer
if im
then -- if we are inserting, we just want a line
drawLine drawWindow gc (round curX, round curY)
(round $ curX + curW, round $ curY + curH)
-- we aren't inserting, we want a rectangle around the current character
else do
PangoRectangle (succ -> chx) chy chw chh <- layoutIndexToPos
layout (rel cur)
drawRectangle drawWindow gc False (round chx) (round chy)
(if chw > 0 then round chw else 8) (round chh)
return True
doLayout :: UI -> Editor -> IO Editor
doLayout ui e = do
updateCache ui e
tabs <- readIORef $ tabCache ui
f <- readIORef (uiFont ui)
dims <- fold <$> mapM (getDimensionsInTab ui f e) tabs
let e' = (tabsA %~ fmap (mapWindows updateWin)) e
updateWin w = case M.lookup (wkey w) dims of
Nothing -> w
Just (wi,h,rgn) -> w { width = wi, height = h, winRegion = rgn }
-- Don't leak references to old Windows
let forceWin x w = height w `seq` winRegion w `seq` x
return $ (foldl . tabFoldl) forceWin e' (e' ^. tabsA)
-- | Width, Height
getDimensionsInTab :: UI -> FontDescription -> Editor
-> TabInfo -> IO (M.Map WindowRef (Int,Int,Region))
getDimensionsInTab ui f e tab = do
wCache <- readIORef (windowCache tab)
forM wCache $ \wi -> do
(wid, h) <- widgetGetSize $ textview wi
win <- readIORef (coreWin wi)
let metrics = winMetrics wi
lineHeight = ascent metrics + descent metrics
charWidth = max (approximateCharWidth metrics) (approximateDigitWidth metrics)
width = round $ fromIntegral wid / charWidth
height = round $ fromIntegral h / lineHeight
b0 = findBufferWith (bufkey win) e
rgn <- shownRegion ui f wi b0
return (width, height, rgn)
shownRegion :: UI -> FontDescription -> WinInfo -> FBuffer -> IO Region
shownRegion ui f w b = modifyMVar (winLayoutInfo w) $ \wli -> do
(tos, cur, bos, bufEnd) <- updatePango ui f w b (winLayout wli)
return (wli{tos,cur=clampTo tos bos cur,bos,bufEnd}, mkRegion tos bos)
where clampTo lo hi x = max lo (min hi x)
-- during scrolling, cur might not lie between tos and bos,
-- so we clamp it to avoid Pango errors
{-|
== Note [PangoLayout width]
We start rendering the PangoLayout one pixel from the left of the
rendering area, which means a few +/-1 offsets in Pango rendering and
point lookup code. The reason for this is to support the "wide
cursor", which is 2 pixels wide. If we started rendering the
PangoLayout directly from the left of the rendering area instead of at
a 1-pixel offset, then the "wide cursor" would only be half-displayed
when the cursor is at the beginning of the line, and would then be a
"thin cursor".
An alternative would be to special-case the wide cursor rendering at
the beginning of the line, and draw it one pixel to the right of where
it "should" be. I haven't tried this out to see how it looks.
Reiner
-}
-- we update the regex and the buffer to avoid holding on to potential garbage.
-- These will be overwritten with correct values soon, in
-- updateWinInfoForRendering.
updatePango :: UI -> FontDescription -> WinInfo -> FBuffer
-> PangoLayout -> IO (Point, Point, Point, Point)
updatePango ui font w b layout = do
(width_', height') <- widgetGetSize $ textview w
let width' = max 0 (width_' - 1) -- see Note [PangoLayout width]
fontDescriptionToStringT :: FontDescription -> IO Text
fontDescriptionToStringT = fontDescriptionToString
-- Resize (and possibly copy) the currently used font.
curFont <- case fromIntegral <$> configFontSize (uiConfig ui) of
Nothing -> return font
Just defSize -> fontDescriptionGetSize font >>= \case
Nothing -> fontDescriptionSetSize font defSize >> return font
Just currentSize -> let fsv = fontsizeVariation $ attributes b
newSize = max 1 (fromIntegral fsv + defSize) in do
if (newSize == currentSize)
then return font
else do
-- This seems like it would be very expensive but I'm
-- justifying it with that it only gets ran once per font
-- size change. If the font size stays the same, we only
-- enter this once per layout. We're effectivelly copying
-- the default font for each layout that changes. An
-- alternative would be to assign each buffer its own font
-- but that seems a pain to maintain and if the user never
-- changes font sizes, it's a waste of memory.
nf <- fontDescriptionCopy font
fontDescriptionSetSize nf newSize
return nf
oldFont <- layoutGetFontDescription layout
oldFontStr <- maybe (return Nothing)
(fmap Just . fontDescriptionToStringT) oldFont
newFontStr <- Just <$> fontDescriptionToStringT curFont
when (oldFontStr /= newFontStr) $
layoutSetFontDescription layout (Just curFont)
win <- readIORef (coreWin w)
let [width'', height''] = fmap fromIntegral [width', height']
metrics = winMetrics w
lineHeight = ascent metrics + descent metrics
charWidth = max (approximateCharWidth metrics)
(approximateDigitWidth metrics)
winw = max 1 $ floor (width'' / charWidth)
winh = max 1 $ floor (height'' / lineHeight)
maxChars = winw * winh
conf = uiConfig ui
(tos, size, point, text) = askBuffer win b $ do
from <- use . markPointA =<< fromMark <$> askMarks
rope <- streamB Forward from
p <- pointB
bufEnd <- sizeB
let content = takeContent conf maxChars . fst $ R.splitAtLine winh rope
-- allow BOS offset to be just after the last line
let addNL = if R.countNewLines content == winh
then id
else (`R.snoc` '\n')
return (from, bufEnd, p, R.toText $ addNL content)
if configLineWrap conf
then wrapToWidth layout WrapAnywhere width''
else do
(Rectangle px _py pwidth _pheight, _) <- layoutGetPixelExtents layout
widgetSetSizeRequest (textview w) (px+pwidth) (-1)
-- optimize for cursor movement
oldText <- layoutGetText layout
when (oldText /= text) (layoutSetText layout text)
(_, bosOffset, _) <- layoutXYToIndex layout width''
(fromIntegral winh * lineHeight - 1)
return (tos, point, tos + fromIntegral bosOffset + 1, size)
-- | This is a hack that makes this renderer not suck in the common
-- case. There are two scenarios: we're line wrapping or we're not
-- line wrapping. This function already assumes that the contents
-- given have all the possible lines we can fit on the screen.
--
-- If we are line wrapping then the most text we'll ever need to
-- render is precisely the number of characters that can fit on the
-- screen. If that's the case, that's precisely what we do, truncate
-- up to the point where the text would be off-screen anyway.
--
-- If we aren't line-wrapping then we can't simply truncate at the max
-- number of characters: lines might be really long, but considering
-- we're not truncating, we should still be able to see every single
-- line that can fit on screen up to the screen bound. This suggests
-- that we could simply render each line up to the bound. While this
-- does work wonders for performance and would work regardless whether
-- we're wrapping or not, currently our implementation of the rest of
-- the module depends on all characters used being set into the
-- layout: if we cut some text off, painting strokes on top or going
-- to the end makes for strange effects. So currently we have no
-- choice but to render all characters in the visible lines. If you
-- have really long lines, this will kill the performance.
--
-- So here we implement the hack for the line-wrapping case. Once we
-- fix stroke painting &c, this distinction can be removed and we can
-- simply snip at the screen boundary whether we're wrapping or not
-- which actually results in great performance in the end. Until that
-- happens, only the line-wrapping case doesn't suck. Fortunately it
-- is the default.
takeContent :: UIConfig -> Int -> R.YiString -> R.YiString
takeContent cf cl t = case configLineWrap cf of
True -> R.take cl t
False -> t
-- | Wraps the layout according to the given 'LayoutWrapMode', using
-- the specified width.
--
-- In contrast to the past, it actually implements wrapping properly
-- which was previously broken.
wrapToWidth :: PangoLayout -> LayoutWrapMode -> Double -> IO ()
wrapToWidth l wm w = do
layoutGetWrap l >>= \wr -> case (wr, wm) of
-- No Eq instance…
(WrapWholeWords, WrapWholeWords) -> return ()
(WrapAnywhere, WrapAnywhere) -> return ()
(WrapPartialWords, WrapPartialWords) -> return ()
_ -> layoutSetWrap l wm
layoutGetWidth l >>= \case
Just x | x == w -> return ()
_ -> layoutSetWidth l (Just w)
reloadProject :: IO ()
reloadProject = return ()
mkCol :: Bool -- ^ is foreground?
-> Yi.Style.Color -> Gtk.Color
mkCol True Default = Color 0 0 0
mkCol False Default = Color maxBound maxBound maxBound
mkCol _ (RGB x y z) = Color (fromIntegral x * 256)
(fromIntegral y * 256)
(fromIntegral z * 256)
-- * GTK Event handlers
-- | Process GTK keypress if IM fails
handleKeypress :: ([Event] -> IO ()) -- ^ Event dispatcher (Yi.Core.dispatch)
-> IMContext
-> EventM EKey Bool
handleKeypress ch im = do
gtkMods <- eventModifier
gtkKey <- eventKeyVal
ifIM <- imContextFilterKeypress im
let char = keyToChar gtkKey
modsWithShift = M.keys $ M.filter (`elem` gtkMods) modTable
mods | isJust char = filter (/= MShift) modsWithShift
| otherwise = modsWithShift
key = case char of
Just c -> Just $ KASCII c
Nothing -> M.lookup (keyName gtkKey) keyTable
case (ifIM, key) of
(True, _ ) -> return ()
(_, Nothing) -> logPutStrLn $ "Event not translatable: " <> showT key
(_, Just k ) -> io $ ch [Event k mods]
return True
-- | Map Yi modifiers to GTK
modTable :: M.Map Modifier EventM.Modifier
modTable = M.fromList
[ (MShift, EventM.Shift )
, (MCtrl, EventM.Control)
, (MMeta, EventM.Alt )
, (MSuper, EventM.Super )
, (MHyper, EventM.Hyper )
]
-- | Same as Gtk.on, but discards the ConnectId
on :: object -> Signal object callback -> callback -> IO ()
on widget signal handler = void $ Gtk.on widget signal handler
handleButtonClick :: UI -> WindowRef -> EventM EButton Bool
handleButtonClick ui ref = do
(x, y) <- eventCoordinates
click <- eventClick
button <- eventButton
io $ do
w <- getWinInfo ui ref
point <- pointToOffset (x, y) w
let focusWindow = focusWindowE ref
runAction = uiActionCh ui . makeAction
runAction focusWindow
win <- io $ readIORef (coreWin w)
let selectRegion tu = runAction $ do
b <- gets $ bkey . findBufferWith (bufkey win)
withGivenBufferAndWindow win b $
moveTo point >> regionOfB tu >>= setSelectRegionB
case (click, button) of
(SingleClick, LeftButton) -> do
io $ writeIORef (lButtonPressed w) True
runAction $ do
b <- gets $ bkey . findBufferWith (bufkey win)
withGivenBufferAndWindow win b $ do
m <- selMark <$> askMarks
markPointA m .= point
moveTo point
setVisibleSelection False
(DoubleClick, LeftButton) -> selectRegion unitWord
(TripleClick, LeftButton) -> selectRegion Line
_ -> return ()
return True
handleButtonRelease :: UI -> WinInfo -> EventM EButton Bool
handleButtonRelease ui w = do
(x, y) <- eventCoordinates
button <- eventButton
io $ do
point <- pointToOffset (x, y) w
disp <- widgetGetDisplay $ textview w
cb <- clipboardGetForDisplay disp selectionPrimary
case button of
MiddleButton -> pasteSelectionClipboard ui w point cb
LeftButton -> setSelectionClipboard ui w cb >>
writeIORef (lButtonPressed w) False
_ -> return ()
return True
handleScroll :: UI -> WinInfo -> EventM EScroll Bool
handleScroll ui w = do
scrollDirection <- eventScrollDirection
xy <- eventCoordinates
io $ do
ifPressed <- readIORef $ lButtonPressed w
-- query new coordinates
let editorAction =
withCurrentBuffer $ scrollB $ case scrollDirection of
ScrollUp -> negate configAmount
ScrollDown -> configAmount
_ -> 0 -- Left/right scrolling not supported
configAmount = configScrollWheelAmount $ uiConfig ui
uiActionCh ui (EditorA editorAction)
when ifPressed $ selectArea ui w xy
return True
handleConfigure :: UI -> EventM EConfigure Bool
handleConfigure ui = do
-- trigger a layout
-- why does this cause a hang without postGUIAsync?
io $ postGUIAsync $ uiActionCh ui (makeAction (return () :: EditorM()))
return False -- allow event to be propagated
handleMove :: UI -> WinInfo -> EventM EMotion Bool
handleMove ui w = eventCoordinates >>= (io . selectArea ui w) >>
return True
handleDividerMove :: (Action -> IO ()) -> DividerRef -> DividerPosition -> IO ()
handleDividerMove actionCh ref pos =
actionCh (makeAction (setDividerPosE ref pos))
-- | Convert point coordinates to offset in Yi window
pointToOffset :: (Double, Double) -> WinInfo -> IO Point
pointToOffset (x,y) w =
withMVar (winLayoutInfo w) $ \WinLayoutInfo{winLayout,tos,bufEnd} -> do
im <- readIORef (insertingMode w)
-- see Note [PangoLayout width]
(_, charOffsetX, extra) <- layoutXYToIndex winLayout (max 0 (x-1)) y
return $ min bufEnd (tos + fromIntegral
(charOffsetX + if im then extra else 0))
selectArea :: UI -> WinInfo -> (Double, Double) -> IO ()
selectArea ui w (x,y) = do
p <- pointToOffset (x,y) w
let editorAction = do
txt <- withCurrentBuffer $ do
moveTo p
setVisibleSelection True
readRegionB =<< getSelectRegionB
setRegE txt
uiActionCh ui (makeAction editorAction)
-- drawWindowGetPointer (textview w) -- be ready for next message.
pasteSelectionClipboard :: UI -> WinInfo -> Point -> Clipboard -> IO ()
pasteSelectionClipboard ui w p cb = do
win <- io $ readIORef (coreWin w)
let cbHandler :: Maybe R.YiString -> IO ()
cbHandler Nothing = return ()
cbHandler (Just txt) = uiActionCh ui $ EditorA $ do
b <- gets $ bkey . findBufferWith (bufkey win)
withGivenBufferAndWindow win b $ do
pointB >>= setSelectionMarkPointB
moveTo p
insertN txt
clipboardRequestText cb (cbHandler . fmap R.fromText)
-- | Set selection clipboard contents to current selection
setSelectionClipboard :: UI -> WinInfo -> Clipboard -> IO ()
setSelectionClipboard ui _w cb = do
-- Why uiActionCh doesn't allow returning values?
selection <- newIORef mempty
let yiAction = do
txt <- withCurrentBuffer $
fmap R.toText . readRegionB =<< getSelectRegionB :: YiM T.Text
io $ writeIORef selection txt
uiActionCh ui $ makeAction yiAction
txt <- readIORef selection
unless (T.null txt) $ clipboardSetText cb txt
|
atsukotakahashi/wi
|
src/library/Yi/UI/Pango.hs
|
gpl-2.0
| 35,007 | 570 | 23 | 9,506 | 8,340 | 4,513 | 3,827 | 653 | 8 |
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveDataTypeable
, FlexibleInstances, UndecidableInstances, ExistentialQuantification #-}
{- |
Module : $Header$
Description : interface and class for logic translations
Copyright : (c) Till Mossakowski, Uni Bremen 2002-2006
License : GPLv2 or higher, see LICENSE.txt
Maintainer : [email protected]
Stability : provisional
Portability : non-portable (via Logic)
Central interface (type class) for logic translations (comorphisms) in Hets
These are just collections of
functions between (some of) the types of logics.
References: see Logic.hs
-}
module Logic.Comorphism
( CompComorphism (..)
, InclComorphism
, inclusion_logic
, inclusion_source_sublogic
, inclusion_target_sublogic
, mkInclComorphism
, mkIdComorphism
, Comorphism (..)
, targetSublogic
, map_sign
, wrapMapTheory
, mkTheoryMapping
, AnyComorphism (..)
, idComorphism
, isIdComorphism
, isModelTransportable
, hasModelExpansion
, isWeaklyAmalgamable
, compComorphism
) where
import Logic.Logic
import Logic.Coerce
import Common.AS_Annotation
import Common.Doc
import Common.DocUtils
import Common.Id
import Common.LibName
import Common.ProofUtils
import Common.Result
import Data.Maybe
import qualified Data.Set as Set
import Data.Typeable
class (Language cid,
Logic lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1,
Logic lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2) =>
Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
| cid -> lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
where
{- source and target logic and sublogic
the source sublogic is the maximal one for which the comorphism works -}
sourceLogic :: cid -> lid1
sourceSublogic :: cid -> sublogics1
minSourceTheory :: cid -> Maybe (LibName, String)
minSourceTheory _ = Nothing
targetLogic :: cid -> lid2
{- finer information of target sublogics corresponding to source sublogics
this function must be partial because mapTheory is partial -}
mapSublogic :: cid -> sublogics1 -> Maybe sublogics2
{- the translation functions are partial
because the target may be a sublanguage
map_basic_spec :: cid -> basic_spec1 -> Result basic_spec2
cover theoroidal comorphisms as well -}
map_theory :: cid -> (sign1, [Named sentence1])
-> Result (sign2, [Named sentence2])
map_morphism :: cid -> morphism1 -> Result morphism2
map_morphism = mapDefaultMorphism
map_sentence :: cid -> sign1 -> sentence1 -> Result sentence2
{- also covers semi-comorphisms
with no sentence translation
- but these are spans! -}
map_sentence = failMapSentence
map_symbol :: cid -> sign1 -> symbol1 -> Set.Set symbol2
map_symbol = errMapSymbol
extractModel :: cid -> sign1 -> proof_tree2
-> Result (sign1, [Named sentence1])
extractModel cid _ _ = fail
$ "extractModel not implemented for comorphism "
++ language_name cid
-- properties of comorphisms
is_model_transportable :: cid -> Bool
{- a comorphism (\phi, \alpha, \beta) is model-transportable
if for any signature \Sigma,
any \Sigma-model M and any \phi(\Sigma)-model N
for any isomorphism h : \beta_\Sigma(N) -> M
there exists an isomorphism h': N -> M' such that \beta_\Sigma(h') = h -}
is_model_transportable _ = False
has_model_expansion :: cid -> Bool
has_model_expansion _ = False
is_weakly_amalgamable :: cid -> Bool
is_weakly_amalgamable _ = False
constituents :: cid -> [String]
constituents cid = [language_name cid]
isInclusionComorphism :: cid -> Bool
isInclusionComorphism _ = False
targetSublogic :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sublogics2
targetSublogic cid = fromMaybe (top_sublogic $ targetLogic cid)
$ mapSublogic cid $ sourceSublogic cid
-- | this function is base on 'map_theory' using no sentences as input
map_sign :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> Result (sign2, [Named sentence2])
map_sign cid sign = wrapMapTheory cid (sign, [])
mapDefaultMorphism :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> morphism1 -> Result morphism2
mapDefaultMorphism cid mor = do
(sig1, _) <- map_sign cid $ dom mor
(sig2, _) <- map_sign cid $ cod mor
inclusion (targetLogic cid) sig1 sig2
failMapSentence :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> sentence1 -> Result sentence2
failMapSentence cid _ _ =
fail $ "Unsupported sentence translation " ++ show cid
errMapSymbol :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> sign1 -> symbol1 -> Set.Set symbol2
errMapSymbol cid _ _ = error $ "no symbol mapping for " ++ show cid
-- | use this function instead of 'map_theory'
wrapMapTheory :: Comorphism cid
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2
=> cid -> (sign1, [Named sentence1])
-> Result (sign2, [Named sentence2])
wrapMapTheory cid (sign, sens) =
let res = map_theory cid (sign, sens)
lid1 = sourceLogic cid
thDoc = show (vcat $ pretty sign : map (print_named lid1) sens)
in
if isIdComorphism $ Comorphism cid then res else case sourceSublogic cid of
sub -> case minSublogic sign of
sigLog -> case foldl join sigLog
$ map (minSublogic . sentence) sens of
senLog ->
if isSubElem senLog sub
then res
else Result
[ Diag Hint thDoc nullRange
, Diag Error
("for '" ++ language_name cid ++
"' expected sublogic '" ++
sublogicName sub ++
"'\n but found sublogic '" ++
sublogicName senLog ++
"' with signature sublogic '" ++
sublogicName sigLog ++ "'") nullRange] Nothing
mkTheoryMapping :: Monad m => (sign1 -> m (sign2, [Named sentence2]))
-> (sign1 -> sentence1 -> m sentence2)
-> (sign1, [Named sentence1])
-> m (sign2, [Named sentence2])
mkTheoryMapping mapSig mapSen (sign, sens) = do
(sign', sens') <- mapSig sign
sens'' <- mapM (mapNamedM $ mapSen sign) sens
return (sign', nameAndDisambiguate $ sens' ++ sens'')
data InclComorphism lid sublogics = InclComorphism
{ inclusion_logic :: lid
, inclusion_source_sublogic :: sublogics
, inclusion_target_sublogic :: sublogics }
deriving Show
-- | construction of an identity comorphism
mkIdComorphism :: (Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree) =>
lid -> sublogics -> InclComorphism lid sublogics
mkIdComorphism lid sub = InclComorphism
{ inclusion_logic = lid
, inclusion_source_sublogic = sub
, inclusion_target_sublogic = sub }
-- | construction of an inclusion comorphism
mkInclComorphism :: (Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree,
Monad m) =>
lid -> sublogics -> sublogics
-> m (InclComorphism lid sublogics)
mkInclComorphism lid srcSub trgSub =
if isSubElem srcSub trgSub
then return InclComorphism
{ inclusion_logic = lid
, inclusion_source_sublogic = srcSub
, inclusion_target_sublogic = trgSub }
else fail ("mkInclComorphism: first sublogic must be a " ++
"subElem of the second sublogic")
instance (Language lid, Eq sublogics, Show sublogics, SublogicName sublogics)
=> Language (InclComorphism lid sublogics) where
language_name (InclComorphism lid sub_src sub_trg) =
let sblName = sublogicName sub_src
lname = language_name lid
in if sub_src == sub_trg
then "id_" ++ lname ++
if null sblName then "" else '.' : sblName
else "incl_" ++ lname ++ ':'
: sblName ++ "->" ++ sublogicName sub_trg
instance Logic lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree =>
Comorphism (InclComorphism lid sublogics)
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
lid sublogics
basic_spec sentence symb_items symb_map_items
sign morphism symbol raw_symbol proof_tree
where
sourceLogic = inclusion_logic
targetLogic = inclusion_logic
sourceSublogic = inclusion_source_sublogic
mapSublogic cid subl =
if isSubElem subl $ inclusion_source_sublogic cid
then Just subl
else Nothing
map_theory _ = return
map_morphism _ = return
map_sentence _ _ = return
map_symbol _ _ = Set.singleton
constituents cid =
if inclusion_source_sublogic cid
== inclusion_target_sublogic cid
then []
else [language_name cid]
is_model_transportable _ = True
has_model_expansion _ = True
is_weakly_amalgamable _ = True
isInclusionComorphism _ = True
data CompComorphism cid1 cid2 = CompComorphism cid1 cid2 deriving Show
instance (Language cid1, Language cid2)
=> Language (CompComorphism cid1 cid2) where
language_name (CompComorphism cid1 cid2) =
language_name cid1 ++ ";" ++ language_name cid2
instance (Comorphism cid1
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2,
Comorphism cid2
lid4 sublogics4 basic_spec4 sentence4 symb_items4 symb_map_items4
sign4 morphism4 symbol4 raw_symbol4 proof_tree4
lid3 sublogics3 basic_spec3 sentence3 symb_items3 symb_map_items3
sign3 morphism3 symbol3 raw_symbol3 proof_tree3)
=> Comorphism (CompComorphism cid1 cid2)
lid1 sublogics1 basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid3 sublogics3 basic_spec3 sentence3 symb_items3 symb_map_items3
sign3 morphism3 symbol3 raw_symbol3 proof_tree3 where
sourceLogic (CompComorphism cid1 _) =
sourceLogic cid1
targetLogic (CompComorphism _ cid2) =
targetLogic cid2
sourceSublogic (CompComorphism cid1 _) =
sourceSublogic cid1
mapSublogic (CompComorphism cid1 cid2) sl =
mapSublogic cid1 sl >>=
mapSublogic cid2 .
forceCoerceSublogic (targetLogic cid1) (sourceLogic cid2)
map_sentence (CompComorphism cid1 cid2) si1 se1 =
do (si2, _) <- map_sign cid1 si1
se2 <- map_sentence cid1 si1 se1
(si2', se2') <- coerceBasicTheory
(targetLogic cid1) (sourceLogic cid2)
"Mapping sentence along comorphism" (si2, [makeNamed "" se2])
case se2' of
[x] -> map_sentence cid2 si2' $ sentence x
_ -> error "CompComorphism.map_sentence"
map_theory (CompComorphism cid1 cid2) ti1 =
do ti2 <- map_theory cid1 ti1
ti2' <- coerceBasicTheory (targetLogic cid1) (sourceLogic cid2)
"Mapping theory along comorphism" ti2
wrapMapTheory cid2 ti2'
map_morphism (CompComorphism cid1 cid2) m1 =
do m2 <- map_morphism cid1 m1
m3 <- coerceMorphism (targetLogic cid1) (sourceLogic cid2)
"Mapping signature morphism along comorphism" m2
map_morphism cid2 m3
map_symbol (CompComorphism cid1 cid2) sig1 = let
th = map_sign cid1 sig1 in
case maybeResult th of
Nothing -> error "failed translating signature"
Just (sig2', _) -> let
th2 = coerceBasicTheory
(targetLogic cid1) (sourceLogic cid2)
"Mapping symbol along comorphism" (sig2', [])
in case maybeResult th2 of
Nothing -> error "failed coercing"
Just (sig2, _) ->
\ s1 ->
let mycast = coerceSymbol (targetLogic cid1) (sourceLogic cid2)
in Set.unions
(map (map_symbol cid2 sig2 . mycast)
(Set.toList (map_symbol cid1 sig1 s1)))
extractModel (CompComorphism cid1 cid2) sign pt3 =
let lid1 = sourceLogic cid1
lid3 = sourceLogic cid2
in if language_name lid1 == language_name lid3 then do
bTh1 <- map_sign cid1 sign
(sign1, _) <-
coerceBasicTheory (targetLogic cid1) lid3 "extractModel1" bTh1
bTh2 <- extractModel cid2 sign1 pt3
coerceBasicTheory lid3 lid1 "extractModel2" bTh2
else fail $ "extractModel not implemented for comorphism composition with "
++ language_name cid1
constituents (CompComorphism cid1 cid2) =
constituents cid1 ++ constituents cid2
is_model_transportable (CompComorphism cid1 cid2) =
is_model_transportable cid1 && is_model_transportable cid2
has_model_expansion (CompComorphism cid1 cid2) =
has_model_expansion cid1 && has_model_expansion cid2
is_weakly_amalgamable (CompComorphism cid1 cid2) =
is_weakly_amalgamable cid1 && is_weakly_amalgamable cid2
isInclusionComorphism (CompComorphism cid1 cid2) =
isInclusionComorphism cid1 && isInclusionComorphism cid2
-- * Comorphisms and existential types for the logic graph
-- | Existential type for comorphisms
data AnyComorphism = forall cid lid1 sublogics1
basic_spec1 sentence1 symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2
basic_spec2 sentence2 symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 .
Comorphism cid
lid1 sublogics1 basic_spec1 sentence1
symb_items1 symb_map_items1
sign1 morphism1 symbol1 raw_symbol1 proof_tree1
lid2 sublogics2 basic_spec2 sentence2
symb_items2 symb_map_items2
sign2 morphism2 symbol2 raw_symbol2 proof_tree2 =>
Comorphism cid deriving Typeable -- used for GTheory
instance Eq AnyComorphism where
a == b = compare a b == EQ
instance Ord AnyComorphism where
compare (Comorphism cid1) (Comorphism cid2) = compare
(language_name cid1, constituents cid1)
(language_name cid2, constituents cid2)
-- maybe needs to be refined, using comorphism translations?
instance Show AnyComorphism where
show (Comorphism cid) = language_name cid
++ " : " ++ language_name (sourceLogic cid)
++ " -> " ++ language_name (targetLogic cid)
instance Pretty AnyComorphism where
pretty = text . show
-- | compute the identity comorphism for a logic
idComorphism :: AnyLogic -> AnyComorphism
idComorphism (Logic lid) = Comorphism (mkIdComorphism lid (top_sublogic lid))
-- | Test whether a comporphism is the identity
isIdComorphism :: AnyComorphism -> Bool
isIdComorphism (Comorphism cid) = null $ constituents cid
-- * Properties of comorphisms
-- | Test whether a comorphism is model-transportable
isModelTransportable :: AnyComorphism -> Bool
isModelTransportable (Comorphism cid) = is_model_transportable cid
-- | Test whether a comorphism has model expansion
hasModelExpansion :: AnyComorphism -> Bool
hasModelExpansion (Comorphism cid) = has_model_expansion cid
-- | Test whether a comorphism is weakly amalgamable
isWeaklyAmalgamable :: AnyComorphism -> Bool
isWeaklyAmalgamable (Comorphism cid) = is_weakly_amalgamable cid
-- | Compose comorphisms
compComorphism :: Monad m => AnyComorphism -> AnyComorphism -> m AnyComorphism
compComorphism (Comorphism cid1) (Comorphism cid2) =
let l1 = targetLogic cid1
l2 = sourceLogic cid2
msg = "ogic mismatch in composition of " ++ language_name cid1
++ " and " ++ language_name cid2
in
if language_name l1 == language_name l2 then
if isSubElem (forceCoerceSublogic l1 l2 $ targetSublogic cid1)
$ sourceSublogic cid2
then return $ Comorphism (CompComorphism cid1 cid2)
else fail $ "Subl" ++ msg
else fail $ 'L' : msg
|
nevrenato/Hets_Fork
|
Logic/Comorphism.hs
|
gpl-2.0
| 18,995 | 184 | 31 | 5,260 | 3,832 | 2,004 | 1,828 | 356 | 3 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Control.Monad.Reader (ask)
import Data.List (sortBy, (\\))
import Data.Maybe (listToMaybe)
import Data.String.Utils (replace)
import qualified Data.ConfigFile as ConfigFile
import Data.ByteString.Lazy.Char8 (pack)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B
import Data.Either.Utils (forceEither)
import Data.Digest.Pure.SHA (sha256, showDigest)
import System.Directory (getHomeDirectory, createDirectoryIfMissing, getDirectoryContents)
import qualified Data.Text as T
import Data.SafeCopy (base, deriveSafeCopy)
import Data.Typeable (Typeable)
import Data.DateTime (getCurrentTime, DateTime)
import Control.Applicative
import Snap
import Snap.Snaplet.Heist
import Snap.Snaplet.AcidState
import Snap.Util.FileServe (serveDirectory)
import Snap.Util.FileUploads (handleMultipart, defaultUploadPolicy)
import Snap.Iteratee (consume)
import Control.Lens
import Heist
import Heist.Interpreted
type SourceDir = String
type DestinationDir = String
type AppConfig = (SourceDir, DestinationDir)
type Hash = String
data SourceFile = SourceFile {
_sourceFilePath :: FilePath,
_sourceFileHash :: Hash,
_sourceFileTimestamp :: DateTime
} deriving (Show, Eq, Ord, Typeable)
makeLenses ''SourceFile
deriveSafeCopy 0 'base ''SourceFile
data AppState = AppState {
_tst :: String,
_stateSourceFiles :: [SourceFile],
_stateFilesGiven :: [SourceFile],
_stateSourceDir :: SourceDir,
_stateTargetDir :: DestinationDir
} deriving (Show, Ord, Eq, Typeable)
makeLenses ''AppState
deriveSafeCopy 0 'base ''AppState
readState :: Query AppState AppState
readState = do
state <- ask
return state
writeState :: AppState -> Update AppState ()
writeState newState = put newState
makeAcidic ''AppState ['writeState, 'readState]
data App = App {
_heist :: Snaplet (Heist App),
_acid :: Snaplet (Acid AppState)
}
makeLenses ''App
instance HasAcid App AppState where
getAcidStore = view (acid.snapletValue)
instance HasHeist App where
heistLens = subSnaplet heist
main :: IO ()
main = do
(_, site, _) <- runSnaplet Nothing distributerInit
quickHttpServe site
distributerInit :: SnapletInit App App
distributerInit = makeSnaplet "distributer" "Work distributer" Nothing $ do
h <- nestSnaplet "heist" heist $ heistInit "templates"
(source, target) <- liftIO $ readConfig
sourceFiles' <- liftIO $ getSourceFiles source
sourceFiles <- liftIO $ mapM computeFileHash sourceFiles'
liftIO $ putStrLn "Your watched files:"
liftIO $ mapM_ (putStrLn . show) sourceFiles
liftIO $ createDirectoryIfMissing True target
let s = AppState{
_tst = "",
_stateSourceFiles = sourceFiles,
_stateFilesGiven = [],
_stateSourceDir = source,
_stateTargetDir = target
}
a <- nestSnaplet "acid" acid $ acidInit s
let app = App {
_heist = h,
_acid = a
}
addRoutes [("", workList),
("giveFile", giveFile),
("uploadFile/:hash", uploadFile),
("static", serveDirectory source)
]
return app
readConfig :: IO AppConfig
readConfig = do
home <- getHomeDirectory
val <- ConfigFile.readfile ConfigFile.emptyCP (home ++ "/.work-distributer")
let cp = forceEither val
let source = forceEither $ ConfigFile.get cp "directories" "source"
let target = forceEither $ ConfigFile.get cp "directories" "target"
putStrLn $ "Source dir: " ++ source
putStrLn $ "Target dir: " ++ target
return (source, target)
getSourceFiles :: SourceDir -> IO [FilePath]
getSourceFiles source = do
createDirectoryIfMissing True source
allFiles <- getDirectoryContents source
let sourceFiles = filter (flip notElem [".", ".."]) allFiles
let sourceFilesWithDir = map (\f -> source ++ "/" ++ f) sourceFiles
return sourceFilesWithDir
computeFileHash :: FilePath -> IO SourceFile
computeFileHash filePath = do
now <- liftIO $ getCurrentTime
contents <- readFile filePath
return $ SourceFile {
_sourceFilePath = filePath,
_sourceFileHash = computeFileContentHash filePath contents,
_sourceFileTimestamp = now
}
computeFileContentHash :: FilePath -> String -> Hash
computeFileContentHash filePath contents =
showDigest $ sha256 $ pack $ filePath ++ contents
-- ROUTES
workList :: Handler App App ()
workList = do
s <- query ReadState
let sf = s ^. stateSourceFiles
let source = s ^. stateSourceDir
renderWithSplices "list" $ allWorkItems sf
giveFile :: Handler App App ()
giveFile = do
now <- liftIO $ getCurrentTime
s <- query ReadState
let sfs = s ^. stateSourceFiles
let gfs = s ^. stateFilesGiven
let source = s ^. stateSourceDir
liftIO $ print $ show gfs
let gfsHashes = map (\l -> l ^. sourceFileHash) gfs
let rem = filter (\l -> (l ^. sourceFileHash) `notElem` gfsHashes) sfs
let remaining' =
if rem == []
then sfs
else rem
let sf = head $ sortBy (\a b -> compare (a ^. sourceFileTimestamp) (b ^. sourceFileTimestamp)) remaining'
let sf' = sourceFileTimestamp .~ now $ sf
let s' =
if rem == []
then stateFilesGiven .~ [sf'] $ s
else stateFilesGiven <>~ [sf'] $ s
update $ WriteState s'
renderWithSplices "giveFile" $ giveFileItem sf source
uploadFile :: Handler App App ()
uploadFile = method GET getter <|> method POST setter
where
getter = do
esf <- hashReader
case esf of
Left err -> writeBS err
Right sf -> do
--writeBS $ B.pack $ show sf
s <- query ReadState
let source = s ^. stateSourceDir
renderWithSplices "uploadFile" $ giveFileItem sf source
setter = do
esf <- hashReader
liftIO $ print $ show $ esf
case esf of
Left err -> writeBS err
Right sf -> do
[file] <- handleMultipart defaultUploadPolicy $ \part -> do
content <- liftM B.concat consume
return content
s <- query ReadState
let source = s ^. stateSourceDir
let target = s ^. stateTargetDir
let path = replace source target $ sf ^. sourceFilePath
liftIO $ BS.writeFile path file
let sfs = filter
(\sf' -> (sf' ^. sourceFileHash) /= (sf ^. sourceFileHash)) $
s ^. stateSourceFiles
let s' = stateSourceFiles .~ sfs $ s
update $ WriteState s'
writeBS $ B.pack $ show sf
hashReader = do
mhash <- getParam "hash"
case mhash of
Nothing -> return $ Left "No hash provided"
Just hash' -> do
let hash = B.unpack hash'
s <- query ReadState
let msf = sourceFileFromAppStateByHash s hash
case msf of
Nothing -> return $ Left "File not found"
Just sf -> return $ Right sf
sourceFileFromAppStateByHash :: AppState -> Hash -> Maybe SourceFile
sourceFileFromAppStateByHash s hash = listToMaybe filtered
where
sfs = s ^. stateSourceFiles
filtered = filter (\l -> (l ^. sourceFileHash) == hash) sfs
-- RENDERERS
allWorkItems :: [SourceFile] -> Splices (SnapletISplice App)
allWorkItems sfs = "items" ## (mapSplices $ runChildrenWith . listItem) sfs
listItem :: Monad m => SourceFile -> Splices (Splice m)
listItem sf = do
let hi = hashItem sf
"listItem" ## hi
"listItemURL" ## hi
giveFileItem :: SourceFile -> SourceDir -> Splices (SnapletISplice App)
giveFileItem sf source = "file" ## runChildrenWith $ do
let pi = pathItem sf source
let hi = hashItem sf
"path" ## pi
"hash" ## hi
pathItem :: Monad m => SourceFile -> SourceDir -> Splice m
pathItem sf source = do
let fp = replace source "/static" $ sf ^. sourceFilePath
textSplice (T.pack fp)
hashItem :: Monad m => SourceFile -> Splice m
hashItem sf = textSplice $ T.pack $ sf ^. sourceFileHash
|
CGenie/work-distributer
|
src/Main.hs
|
gpl-2.0
| 8,674 | 0 | 24 | 2,463 | 2,486 | 1,260 | 1,226 | 215 | 5 |
-- launch in ghci with -fno-ghci-sandbox
import Graphics.Gloss
import Graphics.Gloss.Geometry.Angle -- form radToDeg and degToRad
-- data types
type Length = Float
type Angle = Float -- in degrees
-- Point is (Float, Float)
-- angle at 0 means standing up (12 0' clock)
data Stick = Stick Point Length Angle
-- parameters
wWidth = 600 :: Int
wHeight = 600 :: Int
window :: Display
window = InWindow "test!" (wWidth, wHeight) (10, 10)
stickColor = orange
stickSubAngleLeft = pi/7
stickSubAngleRight = pi/8
stickSubLengthRatioLeft = 0.8
stickSubLengthRatioRight = 0.85
stickLengthMin = 10
leafColor = green
-- MAIN
main :: IO ()
main = display window black mytree
-- my tree function
mytree :: Picture
mytree = pictures $ makeSticks (0, fromIntegral (- wHeight) / 2) 100 0.0
makeSticks :: Point -> Length -> Angle -> [Picture]
makeSticks p1 l a = stick : children
where children = if lastStick then [] else child1 ++ child2
child1 = makeSticks p2 (l*stickSubLengthRatioLeft) (a + stickSubAngleLeft)
child2 = makeSticks p2 (l*stickSubLengthRatioRight) (a - stickSubAngleRight)
stick = color getStickColor $ line points
points = [p1, p2]
p2 = calculatePoint2 p1 l a
lastStick = if l < stickLengthMin then True else False
getStickColor = if lastStick then leafColor else stickColor
calculatePoint2 :: Point -> Length -> Angle -> Point
calculatePoint2 (x, y) l a = (x2, y2)
where x2 = l * sin a + x
y2 = l * cos a + y
|
simonced/haskell-kata
|
gloss/tree.hs
|
gpl-3.0
| 1,561 | 0 | 11 | 389 | 448 | 253 | 195 | 34 | 4 |
module Database.Design.Ampersand.FSpec.ToFSpec.ADL2FSpec
(makeFSpec) where
import Prelude hiding (Ord(..))
import Data.Char
import Data.List
import Data.Maybe
import Text.Pandoc
import Database.Design.Ampersand.ADL1
import Database.Design.Ampersand.Basics
import Database.Design.Ampersand.Classes
import Database.Design.Ampersand.Core.AbstractSyntaxTree
import Database.Design.Ampersand.Core.Poset
import Database.Design.Ampersand.FSpec.FSpec
import Database.Design.Ampersand.Misc
import Database.Design.Ampersand.FSpec.Crud
import Database.Design.Ampersand.FSpec.ToFSpec.ADL2Plug
import Database.Design.Ampersand.FSpec.ToFSpec.Calc
import Database.Design.Ampersand.FSpec.ToFSpec.NormalForms
import Database.Design.Ampersand.FSpec.ShowADL
import qualified Data.Set as Set
fatal :: Int -> String -> a
fatal = fatalMsg "FSpec.ToFSpec.ADL2FSpec"
makeFSpec :: Options -> A_Context -> FSpec
makeFSpec opts context
= FSpec { fsName = name context
, originalContext = context
, getOpts = opts
, fspos = ctxpos context
, themes = themesInScope
, pattsInScope = pattsInThemesInScope
, rulesInScope = rulesInThemesInScope
, declsInScope = declsInThemesInScope
, concsInScope = concsInThemesInScope
, cDefsInScope = cDefsInThemesInScope
, gensInScope = gensInThemesInScope
, fsLang = printingLanguage
, vplugInfos = definedplugs
, plugInfos = allplugs
, interfaceS = fSpecAllInterfaces -- interfaces specified in the Ampersand script
, interfaceG = [ifc | ifc<-interfaceGen, let ctxrel = objctx (ifcObj ifc)
, isIdent ctxrel && source ctxrel==ONE
|| ctxrel `notElem` map (objctx.ifcObj) fSpecAllInterfaces
, allInterfaces opts] -- generated interfaces
, fSwitchboard
= Fswtch
{ fsbEvIn = nub (map ecaTriggr allVecas) -- eventsIn
, fsbEvOut = nub [evt | eca<-allVecas, evt<-eventsFrom (ecaAction eca)] -- eventsOut
, fsbConjs = nub [ (qRule q, rc_conjunct x) | q <- filter (not . isSignal . qRule) allQuads
, x <- qConjuncts q]
, fsbECAs = allVecas
}
, fDeriveProofs = deriveProofs opts context
, fActivities = allActivities
, fRoleRels = nub [(role,decl) -- fRoleRels says which roles may change the population of which relation.
| rr <- ctxRRels context
, decl <- rrRels rr
, role <- rrRoles rr
]
, fRoleRuls = nub [(role,rule) -- fRoleRuls says which roles maintain which rules.
| rule <- allrules
, role <- maintainersOf rule
]
, fRoles = nub (concatMap arRoles (ctxrrules context)++
concatMap rrRoles (ctxRRels context)++
concatMap ifcRoles (ctxifcs context)
)
, fallRules = allrules
, vrules = filter isUserDefined allrules
, grules = filter (not.isUserDefined) allrules
, invariants = filter (not.isSignal) allrules
, vconjs = allConjs
, allConjsPerRule = fSpecAllConjsPerRule
, allConjsPerDecl = fSpecAllConjsPerDecl
, allConjsPerConcept = fSpecAllConjsPerConcept
, vquads = allQuads
, vEcas = allVecas
, vrels = calculatedDecls
, allUsedDecls = relsUsedIn context
, allDecls = fSpecAllDecls
, allConcepts = fSpecAllConcepts
, kernels = constructKernels
, cptTType = (\cpt -> representationOf contextinfo cpt)
, fsisa = concatMap genericAndSpecifics (gens context)
, vpatterns = patterns context
, vgens = gens context
, vIndices = identities context
, vviews = viewDefs context
, lookupView = lookupView'
, getDefaultViewForConcept = getDefaultViewForConcept'
, conceptDefs = ctxcds context
, fSexpls = ctxps context
, metas = ctxmetas context
, crudInfo = mkCrudInfo fSpecAllConcepts fSpecAllDecls fSpecAllInterfaces
, atomsInCptIncludingSmaller = atomValuesOf contextinfo initialpopsDefinedInScript
, tableContents = tblcontents contextinfo initialpopsDefinedInScript
, pairsInExpr = pairsinexpr
, allViolations = [ (r,vs)
| r <- allrules -- Removed following, because also violations of invariant rules are violations.. , not (isSignal r)
, let vs = ruleviolations r, not (null vs) ]
, allExprs = expressionsIn context
, allSigns = nub $ map sign fSpecAllDecls ++ map sign (expressionsIn context)
, initialConjunctSignals = [ (conj, viols) | conj <- allConjs
, let viols = conjunctViolations conj
, not $ null viols
]
, contextInfo = contextinfo
, specializationsOf = smallerConcepts (gens context)
, generalizationsOf = largerConcepts (gens context)
}
where
pairsinexpr :: Expression -> [AAtomPair]
pairsinexpr = fullContents contextinfo initialpopsDefinedInScript
ruleviolations :: Rule -> [AAtomPair]
ruleviolations r = case rrexp r of
EEqu{} -> (cra >- crc) ++ (crc >- cra)
EImp{} -> cra >- crc
_ -> pairsinexpr (EDcV (sign (consequent r))) >- crc --everything not in con
where cra = pairsinexpr (antecedent r)
crc = pairsinexpr (consequent r)
conjunctViolations :: Conjunct -> [AAtomPair]
conjunctViolations conj =
let vConts = Set.fromList $ pairsinexpr (EDcV (sign (rc_conjunct conj)))
conjConts = Set.fromList $ pairsinexpr (rc_conjunct conj)
in Set.toList $ vConts `Set.difference` conjConts
contextinfo = contextInfoOf context
fSpecAllConcepts = concs context
fSpecAllDecls = relsDefdIn context
fSpecAllInterfaces :: [Interface]
fSpecAllInterfaces = map enrichIfc (ctxifcs context)
where
enrichIfc :: Interface -> Interface
enrichIfc ifc
= ifc{ ifcEcas = fst . assembleECAs opts context $ ifcParams ifc
, ifcControls = makeIfcControls (ifcParams ifc) allConjs
}
themesInScope = if null (ctxthms context) -- The names of patterns/processes to be printed in the functional specification. (for making partial documentation)
then map name (patterns context)
else ctxthms context
pattsInThemesInScope = filter (\p -> name p `elem` themesInScope) (patterns context)
cDefsInThemesInScope = filter (\cd -> cdfrom cd `elem` themesInScope) (ctxcds context)
rulesInThemesInScope = ctxrs context `uni` concatMap ptrls pattsInThemesInScope
declsInThemesInScope = ctxds context `uni` concatMap ptdcs pattsInThemesInScope
concsInThemesInScope = concs (ctxrs context) `uni` concs pattsInThemesInScope
gensInThemesInScope = ctxgs context ++ concatMap ptgns pattsInThemesInScope
initialpopsDefinedInScript =
[ let dcl = popdcl (head eqclass)
in ARelPopu{ popsrc = source dcl
, poptgt = target dcl
, popdcl = dcl
, popps = (nub.concat) [ popps pop | pop<-eqclass ]
}
| eqclass<-eqCl popdcl [ pop | pop@ARelPopu{}<-populations ] ] ++
[ ACptPopu{ popcpt = popcpt (head eqclass)
, popas = (nub.concat) [ popas pop | pop<-eqclass ]
}
| eqclass<-eqCl popcpt [ pop | pop@ACptPopu{}<-populations ] ]
where populations = ctxpopus context++concatMap ptups (patterns context)
allConjs = makeAllConjs opts allrules
fSpecAllConjsPerRule :: [(Rule,[Conjunct])]
fSpecAllConjsPerRule = converse [ (conj, rc_orgRules conj) | conj <- allConjs ]
fSpecAllConjsPerDecl = converse [ (conj, relsUsedIn $ rc_conjunct conj) | conj <- allConjs ]
fSpecAllConjsPerConcept = converse [ (conj, smaller (source r) `uni` smaller (target r)) | conj <- allConjs, r <- relsMentionedIn $ rc_conjunct conj ]
where smaller :: A_Concept -> [A_Concept]
smaller cpt = [cpt] `uni` smallerConcepts (gens context) cpt
allQuads = quadsOfRules opts allrules
allrules = map setIsSignal (allRules context)
where setIsSignal r = r{isSignal = (not.null) (maintainersOf r)}
maintainersOf :: Rule -> [Role]
maintainersOf r
= concatMap arRoles . filter forThisRule . ctxrrules $ context
where
forThisRule :: A_RoleRule -> Bool
forThisRule x = name r `elem` arRules x
isUserDefined rul =
case r_usr rul of
UserDefined -> True
Multiplicity -> False
Identity -> False
allActivities :: [Activity]
allActivities = map makeActivity (filter isSignal allrules)
allVecas = {-preEmpt opts . -} fst (assembleECAs opts context fSpecAllDecls) -- TODO: preEmpt gives problems. Readdress the preEmption problem and redo, but properly.
-- | allDecs contains all user defined plus all generated relations plus all defined and computed totals.
calcProps :: Declaration -> Declaration
calcProps d = d{decprps_calc = Just calculated}
where calculated = decprps d `uni` [Tot | d `elem` totals]
`uni` [Sur | d `elem` surjectives]
calculatedDecls = map calcProps fSpecAllDecls
constructKernels = foldl f (group (delete ONE fSpecAllConcepts)) (gens context)
where f disjuncLists g = concat haves : nohaves
where
(haves,nohaves) = partition (not.null.intersect (concs g)) disjuncLists
-- determine relations that are total (as many as possible, but not necessarily all)
totals = [ d | EDcD d <- totsurs ]
surjectives = [ d | EFlp (EDcD d) <- totsurs ]
totsurs :: [Expression]
totsurs
= nub [rel | q<-filter (not . isSignal . qRule) allQuads -- all quads for invariant rules
, isIdent (qDcl q)
, x<-qConjuncts q, dnf<-rc_dnfClauses x
, let antc = conjNF opts (foldr (./\.) (EDcV (sign (head (antcs dnf++conss dnf)))) (antcs dnf))
, isRfx antc -- We now know that I is a subset of the antecedent of this dnf clause.
, cons<-map exprCps2list (conss dnf)
-- let I |- r;s;t be an invariant rule, then r and s and t~ and s~ are all total.
, rel<-init cons++[flp r | r<-tail cons]
]
-- Lookup view by id in fSpec.
lookupView' :: String -> ViewDef
lookupView' viewId =
case filter (\v -> vdlbl v == viewId) $ viewDefs context of
[] -> fatal 174 $ "Undeclared view " ++ show viewId ++ "." -- Will be caught by static analysis
[vd] -> vd
vds -> fatal 176 $ "Multiple views with id " ++ show viewId ++ ": " ++ show (map vdlbl vds) -- Will be caught by static analysis
-- Return the default view for concpt, which is either the view for concpt itself (if it has one) or the view for
-- concpt's smallest superconcept that has a view. Return Nothing if there is no default view.
getDefaultViewForConcept' :: A_Concept -> Maybe ViewDef
getDefaultViewForConcept' concpt =
case [ vd
| vd@Vd{vdcpt = c, vdIsDefault = True} <- viewDefs context
, c `elem` (concpt : largerConcepts (gens context) concpt)
] of
[] -> Nothing
(vd:_) -> Just vd
--------------
--making plugs
--------------
vsqlplugs = [ (makeUserDefinedSqlPlug context p) | p<-ctxsql context] --REMARK -> no optimization like try2specific, because these plugs are user defined
definedplugs = map InternalPlug vsqlplugs
++ map ExternalPlug (ctxphp context)
allplugs = definedplugs ++ -- all plugs defined by the user
genPlugs -- all generated plugs
genPlugs = [InternalPlug (rename p (qlfname (name p)))
| p <- uniqueNames (map name definedplugs) -- the names of definedplugs will not be changed, assuming they are all unique
(makeGeneratedSqlPlugs opts context totsurs entityRels)
]
-- relations to be saved in generated plugs: if decplug=True, the declaration has the BYPLUG and therefore may not be saved in a database
-- WHAT -> is a BYPLUG?
entityRels = [ d | d<-calculatedDecls, not (decplug d)] -- The persistent relations.
qlfname x = if null (namespace opts) then x else "ns"++namespace opts++x
--TODO151210 -> Plug A is overbodig, want A zit al in plug r
--CONTEXT Temp
--PATTERN Temp
--r::A*B[TOT].
--t::E*ECps[UNI].
--ENDPATTERN
--ENDCONTEXT
{-
**************************************
* Plug E *
* I [INJ,SUR,UNI,TOT,SYM,ASY,TRN,RFX] *
* t [UNI] *
**************************************
* Plug ECps *
* I [INJ,SUR,UNI,TOT,SYM,ASY,TRN,RFX] *
**************************************
* Plug B *
* I [INJ,SUR,UNI,TOT,SYM,ASY,TRN,RFX] *
**************************************
* Plug A *
* I [INJ,SUR,UNI,TOT,SYM,ASY,TRN,RFX] *
**************************************
* Plug r *
* I [INJ,SUR,UNI,TOT,SYM,ASY,TRN,RFX] *
* r [TOT] *
**************************************
-}
-------------------
--END: making plugs
-------------------
-------------------
--making interfaces
-------------------
-- interfaces (type ObjectDef) can be generated from a basic ontology. That is: they can be derived from a set
-- of relations together with multiplicity constraints. That is what interfaceG does.
-- This is meant to help a developer to build his own list of interfaces, by providing a set of interfaces that works.
-- The developer may relabel attributes by names of his own choice.
-- This is easier than to invent a set of interfaces from scratch.
-- Rule: a interface must be large enough to allow the required transactions to take place within that interface.
-- Attributes of an ObjectDef have unique names within that ObjectDef.
--- generation of interfaces:
-- Ampersand generates interfaces for the purpose of quick prototyping.
-- A script without any mention of interfaces is supplemented
-- by a number of interface definitions that gives a user full access to all data.
-- Step 1: select and arrange all relations to obtain a set cRels of total relations
-- to ensure insertability of entities (signal declarations are excluded)
cRels = [ EDcD d | d@Sgn{}<-fSpecAllDecls, isTot d, not$decplug d]++
[flp (EDcD d) | d@Sgn{}<-fSpecAllDecls, not (isTot d) && isSur d, not$decplug d]
-- Step 2: select and arrange all relations to obtain a set dRels of injective relations
-- to ensure deletability of entities (signal declarations are excluded)
dRels = [ EDcD d | d@Sgn{}<-fSpecAllDecls, isInj d, not$decplug d]++
[flp (EDcD d) | d@Sgn{}<-fSpecAllDecls, not (isInj d) && isUni d, not$decplug d]
-- Step 3: compute longest sequences of total expressions and longest sequences of injective expressions.
maxTotPaths = map (:[]) cRels -- note: instead of computing the longest sequence, we take sequences of length 1, the function clos1 below is too slow!
maxInjPaths = map (:[]) dRels -- note: instead of computing the longest sequence, we take sequences of length 1, the function clos1 below is too slow!
-- Warshall's transitive closure algorithm, adapted for this purpose:
-- clos1 :: [Expression] -> [[Expression]]
-- clos1 xs
-- = foldl f [ [ x ] | x<-xs] (nub (map source xs) `isc` nub (map target xs))
-- where
-- f :: [[Expression]] -> A_Concept -> [[Expression]]
-- f q x = q ++ [l ++ r | l <- q, x == target (last l),
-- r <- q, x == source (head r), null (l `isc` r)]
-- Step 4: i) generate interfaces starting with INTERFACE concept: I[Concept]
-- ii) generate interfaces starting with INTERFACE concepts: V[ONE*Concept]
-- note: based on a theme one can pick a certain set of generated interfaces (there is not one correct set)
-- default theme => generate interfaces from the clos total expressions and clos injective expressions (see step1-3).
-- student theme => generate interface for each concept with relations where concept is source or target (note: step1-3 are skipped)
interfaceGen = step4a ++ step4b
step4a
| theme opts == StudentTheme
= [Ifc { ifcClass = Nothing
, ifcParams = params
, ifcArgs = []
, ifcObj = Obj { objnm = name cpt ++ " (instantie)"
, objpos = Origin "generated object for interface for each concept in TblSQL or ScalarSQL"
, objctx = EDcI cpt
, objmView = Nothing
, objmsub = Just . Box cpt Nothing $
Obj { objnm = "I["++name cpt++"]"
, objpos = Origin "generated object: step 4a - default theme"
, objctx = EDcI cpt
, objmView = Nothing
, objmsub = Nothing
, objstrs = [] }
:[Obj { objnm = name dcl ++ "::"++name (source dcl)++"*"++name (target dcl)
, objpos = Origin "generated object: step 4a - default theme"
, objctx = if source dcl==cpt then EDcD dcl else flp (EDcD dcl)
, objmView = Nothing
, objmsub = Nothing
, objstrs = [] }
| dcl <- params]
, objstrs = []
}
, ifcEcas = fst (assembleECAs opts context params)
, ifcControls = makeIfcControls params allConjs
, ifcPos = Origin "generated interface for each concept in TblSQL or ScalarSQL"
, ifcPrp = "Interface " ++name cpt++" has been generated by Ampersand."
, ifcRoles = []
}
| cpt<-fSpecAllConcepts
, let params = [ d | d<-fSpecAllDecls, cpt `elem` concs d]
]
--end student theme
--otherwise: default theme
| otherwise --note: the uni of maxInj and maxTot may take significant time (e.g. -p while generating index.htm)
--note: associations without any multiplicity are not in any Interface
--note: scalars with only associations without any multiplicity are not in any Interface
= let recur es
= [ Obj { objnm = showADL t
, objpos = Origin "generated recur object: step 4a - default theme"
, objctx = t
, objmView = Nothing
, objmsub = Just . Box (target t) Nothing $ recur [ pth | (_:pth)<-cl, not (null pth) ]
, objstrs = [] }
| cl<-eqCl head es, (t:_)<-take 1 cl] --
-- es is a list of expression lists, each with at least one expression in it. They all have the same source concept (i.e. source.head)
-- Each expression list represents a path from the origin of a box to the attribute.
-- 16 Aug 2011: (recur es) is applied once where es originates from (maxTotPaths `uni` maxInjPaths) both based on clos
-- Interfaces for I[Concept] are generated only for concepts that have been analysed to be an entity.
-- These concepts are collected in gPlugConcepts
gPlugConcepts = [ c | InternalPlug plug@TblSQL{}<-genPlugs , (c,_)<-take 1 (cLkpTbl plug) ]
-- Each interface gets all attributes that are required to create and delete the object.
-- All total attributes must be included, because the interface must allow an object to be deleted.
in
[Ifc { ifcClass = Nothing
, ifcParams = params
, ifcArgs = []
, ifcObj = Obj { objnm = name c
, objpos = Origin "generated object: step 4a - default theme"
, objctx = EDcI c
, objmView = Nothing
, objmsub = Just . Box c Nothing $ objattributes
, objstrs = [] }
, ifcEcas = fst (assembleECAs opts context params)
, ifcControls = makeIfcControls params allConjs
, ifcPos = Origin "generated interface: step 4a - default theme"
, ifcPrp = "Interface " ++name c++" has been generated by Ampersand."
, ifcRoles = []
}
| cl <- eqCl (source.head) [ pth | pth<-maxTotPaths `uni` maxInjPaths, (source.head) pth `elem` gPlugConcepts ]
, let objattributes = recur cl
, not (null objattributes) --de meeste plugs hebben in ieder geval I als attribuut
, --exclude concept A without cRels or dRels (i.e. A in Scalar without total associations to other plugs)
not (length objattributes==1 && isIdent(objctx(head objattributes)))
, let e0=head cl, if null e0 then fatal 284 "null e0" else True
, let c=source (head e0)
, let params = [ d | EDcD d <- concatMap primsMentionedIn (expressionsIn objattributes)]++
[ Isn cpt | EDcI cpt <- concatMap primsMentionedIn (expressionsIn objattributes)]
]
--end otherwise: default theme
--end stap4a
step4b --generate lists of concept instances for those concepts that have a generated INTERFACE in step4a
= [Ifc { ifcClass = ifcClass ifcc
, ifcParams = ifcParams ifcc
, ifcArgs = ifcArgs ifcc
, ifcObj = Obj { objnm = nm
, objpos = Origin "generated object: step 4b"
, objctx = EDcI ONE
, objmView = Nothing
, objmsub = Just . Box ONE Nothing $ [att]
, objstrs = [] }
, ifcEcas = ifcEcas ifcc
, ifcControls = ifcControls ifcc
, ifcPos = ifcPos ifcc
, ifcPrp = ifcPrp ifcc
, ifcRoles = []
}
| ifcc<-step4a
, let c = source(objctx (ifcObj ifcc))
nm'::Int->String
nm' 0 = plural printingLanguage (name c)
nm' i = plural printingLanguage (name c) ++ show i
nms = [nm' i |i<-[0..], nm' i `notElem` map name (ctxifcs context)]
nm
| theme opts == StudentTheme = name c
| null nms = fatal 355 "impossible"
| otherwise = head nms
att = Obj (name c) (Origin "generated attribute object: step 4b") (EDcV (Sign ONE c)) Nothing Nothing []
]
----------------------
--END: making interfaces
----------------------
printingLanguage = fromMaybe (ctxlang context) (language opts) -- The language for printing this specification is taken from the command line options (language opts). If none is specified, the specification is printed in the language in which the context was defined (ctxlang context).
{- makeActivity turns a process rule into an activity definition.
Each activity can be mapped to a single interface.
A call to such an interface takes the population of the current context to another population,
while maintaining all invariants.
-}
makeActivity :: Rule -> Activity
makeActivity rul
= let s = Act{ actRule = rul
, actTrig = decls
, actAffect = nub [ d' | (d,_,d')<-clos2 affectPairs, d `elem` decls]
, actQuads = invQs
, actEcas = [eca | eca<-allVecas, eDcl (ecaTriggr eca) `elem` decls]
, actPurp = [Expl { explPos = OriginUnknown
, explObj = ExplRule (name rul)
, explMarkup = A_Markup { amLang = Dutch
, amPandoc = [Plain [Str "Waartoe activiteit ", Quoted SingleQuote [Str (name rul)], Str" bestaat is niet gedocumenteerd." ]]
}
, explUserdefd = False
, explRefIds = ["Regel "++name rul]
}
,Expl { explPos = OriginUnknown
, explObj = ExplRule (name rul)
, explMarkup = A_Markup { amLang = English
, amPandoc = [Plain [Str "For what purpose activity ", Quoted SingleQuote [Str (name rul)], Str" exists remains undocumented." ]]
}
, explUserdefd = False
, explRefIds = ["Regel "++name rul]
}
]
} in s
where
-- relations that may be affected by an edit action within the transaction
decls = relsUsedIn rul
-- the quads that induce automated action on an editable relation.
-- (A quad contains the conjunct(s) to be maintained.)
-- Those are the quads that originate from invariants.
invQs = [q | q<-allQuads, (not.isSignal.qRule) q
, (not.null) ((relsUsedIn.qRule) q `isc` decls)] -- SJ 20111201 TODO: make this selection more precise (by adding inputs and outputs to a quad).
-- a relation affects another if there is a quad (i.e. an automated action) that links them
affectPairs = [(qDcl q,[q], d) | q<-invQs, d<-(relsUsedIn.qRule) q]
-- the relations affected by automated action
-- triples = [ (r,qs,r') | (r,qs,r')<-clos affectPairs, r `elem` rels]
----------------------------------------------------
-- Warshall's transitive closure algorithm in Haskell, adapted to carry along the intermediate steps:
----------------------------------------------------
clos2 :: (Eq a,Eq b) => [(a,[b],a)] -> [(a,[b],a)] -- e.g. a list of pairs, with intermediates in between
clos2 xs
= foldl f xs (nub (map fst3 xs) `isc` nub (map thd3 xs))
where
f q x = q `un`
[(a, qs `uni` qs', b') | (a, qs, b) <- q, b == x,
(a', qs', b') <- q, a' == x]
ts `un` [] = ts
ts `un` ((a',qs',b'):ts')
= ([(a,qs `uni` qs',b) | (a,qs,b)<-ts, a==a' && b==b']++
[(a,qs,b) | (a,qs,b)<-ts, a/=a' || b/=b']++
[(a',qs',b') | (a',b') `notElem` [(a,b) |(a,_,b)<-ts]]) `un` ts'
makeIfcControls :: [Declaration] -> [Conjunct] -> [Conjunct]
makeIfcControls params allConjs
= [ conj
| conj<-allConjs
, (not.null) (map EDcD params `isc` primsMentionedIn (rc_conjunct conj))
-- Filtering for uni/inj invariants is pointless here, as we can only filter out those conjuncts for which all
-- originating rules are uni/inj invariants. Conjuncts that also have other originating rules need to be included
-- and the uni/inj invariant rules need to be filtered out at a later stage (in Generate.hs).
]
class Named a => Rename a where
rename :: a->String->a
-- | the function uniqueNames ensures case-insensitive unique names like sql plug names
uniqueNames :: [String]->[a]->[a]
uniqueNames taken xs
= [p | cl<-eqCl (map toLower.name) xs -- each equivalence class cl contains (identified a) with the same map toLower (name p)
, p <-if name (head cl) `elem` taken || length cl>1
then [rename p (name p++show i) | (p,i)<-zip cl [(1::Int)..]]
else cl
]
instance Rename PlugSQL where
rename p x = p{sqlname=x}
tblcontents :: ContextInfo -> [Population] -> PlugSQL -> [[Maybe AAtomValue]]
tblcontents ci ps plug
= case plug of
ScalarSQL{} -> [[Just x] | x<-atomValuesOf ci ps (cLkp plug)]
BinSQL{} -> [[(Just . apLeft) p,(Just . apRight) p] |p<-fullContents ci ps (mLkp plug)]
TblSQL{} ->
--TODO15122010 -> remove the assumptions (see comment data PlugSQL)
--fields are assumed to be in the order kernel+other,
--where NULL in a kernel field implies NULL in the following kernel fields
--and the first field is unique and not null
--(r,s,t)<-mLkpTbl: s is assumed to be in the kernel, fldexpr t is expected to hold r or (flp r), s and t are assumed to be different
case fields plug of
[] -> fatal 593 "no fields in plug."
f:fs -> transpose
( map Just cAtoms
: [case fExp of
EDcI c -> [ if a `elem` atomValuesOf ci ps c then Just a else Nothing | a<-cAtoms ]
_ -> [ (lkp a . fullContents ci ps) fExp | a<-cAtoms ]
| fld<-fs, let fExp=fldexpr fld
]
)
where
cAtoms = (atomValuesOf ci ps. source . fldexpr) f
lkp a pairs
= case [ p | p<-pairs, a==apLeft p ] of
[] -> Nothing
[p] -> Just (apRight p)
_ -> fatal 428 ("(this could happen when using --dev flag, when there are violations)\n"++
"Looking for: '"++showValADL a++"'.\n"++
"Multiple values in one field. \n"
)
|
guoy34/ampersand
|
src/Database/Design/Ampersand/FSpec/ToFSpec/ADL2FSpec.hs
|
gpl-3.0
| 32,198 | 497 | 21 | 11,957 | 5,867 | 3,303 | 2,564 | 380 | 14 |
{-
Converts a nondeterministic finite automaton (NFA) into a deterministic one (DFA).
This was created as Project 1 for EECS 665 at the University of Kansas.
Author: Ryan Scott
-}
{-# LANGUAGE RankNTypes #-}
module Main where
import Control.Applicative
import Control.Monad
import Data.List
import qualified Data.Map as M
import Data.Map (Map)
import Data.Maybe
import qualified Data.Set as S
import Data.Set (Set)
import Data.Word
import Text.Parsec (parse)
import Text.Parsec.Char
import Text.Parsec.Language
import qualified Text.Parsec.Prim as PT
import qualified Text.Parsec.Token as PT
import Text.Parsec.Token (TokenParser)
import Text.Parsec.String
-- | Where the program begins
main :: IO ()
main = do
-- Parse standard input
stuff <- getContents
case parse nfa2dfaInput "" stuff of
Left _ -> error "Improper input"
Right nfa -> printDFA =<< subsetConstr nfa
-- | Create the minimal DFA by subset construction
subsetConstr :: NFA -> IO DFA
subsetConstr nfa = do
-- e-closure(s_0) is unmarked initially
let ecS0 = MarkedAStateSet 1 False . epsilonClosure (nfaTransitionFun nfa) . S.singleton $ nfaInitialAState nfa
putStr "E-closure(IO) = "
printSet $ markedSet ecS0
putStr " = "
putStrLn "1\n"
-- Determine the DFA transition table
dtran <- subsetConstr' (S.singleton ecS0) M.empty nfa
-- Use the transition table to determine the states
let dfaStates = S.fromList . map fst $ M.keys dtran
-- Filter the final states from dfaStates
dfaFinals = S.filter (\ms -> any (\u -> S.member u $ markedSet ms) . S.toList $ nfaFinalAStates nfa) dfaStates
return $ DFA dfaStates (nfaInputSymbols nfa) dtran ecS0 dfaFinals
-- | Construct the DFA transition table
subsetConstr' :: Set MarkedAStateSet -> DFATran -> NFA -> IO DFATran
subsetConstr' dStates dtran nfa =
let umdStates = S.filter ((==False) . marked) dStates -- Find unmarked states
in if (S.null umdStates) -- If there are no unmarked states...
then return dtran -- ...then do nothing...
else do -- ...otherwise, call subsetConstrBody on an unmarked state, then check again.
(dtran', dStates') <- subsetConstrBody (S.findMin umdStates) dStates dtran nfa
subsetConstr' dStates' dtran' nfa
-- | Marks a state T and computes e-close(move(T,a)) for all input symbols a, modifying Dstates and Dtran accordingly.
subsetConstrBody :: MarkedAStateSet -> Set MarkedAStateSet -> DFATran -> NFA -> IO (DFATran, Set MarkedAStateSet)
subsetConstrBody t' dstates''' dtran nfa = do
let lastNum = markedNum $ S.findMax dstates''' -- The index of the most recently marked state
t = setL _marked True t' -- Mark the state
dstates = S.insert t (S.delete t' dstates''') -- Put the marked state in Dstates
putStrLn $ "Mark " ++ show t
-- A big, ugly fold that goes through every input symbol a
(dtran', dstates', _) <- (flip . flip foldM) (dtran, dstates, lastNum) (S.toList $ nfaInputSymbols nfa) $ \(dtran', dstates', lastNum') a -> do
let m = move (nfaTransitionFun nfa) (markedSet t) (Just a) -- Compute move(T, a)
if S.null m -- If move(T,a) is the empty set, do nothing
then return (dtran', dstates', lastNum')
else do -- Otherwise, compute the e-closure
printSet $ markedSet t
putStr $ " --" ++ [a] ++ "--> "
printSet m
putStrLn ""
let u = MarkedAStateSet (lastNum'+1) False (epsilonClosure (nfaTransitionFun nfa) m) -- e-closure(move(T, a))
putStr "E-closure"
printSet m
putStr " = "
printSet $ markedSet u
putStr " = "
-- Check if u is in Dstates; if not, add it and increment lastNum
if inDStates u dstates'
then do
let u' = lookupDStates u dstates'
putStrLn $ show u'
return (M.insert (t, a) u' dtran', dstates', lastNum')
else do
let dstates'' = S.insert u dstates'
putStrLn $ show u
return (M.insert (t, a) u dtran', dstates'', lastNum' + 1)
putStrLn ""
return (dtran', dstates')
-------------------------------------------------------------------------------
-- Some of the algorithms used for NFA-DFA conversion.
-------------------------------------------------------------------------------
-- | Calculates the set of states that can be reached from set of states by
-- consuming exactly one input symbol.
move :: NFATran -> Set AState -> Transition -> Set AState
move nfaTran aStates trans = S.foldl' folder S.empty aStates
where
folder :: Set AState -> AState -> Set AState
folder moveStates aState =
-- Take all the states that can be reached from one state...
let transStates = fromJust $ M.lookup (aState, trans) nfaTran
-- ...and add them to the total.
in S.union transStates moveStates
-- | Calculates the set of states that can be reached from a set of states by
-- taking zero or more empty transitions.
epsilonClosure :: NFATran -> Set AState -> Set AState
epsilonClosure nfaTran set = epsilonClosure' (S.toList set) nfaTran set
-- | Does the "iterative" part (actually, via recursion) of epsilonClosure.
epsilonClosure' :: Stack AState -> NFATran -> Set AState -> Set AState
epsilonClosure' stack nfaTran set = if null stack then set -- If the stack is empty, do nothing
else let t = peek stack
stack' = pop stack
-- uMap is every state with with an incoming empty transition
uMap = M.filterWithKey (\(st,symb) _ -> st == t && symb == epsilon) nfaTran
-- If u is not in the closure, then add it and push it onto the stack.
setFolder (ecSet, qStack) u = if S.member u ecSet
then (ecSet, qStack)
else (S.insert u ecSet, push u qStack)
(set', stack'') = M.foldl' (S.foldl' setFolder) (set, stack') uMap
in epsilonClosure' stack'' nfaTran set'
-- | Checks if a marked state's sets are in a marked state set.
inDStates :: MarkedAStateSet -> Set MarkedAStateSet -> Bool
inDStates (MarkedAStateSet _ _ set) dstates = any ((==set) . markedSet) $ S.toList dstates
-- | Retrieves a marked state in a set of marked states that has the same
-- set contents as another marked state.
lookupDStates :: MarkedAStateSet -> Set MarkedAStateSet -> MarkedAStateSet
lookupDStates (MarkedAStateSet _ _ set) dstates = fromJust . find ((==set) . markedSet) $ S.toList dstates
-------------------------------------------------------------------------------
-- The data structures used for NFA-DFA conversion.
-------------------------------------------------------------------------------
-- | Magical data accessor/setter type.
type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
-- | The simpler Lens type used for most operations.
type Lens' s a = Lens s s a a
-- | The trivial functor.
newtype Identity a = Identity { runIdentity :: a }
instance Functor Identity where
fmap f = Identity . f . runIdentity
-- | View a data structure element via a 'Lens'.
viewL :: Lens' s a -> s -> a
viewL lens = getConst . lens Const
{-# INLINE viewL #-}
-- | Replace a data structure element via a 'Lens'.
setL :: Lens' s a -> a -> s -> s
setL lens = overL lens . const
{-# INLINE setL #-}
-- | Modify a data structure element via a 'Lens'.
overL :: Lens' s a -> (a -> a) -> s -> s
overL lens f = runIdentity . lens (Identity . f)
{-# INLINE overL #-}
-- | A stack is simply a singly linked list.
type Stack = []
-- Pushing is cons
push :: a -> Stack a -> Stack a
push = (:)
-- Popping is cdr
pop :: Stack a -> Stack a
pop = tail
-- Peeking is car
peek :: Stack a -> a
peek = head
-- | A nondeterminstic finite automaton data structure.
data NFA = NFA {
nfaAStates :: Set AState
, nfaInputSymbols :: Set InputSymbol
, nfaTransitionFun :: NFATran
, nfaInitialAState :: AState
, nfaFinalAStates :: Set AState
} deriving (Eq, Ord, Read, Show)
-- | An NFA transition table.
type NFATran = Map (AState, Transition) (Set AState)
-- | A state data structure.
newtype AState = AState { runAState :: Word } deriving (Bounded, Eq, Ord, Read)
instance Num AState where
abs = error "AState arithmetic not permitted"
signum = error "AState arithmetic not permitted"
(+) = error "AState arithmetic not permitted"
(-) = error "AState arithmetic not permitted"
(*) = error "AState arithmetic not permitted"
fromInteger = AState . fromInteger
instance Show AState where
showsPrec d (AState w) = showsPrec d w
-- After an NFA is converted to a DFA, the DFA's states will actually consist
-- of marked sets of NFA states. Nifty!
data MarkedAStateSet = MarkedAStateSet {
markedNum :: Word
, marked :: Bool
, markedSet :: Set AState
} deriving (Eq, Read)
-- Only compare 'MarkedAStateSet's by their indexes.
instance Ord MarkedAStateSet where
compare ms1 ms2 = compare (markedNum ms1) (markedNum ms2)
instance Show MarkedAStateSet where
showsPrec d (MarkedAStateSet n _ _) = showsPrec d n
-- A 'Lens' that views a 'MarkedAStateSet`'s marked status.
_marked :: Lens' MarkedAStateSet Bool
_marked inj (MarkedAStateSet mn m ms) = (\m' -> MarkedAStateSet mn m' ms) <$> inj m
{-# INLINE _marked #-}
type InputSymbol = Char
-- An input symbol, or epsilon
type Transition = Maybe InputSymbol
epsilon :: Transition
epsilon = Nothing
-- A deterministic finite automaton data structure (as converted from an NFA).
data DFA = DFA {
dfaAStates :: Set MarkedAStateSet
, dfaInputSymbols :: Set InputSymbol
, dfaTransitionFun :: DFATran
, dfaInitialAState :: MarkedAStateSet
, dfaFinalStates :: Set MarkedAStateSet
}
-- | A DFA transition table.
type DFATran = Map (MarkedAStateSet, InputSymbol) MarkedAStateSet
-- Prettily prints a DFA to the screen.
printDFA :: DFA -> IO ()
printDFA (DFA states inputs trans initial finals) = do
putStr "Initial State: "
printSet $ S.singleton initial
putStrLn ""
putStr "Final States: "
printSet finals
putStrLn ""
putStr "State\t"
let inputsList = S.toList inputs
forM_ inputsList $ \input -> do
putChar input
putStr "\t"
putStrLn ""
forM_ (S.toList states) $ \st -> do
putStr $ show st
putStr "\t"
forM_ inputsList $ \input -> do
if (M.member (st, input) trans)
then do
putChar '{'
putStr . show . fromJust $ M.lookup (st, input) trans
putStr "}\t"
else putStr "{}\t"
putStrLn ""
-- Prettily prints a set's contents surrounded by braces.
printSet :: Show a => Set a -> IO ()
printSet set = do
putChar '{'
unless (S.null set) $ do
let setList = S.toList set
putStr . show $ head setList
forM_ (tail setList) $ \e -> do
putChar ','
putStr $ show e
putChar '}'
-------------------------------------------------------------------------------
-- The parser combinators used when reading in NFA input.
-------------------------------------------------------------------------------
lexer :: TokenParser st
lexer = PT.makeTokenParser emptyDef
-- | Parses something between curly braces.
braces :: Parser a -> Parser a
braces = PT.braces lexer
-- | Parses a natural number.
natural :: Parser Integer
natural = PT.natural lexer
-- | Parses a string, ignoring surrounding whitespace.
wsString :: String -> Parser String
wsString str = spaces *> string str <* spaces
-- | Parses any number of natural numbers, separated by commas.
csNaturals :: Parser (Set Integer)
csNaturals = (S.fromList . map fromInteger <$> oneOrMore)
<|> (spaces *> return S.empty)
where
oneOrMore :: Parser [Integer]
oneOrMore = do
n <- natural
spaces
ns <- PT.many (char ',' *> spaces *> natural)
return $ n:ns
-- | Parses "Initial State: {x}"
initialState :: Parser AState
initialState = wsString "Initial" *> wsString "State:" *> (fromInteger <$> braces natural)
-- | Parses "Final States: {x}"
finalStates :: Parser (Set AState)
finalStates = wsString "Final" *> wsString "States:" *> (S.map fromInteger <$> braces csNaturals)
-- | Parses "Total States: x"
totalStates :: Parser Word
totalStates = wsString "Total" *> wsString "States:" *> (fromInteger <$> natural)
-- | Parses the input symbols (e.g., "State a b c E")
transitions :: Parser [Char]
transitions = wsString "State" *> PT.many (PT.try $ spaces *> letter) <* spaces
-- | Parses a list of transitions (e.g., "1 {} {2,3}")
transitionFun :: [Transition] -> Parser NFATran
transitionFun trans = do
spaces
aStateKey <- fromInteger <$> natural
tFun <- (flip . flip foldM) M.empty trans $ \q t -> do
aStatesValues <- S.map fromInteger <$> braces csNaturals
return $ M.insert (aStateKey, t) aStatesValues q
spaces
return tFun
-- | Combines all of the above parsers to parse the entire input.
nfa2dfaInput :: Parser NFA
nfa2dfaInput = do
iAState <- initialState
fAStates <- finalStates
numAStates <- totalStates
symbsList <- transitions
let transList = flip map symbsList $ \c -> case c of 'E' -> Nothing
c' -> Just c'
aStatesList = [1..numAStates]
aStatesSet = S.fromList . map fromIntegral $ aStatesList
transSet = S.fromList . map fromJust $ filter isJust transList
tFun <- foldM (\q _ -> flip M.union q <$> transitionFun transList) M.empty aStatesList
return $ NFA aStatesSet transSet tFun iAState fAStates
|
RyanGlScott/nfa2dfa
|
Main.hs
|
gpl-3.0
| 14,198 | 0 | 23 | 3,758 | 3,437 | 1,754 | 1,683 | 241 | 3 |
module Spacewalk.Api.Preferences.Locale
( listLocales
, listTimeZones
, setLocale
, setTimeZone
) where
import Spacewalk.ApiTypes
import Spacewalk.ApiInternal
import Network.XmlRpc.Internals
listLocales :: SpacewalkRPC String
listLocales = swRemoteBase "preferences.locale.listTimeZones" id
listTimeZones :: SpacewalkRPC Value
listTimeZones = swRemoteBase "preferences.locale.listTimeZones" id
setLocale :: String -> String -> SpacewalkRPC ()
setLocale login locale = voidInt $
swRemote "preferences.locale.setLocale" (\ x -> x login locale )
setTimeZone :: String -> Int -> SpacewalkRPC ()
setTimeZone login tzid = voidInt $
swRemote "preferences.locale.setTimeZone" (\ x -> x login tzid )
|
xkollar/spacewalk-api-hs
|
src/Spacewalk/Api/Preferences/Locale.hs
|
gpl-3.0
| 725 | 0 | 9 | 116 | 174 | 93 | 81 | 18 | 1 |
module Main where
main = do
x <- getLine
print $ f (read x :: Integer) 2
f :: Integer -> Integer -> Integer
f m n = if m < n then 0
else 1 + (f (div m a) (a+1)) where a = g m n
-- f :: Int -> Int -> Int
-- f 1 _ = 0
-- f 2 _ = 1
-- f m n = 1 + (f (div m a) a)
-- where
-- a = g m n
g m n | (mod m n) == 0 = n
| (n*n) > m = m
| otherwise = g m (n+1)
|
cwlmyjm/haskell
|
Learning/listgame2.hs
|
mpl-2.0
| 368 | 2 | 10 | 130 | 188 | 98 | 90 | 10 | 2 |
{-# LANGUAGE OverloadedStrings, TemplateHaskell, QuasiQuotes, RecordWildCards, DataKinds, ViewPatterns #-}
module Model.RecordSlot
( module Model.RecordSlot.Types
, lookupRecordSlots
, lookupSlotRecords
, lookupContainerRecords
, lookupRecordSlotRecords
, lookupVolumeContainersRecords
, lookupVolumeContainersRecordIds
, lookupVolumeRecordSlotIds
, moveRecordSlot
, removeRecordAllSlot
, recordSlotAge
, recordSlotJSON
) where
import Control.Arrow (second)
import Control.Monad (guard, liftM2)
import Data.Function (on)
import Data.Maybe (catMaybes)
import Data.Monoid ((<>))
import qualified Database.PostgreSQL.Typed.Range as Range
import Database.PostgreSQL.Typed.Types (PGTypeName(..))
import Ops
import qualified JSON
import Service.DB
import Model.Id.Types
import Model.Segment
import Model.Permission
import Model.Audit
import Model.Audit.SQL
import Model.Volume.Types
import Model.Container.Types
import Model.Slot
import Model.Metric
import Model.Record
import Model.Age
import Model.Measure
import Model.SQL
import Model.RecordSlot.Types
import Model.RecordSlot.SQL
lookupRecordSlots :: (MonadDB c m) => Record -> m [RecordSlot]
lookupRecordSlots r =
dbQuery $ ($ r) <$> $(selectQuery selectRecordSlotRecord "$WHERE slot_record.record = ${recordId $ recordRow r}")
lookupSlotRecords :: (MonadDB c m) => Slot -> m [RecordSlot]
lookupSlotRecords (Slot c s) =
dbQuery $ ($ c) <$> $(selectQuery selectContainerSlotRecord "$WHERE slot_record.container = ${containerId $ containerRow c} AND slot_record.segment && ${s}")
lookupContainerRecords :: (MonadDB c m) => Container -> m [RecordSlot]
lookupContainerRecords = lookupSlotRecords . containerSlot
lookupRecordSlotRecords :: (MonadDB c m) => Record -> Slot -> m [RecordSlot]
lookupRecordSlotRecords r (Slot c s) =
dbQuery $ ($ c) . ($ r) <$> $(selectQuery selectRecordContainerSlotRecord "WHERE slot_record.record = ${recordId $ recordRow r} AND slot_record.container = ${containerId $ containerRow c} AND slot_record.segment && ${s}")
lookupVolumeContainersRecords :: (MonadDB c m) => Volume -> m [(Container, [RecordSlot])]
lookupVolumeContainersRecords v =
map (second catMaybes) . groupTuplesBy ((==) `on` containerId . containerRow) <$>
dbQuery (($ v) <$> $(selectQuery selectVolumeSlotMaybeRecord "WHERE container.volume = ${volumeId $ volumeRow v} ORDER BY container.id, record.category NULLS FIRST, slot_record.segment, slot_record.record"))
lookupVolumeContainersRecordIds :: (MonadDB c m) => Volume -> m [(Container, [(Segment, Id Record)])]
lookupVolumeContainersRecordIds v =
map (second catMaybes) . groupTuplesBy ((==) `on` containerId . containerRow) <$>
dbQuery (($ v) <$> $(selectQuery selectVolumeSlotMaybeRecordId "$WHERE container.volume = ${volumeId $ volumeRow v} ORDER BY container.id, slot_record.segment, slot_record.record"))
lookupVolumeRecordSlotIds :: (MonadDB c m) => Volume -> m [(Record, SlotId)]
lookupVolumeRecordSlotIds v =
dbQuery (($ v) <$> $(selectQuery selectVolumeSlotIdRecord "WHERE record.volume = ${volumeId $ volumeRow v} ORDER BY container"))
moveRecordSlot :: (MonadAudit c m) => RecordSlot -> Segment -> m Bool
moveRecordSlot rs@RecordSlot{ recordSlot = s@Slot{ slotSegment = src } } dst = do
ident <- getAuditIdentity
either (const False) id
<$> case (Range.isEmpty (segmentRange src), Range.isEmpty (segmentRange dst)) of
(True, True) -> return $ Right False
(False, True) -> Right <$> dbExecute1 $(deleteSlotRecord 'ident 'rs)
(True, False) -> dbTryJust err $ dbExecute1 $(insertSlotRecord 'ident 'rd)
(False, False) -> dbTryJust err $ dbExecute1 $(updateSlotRecord 'ident 'rs 'dst)
where
rd = rs{ recordSlot = s{ slotSegment = dst } }
err = guard . isExclusionViolation
removeRecordAllSlot :: (MonadAudit c m) => Record -> m Int
removeRecordAllSlot r = do
ident <- getAuditIdentity
dbExecute $(auditDelete 'ident "slot_record" "record = ${recordId $ recordRow r} AND segment = '(,)'" Nothing)
recordSlotAge :: RecordSlot -> Maybe Age
recordSlotAge rs@RecordSlot{..} =
clip <$> liftM2 age (decodeMeasure (PGTypeProxy :: PGTypeName "date") =<< getMeasure birthdateMetric (recordMeasures slotRecord)) (containerDate $ containerRow $ slotContainer recordSlot)
where
clip a
| not (canReadData2 getRecordSlotRelease getRecordSlotVolumePermission rs) = a `min` ageLimit
| otherwise = a
recordSlotJSON :: JSON.ToObject o => Bool -> RecordSlot -> JSON.Record (Id Record) o
recordSlotJSON _ rs@RecordSlot{..} = JSON.Record (recordId $ recordRow slotRecord) $
segmentJSON (slotSegment recordSlot)
<> "age" `JSON.kvObjectOrEmpty` recordSlotAge rs
{-
recordSlotJSONRestricted :: JSON.ToObject o => RecordSlot -> JSON.Record (Id Record) o
recordSlotJSONRestricted rs@RecordSlot{..} = JSON.Record (recordId $ recordRow slotRecord) $
segmentJSON (slotSegment recordSlot)
<> "age" `JSON.kvObjectOrEmpty` recordSlotAge rs -- allow age to pass through so that summary can be computed
-}
|
databrary/databrary
|
src/Model/RecordSlot.hs
|
agpl-3.0
| 5,001 | 0 | 15 | 711 | 1,279 | 697 | 582 | -1 | -1 |
module Main where
import Graphics.UI.Gtk
import Graphics.UI.Gtk.Glade
import Graphics.UI.Gtk.ModelView as New
data Phone = Phone { name :: String, number :: Int, marked :: Bool }
main = do
initGUI
Just xml <- xmlNew "ListTest.glade"
win <- xmlGetWidget xml castToWindow "window"
onDestroy win mainQuit
view <- xmlGetWidget xml castToTreeView "view"
stringValue <- xmlGetWidget xml castToEntry "stringValue"
intValue <- xmlGetWidget xml castToSpinButton "intValue"
boolValue <- xmlGetWidget xml castToCheckButton "boolValue"
insertButton <- xmlGetWidget xml castToButton "insert"
prependButton <- xmlGetWidget xml castToButton "prepend"
appendButton <- xmlGetWidget xml castToButton "append"
updateButton <- xmlGetWidget xml castToButton "update"
newIndex <- xmlGetWidget xml castToSpinButton "newIndex"
updateIndex <- xmlGetWidget xml castToSpinButton "updateIndex"
removeButton <- xmlGetWidget xml castToButton "remove"
clearButton <- xmlGetWidget xml castToButton "clear"
removeIndex <- xmlGetWidget xml castToSpinButton "removeIndex"
-- create a new list store
store <- storeImpl
New.treeViewSetModel view store
setupView view store
let getValues = do
name <- entryGetText stringValue
number <- spinButtonGetValue intValue
marked <- toggleButtonGetActive boolValue
return Phone {
name = name,
number = floor number,
marked = marked
}
onClicked prependButton $ getValues >>= New.listStorePrepend store
onClicked appendButton $ getValues >>= New.listStoreAppend store >> return ()
onClicked insertButton $ do
value <- getValues
index <- fmap floor $ spinButtonGetValue newIndex
New.listStoreInsert store index value
onClicked updateButton $ do
value <- getValues
index <- fmap floor $ spinButtonGetValue updateIndex
New.listStoreSetValue store index value
onClicked removeButton $ do
index <- fmap floor $ spinButtonGetValue removeIndex
New.listStoreRemove store index
onClicked clearButton $ New.listStoreClear store
New.treeViewSetReorderable view True
-- containerAdd win view
widgetShowAll win
mainGUI
setupView view model = do
New.treeViewSetHeadersVisible view True
-- add a couple columns
renderer1 <- New.cellRendererTextNew
col1 <- New.treeViewColumnNew
New.treeViewColumnPackStart col1 renderer1 True
New.cellLayoutSetAttributes col1 renderer1 model $ \row -> [ New.cellText := name row ]
New.treeViewColumnSetTitle col1 "String column"
New.treeViewAppendColumn view col1
renderer2 <- New.cellRendererTextNew
col2 <- New.treeViewColumnNew
New.treeViewColumnPackStart col2 renderer2 True
New.cellLayoutSetAttributes col2 renderer2 model $ \row -> [ New.cellText := show (number row) ]
New.treeViewColumnSetTitle col2 "Int column"
New.treeViewAppendColumn view col2
renderer3 <- New.cellRendererToggleNew
col3 <- New.treeViewColumnNew
New.treeViewColumnPackStart col3 renderer3 True
New.cellLayoutSetAttributes col3 renderer3 model $ \row -> [ New.cellToggleActive := marked row ]
New.treeViewColumnSetTitle col3 "Check box column"
New.treeViewAppendColumn view col3
storeImpl =
New.listStoreNew
[Phone { name = "Foo", number = 12345, marked = False }
,Phone { name = "Bar", number = 67890, marked = True }
,Phone { name = "Baz", number = 39496, marked = False }]
|
thiagoarrais/gtk2hs
|
demo/treeList/ListTest.hs
|
lgpl-2.1
| 3,444 | 0 | 15 | 664 | 938 | 436 | 502 | 76 | 1 |
{-# OPTIONS_GHC -Wall #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE RankNTypes #-}
module FittingTests
( fittingTests
) where
import Casadi.GenericType ( GType(..) )
import Casadi.Overloading ( ArcTan2 )
import qualified Data.Map as M
import qualified Test.HUnit.Base as HUnit
import Test.Framework ( Test, testGroup )
import Test.Framework.Providers.HUnit ( testCase )
import Text.Printf ( printf )
import Dyno.Fitting ( l1Fit, l2Fit, lInfFit )
import Dyno.Nlp ( Bounds )
import Dyno.Solvers ( Solver(..), ipoptSolver )
import Dyno.TypeVecs ( Vec )
import Dyno.View.MapFun ( MapStrategy(..) )
import qualified Dyno.TypeVecs as TV
import Dyno.Vectorize
toHUnit :: IO (Maybe String) -> HUnit.Assertion
toHUnit f = HUnit.assert $ do
r <- f
case r of
Just msg -> return (HUnit.assertString msg)
Nothing -> return (HUnit.assertBool "LGTM" True)
solver :: Solver
solver =
ipoptSolver
{ options = [("ipopt.tol", GDouble 1e-9)]
}
-- Our data set is [1, 2, 1]
--
-- y ^
-- 2.0 - | *
-- 1.5 - |
-- 1.0 - | * *
-- 0.5 - |
-- 0.0 - |
-- +------------>
-- x
--
-- The model is f(c, x) = c
-- So the L1 minimum should be 1
-- L2 minimum should be 4/3
-- Linf minimum should be 3/2
fitModel :: Id a -> None a -> Id a
fitModel c None = c
qbounds :: Id Bounds
qbounds = Id (Nothing, Nothing)
gbounds :: None Bounds
gbounds = None
fitData :: Vec 3 (None Double, Id Double)
fitData = fmap (\x -> (None, Id x)) $ TV.mkVec' [1, 2, 1]
testFit ::
Double
-> (Double
-> Solver
-> (forall a . (Floating a, ArcTan2 a) => Id a -> None a -> Id a)
-> (forall a . (Floating a, ArcTan2 a) => Id a -> None a)
-> Maybe (Id Double)
-> Id Bounds
-> None Bounds
-> MapStrategy
-> M.Map String GType
-> Vec 3 (None Double, Id Double)
-> IO (Either String (Id Double))
)
-> MapStrategy
-> HUnit.Assertion
testFit expectedValue fit mapStrategy = toHUnit $ do
ret <- fit 0.0 solver fitModel (const None) Nothing qbounds gbounds mapStrategy mempty fitData
return $ case ret of
Left msg -> Just msg
Right (Id x)
| abs (x - expectedValue) <= 1e-9 -> Nothing
| otherwise -> Just $ printf "expected %.4f, got %.4f, error: %.2g" expectedValue x (abs (expectedValue - x))
fittingTests :: Test
fittingTests =
testGroup "fitting tests"
[ testGroup (show mapStrat)
[ testCase "L1 fit" (testFit 1 l1Fit mapStrat)
, testCase "L2 fit" (testFit (4/3) l2Fit mapStrat)
, testCase "L-infinity fit" (testFit (3/2) lInfFit mapStrat)
]
| mapStrat <- [Unroll, Serial, OpenMP]
]
|
ghorn/dynobud
|
dynobud/tests/FittingTests.hs
|
lgpl-3.0
| 2,634 | 0 | 22 | 650 | 881 | 475 | 406 | 67 | 2 |
-- Chapter Exercises
--import Control.Monad
import Control.Monad.Trans.Reader
import Control.Monad.Trans.State
import Control.Monad.Trans.Maybe
import Control.Monad.Identity
import Control.Monad.IO.Class
-- Write the Code
-- 1.
rDec :: Num a => Reader a a
rDec = ReaderT $ \r -> return (r - 1)
-- 2.
rDec_pf :: Num a => Reader a a
rDec_pf = ReaderT $ return . subtract 1
-- 3.
rShow :: Show a => ReaderT a Identity String
rShow = ReaderT $ \r -> return (show r)
-- 4.
rShow_pf :: Show a => ReaderT a Identity String
rShow_pf = ReaderT $ return . show
-- 5.
rPrintAndInc :: (Num a, Show a) => ReaderT a IO a
rPrintAndInc = ReaderT $ \r -> do
putStrLn $ "Hi: " ++ show r
return $ r + 1
-- 6.
sPrintIncAccum :: (Num a, Show a) => StateT a IO String
sPrintIncAccum = StateT (\s -> do
putStrLn $ "Hi: " ++ show s
return (show s, s+1))
-- Fix the code
isValid :: String -> Bool
isValid v = '!' `elem` v
maybeExcite :: MaybeT IO String
maybeExcite = do
--v <- getLine
v <- liftIO getLine
guard $ isValid v
return v
doExcite :: IO ()
doExcite = do
putStrLn "say something excite!"
excite <- runMaybeT maybeExcite
case excite of
Nothing -> putStrLn "MOAR EXCITE"
Just e ->
putStrLn ("Good, was very excite: " ++ e)
|
dmp1ce/Haskell-Programming-Exercises
|
Chapter 26/Chapter Exercises.hs
|
unlicense
| 1,253 | 0 | 12 | 274 | 466 | 241 | 225 | 36 | 2 |
{-# LANGUAGE NoMonomorphismRestriction, ScopedTypeVariables #-}
-----------------------------------------------------------------------------
--
-- Module : UIBehaviour
-- Copyright : 2009 Renaissance Computing Institute
-- License : BSD3
--
-- Maintainer : Jeff Heard <[email protected]>
-- Stability : Experimental
-- Portability :
--
-- |
--
-----------------------------------------------------------------------------
module UIBehaviour where
import Graphics.Rendering.Hieroglyph.OpenGL
import Graphics.Rendering.Hieroglyph.Primitives
import Graphics.Rendering.Hieroglyph.Visual
import Control.Applicative
import Data.Monoid
import Control.Monad
import App.EventBus
import Data.Maybe
import qualified Data.Set as Set
import qualified Data.Map as Map
import Graphics.UI.Gtk
import System.Glib.MainLoop
import Data.List (sort)
import WktHieroglyph
import Control.Concurrent
import EventNames
import UIGeometry
import ServerFunctions
import Dialogs
import Debug.Trace
import Try
import System.Process (runCommand)
import Foreign (void)
import Data.IORef
monoidFromMaybe (Just x) = return x
monoidFromMaybe Nothing = mzero
myNothing = Nothing ::(Maybe (Entry, Entry -> IO [EData a]))
parseDialogResponse (dialog : rest)
| dialog == "itemSelectionDialogue" = parseItemSelectionResp rest
| dialog == "singleEntryDialogue" = parseSingleEntryResp rest
| dialog == "fileSelectionDialogue" = parseFileSelectionResp rest
| dialog == "contentAdditionDialogue" = parseContentAdditionResp rest
parseSingleEntryResp [] = return Nothing
parseSingleEntryResp (lbltxt:x) = produce responseGrp dialogueSrc lbltxt once [EString . unlines $ x] >>= return . Just
parseItemSelectionResp [] = return Nothing
parseItemSelectionResp (lbltxt:x) = produce responseGrp dialogueSrc lbltxt once [EStringL x] >>= return . Just
parseFileSelectionResp [] = return Nothing
parseFileSelectionResp (lbltxt:x) = produce responseGrp dialogueSrc lbltxt once [EString . head $ x] >>= return . Just
parseContentAdditionResp [] = return Nothing
parseContentAdditionResp (lbltxt:_:rest) = produce responseGrp dialogueSrc lbltxt Persistent [EString lbltxt, EString anntxt, EString edata] >>= return . Just
where (anntxt,(_:rest')) = parseAnnTxt [] rest
edata = parseEData rest'
parseAnnTxt a ("</ANNTXT>":x) = a
parseAnnTxt a (x:xs) = parseAnnTxt (a++('\n':x)) xs
parseEData a ("</EDATA>":_) = a
parseEData a (x:xs) = parseEData (a++('\n':x)) xs
runDialog = proc ("." </> "RunDialog.exe")
mapSelectionDialogue maps = runDialog ("itemSelectionDialogue" : "Select map:" : "False" : maps)
urlDialogue = runDialog ["singleEntryDialogue", "Connect to map server at url:"]
newConferenceRoomDialogue l = runDialog ["singleEntryDialogue", ",Name your newly created conference room:"]
enterConferenceRoomDialogue = runDialog ["itemSelectionDialogue" "Select conference room to enter", "False"]++ l
overlayConferenceRoomDialogue l = runDialog ["itemSelectionDialogue", "Select conference room to overlay", "True"]++ l
snapToBookmarkDialogue l= runDialog ["itemSelectionDialogue", "Snap to bookmark", "False"]++ l
addBookmarkDialogue = runDialog ["singleEntryDialogue", "Name the current viewport bookmark:"]
addOverlayDialogue = runDialog ["fileSelectionDialogue", "Select a GeoTIFF", ".tif$"]
addWebServiceDialogue = runDialog ["singleEntryDialogue", "Type the URL of the webservice to add"]
addImageDialogue = runDialog ["fileSelectionDialogue", "Select an image icon", "(tif|png|jpg|gif)$"]
addWebLinkDialogue = runDialog ["contentAdditionDialogue", "Link the current annotation to a URL:"]
addContentDialogue = runDialog ["contentAdditionDialogue", "Title of the added content:"]
addElsewhereDialogue = runDialog ["contentAdditionDialogue", "Link the current annotation to a bookmark:"]
addElsewhereOtherMapDialogue = runDialog ["contentAdditionDialogue", "Link the current annotation to a position on another map:"]
selectShapefileDialogue = runDialog ["itemSelectionDialogue", "Select a data layer" "False"] ++ l
uiResponses b = pollEventGroupWith b selectionGrp $ \event -> do
let AttributedCoords _ _ namesL = getHieroglyphData . eventdata $ event
names = Set.fromList namesL
innames = (flip Set.member) names
currentURL = head . eventdata <$> defaultURL b
currentCR = Nothing
newAnnotations = eventsBySource finishedAnnotationsSrc b /= Set.empty
shpevent <- if innames overlayShapefileName then Just <$> (produce requestGrp userDataSrc "raise select shapefile dialogue" Persistent []) else return Nothing
mapevent <- if innames goToMapName then Just <$> (produce requestGrp userDataSrc "raise map selection dialogue" Persistent []) else return Nothing
urlevent <- if innames goToUrlName then Just <$> (produce requestGrp userDataSrc "raise url dialogue" Persistent ((monoidFromMaybe currentURL)::[EData HieroglyphGLRuntime]) ) else return Nothing
ncrevent <- if innames addConferenceRoomName then Just <$> (produce requestGrp userDataSrc "raise new conference room dialogue" Persistent []) else return Nothing
ecrevent <- if innames enterConferenceRoomName then Just <$> (produce requestGrp userDataSrc "raise enter conference room dialogue" Persistent ((monoidFromMaybe currentCR)::[EData a])) else return Nothing
ocrevent <- if innames overlayConferenceRoomName then Just <$> (produce requestGrp userDataSrc "raise overlay conference room dialogue" Persistent []) else return Nothing
abevent <- if innames addBookmarkName then Just <$> (produce requestGrp userDataSrc "raise add bookmark dialogue" Persistent []) else return Nothing
daevent <- if innames deleteAnnotationName then Just <$> (produce requestGrp userDataSrc "delete next selected annotation" Persistent []) else return Nothing
haevent <- if innames hideAnnotationsName then Just <$> (produce requestGrp userDataSrc "hide annotations" Persistent []) else return Nothing
nrevent <- if innames addRectangleName then Just <$> (produce visibleGrp newAnnotationsSrc addRectangleName Persistent [EOther $ Geometry newrect]) else return Nothing
ncevent <- if innames addCircleName then Just <$> (produce visibleGrp newAnnotationsSrc addCircleName Persistent [EOther $ Geometry newcircle]) else return Nothing
npoevent <- if innames addPolygonName then Just <$> (produce visibleGrp newAnnotationsSrc addPolygonName Persistent [EOther $ Geometry newpolygon]) else return Nothing
npaevent <- if innames addPathName then Just <$> (produce visibleGrp newAnnotationsSrc addPathName Persistent [EOther $ Geometry newpath]) else return Nothing
nmevent <- if innames addMarkerName then Just <$> (produce visibleGrp newAnnotationsSrc addMarkerName Persistent [EOther $ Geometry newmarker]) else return Nothing
awsevent <- if innames addWebServiceName then Just <$> (produce requestGrp userDataSrc "raise add web service dialogue" Persistent []) else return Nothing
acevent <- if innames addContentName && newAnnotations then Just <$> (produce requestGrp userDataSrc addContentDialogNm Persistent []) else return Nothing
alwevent <- if innames addWebLinkName && newAnnotations then Just <$> (produce requestGrp userDataSrc addWebLinkDialogNm Persistent []) else return Nothing
aleevent <- if innames addElsewhereName && newAnnotations then Just <$> (produce requestGrp userDataSrc addElsewhereDialogNm Persistent []) else return Nothing
alomevent <- if innames addOtherMapElsewhereName && newAnnotations then Just <$> (produce requestGrp userDataSrc addOtherMapLinkDialogNm Persistent []) else return Nothing
huievent <- if innames hideUIName then Just <$> (produce requestGrp userDataSrc "hide UI" Persistent []) else return Nothing
let deleteMouseEvent = Deletion . tryJust "ui responses: no mouse event associated" . eventByQName mouseGrp hieroglyphWindowSrc clickNm $ b
changes = catMaybes [shpevent, mapevent, urlevent
, ncrevent, ecrevent, ocrevent
, abevent, daevent, haevent
, nrevent, ncevent, npoevent
, npaevent, nmevent
, awsevent, acevent
, alwevent, aleevent, alomevent
, huievent]
return $ (Deletion event) : (if length changes == 0 then [] else [deleteMouseEvent]) ++ changes
dialogmap b = Map.fromList
[("raise map selection dialogue",mapSelectionDialogue maps)
,("raise url dialogue",urlDialogue)
,("raise new conference room dialogue",newConferenceRoomDialogue)
,("raise enter conference room dialogue",enterConferenceRoomDialogue conferencerooms)
,("raise overlay conference room dialogue",overlayConferenceRoomDialogue conferencerooms)
,("raise select shapefile dialogue",selectShapefileDialogue shapefiles)
,("raise snap to bookmark dialogue", snapToBookmarkDialogue bookmarks)
,("raise add bookmark dialogue",addBookmarkDialogue)
,("raise add web service dialogue",addWebServiceDialogue)
,(addWebLinkDialogNm ,addWebLinkDialogue)
,(addContentDialogNm ,addContentDialogue)
,(addElsewhereDialogNm,addElsewhereDialogue)
,(addOtherMapLinkDialogNm,addElsewhereOtherMapDialogue)
]
where shapefiles = fromMaybe [] $ fromEStringL <$> Map.lookup "available shapefiles" viewM
conferencerooms = fromMaybe [] $ fromEStringL <$> Map.lookup "available conference room names" viewM
maps = fromMaybe [] $ map fst . fromEAssocL . head . eventdata <$> metadata b
bookmarks = fromMaybe [] $ map fst . fromEAssocL <$> Map.lookup "available bookmarks" viewM
viewM = Map.fromList . fromMaybe [] $ viewL
viewL = fromEAssocL . head . eventdata <$> view b
myFuture :: IO a -> IO (MVar a)
myFuture expression = newEmptyMVar >>= (\mvar -> forkIO (expression >>= putMVar mvar) >> return mvar)
waitOn = takeMVar
dialogueRaisingBehaviour b = pollEventGroupWith b requestGrp $ \event -> do
if (head . words . ename $ event) == "raise"
then do
(_, Just p_stdout, _, ph) <- createProcess $ dialogmap b Map.! (ename event)
waitForProcess ph
resp <- hGetContents p_stdout
let respEvt = parseDialogResponse . lines $ resp
widgetDestroy (castToWidget w)
return $ Deletion event : maybe [] (:[]) respEvt
else
return []
dialogueResponseBehaviour =
enterConferenceRoomDialogResponseBehaviour
|~| shpfileDialogResponseBehaviour
|~| webSrvcDialogResponseBehaviour
|~| mapListRequestDialogResponseBehaviour
|~| mapSelectionDialogResponseBehaviour
|~| newConferenceRoomDialogResponseBehaviour
|~| addContentDialogResponseBehaviour
|~| addWebLinkDialogResponseBehaviour
|~| addBookmarkDialogResponseBehaviour
|~| snapToBookmarkDialogResponseBehaviour
webSrvcDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Type the URL of the webservice to add" $ \event -> return $
let wsuri = fromEString . head . eventdata $ event
viewL = maybe [] fromEAssocL $ head . eventdata <$> mapView
viewM = Map.fromList viewL
viewM' = Map.insert "overlayed webservices" (EStringL $ wsuri : fromEStringL (viewM Map.! "overlayed webservices")) viewM
viewL' = EAssocL $ Map.toList viewM'
mapView = view b
in maybe [] (\mv -> [Insertion mv{ eventdata = [viewL'] }]) mapView
shpfileDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Select a data layer" $ \event -> do
let wsuri = fromEString . head . eventdata $ event
viewL = maybe [] fromEAssocL $ head . eventdata <$> mapView
viewM = Map.fromList viewL
viewM' = Map.insert "overlayed shapefiles" (EStringL $ wsuri : fromEStringL (viewM Map.! "overlayed shapefiles")) viewM
viewL' = EAssocL $ Map.toList viewM'
mapView = view b
justSelectedE <- produce requestGrp userDataSrc "Just Selected Shapefile" once . eventdata $ event
return $ maybe [] (\mv -> [Insertion $ mv{ eventdata = [viewL'] }, justSelectedE]) mapView
enterConferenceRoomDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc"Select conference room to enter" $ \event -> return $
let crname = fromEString . head . eventdata $ event
viewL = maybe [] fromEAssocL $ head . eventdata <$> mapView
viewM = Map.fromList viewL
viewM'= Map.insert "current conference room name" (EString crname) viewM
viewM'' = Map.insert "current conference room id" (EInt crid) viewM'
viewL' = EAssocL . Map.toList $ viewM''
crids = fromEIntL . tryJust "no avilable conference room ids in view" $ Map.lookup "available conference room ids" viewM
crnames = fromEStringL . tryJust "no available conference rooms in view" $ Map.lookup "available conference room names" viewM
cralist = zip crnames crids
crid = tryJust "conference room id doesn't exist for name" $ lookup crname cralist
mapView= view b
in maybe [] (\mv -> [Insertion $ mv{ eventdata = [viewL'] }]) mapView
mapSelectionDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Select map:" $ \event ->
(let (g,s,n) = selectedMapQName in produce g s n once . eventdata $ event) >>= return . (:[])
mapListRequestDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Connect to map server at url:" $ \event -> do
mapListRequestE <- let (g,s,n) = requestMapListQName in produce g s n once . eventdata $ event
serviceURLE <- (let (g,s,n) = serviceURLQName in produce g s n Persistent . eventdata $ event)
return [serviceURLE,mapListRequestE]
newConferenceRoomDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Name your newly created conference room:" $ \event -> do
let crname = fromEString . head . eventdata $ event
mapid = fromEInt . tryJust "uiresponses: no map id in view" . lookup "id" . fromEAssocL . head . eventdata . fromJust $ mapView
mapView = view b
when (isJust mapView) $ rmtCreateConferenceRoom b mapid crname >> return ()
return []
addContentDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Title of the added content:" $ \event ->
let mapView = view b
viewL = fromEAssocL . head . eventdata . fromJust $ mapView
maybeCrid = fromEInt <$> lookup "current conference room id" viewL
newMarkerE = finishedMarker b
newPathE = finishedPath b
newCircleE = finishedCircle b
newRectangleE = finishedRectangle b
newPolygonE = finishedPolygon b
newAnnotationE = (listToMaybe . catMaybes $ [newMarkerE, newPathE, newCircleE, newRectangleE, newPolygonE])
in if (all id [ isJust mapView, isJust maybeCrid, isJust newAnnotationE ])
then let baseurl = takeWhile (/=':') . fromEString . tryJust "add content dialog resp.: no baseurl in view" . lookup "baseurl" $ viewL
crid = tryJust "add content dialog resp.: the impossible happened" maybeCrid
Geometry newAnn = fromEOther . head . eventdata . tryJust "add content dialog resp.: the impossible happened" $ newAnnotationE
contentpref = fromEString . head . eventdata . tryJust "add content dialog resp.: add content prefix to config file" $ contentPrefix b
[_,anntxt,title] = map fromEString . eventdata $ event
title' = filter (\alpha -> alpha `Set.member` alphanum)
alphanum = Set.fromList (' ':['A'..'z']++['0'..'9'])
cleanedUpTitle = contentpref ++ title
in do
rmtCreateContent b anntxt "content" cleanedUpTitle crid . head . hieroglyph2wkt $ newAnn
return [Deletion . fromJust $ newAnnotationE]
else do
print (isJust mapView)
print maybeCrid
print (isJust newAnnotationE)
return []
addWebLinkDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Link the current annotation to a URL:" $ \event ->
let mapView = view b
viewL = fromEAssocL . head . eventdata . fromJust $ mapView
maybeCrid = fromEInt <$> lookup "current conference room id" viewL
newMarkerE = finishedMarker b
newPathE = finishedPath b
newCircleE = finishedCircle b
newRectangleE = finishedRectangle b
newPolygonE = finishedPolygon b
newAnnotationE = (listToMaybe . catMaybes $ [newMarkerE, newPathE, newCircleE, newRectangleE, newPolygonE])
in if (all id [ isJust mapView, isJust maybeCrid, isJust newAnnotationE ])
then let baseurl = takeWhile (/=':') . fromEString . tryJust "add content dialog resp.: no baseurl in view" . lookup "baseurl" $ viewL
crid = tryJust "add content dialog resp.: the impossible happened" maybeCrid
Geometry newAnn = fromEOther . head . eventdata . tryJust "add content dialog resp.: the impossible happened" $ newAnnotationE
[_,anntxt,title] = map fromEString . eventdata $ event
in do
rmtCreateContent b anntxt "content" title crid . head . hieroglyph2wkt $ newAnn
return [Deletion . fromJust $ newAnnotationE]
else do
print (isJust mapView)
print maybeCrid
print (isJust newAnnotationE)
return []
addBookmarkDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Name the current viewport bookmark:" $ \event -> do
let crname = fromEString . head . eventdata $ event
mapid = fromEInt . tryJust "uiresponses: no map id in view" . lookup "id" . fromEAssocL . head . eventdata . fromJust $ mapView
mapView = view b
maybeCrid = fromEInt <$> lookup "current conference room id" viewL
viewL = fromEAssocL . head . eventdata . fromJust $ mapView
[ox,oy] = fromEDoubleL . tryJust "add bookmark response: view doesn't have origin" $ lookup "view origin" viewL
when (isJust mapView && isJust maybeCrid) $ rmtInsertBookmark b crname (fromJust maybeCrid) ox oy >> return ()
return []
snapToBookmarkDialogResponseBehaviour b = consumeFullyQualifiedEventWith b responseGrp dialogueSrc "Snap to bookmark" $ \event -> do
let (w,e,s,n) = tryJust "should be an ortho by this point" . ortho $ hdata
hdata = getHieroglyphData . eventdata $ renderDataE
renderDataE = tryJust "snap to bookmark dialog repsonse: no hieroglyph runtime" $ renderData b
bookmarks = fromEAssocL . tryJust "should be a bookmark list if we got here" . lookup "available bookmarks" . fromEAssocL . head . eventdata . tryJust "no view" . view $ b
[w',s'] = fromEDoubleL . tryJust "cannot find bookmark in list" . lookup (fromEString . head . eventdata $ event) $ bookmarks
e' = e-w + w'
n' = n-s + s'
return [Insertion renderDataE{ eventdata = setHieroglyphData hdata{ortho = Just (w',e',s',n') } . eventdata $ renderDataE } ]
annotationClickedBehaviour b = pollEventGroupWith b selectionGrp $ \event -> do
let anns = Set.toList $ eventsBySource annotationsSrc b
annNames = map ename anns
annMap = Map.fromList $ zip annNames anns
AttributedCoords _ _ namesL = getHieroglyphData . eventdata $ event
selAnns = filter ((flip Map.member) annMap) namesL
browser = fromEString . head . eventdata . tryJust "Set browser path in config file" $ browserPath b
forM_ selAnns $ \ann ->
let annType = fromEString $ annM Map.! "type"
annUrl = fromEString $ annM Map.! "data"
annM = Map.fromList . fromEAssocL $ (eventdata $ annMap Map.! ann) !! 1
in when (annType == "content") . void $ runCommand (browser ++ " " ++ annUrl)
return []
deleteAnnotationBehaviour b = pollEventGroupWith b selectionGrp $ \event -> do
let delEvent = eventsByName "delete next selected annotation" b
doDelete = delEvent /= Set.empty
anns = Set.toList $ eventsBySource annotationsSrc b
annNames = map ename anns
annMap = Map.fromList $ zip annNames anns
AttributedCoords _ _ namesL = getHieroglyphData . eventdata $ event
selAnns = filter ((flip Map.member) annMap) namesL
when doDelete . forM_ selAnns $ rmtDeleteContent b . fromEInt . fromJust . lookup "id" . fromEAssocL . (!!1) . eventdata . (annMap Map.!)
if doDelete then return (map Deletion $ event:(Set.toList delEvent) ++ map (annMap Map.!) selAnns) else return []
|
JeffHeard/Hieroglyph
|
Graphics/Rendering/Hieroglyph/UIBehaviour.hs
|
bsd-2-clause
| 20,964 | 0 | 20 | 4,472 | 5,492 | 2,795 | 2,697 | 278 | 22 |
{-# LANGUAGE TemplateHaskell #-}
{-| Implementation of the Ganeti logging functionality.
This currently lacks the following (FIXME):
- log file reopening
Note that this requires the hslogger library version 1.1 and above.
-}
{-
Copyright (C) 2011, 2012, 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
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
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Logging
( setupLogging
, logDebug
, logInfo
, logNotice
, logWarning
, logError
, logCritical
, logAlert
, logEmergency
, SyslogUsage(..)
, syslogUsageToRaw
, syslogUsageFromRaw
) where
import Control.Monad (when)
import System.Log.Logger
import System.Log.Handler.Simple
import System.Log.Handler.Syslog
import System.Log.Handler (setFormatter, LogHandler)
import System.Log.Formatter
import System.IO
import Ganeti.THH
import qualified Ganeti.ConstantUtils as ConstantUtils
-- | Syslog usage type.
$(declareLADT ''String "SyslogUsage"
[ ("SyslogNo", "no")
, ("SyslogYes", "yes")
, ("SyslogOnly", "only")
])
-- | Builds the log formatter.
logFormatter :: String -- ^ Program
-> Bool -- ^ Multithreaded
-> Bool -- ^ Syslog
-> LogFormatter a
logFormatter prog mt syslog =
let parts = [ if syslog
then "[$pid]:"
else "$time: " ++ prog ++ " pid=$pid"
, if mt then if syslog then " ($tid)" else "/$tid"
else ""
, " $prio $msg"
]
in tfLogFormatter "%F %X,%q %Z" $ concat parts
-- | Helper to open and set the formatter on a log if enabled by a
-- given condition, otherwise returning an empty list.
openFormattedHandler :: (LogHandler a) => Bool
-> LogFormatter a -> IO a -> IO [a]
openFormattedHandler False _ _ = return []
openFormattedHandler True fmt opener = do
handler <- opener
return [setFormatter handler fmt]
-- | Sets up the logging configuration.
setupLogging :: Maybe String -- ^ Log file
-> String -- ^ Program name
-> Bool -- ^ Debug level
-> Bool -- ^ Log to stderr
-> Bool -- ^ Log to console
-> SyslogUsage -- ^ Syslog usage
-> IO ()
setupLogging logf program debug stderr_logging console syslog = do
let level = if debug then DEBUG else INFO
destf = if console then Just ConstantUtils.devConsole else logf
fmt = logFormatter program False False
file_logging = syslog /= SyslogOnly
updateGlobalLogger rootLoggerName (setLevel level)
stderr_handlers <- openFormattedHandler stderr_logging fmt $
streamHandler stderr level
file_handlers <- case destf of
Nothing -> return []
Just path -> openFormattedHandler file_logging fmt $
fileHandler path level
let handlers = file_handlers ++ stderr_handlers
updateGlobalLogger rootLoggerName $ setHandlers handlers
-- syslog handler is special (another type, still instance of the
-- typeclass, and has a built-in formatter), so we can't pass it in
-- the above list
when (syslog /= SyslogNo) $ do
syslog_handler <- openlog program [PID] DAEMON INFO
updateGlobalLogger rootLoggerName $ addHandler syslog_handler
-- * Logging function aliases
-- | Log at debug level.
logDebug :: String -> IO ()
logDebug = debugM rootLoggerName
-- | Log at info level.
logInfo :: String -> IO ()
logInfo = infoM rootLoggerName
-- | Log at notice level.
logNotice :: String -> IO ()
logNotice = noticeM rootLoggerName
-- | Log at warning level.
logWarning :: String -> IO ()
logWarning = warningM rootLoggerName
-- | Log at error level.
logError :: String -> IO ()
logError = errorM rootLoggerName
-- | Log at critical level.
logCritical :: String -> IO ()
logCritical = criticalM rootLoggerName
-- | Log at alert level.
logAlert :: String -> IO ()
logAlert = alertM rootLoggerName
-- | Log at emergency level.
logEmergency :: String -> IO ()
logEmergency = emergencyM rootLoggerName
|
apyrgio/snf-ganeti
|
src/Ganeti/Logging.hs
|
bsd-2-clause
| 5,242 | 0 | 12 | 1,223 | 812 | 436 | 376 | 85 | 4 |
module Blog.BackEnd.ModelSupport where
import Blog.Model.Entry (Item, Model)
import qualified Blog.BackEnd.ModelTransformations as MT
import qualified Blog.BackEnd.IoOperations as IoO
import qualified Blog.BackEnd.Holder as H
import Control.Monad ((=<<))
boot :: IO (H.Holder Model)
boot = H.newHolder =<< IoO.boot
ingest_draft :: (H.Holder Model) -> String -> IO (Either String Item)
ingest_draft h s = do { d <- IoO.load_draft s
; case d of
Right i ->
do { H.applyIO' h (MT.ingest_draft i)
; return $ Right i }
Left err ->
return $ Left $ show err }
post_comment :: (H.Holder Model) -> Item -> IO ()
post_comment h i = do H.applyIO' h (MT.ingest_comment i)
|
prb/perpubplat
|
src/Blog/BackEnd/ModelSupport.hs
|
bsd-3-clause
| 833 | 4 | 12 | 277 | 256 | 142 | 114 | 18 | 2 |
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE OverloadedStrings #-}
module Table where
import Data.Monoid
import Data.List
import Data.Text (Text)
import qualified Data.Text as T
-- Types --
newtype Cell a = Cell a deriving (Eq, Show, Functor)
type Row = [Cell Text]
type Table = [Row]
type Column = [Cell Text]
-- Main --
renderTable :: Table -> Text
renderTable = T.unlines . fmap renderRow . sizeColumns
where
sizeColumns = mapColumns sizeColumn
renderRow = T.intercalate columnBorder . fmap cellValue
columnBorder = " "
-- Helpers --
sizeColumn :: Column -> Column
sizeColumn cells = (fmap . fmap) (T.justifyLeft n ' ') cells
where
n = maximum . fmap (T.length . cellValue) $ cells
mapColumns :: (Column -> Column) -> Table -> Table
mapColumns f = transpose . fmap f . transpose
cellValue (Cell x) = x
makeTable :: [[Text]] -> Table
makeTable = fmap . fmap $ Cell
-- Development --
t = putStr $ "\n" ++ T.unpack (renderTable mockData) ++ "\n"
mockData :: Table
mockData = makeTable
[
["", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"],
["Temperature", "3", "5", "10", "11", "9"],
["Humidity", "10", "15", "50", "0", "2"],
["Cloud Cover", "33", "22", "11", "90", "100"]
]
|
jasonkuhrt/weather
|
source/Table.hs
|
bsd-3-clause
| 1,237 | 0 | 12 | 248 | 427 | 245 | 182 | 32 | 1 |
{-|
Module : Idris.DSL
Description : Code to deal with DSL blocks.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE PatternGuards #-}
module Idris.DSL (debindApp, desugar) where
import Idris.AbsSyntax
import Idris.Core.TT
import Control.Monad.State.Strict
import Data.Generics.Uniplate.Data (transform)
debindApp :: SyntaxInfo -> PTerm -> PTerm
debindApp syn t = debind (dsl_bind (dsl_info syn)) t
dslify :: SyntaxInfo -> IState -> PTerm -> PTerm
dslify syn i = transform dslifyApp
where
dslifyApp (PApp fc (PRef _ _ f) [a])
| [d] <- lookupCtxt f (idris_dsls i)
= desugar (syn { dsl_info = d }) i (getTm a)
dslifyApp t = t
desugar :: SyntaxInfo -> IState -> PTerm -> PTerm
desugar syn i t = let t' = expandSugar (dsl_info syn) t
in dslify syn i t'
mkTTName :: FC -> Name -> PTerm
mkTTName fc n =
let mkList fc [] = PRef fc [] (sNS (sUN "Nil") ["List", "Prelude"])
mkList fc (x:xs) = PApp fc (PRef fc [] (sNS (sUN "::") ["List", "Prelude"]))
[ pexp (stringC x)
, pexp (mkList fc xs)]
stringC = PConstant fc . Str . str
intC = PConstant fc . I
reflm n = sNS (sUN n) ["Reflection", "Language"]
in case n of
UN nm -> PApp fc (PRef fc [] (reflm "UN")) [ pexp (stringC nm)]
NS nm ns -> PApp fc (PRef fc [] (reflm "NS")) [ pexp (mkTTName fc nm)
, pexp (mkList fc ns)]
MN i nm -> PApp fc (PRef fc [] (reflm "MN")) [ pexp (intC i)
, pexp (stringC nm)]
_ -> error "Invalid name from user syntax for DSL name"
expandSugar :: DSL -> PTerm -> PTerm
expandSugar dsl (PLam fc n nfc ty tm)
| Just lam <- dsl_lambda dsl
= PApp fc lam [ pexp (mkTTName fc n)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PLam fc n nfc ty tm) = PLam fc n nfc (expandSugar dsl ty) (expandSugar dsl tm)
expandSugar dsl (PLet fc rc n nfc ty v tm)
| Just letb <- dsl_let dsl
= PApp (fileFC "(dsl)") letb [ pexp (mkTTName fc n)
, pexp (expandSugar dsl v)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PLet fc rc n nfc ty v tm) = PLet fc rc n nfc (expandSugar dsl ty) (expandSugar dsl v) (expandSugar dsl tm)
expandSugar dsl (PPi p n fc ty tm)
| Just pi <- dsl_pi dsl
= PApp (fileFC "(dsl)") pi [ pexp (mkTTName (fileFC "(dsl)") n)
, pexp (expandSugar dsl ty)
, pexp (expandSugar dsl (var dsl n tm 0))]
expandSugar dsl (PPi p n fc ty tm) = PPi p n fc (expandSugar dsl ty) (expandSugar dsl tm)
expandSugar dsl (PApp fc t args) = PApp fc (expandSugar dsl t)
(map (fmap (expandSugar dsl)) args)
expandSugar dsl (PWithApp fc t arg) = PWithApp fc (expandSugar dsl t)
(expandSugar dsl arg)
expandSugar dsl (PAppBind fc t args) = PAppBind fc (expandSugar dsl t)
(map (fmap (expandSugar dsl)) args)
expandSugar dsl (PCase fc s opts) = PCase fc (expandSugar dsl s)
(map (pmap (expandSugar dsl)) opts)
expandSugar dsl (PIfThenElse fc c t f) =
PApp fc (PRef NoFC [] (sUN "ifThenElse"))
[ PExp 0 [] (sMN 0 "condition") $ expandSugar dsl c
, PExp 0 [] (sMN 0 "whenTrue") $ expandSugar dsl t
, PExp 0 [] (sMN 0 "whenFalse") $ expandSugar dsl f
]
expandSugar dsl (PPair fc hls p l r) = PPair fc hls p (expandSugar dsl l) (expandSugar dsl r)
expandSugar dsl (PDPair fc hls p l t r) = PDPair fc hls p (expandSugar dsl l) (expandSugar dsl t)
(expandSugar dsl r)
expandSugar dsl (PAlternative ms a as) = PAlternative ms a (map (expandSugar dsl) as)
expandSugar dsl (PHidden t) = PHidden (expandSugar dsl t)
expandSugar dsl (PNoImplicits t) = PNoImplicits (expandSugar dsl t)
expandSugar dsl (PUnifyLog t) = PUnifyLog (expandSugar dsl t)
expandSugar dsl (PDisamb ns t) = PDisamb ns (expandSugar dsl t)
expandSugar dsl (PRewrite fc by r t ty)
= PRewrite fc by r (expandSugar dsl t) ty
expandSugar dsl (PGoal fc r n sc)
= PGoal fc (expandSugar dsl r) n (expandSugar dsl sc)
expandSugar dsl (PDoBlock ds)
= expandSugar dsl $ debind (dsl_bind dsl) (block (dsl_bind dsl) ds)
where
block b [DoExp fc tm] = tm
block b [a] = PElabError (Msg "Last statement in do block must be an expression")
block b (DoBind fc n nfc tm : rest)
= PApp fc b [pexp tm, pexp (PLam fc n nfc Placeholder (block b rest))]
block b (DoBindP fc p tm alts : rest)
= PApp fc b [pexp tm, pexp (PLam fc (sMN 0 "__bpat") NoFC Placeholder
(PCase fc (PRef fc [] (sMN 0 "__bpat"))
((p, block b rest) : alts)))]
block b (DoLet fc rc n nfc ty tm : rest)
= PLet fc rc n nfc ty tm (block b rest)
block b (DoLetP fc p tm : rest)
= PCase fc tm [(p, block b rest)]
block b (DoRewrite fc h : rest)
= PRewrite fc Nothing h (block b rest) Nothing
block b (DoExp fc tm : rest)
= PApp fc b
[pexp tm,
pexp (PLam fc (sMN 0 "__bindx") NoFC (mkTy tm) (block b rest))]
where mkTy (PCase _ _ _) = PRef fc [] unitTy
mkTy (PMetavar _ _) = PRef fc [] unitTy
mkTy _ = Placeholder
block b _ = PElabError (Msg "Invalid statement in do block")
expandSugar dsl (PIdiom fc e) = expandSugar dsl $ unIdiom (dsl_apply dsl) (dsl_pure dsl) fc e
expandSugar dsl (PRunElab fc tm ns) = PRunElab fc (expandSugar dsl tm) ns
expandSugar dsl (PConstSugar fc tm) = PConstSugar fc (expandSugar dsl tm)
expandSugar dsl t = t
-- | Replace DSL-bound variable in a term
var :: DSL -> Name -> PTerm -> Int -> PTerm
var dsl n t i = v' i t where
v' i (PRef fc hl x) | x == n =
case dsl_var dsl of
Nothing -> PElabError (Msg "No 'variable' defined in dsl")
Just v -> PApp fc v [pexp (mkVar fc i)]
v' i (PLam fc n nfc ty sc)
| Nothing <- dsl_lambda dsl
= PLam fc n nfc ty (v' i sc)
| otherwise = PLam fc n nfc (v' i ty) (v' (i + 1) sc)
v' i (PLet fc rc n nfc ty val sc)
| Nothing <- dsl_let dsl
= PLet fc rc n nfc (v' i ty) (v' i val) (v' i sc)
| otherwise = PLet fc rc n nfc (v' i ty) (v' i val) (v' (i + 1) sc)
v' i (PPi p n fc ty sc)
| Nothing <- dsl_pi dsl
= PPi p n fc (v' i ty) (v' i sc)
| otherwise = PPi p n fc (v' i ty) (v' (i+1) sc)
v' i (PTyped l r) = PTyped (v' i l) (v' i r)
v' i (PApp f x as) = PApp f (v' i x) (fmap (fmap (v' i)) as)
v' i (PWithApp f x a) = PWithApp f (v' i x) (v' i a)
v' i (PCase f t as) = PCase f (v' i t) (fmap (pmap (v' i)) as)
v' i (PPair f hls p l r) = PPair f hls p (v' i l) (v' i r)
v' i (PDPair f hls p l t r) = PDPair f hls p (v' i l) (v' i t) (v' i r)
v' i (PAlternative ms a as) = PAlternative ms a $ map (v' i) as
v' i (PHidden t) = PHidden (v' i t)
v' i (PIdiom f t) = PIdiom f (v' i t)
v' i (PDoBlock ds) = PDoBlock (map (fmap (v' i)) ds)
v' i (PNoImplicits t) = PNoImplicits (v' i t)
v' i t = t
mkVar fc 0 = case index_first dsl of
Nothing -> PElabError (Msg "No index_first defined")
Just f -> setFC fc f
mkVar fc n = case index_next dsl of
Nothing -> PElabError (Msg "No index_next defined")
Just f -> PApp fc f [pexp (mkVar fc (n-1))]
setFC fc (PRef _ _ n) = PRef fc [] n
setFC fc (PApp _ f xs) = PApp fc (setFC fc f) (map (fmap (setFC fc)) xs)
setFC fc t = t
unIdiom :: PTerm -> PTerm -> FC -> PTerm -> PTerm
unIdiom ap pure fc e@(PApp _ _ _) = mkap (getFn e)
where
getFn (PApp fc f args) = (PApp fc pure [pexp f], args)
getFn f = (f, [])
mkap (f, []) = f
mkap (f, a:as) = mkap (PApp fc ap [pexp f, a], as)
unIdiom ap pure fc e = PApp fc pure [pexp e]
debind :: PTerm -> PTerm -> PTerm
-- For every arg which is an AppBind, lift it out
debind b tm = let (tm', (bs, _)) = runState (db' tm) ([], 0) in
bindAll (reverse bs) tm'
where
db' :: PTerm -> State ([(Name, FC, PTerm)], Int) PTerm
db' (PAppBind _ (PApp fc t args) [])
= db' (PAppBind fc t args)
db' (PAppBind fc t args)
= do args' <- dbs args
(bs, n) <- get
let nm = sUN ("_bindApp" ++ show n)
put ((nm, fc, PApp fc t args') : bs, n+1)
return (PRef fc [] nm)
db' (PApp fc t args)
= do t' <- db' t
args' <- mapM dbArg args
return (PApp fc t' args')
db' (PWithApp fc t arg)
= do t' <- db' t
arg' <- db' arg
return (PWithApp fc t' arg')
db' (PLam fc n nfc ty sc) = return (PLam fc n nfc ty (debind b sc))
db' (PLet fc rc n nfc ty v sc)
= do v' <- db' v
return (PLet fc rc n nfc ty v' (debind b sc))
db' (PCase fc s opts) = do s' <- db' s
return (PCase fc s' (map (pmap (debind b)) opts))
db' (PPair fc hls p l r) = do l' <- db' l
r' <- db' r
return (PPair fc hls p l' r')
db' (PDPair fc hls p l t r) = do l' <- db' l
r' <- db' r
return (PDPair fc hls p l' t r')
db' (PRunElab fc t ns) = fmap (\tm -> PRunElab fc tm ns) (db' t)
db' (PConstSugar fc tm) = liftM (PConstSugar fc) (db' tm)
db' t = return t
dbArg a = do t' <- db' (getTm a)
return (a { getTm = t' })
dbs [] = return []
dbs (a : as) = do let t = getTm a
t' <- db' t
as' <- dbs as
return (a { getTm = t' } : as')
bindAll [] tm = tm
bindAll ((n, fc, t) : bs) tm
= PApp fc b [pexp t, pexp (PLam fc n NoFC Placeholder (bindAll bs tm))]
|
uuhan/Idris-dev
|
src/Idris/DSL.hs
|
bsd-3-clause
| 10,287 | 0 | 17 | 3,694 | 4,867 | 2,384 | 2,483 | 195 | 22 |
module Shakefiles.Haskell (cabalProject, executable) where
import Development.Shake
import Development.Shake.Command
import Development.Shake.FilePath
import Development.Shake.Util
import qualified System.Directory
import Shakefiles.Platform (platform)
import qualified Shakefiles.Platform
import Data.Char (isSpace)
import Data.List (dropWhileEnd, stripPrefix)
import Shakefiles.Extra
cabalProject :: String -> [String] -> [String] -> [String] -> [String] -> [String] -> Rules ()
cabalProject name sourceFiles sourcePatterns deps testPatterns testDeps =
let
globalConfig =
[ "cabal.project"
, "cabal.project.freeze"
-- , "cabal.project.local"
]
needProjectFiles = do
sourceFilesFromPatterns <- getDirectoryFiles "" sourcePatterns
let allFiles = mconcat
[ globalConfig
, fmap (\d -> "_build/cabal" </> d </> "build.ok") deps
, sourceFiles
, sourceFilesFromPatterns
]
need allFiles
liftIO $ getHashedShakeVersion allFiles
in
do
"_build/cabal/" </> name </> "build.ok" %> \out -> do
hash <- needProjectFiles
cmd_ "cabal" "v2-build" "-O0" (name ++ ":libs") "--enable-tests"
writeFile' out hash
cabalBinPath name "noopt" %> \out -> do
_ <- needProjectFiles
cmd_ "cabal" "v2-build" "-O0" (name ++ ":exes") "--enable-tests"
cabalBinPath name "opt" %> \out -> do
_ <- needProjectFiles
cmd_ "cabal" "v2-build" "-O2" (name ++ ":exes")
"_build/cabal/" </> name </> "test.ok" %> \out -> do
need globalConfig
need $ fmap (\d -> "_build/cabal" </> d </> "build.ok") deps
need $ fmap (\d -> "_build/cabal" </> d </> "build.ok") testDeps
need sourceFiles
sourceFilesFromPatterns <- getDirectoryFiles "" sourcePatterns
need sourceFilesFromPatterns
testFiles <- getDirectoryFiles "" testPatterns
need testFiles
cmd_ "cabal" "v2-test" "-O0" (name ++ ":tests") "--test-show-details=streaming"
writeFile' out ""
cabalBinPath :: String -> String -> FilePath
cabalBinPath projectName opt =
let
version =
case projectName of
"elm-format" -> "0.8.5"
_ -> "0.0.0"
in
"dist-newstyle/build" </> Shakefiles.Platform.cabalInstallOs </> "ghc-9.0.1" </> projectName ++ "-" ++ version </> "x" </> projectName </> opt </> "build" </> projectName </> projectName <.> exe
executable :: FilePath -> String -> String -> Rules ()
executable target projectName gitDescribe =
do
target %> \out -> do
copyFileChanged (cabalBinPath projectName "noopt") out
phony ("dist-" ++ projectName) $ need
[ "dist" </> projectName ++ "-" ++ gitDescribe ++ "-" ++ show platform <.> Shakefiles.Platform.zipFormatFor platform
]
("_build" </> "dist" </> show platform </> projectName <.> exe) %> \out -> do
let binDist = cabalBinPath projectName "opt"
need [ binDist ]
cmd_ "strip" "-o" out binDist
("dist" </> projectName ++ "-" ++ gitDescribe ++ "-" ++ show platform <.> "tgz") %> \out -> do
let binDir = "_build/dist/" ++ show platform
need [ binDir </> projectName <.> exe ]
cmd_ "tar" "zcvf" out "-C" binDir (projectName <.> exe)
("dist" </> projectName ++ "-" ++ gitDescribe ++ "-" ++ show platform <.> "zip") %> \out -> do
let binDir = "_build/dist/" ++ show platform
let bin = binDir </> projectName <.> exe
need [ bin ]
absoluteBinPath <- liftIO $ System.Directory.makeAbsolute bin
liftIO $ removeFiles "." [ out ]
cmd_ "7z" "a" "-bb3" "-tzip" "-mfb=258" "-mpass=15" out absoluteBinPath
phonyPrefix (projectName ++ "-publish-") $ \version ->
need $
concatMap (\target ->
[ "publish" </> version </> projectName ++ "-" ++ version ++ "-" ++ show target <.> Shakefiles.Platform.zipFormatFor target
, "publish" </> version </> projectName ++ "-" ++ version ++ "-" ++ show target <.> Shakefiles.Platform.zipFormatFor target <.> "asc"
]
)
Shakefiles.Platform.all
let buildInDocker =
[ Shakefiles.Platform.Linux
]
let buildOnCi =
[ Shakefiles.Platform.Windows
, Shakefiles.Platform.Mac
]
forEach buildInDocker $ \target -> do
let zipExt = Shakefiles.Platform.zipFormatFor target
("_build" </> "docker" </> "*" </> show target </> projectName) %> \out -> do
need
[ "package/linux/build-in-docker.sh"
]
let sha = takeDirectory1 $ dropDirectory1 $ dropDirectory1 out
cmd_ "package/linux/build-in-docker.sh" sha
("publish" </> "*" </> projectName ++ "-*-" ++ show target <.> zipExt) %> \out -> do
let tag = takeDirectory1 $ dropDirectory1 out
StdoutTrim sha <- cmd "git" "rev-list" "-n1" ("tags/" ++ tag)
let binDir = "_build" </> "docker" </> sha </> show target
let binFile = projectName ++ Shakefiles.Platform.binExt target
need [ binDir </> binFile ]
cmd_ "tar" "zcvf" out "-C" binDir binFile
forEach buildOnCi $ \target -> do
let githubRunnerOs = Shakefiles.Platform.githubRunnerOs target
let zipExt = Shakefiles.Platform.zipFormatFor target
[ "_build" </> "github-ci" </> "unzipped" </> projectName ++ "-*-" ++ show target <.> zipExt,
"_build" </> "github-ci" </> "unzipped" </> projectName ++ "-*-" ++ show target <.> zipExt <.> "sig"
] &%> \[zip, sig] -> do
let outDir = takeDirectory zip
let tag = drop (length projectName + 1) $ (reverse . drop (length (show target) + 1) . reverse) $ dropExtension $ takeFileName zip
StdoutTrim sha <- cmd "git" "rev-list" "-n1" ("tags/" ++ tag)
let ciArchive = "downloads" </> projectName ++ "-" ++ sha ++ "-" ++ githubRunnerOs <.> "zip"
need [ ciArchive ]
liftIO $ removeFiles "." [ zip, sig ]
cmd_ "unzip" "-o" "-d" outDir ciArchive
cmd_ "gpgv" "--keyring" "keys/github-actions.gpg" sig zip
"publish" </> "*" </> projectName ++ "-*-" ++ show target <.> zipExt %> \out -> do
let source = "_build" </> "github-ci" </> "unzipped" </> takeFileName out
copyFileChanged source out
|
avh4/elm-format
|
Shakefiles/Haskell.hs
|
bsd-3-clause
| 6,931 | 16 | 26 | 2,251 | 1,825 | 910 | 915 | 120 | 2 |
#!/usr/bin/runhaskell
import Distribution.Franchise
import Data.List ( isSuffixOf )
main = build [] $
do copyright "Copyright 2008 Stephen Hicks"
license "BSD3"
withLib "c" "sys/stat.h" "umask(0)" $ define "HAVE_UMASK"
addExtraData "category" "Language"
addExtraData "maintainer" "Stephen Hicks <[email protected]>"
addExtraData "synopsis"
"A package for parsing shell scripts"
addExtraData "description" $ unlines
["",
" Language.Sh is a collection of modules for parsing and",
" manipulating expressions in shell grammar.",
"",
" Note: the API is still rather unstable, at the moment."]
ghcFlags ["-threaded","-O2","-I."]
-- Tests
withModule "System.Posix.Signals" $ define "HAVE_SIGNALS"
withModule "System.Posix.Files" $ define "UNIX"
withModule "System.Console.Haskeline" $ define "HAVE_HASKELINE"
-- withModuleExporting "System.FilePath.Glob"
-- "compPosix, commonPrefix" "(compPosix,commonPrefix)" $
-- define "HAVE_GLOB" -- cannot be satisfied w/ released glob!
withModuleExporting "Text.ParserCombinators.Parsec.Expr"
"Operator(..)" "Postfix" $
define "HAVE_PARSEC_POSTFIX"
withModule "System.Process.Redirects" $
define "HAVE_REDIRECTS_CREATEPROCESS"
withModuleExporting "System.Process" "createProcess, shell"
"createProcess (shell \"echo 1\") >> return ()" $
define "HAVE_CREATEPROCESS"
tryHeader "pwd.h" (define "HAVE_PWD") -- test function?!
"tilde expansion will not work fully."
whenC amInWindows $ define "WINDOWS"
-- Constants.hs
autoVersion NumberedPreRc >>= replace "@VERSION@"
createFile "System/Console/ShSh/Constants.hs"
-- cfiles
cfiles <- whenC (isDefined "HAVE_PWD") $ return ["hspwd.c"]
let cfiles' = map ("System/Console/ShSh/Foreign/"++) cfiles
buildDoc
package "language-sh" ["Language.Sh.Arithmetic",
"Language.Sh.Expansion",
"Language.Sh.Glob",
"Language.Sh.Map",
"Language.Sh.Parser",
"Language.Sh.Pretty",
"Language.Sh.Syntax"] []
privateExecutable "testlex" "testlex.hs" cfiles'
privateExecutable "pretty-sh" "pretty-sh.hs" cfiles'
executable "shsh" "shsh.hs" cfiles'
tryHeader h job warn = requireWithFeedback ("for header "++h)
((checkHeader h >> job >> return "yes")
`catchC` \_ -> return ("no\n"++warn))
buildDoc =
do addExtraData "haddock-directory" "doc/haddock"
rm_rf "test/check-output"
rm_rf "test/known-output"
txtfiles <- concat `fmap` mapDirectory buildOneTest "test"
beginTestWith $ do pwd >>= addToPath
pwd >>= setEnv "HOME"
withDirectory "doc" $
do htmls <- concat `fmap` mapM (\i -> markdownToHtml "../doc.css" i "")
txtfiles
addTarget $ ["*manual*","*html*"] :<
("manual/index.html":htmls) |<- defaultRule
outputTests <- flip mapDirectory "test/check-output" $ \t ->
if ".sh" `isSuffixOf` t
then do expected <- cat $ "../known-output/"++t
shshprefix <- whenC ((elem "fails-in-shsh" . words)
`fmap` cat t) $ return "failing-"
testOutput (shshprefix++t) expected $
fmap (filter (/='\r')) $ systemOut "shsh" [t]
basht <- withProgram "bash" [] $ \_ ->
do prefix <- whenC ((elem "fails-in-bash" . words)
`fmap` cat t) $
return "failing-"
testOutput (prefix++"bash-"++t) expected $
fmap (filter (/='\r')) $ systemOut "bash" [t]
return [prefix++"bash-"++t]
dasht <- withProgram "dash" ["sash"] $ \dash ->
do prefix <- whenC ((elem "fails-in-dash" . words)
`fmap` cat t) $
return "failing-"
testOutput (prefix++dash++"-"++t) expected $
fmap (filter (/='\r')) $ systemOut dash [t]
return [prefix++dash++"-"++t]
return ((shshprefix++t):basht++dasht)
else return []
test $ concat outputTests
where buildOneTest f | ".splits" `isSuffixOf` f = return []
buildOneTest f = take 1 `fmap` splitMarkdown f ("../doc/"++f++".txt")
|
shicks/shsh
|
Setup.hs
|
bsd-3-clause
| 5,608 | 5 | 25 | 2,463 | 1,084 | 516 | 568 | 87 | 3 |
module ToBytecode(toByecode) where
import Instructions
import qualified Data.ByteString.Lazy as BL
import Data.Binary.Put
toBs :: [Instruction] -> Put
toBs [] = putWord8 0
toBs (x:xs) = do
toB x
toBs xs
pint :: Int -> Put
pint = putInt32be . fromIntegral
pbytes :: Integer -> Put
pbytes a
| a < 256 = putWord8 . fromIntegral $ a
| otherwise = (putWord8 . fromIntegral) ( a `mod` 256 ) >> pbytes ( a `div` 256 )
toB :: Instruction -> Put
toB (InstrJump a)
= putWord8 1 >> pint a
toB (InstrConditionalJump a)
= putWord8 2 >> pint a
toB (InstrFunctionDecl name args len)
= do
putWord8 3
puts name
putstrs args
pint len
toB (InstrClassDecl name mem)
= putWord8 4 >> puts name >> putstrs mem
toB (InstrVarLookup name)
= putWord8 6 >> puts name
toB (InstrGlobalLookup name)
= putWord8 7 >> puts name
toB (InstrPushConstStr str)
= putWord8 8 >> puts str
toB (InstrPushConstInt int)
= putWord8 9 >> pint int
toB (InstrObjNew name)
= putWord8 12 >> puts name
toB (InstrLiteral num list)
= foldl (>>) (putInt8 (fromIntegral num)) (map (pbytes . fromIntegral) list)
toB (InstrLoad str)
= putWord8 34 >> puts str
toB a = putWord8 $
case a of
InstrReturn -> 5
InstrFunctionCall -> 10
InstrArrayAccess -> 11
InstrObjMemberAccess -> 13
InstrAssign -> 14
InstrCompareEq -> 15
InstrCompareLt -> 16
InstrCompareGt -> 17
InstrCompareLeq -> 18
InstrCompareGeq -> 19
InstrArithPlus -> 20
InstrArithMinus -> 21
InstrArithMul -> 22
InstrArithDiv -> 23
InstrArithMod -> 24
InstrArithInc -> 25
InstrArithDec -> 26
InstrLogicNot -> 27
InstrLogicAnd -> 28
InstrLogicOr -> 29
InstrBlockEnter -> 30
InstrBlockLeave -> 31
InstrStackPop -> 32
_ -> error "Invalid instruction type"
putstrs :: [String] -> Put
putstrs [] = putWord8 0
putstrs (x:xs) = puts x >> putstrs xs
puts :: String -> Put
puts a = putStringUtf8 a >> putWord8 0
toByecode :: [Instruction] -> BL.ByteString
toByecode a = runPut $ toBs a
|
fegies/pseudocodeCompiler
|
src/ToBytecode.hs
|
bsd-3-clause
| 2,429 | 0 | 9 | 876 | 773 | 381 | 392 | 75 | 24 |
module Dwarf.Types
( -- * Dwarf information
DwarfInfo(..)
, pprDwarfInfo
, pprAbbrevDecls
-- * Dwarf frame
, DwarfFrame(..), DwarfFrameProc(..), DwarfFrameBlock(..)
, pprDwarfFrame
-- * Utilities
, pprByte
, pprData4'
, pprDwWord
, pprWord
, pprLEBWord
, pprLEBInt
, wordAlign
)
where
import Debug
import CLabel
import CmmExpr ( GlobalReg(..) )
import FastString
import Outputable
import Platform
import Reg
import Dwarf.Constants
import Data.Bits
import Data.List ( mapAccumL )
import qualified Data.Map as Map
import Data.Word
import Data.Char
import CodeGen.Platform
-- | Individual dwarf records. Each one will be encoded as an entry in
-- the .debug_info section.
data DwarfInfo
= DwarfCompileUnit { dwChildren :: [DwarfInfo]
, dwName :: String
, dwProducer :: String
, dwCompDir :: String
, dwLineLabel :: LitString }
| DwarfSubprogram { dwChildren :: [DwarfInfo]
, dwName :: String
, dwLabel :: CLabel }
| DwarfBlock { dwChildren :: [DwarfInfo]
, dwLabel :: CLabel
, dwMarker :: CLabel }
-- | Abbreviation codes used for encoding above records in the
-- .debug_info section.
data DwarfAbbrev
= DwAbbrNull -- ^ Pseudo, used for marking the end of lists
| DwAbbrCompileUnit
| DwAbbrSubprogram
| DwAbbrBlock
deriving (Eq, Enum)
-- | Generate assembly for the given abbreviation code
pprAbbrev :: DwarfAbbrev -> SDoc
pprAbbrev = pprLEBWord . fromIntegral . fromEnum
-- | Abbreviation declaration. This explains the binary encoding we
-- use for representing @DwarfInfo@.
pprAbbrevDecls :: Bool -> SDoc
pprAbbrevDecls haveDebugLine =
let mkAbbrev abbr tag chld flds =
let fld (tag, form) = pprLEBWord tag $$ pprLEBWord form
in pprAbbrev abbr $$ pprLEBWord tag $$ pprByte chld $$
vcat (map fld flds) $$ pprByte 0 $$ pprByte 0
in dwarfAbbrevSection $$
ptext dwarfAbbrevLabel <> colon $$
mkAbbrev DwAbbrCompileUnit dW_TAG_compile_unit dW_CHILDREN_yes
([ (dW_AT_name, dW_FORM_string)
, (dW_AT_producer, dW_FORM_string)
, (dW_AT_language, dW_FORM_data4)
, (dW_AT_comp_dir, dW_FORM_string)
] ++
(if haveDebugLine
then [ (dW_AT_stmt_list, dW_FORM_data4) ]
else [])) $$
mkAbbrev DwAbbrSubprogram dW_TAG_subprogram dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_MIPS_linkage_name, dW_FORM_string)
, (dW_AT_external, dW_FORM_flag)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
, (dW_AT_frame_base, dW_FORM_block1)
] $$
mkAbbrev DwAbbrBlock dW_TAG_lexical_block dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
]
-- | Generate assembly for DWARF data
pprDwarfInfo :: Bool -> DwarfInfo -> SDoc
pprDwarfInfo haveSrc d
= pprDwarfInfoOpen haveSrc d $$
vcat (map (pprDwarfInfo haveSrc) (dwChildren d)) $$
pprDwarfInfoClose
-- | Prints assembler data corresponding to DWARF info records. Note
-- that the binary format of this is paramterized in @abbrevDecls@ and
-- has to be kept in synch.
pprDwarfInfoOpen :: Bool -> DwarfInfo -> SDoc
pprDwarfInfoOpen haveSrc (DwarfCompileUnit _ name producer compDir lineLbl) =
pprAbbrev DwAbbrCompileUnit
$$ pprString name
$$ pprString producer
$$ pprData4 dW_LANG_Haskell
$$ pprString compDir
$$ if haveSrc
then pprData4' (ptext lineLbl <> char '-' <> ptext dwarfLineLabel)
else empty
pprDwarfInfoOpen _ (DwarfSubprogram _ name label) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrSubprogram
$$ pprString name
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprFlag (externallyVisibleCLabel label)
$$ pprWord (ppr label)
$$ pprWord (ppr $ mkAsmTempEndLabel label)
$$ pprByte 1
$$ pprByte dW_OP_call_frame_cfa
pprDwarfInfoOpen _ (DwarfBlock _ label marker) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrBlock
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprWord (ppr marker)
$$ pprWord (ppr $ mkAsmTempEndLabel marker)
-- | Close a DWARF info record with children
pprDwarfInfoClose :: SDoc
pprDwarfInfoClose = pprAbbrev DwAbbrNull
-- | Information about unwind instructions for a procedure. This
-- corresponds to a "Common Information Entry" (CIE) in DWARF.
data DwarfFrame
= DwarfFrame
{ dwCieLabel :: CLabel
, dwCieInit :: UnwindTable
, dwCieProcs :: [DwarfFrameProc]
}
-- | Unwind instructions for an individual procedure. Corresponds to a
-- "Frame Description Entry" (FDE) in DWARF.
data DwarfFrameProc
= DwarfFrameProc
{ dwFdeProc :: CLabel
, dwFdeHasInfo :: Bool
, dwFdeBlocks :: [DwarfFrameBlock]
-- ^ List of blocks. Order must match asm!
}
-- | Unwind instructions for a block. Will become part of the
-- containing FDE.
data DwarfFrameBlock
= DwarfFrameBlock
{ dwFdeBlock :: CLabel
, dwFdeBlkHasInfo :: Bool
, dwFdeUnwind :: UnwindTable
}
-- | Header for the .debug_frame section. Here we emit the "Common
-- Information Entry" record that etablishes general call frame
-- parameters and the default stack layout.
pprDwarfFrame :: DwarfFrame -> SDoc
pprDwarfFrame DwarfFrame{dwCieLabel=cieLabel,dwCieInit=cieInit,dwCieProcs=procs}
= sdocWithPlatform $ \plat ->
let cieStartLabel= mkAsmTempDerivedLabel cieLabel (fsLit "_start")
cieEndLabel = mkAsmTempEndLabel cieLabel
length = ppr cieEndLabel <> char '-' <> ppr cieStartLabel
spReg = dwarfGlobalRegNo plat Sp
retReg = dwarfReturnRegNo plat
wordSize = platformWordSize plat
pprInit (g, uw) = pprSetUnwind plat g (Nothing, uw)
in vcat [ ppr cieLabel <> colon
, pprData4' length -- Length of CIE
, ppr cieStartLabel <> colon
, pprData4' (ptext (sLit "-1"))
-- Common Information Entry marker (-1 = 0xf..f)
, pprByte 3 -- CIE version (we require DWARF 3)
, pprByte 0 -- Augmentation (none)
, pprByte 1 -- Code offset multiplicator
, pprByte (128-fromIntegral wordSize)
-- Data offset multiplicator
-- (stacks grow down => "-w" in signed LEB128)
, pprByte retReg -- virtual register holding return address
] $$
-- Initial unwind table
vcat (map pprInit $ Map.toList cieInit) $$
vcat [ -- RET = *CFA
pprByte (dW_CFA_offset+retReg)
, pprByte 0
-- Sp' = CFA
-- (we need to set this manually as our Sp register is
-- often not the architecture's default stack register)
, pprByte dW_CFA_val_offset
, pprLEBWord (fromIntegral spReg)
, pprLEBWord 0
] $$
wordAlign $$
ppr cieEndLabel <> colon $$
-- Procedure unwind tables
vcat (map (pprFrameProc cieLabel cieInit) procs)
-- | Writes a "Frame Description Entry" for a procedure. This consists
-- mainly of referencing the CIE and writing state machine
-- instructions to describe how the frame base (CFA) changes.
pprFrameProc :: CLabel -> UnwindTable -> DwarfFrameProc -> SDoc
pprFrameProc frameLbl initUw (DwarfFrameProc procLbl hasInfo blocks)
= let fdeLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde")
fdeEndLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde_end")
procEnd = mkAsmTempEndLabel procLbl
ifInfo str = if hasInfo then text str else empty
-- see [Note: Info Offset]
in vcat [ pprData4' (ppr fdeEndLabel <> char '-' <> ppr fdeLabel)
, ppr fdeLabel <> colon
, pprData4' (ppr frameLbl <> char '-' <>
ptext dwarfFrameLabel) -- Reference to CIE
, pprWord (ppr procLbl <> ifInfo "-1") -- Code pointer
, pprWord (ppr procEnd <> char '-' <>
ppr procLbl <> ifInfo "+1") -- Block byte length
] $$
vcat (snd $ mapAccumL pprFrameBlock initUw blocks) $$
wordAlign $$
ppr fdeEndLabel <> colon
-- | Generates unwind information for a block. We only generate
-- instructions where unwind information actually changes. This small
-- optimisations saves a lot of space, as subsequent blocks often have
-- the same unwind information.
pprFrameBlock :: UnwindTable -> DwarfFrameBlock -> (UnwindTable, SDoc)
pprFrameBlock oldUws (DwarfFrameBlock blockLbl hasInfo uws)
| uws == oldUws
= (oldUws, empty)
| otherwise
= (,) uws $ sdocWithPlatform $ \plat ->
let lbl = ppr blockLbl <> if hasInfo then text "-1" else empty
-- see [Note: Info Offset]
isChanged g v | old == Just v = Nothing
| otherwise = Just (old, v)
where old = Map.lookup g oldUws
changed = Map.toList $ Map.mapMaybeWithKey isChanged uws
died = Map.toList $ Map.difference oldUws uws
in pprByte dW_CFA_set_loc $$ pprWord lbl $$
vcat (map (uncurry $ pprSetUnwind plat) changed) $$
vcat (map (pprUndefUnwind plat . fst) died)
-- [Note: Info Offset]
--
-- GDB was pretty much written with C-like programs in mind, and as a
-- result they assume that once you have a return address, it is a
-- good idea to look at (PC-1) to unwind further - as that's where the
-- "call" instruction is supposed to be.
--
-- Now on one hand, code generated by GHC looks nothing like what GDB
-- expects, and in fact going up from a return pointer is guaranteed
-- to land us inside an info table! On the other hand, that actually
-- gives us some wiggle room, as we expect IP to never *actually* end
-- up inside the info table, so we can "cheat" by putting whatever GDB
-- expects to see there. This is probably pretty safe, as GDB cannot
-- assume (PC-1) to be a valid code pointer in the first place - and I
-- have seen no code trying to correct this.
--
-- Note that this will not prevent GDB from failing to look-up the
-- correct function name for the frame, as that uses the symbol table,
-- which we can not manipulate as easily.
-- | Get DWARF register ID for a given GlobalReg
dwarfGlobalRegNo :: Platform -> GlobalReg -> Word8
dwarfGlobalRegNo p = maybe 0 (dwarfRegNo p . RegReal) . globalRegMaybe p
-- | Generate code for setting the unwind information for a register,
-- optimized using its known old value in the table. Note that "Sp" is
-- special: We see it as synonym for the CFA.
pprSetUnwind :: Platform -> GlobalReg -> (Maybe UnwindExpr, UnwindExpr) -> SDoc
pprSetUnwind _ Sp (Just (UwReg s _), UwReg s' o') | s == s'
= if o' >= 0
then pprByte dW_CFA_def_cfa_offset $$ pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_offset_sf $$ pprLEBInt o'
pprSetUnwind plat Sp (_, UwReg s' o')
= if o' >= 0
then pprByte dW_CFA_def_cfa $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_sf $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBInt o'
pprSetUnwind _ Sp (_, uw)
= pprByte dW_CFA_def_cfa_expression $$ pprUnwindExpr False uw
pprSetUnwind plat g (_, UwDeref (UwReg Sp o))
| o < 0 && ((-o) `mod` platformWordSize plat) == 0 -- expected case
= pprByte (dW_CFA_offset + dwarfGlobalRegNo plat g) $$
pprLEBWord (fromIntegral ((-o) `div` platformWordSize plat))
| otherwise
= pprByte dW_CFA_offset_extended_sf $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprLEBInt o
pprSetUnwind plat g (_, UwDeref uw)
= pprByte dW_CFA_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
pprSetUnwind plat g (_, uw)
= pprByte dW_CFA_val_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
-- | Generates a DWARF expression for the given unwind expression. If
-- @spIsCFA@ is true, we see @Sp@ as the frame base CFA where it gets
-- mentioned.
pprUnwindExpr :: Bool -> UnwindExpr -> SDoc
pprUnwindExpr spIsCFA expr
= sdocWithPlatform $ \plat ->
let ppr (UwConst i)
| i >= 0 && i < 32 = pprByte (dW_OP_lit0 + fromIntegral i)
| otherwise = pprByte dW_OP_consts $$ pprLEBInt i -- lazy...
ppr (UwReg Sp i) | spIsCFA
= if i == 0
then pprByte dW_OP_call_frame_cfa
else ppr (UwPlus (UwReg Sp 0) (UwConst i))
ppr (UwReg g i) = pprByte (dW_OP_breg0+dwarfGlobalRegNo plat g) $$
pprLEBInt i
ppr (UwDeref u) = ppr u $$ pprByte dW_OP_deref
ppr (UwPlus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_plus
ppr (UwMinus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_minus
ppr (UwTimes u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_mul
in ptext (sLit "\t.byte 1f-.-1") $$
ppr expr $$
ptext (sLit "1:")
-- | Generate code for re-setting the unwind information for a
-- register to "undefined"
pprUndefUnwind :: Platform -> GlobalReg -> SDoc
pprUndefUnwind _ Sp = panic "pprUndefUnwind Sp" -- should never happen
pprUndefUnwind plat g = pprByte dW_CFA_undefined $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat g)
-- | Align assembly at (machine) word boundary
wordAlign :: SDoc
wordAlign = sdocWithPlatform $ \plat ->
ptext (sLit "\t.align ") <> case platformOS plat of
OSDarwin -> case platformWordSize plat of
8 -> text "3"
4 -> text "2"
_other -> error "wordAlign: Unsupported word size!"
_other -> ppr (platformWordSize plat)
-- | Assembly for a single byte of constant DWARF data
pprByte :: Word8 -> SDoc
pprByte x = ptext (sLit "\t.byte ") <> ppr (fromIntegral x :: Word)
-- | Assembly for a constant DWARF flag
pprFlag :: Bool -> SDoc
pprFlag f = pprByte (if f then 0xff else 0x00)
-- | Assembly for 4 bytes of dynamic DWARF data
pprData4' :: SDoc -> SDoc
pprData4' x = ptext (sLit "\t.long ") <> x
-- | Assembly for 4 bytes of constant DWARF data
pprData4 :: Word -> SDoc
pprData4 = pprData4' . ppr
-- | Assembly for a DWARF word of dynamic data. This means 32 bit, as
-- we are generating 32 bit DWARF.
pprDwWord :: SDoc -> SDoc
pprDwWord = pprData4'
-- | Assembly for a machine word of dynamic data. Depends on the
-- architecture we are currently generating code for.
pprWord :: SDoc -> SDoc
pprWord s = (<> s) . sdocWithPlatform $ \plat ->
case platformWordSize plat of
4 -> ptext (sLit "\t.long ")
8 -> ptext (sLit "\t.quad ")
n -> panic $ "pprWord: Unsupported target platform word length " ++
show n ++ "!"
-- | Prints a number in "little endian base 128" format. The idea is
-- to optimize for small numbers by stopping once all further bytes
-- would be 0. The highest bit in every byte signals whether there
-- are further bytes to read.
pprLEBWord :: Word -> SDoc
pprLEBWord x | x < 128 = pprByte (fromIntegral x)
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBWord (x `shiftR` 7)
-- | Same as @pprLEBWord@, but for a signed number
pprLEBInt :: Int -> SDoc
pprLEBInt x | x >= -64 && x < 64
= pprByte (fromIntegral (x .&. 127))
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBInt (x `shiftR` 7)
-- | Generates a dynamic null-terminated string. If required the
-- caller needs to make sure that the string is escaped properly.
pprString' :: SDoc -> SDoc
pprString' str = ptext (sLit "\t.asciz \"") <> str <> char '"'
-- | Generate a string constant. We take care to escape the string.
pprString :: String -> SDoc
pprString = pprString' . hcat . map escape
where escape '\\' = ptext (sLit "\\\\")
escape '\"' = ptext (sLit "\\\"")
escape '\n' = ptext (sLit "\\n")
escape c | isAscii c && isPrint c && c /= '?'
-- escaping '?' prevents trigraph warnings
= char c
| otherwise
= let ch = ord c
in char '\\' <>
char (intToDigit (ch `div` 64)) <>
char (intToDigit ((ch `div` 8) `mod` 8)) <>
char (intToDigit (ch `mod` 8))
|
bitemyapp/ghc
|
compiler/nativeGen/Dwarf/Types.hs
|
bsd-3-clause
| 16,627 | 0 | 21 | 4,462 | 3,738 | 1,955 | 1,783 | 291 | 8 |
{-# LANGUAGE QuasiQuotes, TypeSynonymInstances #-}
module Atomo.Valuable where
import Control.Monad (liftM)
import System.IO
import qualified Data.Text as T
import qualified Data.Vector as V
import Atomo.Environment
import Atomo.Helpers
import Atomo.Pretty (Prettied)
import Atomo.QuasiQuotes
import Atomo.Types
class Valuable a where
-- | Convert to an Atomo value.
toValue :: a -> VM Value
-- | Convert from an Atomo value.
fromValue :: Value -> VM a
instance Valuable Value where
toValue = return
fromValue = return
instance Valuable Char where
toValue = return . Character
fromValue (Character c) = return c
fromValue v = raise ["wrong-value", "needed"] [v, string "Character"]
instance Valuable Double where
toValue = return . Double
fromValue (Double d) = return d
fromValue v = raise ["wrong-value", "needed"] [v, string "Double"]
instance Valuable Float where
toValue = return . Double . fromRational . toRational
fromValue (Double d) = return (fromRational . toRational $ d)
fromValue v = raise ["wrong-value", "needed"] [v, string "Double"]
instance Valuable Integer where
toValue = return . Integer
fromValue (Integer i) = return i
fromValue v = raise ["wrong-value", "needed"] [v, string "Integer"]
instance Valuable Int where
toValue = return . Integer . fromIntegral
fromValue (Integer i) = return (fromIntegral i)
fromValue v = raise ["wrong-value", "needed"] [v, string "Integer"]
instance Valuable a => Valuable [a] where
toValue xs = liftM list (mapM toValue xs)
fromValue (List v) = mapM fromValue (V.toList v)
fromValue v = raise ["wrong-value", "needed"] [v, string "List"]
instance Valuable a => Valuable (V.Vector a) where
toValue xs = liftM List (V.mapM toValue xs)
fromValue (List v) = V.mapM fromValue v
fromValue v = raise ["wrong-value", "needed"] [v, string "List"]
instance Valuable T.Text where
toValue = return . String
fromValue (String s) = return s
fromValue v = raise ["wrong-value", "needed"] [v, string "String"]
instance Valuable Pattern where
toValue = return . Pattern
fromValue (Pattern x) = return x
fromValue v = raise ["wrong-value", "needed"] [v, string "Pattern"]
instance Valuable Expr where
toValue = return . Expression
fromValue (Expression x) = return x
fromValue v = raise ["wrong-value", "needed"] [v, string "Expression"]
instance Valuable x => Valuable (Maybe x) where
toValue (Just x) = liftM (keyParticleN ["ok"] . (:[])) (toValue x)
toValue Nothing = return (particle "none")
fromValue (Particle (Single { mName = "none" })) = return Nothing
fromValue (Particle (Keyword { mNames = ["ok"], mTargets = [_, Just v]})) =
liftM Just (fromValue v)
fromValue v = raise ["wrong-value", "needed"]
[ v
, keyParticleN ["one-of"]
[ tuple
[ particle "none"
, keyParticle ["ok"] [Nothing, Nothing]
]
]
]
instance (Valuable x, Valuable y) => Valuable (x, y) where
toValue (x, y) = do
xv <- toValue x
yv <- toValue y
dispatch (keyword ["->"] [xv, yv])
fromValue v = do
x <- dispatch (single "from" v) >>= fromValue
y <- dispatch (single "to" v) >>= fromValue
return (x, y)
instance Valuable BufferMode where
toValue (BlockBuffering Nothing) = return (particle "block")
toValue (BlockBuffering (Just i)) = return (keyParticleN ["block"] [Integer (fromIntegral i)])
toValue LineBuffering = return (particle "line")
toValue NoBuffering = return (particle "none")
fromValue (Particle (Single { mName = "block" })) = return (BlockBuffering Nothing)
fromValue (Particle (Keyword { mNames = ["block"], mTargets = [Nothing, Just (Integer i)] })) =
return (BlockBuffering (Just (fromIntegral i)))
fromValue (Particle (Single { mName = "line" })) = return LineBuffering
fromValue (Particle (Single { mName = "none" })) = return NoBuffering
fromValue v = raise ["wrong-value", "needed"]
[ v
, keyParticleN ["one-of"]
[ tuple
[ particle "block"
, keyParticle ["block"] [Nothing, Nothing]
, particle "line"
, particle "none"
]
]
]
instance Valuable Prettied where
toValue d =
[e|Pretty|] `newWith` [("doc", haskell d)]
fromValue v = dispatch (single "doc" v) >>= fromHaskell
|
vito/atomo
|
src/Atomo/Valuable.hs
|
bsd-3-clause
| 4,544 | 0 | 16 | 1,146 | 1,625 | 846 | 779 | 100 | 0 |
import Data.Complex
import Data.List
type C=Complex Float
type Width=Int
type Height=Int
type X=Float
type Y=Float
--f::C->Int
data Crop = Rectangle {lowerLeft::C, higherRight::C, width::Width, height::Height}
type Grid = [[C]]
--Takes the lists of floating points (Real part and Imaginary part) and permutates them with help of helpfunction cross to the matrix of all points.
--doAll::[X]->[Y]->Grid
--List crossing to matrix.
--cross::[a]->[b]->[[(a,b)]]
--Converts a complex point with the help of the width and height to all the lists of floating points.
--complexToFloat::C->C->Width->Height->[X]->[Y]
--Do bitmap
--doBitmap::(C->Int)->Crop->Bitmap
--type Bitmap=[[Int]]
-------------------------------------------------------------------------------
--Working on cross
--Testing the unit circle
unitcircle=zip (map realPart [1,i,-1,-i]) (map imagPart [1,i,-1,-i])
i::C
i=0:+1
--We know here how to unite two lists, with zip, but how do we do it when we want all the permutations?
--I introduce an example that come from cross [0.0,0.5,1.0] [0.0,0.5,1.0]
example::[[C]]
example=[[(0.0:+0.0),(0.0:+0.5),(0.0:+1.0)],[(0.5:+0.0),(0.5:+0.5),(0.5:+1.0)],[(1.0:+0.0),(1.0:+0.5),(1.0:+1.0)]]
cross::[a]->[b]->[[(a,b)]]
cross xs ys = [ [ (x, y) | x<-xs ] | y<-ys]
--We want to go between complex float and tuple
complexToTuple::C->(Float,Float)
complexToTuple c=(realPart c,imagPart c)
tupleToComplex::(Float,Float)->C
tupleToComplex (a,b)=a:+b
test=map (map tupleToComplex )(cross [0.0,0.5,1.0] [0.0,0.5,1.0])==transpose example
--So the combination of tupleToComplex and cross gives us the complex points, but that's actually probably completely unneccesary, nevermind I'll see later
-----------------------------------------------------------------------------
--Working on complexToFloat
--Converts a complex point with the help of the width and height to all the lists of floating points.
--complexToFloat::C->C->Width->Height->[X]->[Y]
--I realise that it is better to split it up in two separate functions, x and y, which will be very similar.
--complexToFloatx::C->C->Width->[X]
--complexToFloaty::C->C->Height->[Y]
--lowerLeft is defined c=(r1:+i1) and higherRight=(r2,i2) then the side x will be r2-r1 and the side y will be i2-i1, then the distance with which it changes for each point can be found by dividing r2-r1 with the width-1 etc. Why -1 I'm not sore right now but it is that way
--I reconsider and realise I want a help function that can give me the real side from the two lowerLeft and higherRight points
complexToFloatx::C->C->Width->[X]
complexToFloatx a b x=[realPart a+step*(fromIntegral n)|n<-[0..(x-1)]]
where step=(realSide a b)/fromIntegral(x-1)
realSide::C->C->Float
realSide a b=(realPart b) - (realPart a)
--Then complexToFloaty can be defined similarly
complexToFloaty::C->C->Height->[Y]
complexToFloaty a b y=[realPart a+step*(fromIntegral n)|n<-[0..(y-1)]]
where step=(imagSide a b)/fromIntegral(y-1)
imagSide::C->C->Float
imagSide a b=(imagPart b) - (imagPart a)
test2=cross (complexToFloatx (0:+0) (1:+1) 3) (complexToFloaty (0:+0) (1:+1) 3)
--Yay it worked :)
-----------------------------------------------------------------------------
--Defining the top-level function makeGrid
makeGrid::Crop->Grid
makeGrid (Rectangle a b x y)=map (map tupleToComplex) (cross xs ys)
where xs=complexToFloatx a b x
ys=complexToFloaty a b y
--It worked excellently :)
|
juliajansson/NonlinearDynamicsAndChaos
|
Helpfunctions.hs
|
bsd-3-clause
| 3,522 | 0 | 10 | 540 | 905 | 517 | 388 | 36 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Saturnin.Server.Connection
( handleConnection
)
where
import Prelude hiding (lookup, log, readFile)
import Control.Applicative
import Control.Arrow
import Control.Concurrent.Spawn
import Control.Concurrent.STM
import Control.Monad.State
import Data.HashMap.Strict
import Data.Text.Lazy hiding (head, all, length)
import Data.Time.Clock
import Formatting
import Network.Socket
import System.IO hiding (readFile)
import Text.Read hiding (get, lift)
import Saturnin.Jobs
import Saturnin.Logging
import Saturnin.Server.Config
import Saturnin.Types
-- getServerState :: JobRequestListenerConnectionHandler YBServerState
-- getServerState = lift get
--getConfig :: JobRequestListenerConnectionHandler ConfigServer
--getConfig = ybssConfig <$> getServerState
readBytes :: JobRequestListenerConnectionHandler String
readBytes = (\x -> liftIO $ fst3 <$> recvFrom x 1024) =<< (fst <$> get)
-- | Log to both log file and the client connection
logBoth :: Job -> Text -> JobRequestListenerConnectionHandler ()
logBoth j x = logToConnection x >> (logJob j x)
logJob :: Job -> Text -> JobRequestListenerConnectionHandler ()
logJob j x = do
l <- liftIO . getJobLogger $ jobID j
liftIO $ l "master" x
-- | Log to both server stderr and client connection
logToServerAndConn :: Text -> JobRequestListenerConnectionHandler ()
logToServerAndConn x = logToConnection x >> (lift $ logInfo x)
handleConnection :: (Socket, SockAddr) -> YBServer ()
handleConnection = evalStateT handle'
where
handle' = logClientConnected
>> readJobRequest
>>= mkJob
>>= logJobStart
>>= distributeJob
>>= returnMachines
>>= reportJobResult
>> reportFreeMachines
>> closeConnection
>> logClientDisconnected
logClientConnected :: JobRequestListenerConnectionHandler ()
logClientConnected = do
addr <- snd <$> get
t <- liftIO getCurrentTime
lift . logInfo $ format (shown % " connected: " % shown) t addr
logClientDisconnected :: JobRequestListenerConnectionHandler ()
logClientDisconnected = do
addr <- snd <$> get
t <- liftIO getCurrentTime
lift . logInfo $ format (shown % " disconnected: " % shown) t addr
readJobRequest :: JobRequestListenerConnectionHandler (Maybe JobRequest)
readJobRequest = do
bytes <- readBytes
let mjr = readMaybe bytes
whenNothing mjr . logToServerAndConn
$ format ("failed to read JobRequest: " % shown) bytes
return mjr
mkJob
:: Maybe JobRequest
-> JobRequestListenerConnectionHandler (Maybe Job)
mkJob (Just x) = do
ms <- selectMachines x
whenNothing ms $
logToServerAndConn "Unable to select all requested machines"
mk ms
where
mk :: Maybe [(MachineDescription, Hostname)] -> JobRequestListenerConnectionHandler (Maybe Job)
mk (Just ms) = do
jid <- getJobID
return . Just $ Job
{ remoteJobs = uncurry (mkRemoteJob x) <$> ms
, request = x
, jobID = jid
}
mk Nothing = return Nothing
mkJob Nothing = return Nothing
logJobStart
:: Maybe Job
-> JobRequestListenerConnectionHandler (Maybe Job)
logJobStart (Just j) = do
t <- liftIO getCurrentTime
logBoth j $ format (shown% " starting job " %shown) t j
return $ Just j
logJobStart x = return x
distributeJob
:: Maybe Job
-> JobRequestListenerConnectionHandler (Maybe (Job, [JobResult]))
distributeJob (Just x) = do
baseLogger <- liftIO . getJobLogger $ jobID x
c <- fst <$> get
rs <- liftIO $ parMapIO runRemoteJob (rJobs x baseLogger $ logToConnection' c)
return $ Just (x, rs)
where
rJobs :: Job -> DistributedJobLogger -> Logger -> [RemoteJobRunnerState]
rJobs j l cL =
(\y -> RemoteJobRunnerState y (l $ jobMachine y) cL) <$> (remoteJobs j)
distributeJob Nothing = return Nothing
returnMachines
:: Maybe (Job, [JobResult])
-> JobRequestListenerConnectionHandler (Maybe (Job, [JobResult]))
returnMachines (x @ (Just (j, _))) = do
ts <- lift get
let returning = fromList $ (jobMachine &&& jobHost) <$> remoteJobs j
liftIO . atomically $ do
s <- readTVar ts
let old = freeMachines s
writeTVar ts $ s { freeMachines = old `union` returning }
return x
returnMachines Nothing = return Nothing
reportJobResult
:: Maybe (Job, [JobResult])
-> JobRequestListenerConnectionHandler ()
reportJobResult (Just (j, xs)) = do
logBoth j $ format (
"\n\n\nJob finished: " %shown% "\n" %
"Job results: " %shown% "\n" %
"Overal result: " %shown% "\n"
) (request j) xs overall
where
overall = if all isPassed $ result <$> xs
then Passed
else Failed
reportJobResult Nothing = return ()
closeConnection :: JobRequestListenerConnectionHandler ()
closeConnection = do
c <- fst <$> get
h <- liftIO $ socketToHandle c ReadWriteMode
_ <- liftIO $ hFlush h
_ <- liftIO $ hClose h
return ()
getJobID :: JobRequestListenerConnectionHandler JobID
getJobID = do
ts <- lift get
ps <- liftIO . atomically $ do
s <- readTVar ts
let new = s { pState = bumpJobID $ pState s }
writeTVar ts new
return $ pState new
liftIO $ writePState ps
return $ lastJobID ps
reportFreeMachines :: JobRequestListenerConnectionHandler ()
reportFreeMachines = lift get
>>= (freeMachines <$>) . liftIO . atomically . readTVar
>>= lift . logInfo . format ("free machines: "%shown)
-- | Returns Nothing if all the request machines were not found
-- otherwise removes the taken machines the freeMachines in
-- YBServerState and returns Just the taken machines
selectMachines
:: JobRequest
-> JobRequestListenerConnectionHandler (Maybe [(MachineDescription, Hostname)])
selectMachines r = do
ts <- lift get
liftIO . atomically $ do
s <- readTVar ts
let requested = testMachines r
free = freeMachines s
found = filterMachines requested free
if length found /= length requested
then return Nothing
else writeTVar ts
(s { freeMachines = difference free $ fromList found})
>> (return $ Just found)
filterMachines
:: [MachineDescription]
-> HashMap MachineDescription Hostname
-> [(MachineDescription, Hostname)]
filterMachines ss xs = toList $ filterWithKey (\k _ -> elem k ss) xs
whenNothing :: Applicative m => Maybe a -> m () -> m ()
whenNothing (Just _) _ = pure ()
whenNothing Nothing f = f
|
yaccz/saturnin
|
library/Saturnin/Server/Connection.hs
|
bsd-3-clause
| 6,583 | 1 | 17 | 1,546 | 1,943 | 971 | 972 | 165 | 2 |
{-# LANGUAGE GADTs, RankNTypes, TupleSections, FlexibleInstances, NamedFieldPuns #-}
module QnA1
where
instance Functor (Question i) where
fmap f Question{ ask, answer } = Question {ask = ask, answer = \ i -> f . answer i}
fmap f (Always g) = Always $ f . g
-- useless?
instance Applicative (Question i) where
pure = Always . const
(Always f) <*> (Always g) = Always $ \ i -> f i (g i)
(Always f) <*> Question{ ask, answer } = Question { ask = ask, answer = \ i -> f i . answer i }
Question{ ask, answer } <*> (Always f) = Question { ask = ask, answer = \ i s -> answer i s (f i) }
Question{ ask=ask', answer=answer' } <*> Question{ ask, answer } =
Question { ask = \ i -> ask i ++ "\n" ++ ask' i, answer = \ i s -> answer' i s (answer i s) }
type Prompt = String
type Input = String
-- @i@ is the state and @a@ is the answer to this Question
data Question i a = Question {
ask :: i -> Prompt,
answer :: i -> Input -> a
} | Always (i -> a)
-- | @Link s o@ is a linked list of Questions.
-- @s@ is the before state and @o@ is the after state
-- @s -> i@ maps QnA state @i@ to Question's input @i'@
-- @s -> a -> s'@ converts the answer to the before-state of the next Link
-- @s -> a -> Link s' o@ selects the next Link.
data Link s o where
Link :: (s -> i) -> (s -> a -> s') -> Question i a -> (s -> a -> Link s' o) -> Link s o
Final :: Link s o
-- | Prepend a Question to a Link
(~:>) :: Question i a -> Link (i, a) o -> Link i o
q ~:> l = q ~?> (const . const) l
-- | Prepend a Question to some Link using link selector funciton
(~?>) :: Question i a -> (i -> a -> Link (i, a) o) -> Link i o
q ~?> f = Link id (,) q f
-- | Create a Question that does not depend on the QnA state
simpleQuestion :: (Prompt -> a) -> Prompt -> Question i a
simpleQuestion r msg = Question {
ask = const msg,
answer = const r
}
-- | Extract the leading Question's Prompt from a Link
startLink :: i -> Link i o -> Prompt
startLink i (Link f c q@Question{} _) = ask q (f i)
startLink i (Link f c (Always next) l) =
let a = next (f i)
in startLink (c i a) (l i a)
startLink _ Final = "Done!"
-- | Receive the user's Input to the leading Question and return the after state of the QnA
-- TODO: I want to teturn the after state of the QnA and the next Link in the chain.
-- endLink :: i -> Link i o -> Input -> o -- TODO: return this tuple: (o, Link o o')
endLink i (Link f c q l) ans =
let a = answer q (f i) ans
o = c i a
link = l i a -- the next link. TODO: error: variable ‘o'’ would escape its scope
in undefined
-- in link
endLink _ Final _ = error "Cannot go further than the Final Link"
processLink :: Link i o -> i -> IO o
processLink l i = do
putStrLn $ startLink i l -- prompt the Question
a <- getLine -- get the answer
return $ endLink i l a -- return the input to the next Link (**and the next Link**)
-- Some sample questions
class KnownAge i where
age :: i -> Int
instance KnownAge (((a, b), Int), c) where
age ((_, a), _) = a
yourNameQ :: Question i String
yourNameQ = simpleQuestion id "Your name?"
yourAgeQ :: Question i Int
yourAgeQ = simpleQuestion read "Your age?"
yourDrinkQ :: Question i Prompt
yourDrinkQ = simpleQuestion id "Your drink?"
yourMinor :: Question i Int
yourMinor = simpleQuestion read "Grad year?"
gradAge :: KnownAge i => Question i Int
gradAge = Question {
ask = const "Graduation year?",
answer = \ i a -> 2016 - read a + age i
}
-- A sample QnA
nameAndDrinkL = yourNameQ ~:> ageAndDrinkL
ageAndDrinkL = yourAgeQ ~?> const (\ i -> if i > 21 then drinkL else (Always $ const Nothing) ~:> gradL)
drinkL = fmap Just yourDrinkQ ~:> gradL
gradL = gradAge ~:> Final
|
homam/fsm-conversational-ui
|
src/QnA1.hs
|
bsd-3-clause
| 3,685 | 0 | 13 | 884 | 1,272 | 672 | 600 | 66 | 2 |
{-# LANGUAGE CPP #-}
--------------------------------------------------------------------
-- |
-- Module : Text.Feed.Query
-- Copyright : (c) Galois, Inc. 2008,
-- (c) Sigbjorn Finne 2009-
-- License : BSD3
--
-- Maintainer: Sigbjorn Finne <[email protected]>
-- Stability : provisional
-- Portability: portable
--
--------------------------------------------------------------------
module Text.Feed.Query
( Text.Feed.Query.feedItems -- :: Feed.Feed -> [Feed.Item]
, FeedGetter -- type _ a = Feed -> a
, getFeedTitle -- :: FeedGetter String
, getFeedAuthor -- :: FeedGetter String
, getFeedHome -- :: FeedGetter URLString
, getFeedHTML -- :: FeedGetter URLString
, getFeedDescription -- :: FeedGetter String
, getFeedPubDate -- :: FeedGetter DateString
, getFeedLastUpdate -- :: FeedGetter (Maybe String)
, getFeedDate -- :: FeedGetter DateString
, getFeedLogoLink -- :: FeedGetter URLString
, getFeedLanguage -- :: FeedGetter String
, getFeedCategories -- :: FeedGetter [(String, Maybe String)]
, getFeedGenerator -- :: FeedGetter String
, getFeedItems -- :: FeedGetter [Item]
, ItemGetter -- type _ a = Item -> Maybe a
, getItemTitle -- :: ItemGetter (String)
, getItemLink -- :: ItemGetter (String)
, getItemPublishDate -- :: Data.Time.ParseTime t => ItemGetter (Maybe t)
, getItemPublishDateString -- :: ItemGetter (DateString)
, getItemDate -- :: ItemGetter (DateString)
, getItemAuthor -- :: ItemGetter (String)
, getItemCommentLink -- :: ItemGetter (URLString)
, getItemEnclosure -- :: ItemGetter (String,Maybe String,Integer)
, getItemFeedLink -- :: ItemGetter (URLString)
, getItemId -- :: ItemGetter (Bool,String)
, getItemCategories -- :: ItemGetter [String]
, getItemRights -- :: ItemGetter String
, getItemSummary -- :: ItemGetter String
, getItemDescription -- :: ItemGetter String (synonym of previous.)
) where
import Text.Feed.Types as Feed
import Text.RSS.Syntax as RSS
import Text.Atom.Feed as Atom
import Text.RSS1.Syntax as RSS1
import Text.XML.Light as XML
import Text.DublinCore.Types
import Control.Monad ( mplus )
import Data.List
import Data.Maybe
-- for getItemPublishDate rfc822 date parsing.
import Data.Time.Locale.Compat ( defaultTimeLocale, rfc822DateFormat, iso8601DateFormat )
import Data.Time.Format ( ParseTime )
import qualified Data.Time.Format as F
feedItems :: Feed.Feed -> [Feed.Item]
feedItems fe =
case fe of
AtomFeed f -> map Feed.AtomItem (Atom.feedEntries f)
RSSFeed f -> map Feed.RSSItem (RSS.rssItems $ RSS.rssChannel f)
RSS1Feed f -> map Feed.RSS1Item (RSS1.feedItems f)
-- ToDo: look for 'entry' elements if 'items' are missing..
XMLFeed f -> map Feed.XMLItem $ XML.findElements (XML.unqual "item") f
getFeedItems :: Feed.Feed -> [Feed.Item]
getFeedItems = Text.Feed.Query.feedItems
type FeedGetter a = Feed.Feed -> Maybe a
getFeedAuthor :: FeedGetter String
getFeedAuthor ft =
case ft of
Feed.AtomFeed f -> fmap Atom.personName $ listToMaybe $ Atom.feedAuthors f
Feed.RSSFeed f -> RSS.rssEditor (RSS.rssChannel f)
Feed.RSS1Feed f -> fmap dcText $ listToMaybe $ filter isAuthor $ RSS1.channelDC (RSS1.feedChannel f)
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "editor") e1
Nothing -> Nothing
where
isAuthor dc = dcElt dc == DC_Creator
getFeedTitle :: Feed.Feed -> String
getFeedTitle ft =
case ft of
Feed.AtomFeed f -> contentToStr $ Atom.feedTitle f
Feed.RSSFeed f -> RSS.rssTitle (RSS.rssChannel f)
Feed.RSS1Feed f -> RSS1.channelTitle (RSS1.feedChannel f)
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fromMaybe "" (fmap XML.strContent $ findElement (unqual "title") e1)
Nothing -> ""
getFeedHome :: FeedGetter URLString
getFeedHome ft =
case ft of
Feed.AtomFeed f -> fmap Atom.linkHref $ listToMaybe $ filter isSelf (Atom.feedLinks f)
Feed.RSSFeed f -> Just (RSS.rssLink (RSS.rssChannel f))
Feed.RSS1Feed f -> Just (RSS1.channelURI (RSS1.feedChannel f))
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "link") e1
Nothing -> Nothing
where
isSelf lr = toStr (Atom.linkRel lr) == "self"
getFeedHTML :: FeedGetter URLString
getFeedHTML ft =
case ft of
Feed.AtomFeed f -> fmap Atom.linkHref $ listToMaybe $ filter isSelf (Atom.feedLinks f)
Feed.RSSFeed f -> Just (RSS.rssLink (RSS.rssChannel f))
Feed.RSS1Feed f -> Just (RSS1.channelURI (RSS1.feedChannel f))
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "link") e1
Nothing -> Nothing
where
isSelf lr =
let rel = Atom.linkRel lr
in (isNothing rel || toStr rel == "alternate") && isHTMLType (linkType lr)
isHTMLType (Just str) = "lmth" `isPrefixOf` (reverse str)
isHTMLType _ = True -- if none given, assume html.
getFeedDescription :: FeedGetter String
getFeedDescription ft =
case ft of
Feed.AtomFeed f -> fmap contentToStr (Atom.feedSubtitle f)
Feed.RSSFeed f -> Just $ RSS.rssDescription (RSS.rssChannel f)
Feed.RSS1Feed f -> Just (RSS1.channelDesc (RSS1.feedChannel f))
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "description") e1
Nothing -> Nothing
getFeedPubDate :: FeedGetter DateString
getFeedPubDate ft =
case ft of
Feed.AtomFeed f -> Just $ Atom.feedUpdated f
Feed.RSSFeed f -> RSS.rssPubDate (RSS.rssChannel f)
Feed.RSS1Feed f -> fmap dcText $ listToMaybe $ filter isDate (RSS1.channelDC $ RSS1.feedChannel f)
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "pubDate") e1
Nothing -> Nothing
where
isDate dc = dcElt dc == DC_Date
getFeedLastUpdate :: FeedGetter (String)
getFeedLastUpdate ft =
case ft of
Feed.AtomFeed f -> Just $ Atom.feedUpdated f
Feed.RSSFeed f -> RSS.rssPubDate (RSS.rssChannel f)
Feed.RSS1Feed f -> fmap dcText $ listToMaybe $ filter isDate (RSS1.channelDC $ RSS1.feedChannel f)
Feed.XMLFeed f ->
case findElement (unqual "channel") f of
Just e1 -> fmap XML.strContent $ findElement (unqual "pubDate") e1
Nothing -> Nothing
where
isDate dc = dcElt dc == DC_Date
getFeedDate :: FeedGetter DateString
getFeedDate ft = getFeedPubDate ft
getFeedLogoLink :: FeedGetter URLString
getFeedLogoLink ft =
case ft of
Feed.AtomFeed f -> Atom.feedLogo f
Feed.RSSFeed f -> fmap RSS.rssImageURL (RSS.rssImage $ RSS.rssChannel f)
Feed.RSS1Feed f -> (fmap RSS1.imageURI $ RSS1.feedImage f)
Feed.XMLFeed f -> do
ch <- findElement (unqual "channel") f
e1 <- findElement (unqual "image") ch
v <- findElement (unqual "url") e1
return (XML.strContent v)
getFeedLanguage :: FeedGetter String
getFeedLanguage ft =
case ft of
Feed.AtomFeed f ->
lookupAttr (unqual "lang"){qPrefix=Just "xml"} (Atom.feedAttrs f)
Feed.RSSFeed f -> RSS.rssLanguage (RSS.rssChannel f)
Feed.RSS1Feed f -> fmap dcText $ listToMaybe $ filter isLang (RSS1.channelDC $ RSS1.feedChannel f)
Feed.XMLFeed f -> do
ch <- findElement (unqual "channel") f
e1 <- findElement (unqual "language") ch
return (XML.strContent e1)
where
isLang dc = dcElt dc == DC_Language
getFeedCategories :: Feed.Feed -> [(String, Maybe String)]
getFeedCategories ft =
case ft of
Feed.AtomFeed f -> map (\ c -> (Atom.catTerm c, Atom.catScheme c)) (Atom.feedCategories f)
Feed.RSSFeed f -> map (\ c -> (RSS.rssCategoryValue c, RSS.rssCategoryDomain c)) (RSS.rssCategories (RSS.rssChannel f))
Feed.RSS1Feed f ->
case filter isCat (RSS1.channelDC $ RSS1.feedChannel f) of
ls -> map (\ l -> (dcText l,Nothing)) ls
Feed.XMLFeed f ->
case fromMaybe [] $ fmap (XML.findElements (XML.unqual "category")) (findElement (unqual "channel") f) of
ls -> map (\ l -> (fromMaybe "" (fmap XML.strContent $ findElement (unqual "term") l), findAttr (unqual "domain") l)) ls
where
isCat dc = dcElt dc == DC_Subject
getFeedGenerator :: FeedGetter String
getFeedGenerator ft =
case ft of
Feed.AtomFeed f -> do
gen <- Atom.feedGenerator f
Atom.genURI gen
Feed.RSSFeed f -> RSS.rssGenerator (RSS.rssChannel f)
Feed.RSS1Feed f -> fmap dcText $ listToMaybe $ filter isSource (RSS1.channelDC (RSS1.feedChannel f))
Feed.XMLFeed f -> do
ch <- findElement (unqual "channel") f
e1 <- findElement (unqual "generator") ch
return (XML.strContent e1)
where
isSource dc = dcElt dc == DC_Source
type ItemGetter a = Feed.Item -> Maybe a
getItemTitle :: ItemGetter String
getItemTitle it =
case it of
Feed.AtomItem i -> Just (contentToStr $ Atom.entryTitle i)
Feed.RSSItem i -> RSS.rssItemTitle i
Feed.RSS1Item i -> Just (RSS1.itemTitle i)
Feed.XMLItem e -> fmap XML.strContent $ findElement (unqual "title") e
getItemLink :: ItemGetter String
getItemLink it =
case it of
-- look up the 'alternate' HTML link relation on the entry, or one
-- without link relation since that is equivalent to 'alternate':
Feed.AtomItem i -> fmap Atom.linkHref $ listToMaybe $ filter isSelf $ Atom.entryLinks i
Feed.RSSItem i -> RSS.rssItemLink i
Feed.RSS1Item i -> Just (RSS1.itemLink i)
Feed.XMLItem i -> fmap (\ ei -> XML.strContent ei) $ findElement (unqual "link") i
where
isSelf lr =
let rel = Atom.linkRel lr
in (isNothing rel || toStr rel == "alternate") && isHTMLType (linkType lr)
isHTMLType (Just str) = "lmth" `isPrefixOf` (reverse str)
isHTMLType _ = True -- if none given, assume html.
-- | 'getItemPublishDate item' returns the publication date of the item,
-- but first parsed per the supported RFC 822 and RFC 3339 formats.
--
-- If the date string cannot be parsed as such, Just Nothing is
-- returned. The caller must then instead fall back to processing the
-- date string from 'getItemPublishDateString'.
--
-- The parsed date representation is one of the ParseTime instances;
-- see 'Data.Time.Format'.
getItemPublishDate :: ParseTime t => ItemGetter (Maybe t)
getItemPublishDate it = do
ds <- getItemPublishDateString it
let
rfc3339DateFormat1 = iso8601DateFormat (Just "%H:%M:%S%Z")
rfc3339DateFormat2 = iso8601DateFormat (Just "%H:%M:%S%Q%Z")
formats = [ rfc3339DateFormat1, rfc3339DateFormat2, rfc822DateFormat ]
date = foldl1 mplus (map (\ fmt -> parseTime defaultTimeLocale fmt ds) formats)
return date
where
#if MIN_VERSION_time(1,5,0)
parseTime = F.parseTimeM True
#else
parseTime = F.parseTime
#endif
getItemPublishDateString :: ItemGetter DateString
getItemPublishDateString it =
case it of
Feed.AtomItem i -> Just $ Atom.entryUpdated i
Feed.RSSItem i -> RSS.rssItemPubDate i
Feed.RSS1Item i -> fmap dcText $ listToMaybe $ filter isDate $ RSS1.itemDC i
-- ToDo: look for it in Atom \/ RSS1 like-content as well if no 'pubDate' element.
Feed.XMLItem e -> fmap XML.strContent $ findElement (unqual "pubDate") e
where
isDate dc = dcElt dc == DC_Date
getItemDate :: ItemGetter DateString
getItemDate it = getItemPublishDateString it
-- | 'getItemAuthor f' returns the optional author of the item.
getItemAuthor :: ItemGetter String
getItemAuthor it =
case it of
Feed.AtomItem i -> fmap Atom.personName $ listToMaybe $ Atom.entryAuthors i
Feed.RSSItem i -> RSS.rssItemAuthor i
Feed.RSS1Item i -> fmap dcText $ listToMaybe $ filter isAuthor $ RSS1.itemDC i
Feed.XMLItem e -> fmap XML.strContent $ findElement (unqual "author") e
where
isAuthor dc = dcElt dc == DC_Creator
getItemCommentLink :: ItemGetter URLString
getItemCommentLink it =
case it of
-- look up the 'replies' HTML link relation on the entry:
Feed.AtomItem e -> fmap Atom.linkHref $ listToMaybe $ filter isReplies $ Atom.entryLinks e
Feed.RSSItem i -> RSS.rssItemComments i
Feed.RSS1Item i -> fmap dcText $ listToMaybe $ filter isRel $ RSS1.itemDC i
Feed.XMLItem i -> fmap (\ ei -> XML.strContent ei) $ findElement (unqual "comments") i
where
isReplies lr = toStr (Atom.linkRel lr) == "replies"
isRel dc = dcElt dc == DC_Relation
getItemEnclosure :: ItemGetter (String, Maybe String, Maybe Integer)
getItemEnclosure it =
case it of
Feed.AtomItem e ->
case filter isEnc $ Atom.entryLinks e of
(l:_) -> Just (Atom.linkHref l,
Atom.linkType l,
readLength (Atom.linkLength l))
_ -> Nothing
Feed.RSSItem i ->
fmap (\ e -> (RSS.rssEnclosureURL e, Just (RSS.rssEnclosureType e), RSS.rssEnclosureLength e))
(RSS.rssItemEnclosure i)
Feed.RSS1Item i ->
case RSS1.itemContent i of
[] -> Nothing
(c:_) -> Just (fromMaybe "" (RSS1.contentURI c), RSS1.contentFormat c, Nothing)
Feed.XMLItem e -> fmap xmlToEnclosure (findElement (unqual "enclosure") e)
where
isEnc lr = toStr (Atom.linkRel lr) == "enclosure"
readLength Nothing = Nothing
readLength (Just str) =
case reads str of
[] -> Nothing
((v,_):_) -> Just v
xmlToEnclosure e =
( fromMaybe "" (findAttr (unqual "url") e)
, findAttr (unqual "type") e
, readLength $ findAttr (unqual "length") e
)
getItemFeedLink :: ItemGetter URLString
getItemFeedLink it =
case it of
Feed.AtomItem e ->
case (Atom.entrySource e) of
Nothing -> Nothing
Just s -> Atom.sourceId s
Feed.RSSItem i ->
case (RSS.rssItemSource i) of
Nothing -> Nothing
Just s -> Just (RSS.rssSourceURL s)
Feed.RSS1Item _ -> Nothing
Feed.XMLItem e ->
case findElement (unqual "source") e of
Nothing -> Nothing
Just s -> fmap XML.strContent (findElement (unqual "url") s)
getItemId :: ItemGetter (Bool,String)
getItemId it =
case it of
Feed.AtomItem e -> Just (True, Atom.entryId e)
Feed.RSSItem i ->
case RSS.rssItemGuid i of
Nothing -> Nothing
Just ig -> Just (fromMaybe True (RSS.rssGuidPermanentURL ig), RSS.rssGuidValue ig)
Feed.RSS1Item i ->
case filter isId (RSS1.itemDC i) of
(l:_) -> Just (True,dcText l)
_ -> Nothing
Feed.XMLItem e ->
fmap (\ e1 -> (True,XML.strContent e1)) (findElement (unqual "guid") e)
where
isId dc = dcElt dc == DC_Identifier
getItemCategories :: Feed.Item -> [String]
getItemCategories it =
case it of
Feed.AtomItem i -> map Atom.catTerm $ Atom.entryCategories i
Feed.RSSItem i -> map RSS.rssCategoryValue $ RSS.rssItemCategories i
Feed.RSS1Item i -> concat $ getCats1 i
Feed.XMLItem i -> map XML.strContent $ XML.findElements (XML.unqual "category") i
where
-- get RSS1 categories; either via DublinCore's subject (or taxonomy topics...not yet.)
getCats1 i1 =
map (words.dcText) $ filter (\ dc -> dcElt dc == DC_Subject) $ RSS1.itemDC i1
getItemRights :: ItemGetter String
getItemRights it =
case it of
Feed.AtomItem e -> fmap contentToStr $ Atom.entryRights e
Feed.RSSItem _ -> Nothing
Feed.RSS1Item i -> fmap dcText $ listToMaybe $ filter isRights (RSS1.itemDC i)
Feed.XMLItem _ -> Nothing
where
isRights dc = dcElt dc == DC_Rights
getItemSummary :: ItemGetter String
getItemSummary it = getItemDescription it
getItemDescription :: ItemGetter String
getItemDescription it =
case it of
Feed.AtomItem e -> fmap contentToStr $ Atom.entrySummary e
Feed.RSSItem e -> RSS.rssItemDescription e
Feed.RSS1Item i -> itemDesc i
Feed.XMLItem _ -> Nothing
-- strip away
toStr :: Maybe (Either String String) -> String
toStr Nothing = ""
toStr (Just (Left x)) = x
toStr (Just (Right x)) = x
contentToStr :: TextContent -> String
contentToStr x =
case x of
Atom.TextString s -> s
Atom.HTMLString s -> s
Atom.XHTMLString s -> XML.strContent s
|
danfran/feed
|
src/Text/Feed/Query.hs
|
bsd-3-clause
| 16,667 | 0 | 20 | 4,016 | 5,100 | 2,496 | 2,604 | 334 | 8 |
{-# LANGUAGE QuasiQuotes #-}
import LiquidHaskell
import qualified Data.Set as S
[lq| measure keys |]
keys :: (Ord k) => [(k, v)] -> S.Set k
keys [] = S.empty
keys (kv:kvs) = (S.singleton (myfst kv)) `S.union` (keys kvs)
[lq| measure myfst |]
myfst :: (a, b) -> a
myfst (x, _) = x
-- this is fine
[lq| measure okeys :: [(a, b)] -> (S.Set a)
okeys ([]) = (Set_empty 0)
okeys (kv:kvs) = (Set_cup (Set_sng (fst kv)) (okeys kvs))
|]
|
spinda/liquidhaskell
|
tests/gsoc15/unknown/pos/Keys.hs
|
bsd-3-clause
| 459 | 0 | 9 | 111 | 151 | 89 | 62 | 11 | 1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
module Dhall.Test.Tutorial where
import qualified Data.Vector
import qualified Dhall
import qualified Dhall.Test.Substitution as Substitution
import qualified Dhall.Test.Util as Util
import qualified Test.Tasty
import qualified Test.Tasty.HUnit
import Data.Text (Text)
import Dhall (ToDhall)
import GHC.Generics (Generic)
import Numeric.Natural (Natural)
import Test.Tasty (TestTree)
import Test.Tasty.HUnit ((@?=))
tests :: TestTree
tests =
Test.Tasty.testGroup "tutorial"
[ Test.Tasty.testGroup "Interpolation"
[ _Interpolation_0
, _Interpolation_1
]
, Test.Tasty.testGroup "Functions"
[ _Functions_0
, _Functions_1
, _Functions_2
]
, Test.Tasty.testGroup "Unions"
[ example 0 "./tests/tutorial/unions0A.dhall" "./tests/tutorial/unions0B.dhall"
, example 1 "./tests/tutorial/unions1A.dhall" "./tests/tutorial/unions1B.dhall"
, example 3 "./tests/tutorial/unions3A.dhall" "./tests/tutorial/unions3B.dhall"
, example 4 "./tests/tutorial/unions4A.dhall" "./tests/tutorial/unions4B.dhall"
]
, Test.Tasty.testGroup "Substitutions"
[ Test.Tasty.HUnit.testCase "substitution1.dhall" $ do
res <- Substitution.substituteResult "tests/tutorial/substitution1.dhall"
res @?= Substitution.Failure 1
, Test.Tasty.HUnit.testCase "substitution2.dhall" $ do
res <- Substitution.substituteResult "tests/tutorial/substitution2.dhall"
res @?= Substitution.Failure 1
, Test.Tasty.HUnit.testCase "substitution3.dhall" $ do
res <- Substitution.substituteFoo "tests/tutorial/substitution3.dhall"
res @?= True
]
]
_Interpolation_0 :: TestTree
_Interpolation_0 = Test.Tasty.HUnit.testCase "Example #0" (do
e <- Util.code
" let name = \"John Doe\" \n\
\in let age = 21 \n\
\in \"My name is ${name} and my age is ${Natural/show age}\"\n"
Util.assertNormalizesTo e "\"My name is John Doe and my age is 21\"" )
_Interpolation_1 :: TestTree
_Interpolation_1 = Test.Tasty.HUnit.testCase "Example #1" (do
e <- Util.code
"''\n\
\ for file in *; do \n\
\ echo \"Found ''${file}\"\n\
\ done \n\
\'' \n"
Util.assertNormalized e )
_Functions_0 :: TestTree
_Functions_0 = Test.Tasty.HUnit.testCase "Example #0" (do
let text = "\\(n : Bool) -> [ n && True, n && False, n || True, n || False ]"
makeBools <- Dhall.input Dhall.auto text
makeBools True @?= Data.Vector.fromList [True,False,True,True] )
_Functions_1 :: TestTree
_Functions_1 = Test.Tasty.HUnit.testCase "Example #1" (do
let text = "λ(x : Bool) → λ(y : Bool) → x && y"
makeBools <- Dhall.input Dhall.auto text
makeBools True False @?= False )
data Example0 = Example0 { foo :: Bool, bar :: Bool }
deriving (Generic, ToDhall)
_Functions_2 :: TestTree
_Functions_2 = Test.Tasty.HUnit.testCase "Example #2" (do
f <- Dhall.input Dhall.auto "λ(r : { foo : Bool, bar : Bool }) → r.foo && r.bar"
f (Example0 { foo = True, bar = False }) @?= False
f (Example0 { foo = True, bar = True }) @?= True )
example :: Natural -> Text -> Text -> TestTree
example n text0 text1 =
Test.Tasty.HUnit.testCase
("Example #" <> show n)
(Util.equivalent text0 text1)
|
Gabriel439/Haskell-Dhall-Library
|
dhall/tests/Dhall/Test/Tutorial.hs
|
bsd-3-clause
| 3,748 | 0 | 14 | 1,068 | 740 | 402 | 338 | 73 | 1 |
import Cookbook.Essential.IO
import Cookbook.Project.Configuration.Configuration
import System.IO
import System.Directory
import System.Environment
main = do
(a:_) <- getArgs
fullpath <- getHomePath "/.alias/aliases"
b <- filelines fullpath
putStrLn (conf b a)
|
natepisarski/WriteUtils
|
espion.hs
|
bsd-3-clause
| 271 | 0 | 9 | 38 | 82 | 42 | 40 | 10 | 1 |
{-# LANGUAGE MultiParamTypeClasses, DeriveDataTypeable,
FlexibleInstances, UndecidableInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Security.InfoFlow.Policy.Paralocks
-- Copyright : (c) Niklas Broberg 2013
-- License : BSD-style (see the file LICENSE.txt)
--
-- Maintainer : Niklas Broberg, [email protected]
-- Stability : transient
-- Portability : portable
--
-- This module provides a concrete instantiation of the
-- Flow Locks Framework, in the form of the Paralocks
-- language, as presented in Broberg & Sands,
-- "Paralocks - Role-Based Information Flow Control and Beyond",
-- POPL'10.
--
-----------------------------------------------------------------------------
module Security.InfoFlow.Policy.Paralocks where
import Security.InfoFlow.Policy.FlowLocks
import Data.Generics (Data, Typeable)
import Control.Applicative
-- $story
-- In order to provide a complete language,
-- Paralocks needs to provide concrete
-- representations for:
-- * Actors, here being a concrete data type
-- * Actor sets, here being either singleton
-- actors or the set of all actors.
{----------------------------------------}
{- Actor identity representation -}
{----------------------------------------}
-- | 'ActorIdentity' are approximations of actual
-- identities of actors, to the best of our
-- knowledge.
data ActorIdentity
= Fresh Int
-- ^ We know the identity.
| Unknown Int [Int]
-- ^ We don't know the identity, but know it
-- to be one of the listed ones.
deriving (Show, Data, Typeable)
instance Eq ActorIdentity where
Fresh i == Fresh j = i == j
Unknown i _ == Unknown j _ = i == j
_ == _ = False
instance ActorId ActorIdentity where
Unknown i is `mayEq` Unknown j js =
or [ x == y | x <- (i:is), y <- (j:js) ]
Unknown _ is `mayEq` Fresh j = j `elem` is
Fresh i `mayEq` Unknown _ js = i `elem` js
Fresh i `mayEq` Fresh j = i == j
{----------------------------------------}
{- Actor set representation -}
{----------------------------------------}
-- | In Paralocks, an actor representation
-- can either mention a concrete actor,
-- or be a quantified variable representing
-- any actor. We also include a distinguished
-- 'top' element, which is one of the
-- requirements (must form a join semi-lattice).
data ActorSetRep aid
= SingletonActor aid
| AnyActor
| NoActor
deriving (Eq, Show, Data, Typeable)
instance (Functor m, Monad m, Applicative m, ActorId aid) =>
PartialOrder m (ActorSetRep aid) where
AnyActor `leq` _ = return True
SingletonActor aid1 `leq` SingletonActor aid2 = return $
aid1 == aid2
_ `leq` NoActor = return True
_ `leq` _ = return False
instance (Functor m, Monad m, Applicative m, ActorId aid) =>
JoinSemiLattice m (ActorSetRep aid) where
topM = return NoActor
NoActor `lub` _ = return NoActor
_ `lub` NoActor = return NoActor
AnyActor `lub` a = return a
a `lub` AnyActor = return a
SingletonActor aid1 `lub` SingletonActor aid2
| aid1 == aid2 = return $ SingletonActor aid1
| otherwise = return NoActor
instance (Functor m, Monad m, Applicative m, ActorId aid) =>
Lattice m (ActorSetRep aid) where
bottomM = return AnyActor
NoActor `glb` a = return a
a `glb` NoActor = return a
AnyActor `glb` _a = return AnyActor
_a `glb` AnyActor = return AnyActor
SingletonActor aid1 `glb` SingletonActor aid2
| aid1 == aid2 = return $ SingletonActor aid1
| otherwise = return AnyActor
instance (Functor m, Monad m, Applicative m, ActorId aid) =>
ActorSet m (ActorSetRep aid) aid where
inSet aid1 (SingletonActor aid2) = return $ aid1 == aid2
inSet _aid AnyActor = return True
inSet _aid NoActor = return False
enumSetMembers (SingletonActor aid) = return $ Just [aid]
enumSetMembers AnyActor = return Nothing
enumSetMembers NoActor = return $ Just []
-- This gives us, for free, the following instances:
--
-- instance (Ord name, Functor m, Monad m) =>
-- Containment m (XPolicy name ActorSetRep)
-- name ActorSetRep ActorId
--
-- where XPolicy \in { Policy, VarPolicy, MetaPolicy }
|
niklasbroberg/flowlocks-framework
|
src/Security/InfoFlow/Policy/Paralocks.hs
|
bsd-3-clause
| 4,406 | 0 | 11 | 1,046 | 956 | 504 | 452 | 60 | 0 |
module Platform.Run32 where
import System.IO
import System.Environment
import System.Exit
import Data.Int
import Data.List
import Data.Word
import Utility.Utility
import Spec.Machine
import Platform.Minimal32
import Platform.MMIO
import Utility.Elf
import qualified Spec.CSRField as Field
import Spec.CSRFile
import Spec.Decode
import Spec.Execute
import Utility.MapMemory
import Control.Monad.Trans
import Control.Monad.Trans.State
import qualified Data.Map as S
import Debug.Trace
import Numeric (showHex, readHex)
processLine :: String -> (Int, [(Int, Word8)]) -> (Int, [(Int, Word8)])
processLine ('@':xs) (p, l) = ((fst $ head $ readHex xs) * 4, l)
processLine s (p, l) = (p + 4, l ++ (zip [p..] $ splitWord (fst $ head $ readHex s :: Word32)))
readHexFile :: FilePath -> IO [(Int, Word8)]
readHexFile f = do
h <- openFile f ReadMode
helper h (0, [])
where helper h l = do
s <- hGetLine h
done <- hIsEOF h
if (null s)
then return $ snd l
else if done
then return $ snd $ processLine s l
else helper h (processLine s l)
checkInterrupt :: IO Bool
checkInterrupt = do
ready <- hReady stdin
if ready then do
c <- hLookAhead stdin
if c == '!' then do
_ <- getChar
_ <- getChar
return True
else return False
else return False
helper :: Maybe Int32 -> IOState Minimal32 Int32
helper maybeToHostAddress = do
toHostValue <- case maybeToHostAddress of
Nothing -> return 0 -- default value
Just toHostAddress -> loadWord Execute toHostAddress
if toHostValue /= 0
then do
-- quit running
if toHostValue == 1
then trace "PASSED" (return 0)
else trace ("FAILED " ++ (show $ quot toHostValue 2)) (return 1)
else do
pc <- getPC
inst <- loadWord Fetch pc
if inst == 0x6f -- Stop on infinite loop instruction.
then do
cycles <- getCSRField Field.MCycle
trace ("Cycles: " ++ show cycles) (return ())
instret <- getCSRField Field.MInstRet
trace ("Insts: " ++ show instret) (return ())
getRegister 10
else do
setPC (pc + 4)
pc <- getPC
execute (decode RV32IM $ (fromIntegral:: Int32 -> MachineInt) inst)
interrupt <- liftIO checkInterrupt
if interrupt then do
-- Signal interrupt by setting MEIP high.
setCSRField Field.MEIP 1
else return ()
commit
helper maybeToHostAddress
runProgram :: Maybe Int32 -> Minimal32 -> IO (Int32, Minimal32)
runProgram maybeToHostAddress = runStateT (helper maybeToHostAddress)
readProgram :: String -> IO (Maybe Int32, [(Int, Word8)])
readProgram f = do
if ".hex" `isSuffixOf` f
then do
mem <- readHexFile f
return (Nothing, mem)
else do
mem <- readElf f
maybeToHostAddress <- readElfSymbol "tohost" f
return (fmap (fromIntegral:: Word64 -> Int32) maybeToHostAddress, mem)
runFile :: String -> IO Int32
runFile f = do
(maybeToHostAddress, mem) <- readProgram f
let c = Minimal32 { registers = (take 31 $ repeat 0),
csrs = (resetCSRFile 32),
pc = (fromIntegral:: Word32 -> Int32) (0x80000000 :: Word32),
nextPC = 0,
privMode = Machine,
mem = MapMemory { bytes = S.fromList mem, reservation = Nothing } } in
fmap fst $ runProgram maybeToHostAddress c
runFiles :: [String] -> IO Int32
runFiles (file:files) = do
myreturn <- runFile file
putStr (file ++ ": " ++ (show myreturn) ++ "\n")
othersreturn <- runFiles files
if myreturn /= 0
then return myreturn
else return othersreturn
runFiles [] = return 0
main :: IO ()
main = do
args <- getArgs
retval <- case args of
[] -> do
putStr "ERROR: this program expects one or more elf files as command-line arguments\n"
return 1
[file] -> runFile file
files -> runFiles files
exitWith (if retval == 0 then ExitSuccess else ExitFailure $ (fromIntegral:: Int32 -> Int) retval)
|
mit-plv/riscv-semantics
|
src/Platform/Run32.hs
|
bsd-3-clause
| 4,105 | 0 | 18 | 1,149 | 1,403 | 716 | 687 | 119 | 6 |
import Distribution.PackageDescription
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo
import System.FilePath
import System.Process (system)
main :: IO ()
main = defaultMainWithHooks autoconfUserHooks
|
mainland/nikola
|
Setup.hs
|
bsd-3-clause
| 223 | 0 | 6 | 20 | 50 | 28 | 22 | 7 | 1 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE GADTs #-}
module Data.Type.Length.Quote
( qL
) where
import Data.Type.Length
import Data.Type.Quote
import Language.Haskell.TH
import Language.Haskell.TH.Quote
qL :: QuasiQuoter
qL = QuasiQuoter
{ quoteExp = parseAsNatTerm qq varE [|LZ|] $ \x -> [|LS $x|]
, quotePat = parseAsNatTerm qq varP [p|LZ|] $ \x -> [p|LS $x|]
, quoteType = stub qq "quoteType"
, quoteDec = stub qq "quoteDec"
}
where
qq = "qL"
|
kylcarte/type-combinators-quote
|
src/Data/Type/Length/Quote.hs
|
bsd-3-clause
| 926 | 0 | 8 | 155 | 153 | 103 | 50 | 29 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Files.Digest where
import Control.Monad ((>=>))
import Crypto.Hash
import Data.Aeson
import qualified Data.ByteString.Lazy as Lazy
import Data.Foldable
import qualified Data.Map.Strict as M
import Data.Monoid ((<>))
import Data.Tree
import System.Directory
import System.FilePath ((</>))
import Files.Tree
import Settings.Monad.Exception
newtype FSDigestTree = FSDigestTree { unFSDigestTree :: Tree (FilePath, String) }
deriving (Eq, Show)
instance ToJSON FSDigestTree where
toJSON (FSDigestTree (Node (path, sha) nodes)) =
object ["filename" .= path, "sha1_digest" .= sha,
"childrens" .= map (toJSON . FSDigestTree) nodes]
toEncoding (FSDigestTree (Node (path, sha) nodes)) =
pairs ("filename" .= path <> "sha1_digest" .= sha <>
"childrens" .= map (toJSON . FSDigestTree) nodes)
getSha1 :: FilePath -> IO String
getSha1 path = do
isFile <- doesFileExist path
if isFile
then do
file <- Lazy.readFile path
return $ show $ hashLazyAlgo file
else return ""
where
hashLazyAlgo :: Lazy.ByteString -> Digest SHA1
hashLazyAlgo = hashlazy
unfoldDirectoryTree :: MonadIO m => FilePath -> m (Tree FilePath)
unfoldDirectoryTree = unfoldTreeM $ \path -> do
isDir <- liftIO $ doesDirectoryExist path
subDirs <- liftIO $ if isDir then listDirectory path else return []
return (path, subDirs)
zipFilePathWithSha1 :: MonadIO m => Tree FilePath -> m FSDigestTree
zipFilePathWithSha1 = fmap FSDigestTree
. liftIO . traverseTreeFoldPar (</>) mapF ""
where
mapF parent this = let full = parent </> this in (,) full <$> liftIO (getSha1 full)
generateDigestOutput :: FilePath -> IO Lazy.ByteString
generateDigestOutput = fmap encode . (unfoldDirectoryTree >=> zipFilePathWithSha1)
generateDigestDict :: FilePath -> IO (M.Map FilePath String)
generateDigestDict path = do
fsTree <- unfoldDirectoryTree path
fsDigestTree <- zipFilePathWithSha1 fsTree
return $ M.fromList $ toList $ unFSDigestTree fsDigestTree
|
Evan-Zhao/FastCanvas
|
src/Files/Digest.hs
|
bsd-3-clause
| 2,252 | 0 | 13 | 586 | 647 | 339 | 308 | 49 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE ViewPatterns #-}
-- | Functionality for downloading packages securely for cabal's usage.
module Stack.Fetch
( unpackPackages
, unpackPackageIdents
, fetchPackages
, resolvePackages
, resolvePackagesAllowMissing
, ResolvedPackage (..)
, withCabalFiles
, withCabalLoader
) where
import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Check as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import Codec.Compression.GZip (decompress)
import Control.Applicative
import Control.Concurrent.Async (Concurrently (..))
import Control.Concurrent.MVar.Lifted (modifyMVar, newMVar)
import Control.Concurrent.STM (TVar, atomically, modifyTVar,
newTVarIO, readTVar,
readTVarIO, writeTVar)
import Control.Exception (assert)
import Control.Monad (join, liftM, unless, void,
when)
import Control.Monad.Catch
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Reader (asks, runReaderT)
import Control.Monad.Trans.Control
import "cryptohash" Crypto.Hash (SHA512 (..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Data.Either (partitionEithers)
import qualified Data.Foldable as F
import Data.Function (fix)
import Data.IORef (newIORef, readIORef,
writeIORef)
import Data.List (intercalate)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NE
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (maybeToList, catMaybes)
import Data.Monoid ((<>))
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Typeable (Typeable)
import Data.Word (Word64)
import Network.HTTP.Download
import Path
import Path.IO
import Prelude -- Fix AMP warning
import Stack.GhcPkg
import Stack.PackageIndex
import Stack.Types
import qualified System.Directory as D
import System.FilePath ((<.>))
import qualified System.FilePath as FP
import System.IO (IOMode (ReadMode),
SeekMode (AbsoluteSeek), hSeek,
withBinaryFile)
import System.PosixCompat (setFileMode)
import Text.EditDistance as ED
type PackageCaches = Map PackageIdentifier (PackageIndex, PackageCache)
data FetchException
= Couldn'tReadIndexTarball FilePath Tar.FormatError
| Couldn'tReadPackageTarball FilePath SomeException
| UnpackDirectoryAlreadyExists (Set FilePath)
| CouldNotParsePackageSelectors [String]
| UnknownPackageNames (Set PackageName)
| UnknownPackageIdentifiers (Set PackageIdentifier) String
deriving Typeable
instance Exception FetchException
instance Show FetchException where
show (Couldn'tReadIndexTarball fp err) = concat
[ "There was an error reading the index tarball "
, fp
, ": "
, show err
]
show (Couldn'tReadPackageTarball fp err) = concat
[ "There was an error reading the package tarball "
, fp
, ": "
, show err
]
show (UnpackDirectoryAlreadyExists dirs) = unlines
$ "Unable to unpack due to already present directories:"
: map (" " ++) (Set.toList dirs)
show (CouldNotParsePackageSelectors strs) =
"The following package selectors are not valid package names or identifiers: " ++
intercalate ", " strs
show (UnknownPackageNames names) =
"The following packages were not found in your indices: " ++
intercalate ", " (map packageNameString $ Set.toList names)
show (UnknownPackageIdentifiers idents suggestions) =
"The following package identifiers were not found in your indices: " ++
intercalate ", " (map packageIdentifierString $ Set.toList idents) ++
(if null suggestions then "" else "\n" ++ suggestions)
-- | Fetch packages into the cache without unpacking
fetchPackages :: (MonadIO m, MonadBaseControl IO m, MonadReader env m, HasHttpManager env, HasConfig env, MonadThrow m, MonadLogger m, MonadCatch m)
=> EnvOverride
-> Set PackageIdentifier
-> m ()
fetchPackages menv idents = do
resolved <- resolvePackages menv idents Set.empty
ToFetchResult toFetch alreadyUnpacked <- getToFetch Nothing resolved
assert (Map.null alreadyUnpacked) (return ())
nowUnpacked <- fetchPackages' Nothing toFetch
assert (Map.null nowUnpacked) (return ())
-- | Intended to work for the command line command.
unpackPackages :: (MonadIO m, MonadBaseControl IO m, MonadReader env m, HasHttpManager env, HasConfig env, MonadThrow m, MonadLogger m, MonadCatch m)
=> EnvOverride
-> FilePath -- ^ destination
-> [String] -- ^ names or identifiers
-> m ()
unpackPackages menv dest input = do
dest' <- resolveDir' dest
(names, idents) <- case partitionEithers $ map parse input of
([], x) -> return $ partitionEithers x
(errs, _) -> throwM $ CouldNotParsePackageSelectors errs
resolved <- resolvePackages menv (Set.fromList idents) (Set.fromList names)
ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just dest') resolved
unless (Map.null alreadyUnpacked) $
throwM $ UnpackDirectoryAlreadyExists $ Set.fromList $ map toFilePath $ Map.elems alreadyUnpacked
unpacked <- fetchPackages' Nothing toFetch
F.forM_ (Map.toList unpacked) $ \(ident, dest'') -> $logInfo $ T.pack $ concat
[ "Unpacked "
, packageIdentifierString ident
, " to "
, toFilePath dest''
]
where
-- Possible future enhancement: parse names as name + version range
parse s =
case parsePackageNameFromString s of
Right x -> Right $ Left x
Left _ ->
case parsePackageIdentifierFromString s of
Left _ -> Left s
Right x -> Right $ Right x
-- | Ensure that all of the given package idents are unpacked into the build
-- unpack directory, and return the paths to all of the subdirectories.
unpackPackageIdents
:: (MonadBaseControl IO m, MonadIO m, MonadReader env m, HasHttpManager env, HasConfig env, MonadThrow m, MonadLogger m, MonadCatch m)
=> EnvOverride
-> Path Abs Dir -- ^ unpack directory
-> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157
-> Set PackageIdentifier
-> m (Map PackageIdentifier (Path Abs Dir))
unpackPackageIdents menv unpackDir mdistDir idents = do
resolved <- resolvePackages menv idents Set.empty
ToFetchResult toFetch alreadyUnpacked <- getToFetch (Just unpackDir) resolved
nowUnpacked <- fetchPackages' mdistDir toFetch
return $ alreadyUnpacked <> nowUnpacked
data ResolvedPackage = ResolvedPackage
{ rpCache :: !PackageCache
, rpIndex :: !PackageIndex
}
-- | Resolve a set of package names and identifiers into @FetchPackage@ values.
resolvePackages :: (MonadIO m, MonadReader env m, HasHttpManager env, HasConfig env, MonadLogger m, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride
-> Set PackageIdentifier
-> Set PackageName
-> m (Map PackageIdentifier ResolvedPackage)
resolvePackages menv idents0 names0 = do
eres <- go
case eres of
Left _ -> do
updateAllIndices menv
go >>= either throwM return
Right x -> return x
where
go = r <$> resolvePackagesAllowMissing idents0 names0
r (missingNames, missingIdents, idents)
| not $ Set.null missingNames = Left $ UnknownPackageNames missingNames
| not $ Set.null missingIdents = Left $ UnknownPackageIdentifiers missingIdents ""
| otherwise = Right idents
resolvePackagesAllowMissing
:: (MonadIO m, MonadReader env m, HasHttpManager env, HasConfig env, MonadLogger m, MonadThrow m, MonadBaseControl IO m, MonadCatch m)
=> Set PackageIdentifier
-> Set PackageName
-> m (Set PackageName, Set PackageIdentifier, Map PackageIdentifier ResolvedPackage)
resolvePackagesAllowMissing idents0 names0 = do
caches <- getPackageCaches
let versions = Map.fromListWith max $ map toTuple $ Map.keys caches
(missingNames, idents1) = partitionEithers $ map
(\name -> maybe (Left name ) (Right . PackageIdentifier name)
(Map.lookup name versions))
(Set.toList names0)
(missingIdents, resolved) = partitionEithers $ map (goIdent caches)
$ Set.toList
$ idents0 <> Set.fromList idents1
return (Set.fromList missingNames, Set.fromList missingIdents, Map.fromList resolved)
where
goIdent caches ident =
case Map.lookup ident caches of
Nothing -> Left ident
Just (index, cache) -> Right (ident, ResolvedPackage
{ rpCache = cache
, rpIndex = index
})
data ToFetch = ToFetch
{ tfTarball :: !(Path Abs File)
, tfDestDir :: !(Maybe (Path Abs Dir))
, tfUrl :: !T.Text
, tfSize :: !(Maybe Word64)
, tfSHA512 :: !(Maybe ByteString)
, tfCabal :: !ByteString
-- ^ Contents of the .cabal file
}
data ToFetchResult = ToFetchResult
{ tfrToFetch :: !(Map PackageIdentifier ToFetch)
, tfrAlreadyUnpacked :: !(Map PackageIdentifier (Path Abs Dir))
}
-- | Add the cabal files to a list of idents with their caches.
withCabalFiles
:: (MonadThrow m, MonadIO m, MonadReader env m, HasConfig env)
=> IndexName
-> [(PackageIdentifier, PackageCache, a)]
-> (PackageIdentifier -> a -> ByteString -> IO b)
-> m [b]
withCabalFiles name pkgs f = do
indexPath <- configPackageIndex name
liftIO $ withBinaryFile (toFilePath indexPath) ReadMode $ \h ->
mapM (goPkg h) pkgs
where
goPkg h (ident, pc, tf) = do
hSeek h AbsoluteSeek $ fromIntegral $ pcOffset pc
cabalBS <- S.hGet h $ fromIntegral $ pcSize pc
f ident tf cabalBS
-- | Provide a function which will load up a cabal @ByteString@ from the
-- package indices.
withCabalLoader
:: (MonadThrow m, MonadIO m, MonadReader env m, HasConfig env, MonadLogger m, HasHttpManager env, MonadBaseControl IO m, MonadCatch m)
=> EnvOverride
-> ((PackageIdentifier -> IO ByteString) -> m a)
-> m a
withCabalLoader menv inner = do
icaches <- getPackageCaches >>= liftIO . newIORef
env <- ask
-- Want to try updating the index once during a single run for missing
-- package identifiers. We also want to ensure we only update once at a
-- time
updateRef <- liftIO $ newMVar True
runInBase <- liftBaseWith $ \run -> return (void . run)
-- TODO in the future, keep all of the necessary @Handle@s open
let doLookup :: PackageIdentifier
-> IO ByteString
doLookup ident = do
cachesCurr <- liftIO $ readIORef icaches
eres <- lookupPackageIdentifierExact ident env cachesCurr
case eres of
Just bs -> return bs
-- Update the cache and try again
Nothing -> do
let fuzzy = fuzzyLookupCandidates ident cachesCurr
suggestions = case fuzzy of
Nothing ->
case typoCorrectionCandidates ident cachesCurr of
Nothing -> ""
Just cs -> "Perhaps you meant " <>
orSeparated cs <> "?"
Just cs -> "Possible candidates: " <>
commaSeparated (NE.map packageIdentifierString cs)
<> "."
join $ modifyMVar updateRef $ \toUpdate ->
if toUpdate then do
runInBase $ do
$logInfo $ T.concat
[ "Didn't see "
, T.pack $ packageIdentifierString ident
, " in your package indices.\n"
, "Updating and trying again."
]
updateAllIndices menv
clearPackageCaches
caches <- getPackageCaches
liftIO $ writeIORef icaches caches
return (False, doLookup ident)
else return (toUpdate,
throwM $ UnknownPackageIdentifiers
(Set.singleton ident) suggestions)
inner doLookup
lookupPackageIdentifierExact
:: HasConfig env
=> PackageIdentifier
-> env
-> PackageCaches
-> IO (Maybe ByteString)
lookupPackageIdentifierExact ident env caches =
case Map.lookup ident caches of
Nothing -> return Nothing
Just (index, cache) -> do
[bs] <- flip runReaderT env
$ withCabalFiles (indexName index) [(ident, cache, ())]
$ \_ _ bs -> return bs
return $ Just bs
-- | Given package identifier and package caches, return list of packages
-- with the same name and the same two first version number components found
-- in the caches.
fuzzyLookupCandidates
:: PackageIdentifier
-> PackageCaches
-> Maybe (NonEmpty PackageIdentifier)
fuzzyLookupCandidates (PackageIdentifier name ver) caches =
let (_, zero, bigger) = Map.splitLookup zeroIdent caches
zeroIdent = PackageIdentifier name $(mkVersion "0.0")
sameName (PackageIdentifier n _) = n == name
sameMajor (PackageIdentifier _ v) = toMajorVersion v == toMajorVersion ver
in NE.nonEmpty . filter sameMajor $ maybe [] (pure . const zeroIdent) zero
<> takeWhile sameName (Map.keys bigger)
-- | Try to come up with typo corrections for given package identifier using
-- package caches. This should be called before giving up, i.e. when
-- 'fuzzyLookupCandidates' cannot return anything.
typoCorrectionCandidates
:: PackageIdentifier
-> PackageCaches
-> Maybe (NonEmpty String)
typoCorrectionCandidates ident =
let getName = packageNameString . packageIdentifierName
name = getName ident
in NE.nonEmpty
. Map.keys
. Map.filterWithKey (const . (== 1) . damerauLevenshtein name)
. Map.mapKeys getName
-- | Figure out where to fetch from.
getToFetch :: (MonadThrow m, MonadIO m, MonadReader env m, HasConfig env)
=> Maybe (Path Abs Dir) -- ^ directory to unpack into, @Nothing@ means no unpack
-> Map PackageIdentifier ResolvedPackage
-> m ToFetchResult
getToFetch mdest resolvedAll = do
(toFetch0, unpacked) <- liftM partitionEithers $ mapM checkUnpacked $ Map.toList resolvedAll
toFetch1 <- mapM goIndex $ Map.toList $ Map.fromListWith (++) toFetch0
return ToFetchResult
{ tfrToFetch = Map.unions toFetch1
, tfrAlreadyUnpacked = Map.fromList unpacked
}
where
checkUnpacked (ident, resolved) = do
dirRel <- parseRelDir $ packageIdentifierString ident
let mdestDir = (</> dirRel) <$> mdest
mexists <-
case mdestDir of
Nothing -> return Nothing
Just destDir -> do
exists <- doesDirExist destDir
return $ if exists then Just destDir else Nothing
case mexists of
Just destDir -> return $ Right (ident, destDir)
Nothing -> do
let index = rpIndex resolved
d = pcDownload $ rpCache resolved
targz = T.pack $ packageIdentifierString ident ++ ".tar.gz"
tarball <- configPackageTarball (indexName index) ident
return $ Left (indexName index, [(ident, rpCache resolved, ToFetch
{ tfTarball = tarball
, tfDestDir = mdestDir
, tfUrl = case d of
Just d' -> decodeUtf8 $ pdUrl d'
Nothing -> indexDownloadPrefix index <> targz
, tfSize = fmap pdSize d
, tfSHA512 = fmap pdSHA512 d
, tfCabal = S.empty -- filled in by goIndex
})])
goIndex (name, pkgs) =
liftM Map.fromList $
withCabalFiles name pkgs $ \ident tf cabalBS ->
return (ident, tf { tfCabal = cabalBS })
-- | Download the given name,version pairs into the directory expected by cabal.
--
-- For each package it downloads, it will optionally unpack it to the given
-- @Path@ (if present). Note that unpacking is not simply a matter of
-- untarring, but also of grabbing the cabal file from the package index. The
-- destinations should not include package identifiers.
--
-- Returns the list of paths unpacked, including package identifiers. E.g.:
--
-- @
-- fetchPackages [("foo-1.2.3", Just "/some/dest")] ==> ["/some/dest/foo-1.2.3"]
-- @
--
-- Since 0.1.0.0
fetchPackages' :: (MonadIO m,MonadReader env m,HasHttpManager env,HasConfig env,MonadLogger m,MonadThrow m,MonadBaseControl IO m)
=> Maybe (Path Rel Dir) -- ^ the dist rename directory, see: https://github.com/fpco/stack/issues/157
-> Map PackageIdentifier ToFetch
-> m (Map PackageIdentifier (Path Abs Dir))
fetchPackages' mdistDir toFetchAll = do
connCount <- asks $ configConnectionCount . getConfig
outputVar <- liftIO $ newTVarIO Map.empty
runInBase <- liftBaseWith $ \run -> return (void . run)
parMapM_
connCount
(go outputVar runInBase)
(Map.toList toFetchAll)
liftIO $ readTVarIO outputVar
where
go :: (MonadIO m,Functor m,MonadThrow m,MonadLogger m,MonadReader env m,HasHttpManager env)
=> TVar (Map PackageIdentifier (Path Abs Dir))
-> (m () -> IO ())
-> (PackageIdentifier, ToFetch)
-> m ()
go outputVar runInBase (ident, toFetch) = do
req <- parseUrl $ T.unpack $ tfUrl toFetch
let destpath = tfTarball toFetch
let toHashCheck bs = HashCheck SHA512 (CheckHexDigestByteString bs)
let downloadReq = DownloadRequest
{ drRequest = req
, drHashChecks = map toHashCheck $ maybeToList (tfSHA512 toFetch)
, drLengthCheck = fromIntegral <$> tfSize toFetch
, drRetryPolicy = drRetryPolicyDefault
}
let progressSink _ =
liftIO $ runInBase $ $logInfo $ packageIdentifierText ident <> ": download"
_ <- verifiedDownload downloadReq destpath progressSink
let fp = toFilePath destpath
F.forM_ (tfDestDir toFetch) $ \destDir -> do
let dest = toFilePath $ parent destDir
innerDest = toFilePath destDir
liftIO $ ensureDir (parent destDir)
liftIO $ withBinaryFile fp ReadMode $ \h -> do
-- Avoid using L.readFile, which is more likely to leak
-- resources
lbs <- L.hGetContents h
let entries = fmap (either wrap wrap)
$ Tar.checkTarbomb identStr
$ Tar.read $ decompress lbs
wrap :: Exception e => e -> FetchException
wrap = Couldn'tReadPackageTarball fp . toException
identStr = packageIdentifierString ident
getPerms :: Tar.Entry -> (FilePath, Tar.Permissions)
getPerms e = (dest FP.</> Tar.fromTarPath (Tar.entryTarPath e),
Tar.entryPermissions e)
filePerms :: [(FilePath, Tar.Permissions)]
filePerms = catMaybes $ Tar.foldEntries (\e -> (:) (Just $ getPerms e))
[] (const []) entries
Tar.unpack dest entries
-- Reset file permissions as they were in the tarball
mapM_ (\(fp', perm) -> setFileMode
(FP.dropTrailingPathSeparator fp')
perm) filePerms
case mdistDir of
Nothing -> return ()
-- See: https://github.com/fpco/stack/issues/157
Just distDir -> do
let inner = dest FP.</> identStr
oldDist = inner FP.</> "dist"
newDist = inner FP.</> toFilePath distDir
exists <- D.doesDirectoryExist oldDist
when exists $ do
-- Previously used takeDirectory, but that got confused
-- by trailing slashes, see:
-- https://github.com/commercialhaskell/stack/issues/216
--
-- Instead, use Path which is a bit more resilient
ensureDir . parent =<< parseAbsDir newDist
D.renameDirectory oldDist newDist
let cabalFP =
innerDest FP.</>
packageNameString (packageIdentifierName ident)
<.> "cabal"
S.writeFile cabalFP $ tfCabal toFetch
atomically $ modifyTVar outputVar $ Map.insert ident destDir
parMapM_ :: (F.Foldable f,MonadIO m,MonadBaseControl IO m)
=> Int
-> (a -> m ())
-> f a
-> m ()
parMapM_ (max 1 -> 1) f xs = F.mapM_ f xs
parMapM_ cnt f xs0 = do
var <- liftIO (newTVarIO $ F.toList xs0)
-- See comment on similar line in Stack.Build
runInBase <- liftBaseWith $ \run -> return (void . run)
let worker = fix $ \loop -> join $ atomically $ do
xs <- readTVar var
case xs of
[] -> return $ return ()
x:xs' -> do
writeTVar var xs'
return $ do
runInBase $ f x
loop
workers 1 = Concurrently worker
workers i = Concurrently worker *> workers (i - 1)
liftIO $ runConcurrently $ workers cnt
damerauLevenshtein :: String -> String -> Int
damerauLevenshtein = ED.restrictedDamerauLevenshteinDistance ED.defaultEditCosts
orSeparated :: NonEmpty String -> String
orSeparated xs
| NE.length xs == 1 = NE.head xs
| NE.length xs == 2 = NE.head xs <> " or " <> NE.last xs
| otherwise = intercalate ", " (NE.init xs) <> ", or " <> NE.last xs
commaSeparated :: NonEmpty String -> String
commaSeparated = F.fold . NE.intersperse ", "
|
narrative/stack
|
src/Stack/Fetch.hs
|
bsd-3-clause
| 24,362 | 1 | 29 | 8,334 | 5,606 | 2,856 | 2,750 | 463 | 5 |
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE Rank2Types #-}
module Foreign.Function.Interface.Argument
( Argument(..)
) where
import Foreign.Ptr
import Foreign.Function.Interface.Type
import Data.Functor.Contravariant
data Argument a = forall x. Argument
{ argumentType :: !Type
, withArgument :: forall r. a -> (Ptr x -> IO r) -> IO r
}
instance Contravariant Argument where
contramap f (Argument t k) = Argument t (k . f)
|
ekmett/foreign
|
Foreign/Function/Interface/Argument.hs
|
bsd-3-clause
| 525 | 0 | 14 | 86 | 134 | 78 | 56 | 16 | 0 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecursiveDo #-}
{-# LANGUAGE TemplateHaskell #-}
module Main where
import Control.Concurrent
import Control.Event.Handler
import Control.Monad
import Reactive.Banana.Internal.Combinators
import System.Mem
main :: IO ()
main =
do (ah,tick) <- newAddHandler
network <-
compile (do render <- fromAddHandler ah
addReactimate
(applyE (mapB (\x _ ->
return (print x))
(stepperB 0 render))
render))
actuate network
performGC
tick 1
putStrLn "GC"
putStrLn "Done"
tick 2
mapM_ tick [3 .. 10]
|
ocharles/Francium
|
material/rb.hs
|
bsd-3-clause
| 875 | 0 | 21 | 286 | 187 | 96 | 91 | 31 | 1 |
module Control.Exception.CatchableRPC where
import qualified Control.Exception as B
import Control.Monad.Reader (ReaderT, runReaderT, ask, lift)
import Control.Monad.State (StateT, runStateT, get, put)
class Monad m => Catchable m where
bracket :: m a -> (a -> m b) -> (a -> m c) -> m c
instance Catchable IO where
bracket = B.bracket
instance Catchable m => Catchable (ReaderT r m) where
bracket m mf1 mf2 = do
env <- ask
lift $ bracket (runReaderT m env) (\s -> runReaderT (mf1 s) env) (\s -> runReaderT (mf2 s) env)
instance (Catchable m) => Catchable (StateT s m) where
bracket m mf1 mf2 = do
st <- get
(a,st) <- lift $ bracket (runStateT m st)
(\(a,state) -> runStateT (mf1 a) state)
(\(a,state) -> runStateT (mf2 a) state)
put st
return a
|
mmirman/rpc-framework
|
src/Control/Exception/CatchableRPC.hs
|
bsd-3-clause
| 825 | 0 | 15 | 209 | 369 | 193 | 176 | 20 | 0 |
module Graphics.Gnuplot.Execute where
import qualified System.IO as IO
import System.IO.Temp (withSystemTempFile, )
import System.Exit (ExitCode, )
import System.Process (readProcessWithExitCode, )
tmpScript :: FilePath
tmpScript = "curve.gp"
simple ::
[String] {-^ The lines of the gnuplot script to be piped into gnuplot -}
-> [String] {-^ Options for gnuplot -}
-> IO ExitCode
simple program options =
withSystemTempFile tmpScript $ \path handle -> do
IO.hPutStr handle (unlines program)
IO.hClose handle
-- putStrLn $ showCommandForUser "gnuplot" (options ++ [path])
(exitCode, _out, _err) <-
readProcessWithExitCode "gnuplot" (options ++ [path]) []
-- putStr out
-- putStr err
return exitCode
|
wavewave/gnuplot
|
execute/tmp/Graphics/Gnuplot/Execute.hs
|
bsd-3-clause
| 768 | 0 | 13 | 165 | 175 | 99 | 76 | 18 | 1 |
module Main where
import Network.Libev
{- This is a Haskell port of the demo libev application at
- http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#EXAMPLE_PROGRAM
-}
-- This callback is called when data is readable on stdin.
stdinCb :: IoCallback
stdinCb evLoopPtr evIoPtr revents = do
putStrLn "stdin ready"
evIoStop evLoopPtr evIoPtr
evUnloop evLoopPtr 2 {- 2 = EVUNLOOP_ALL -}
-- Another callback, this time for a timeout.
timeoutCb :: TimerCallback
timeoutCb evLoopPtr evIoPtr revents = do
putStrLn "timeout"
evUnloop evLoopPtr 1 {- 1 = EVUNLOOP_ONE -}
main = do
stdinWatcher <- mkEvIo
timeoutWatcher <- mkEvTimer
stdinCb_ <- mkIoCallback stdinCb
timeoutCb_ <- mkTimerCallback timeoutCb
-- Use the default event loop unless you have special needs
loop <- evDefaultLoop 0
-- Initialise an io watcher, then start it.
-- This one will watch for stdin to become readable
evIoInit stdinWatcher stdinCb_ {- 0 = STDIN_FILENO -} 0 ev_read
evIoStart loop stdinWatcher
-- Initialise a timer watcher, then start it.
-- Simple non-repeating 5.5 second timeout.
evTimerInit timeoutWatcher timeoutCb_ 10 0.0
evTimerStart loop timeoutWatcher
-- Now wait for events to arrive
evLoop loop 0
-- Unloop was called, so exit.
putStrLn "exiting"
|
aycanirican/hlibev
|
Examples/LibEvExample.hs
|
bsd-3-clause
| 1,295 | 0 | 8 | 245 | 195 | 92 | 103 | 23 | 1 |
{-# LANGUAGE Haskell2010 #-}
module Common where
import Options
|
fehu/haskell-java-bridge-fork
|
j2hs/Common.hs
|
mit
| 68 | 0 | 3 | 13 | 8 | 6 | 2 | 3 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE ViewPatterns#-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -ddump-splices #-}
import Test.Hspec
import Test.HUnit ((@?=))
import Data.Text (Text, pack, unpack, singleton)
import Yesod.Routes.Class hiding (Route)
import qualified Yesod.Routes.Class as YRC
import Yesod.Routes.Parse (parseRoutesNoCheck, parseTypeTree, TypeTree (..))
import Yesod.Routes.Overlap (findOverlapNames)
import Yesod.Routes.TH hiding (Dispatch)
import Language.Haskell.TH.Syntax
import Hierarchy
import qualified Data.ByteString.Char8 as S8
import qualified Data.Set as Set
data MyApp = MyApp
data MySub = MySub
instance RenderRoute MySub where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySub = MySubRoute ([Text], [(Text, Text)])
deriving (Show, Eq, Read)
renderRoute (MySubRoute x) = x
instance ParseRoute MySub where
parseRoute = Just . MySubRoute
getMySub :: MyApp -> MySub
getMySub MyApp = MySub
data MySubParam = MySubParam Int
instance RenderRoute MySubParam where
data
#if MIN_VERSION_base(4,5,0)
Route
#else
YRC.Route
#endif
MySubParam = ParamRoute Char
deriving (Show, Eq, Read)
renderRoute (ParamRoute x) = ([singleton x], [])
instance ParseRoute MySubParam where
parseRoute ([unpack -> [x]], _) = Just $ ParamRoute x
parseRoute _ = Nothing
getMySubParam :: MyApp -> Int -> MySubParam
getMySubParam _ = MySubParam
do
texts <- [t|[Text]|]
let resLeaves = map ResourceLeaf
[ Resource "RootR" [] (Methods Nothing ["GET"]) ["foo", "bar"] True
, Resource "BlogPostR" [Static "blog", Dynamic $ ConT ''Text] (Methods Nothing ["GET", "POST"]) [] True
, Resource "WikiR" [Static "wiki"] (Methods (Just texts) []) [] True
, Resource "SubsiteR" [Static "subsite"] (Subsite (ConT ''MySub) "getMySub") [] True
, Resource "SubparamR" [Static "subparam", Dynamic $ ConT ''Int] (Subsite (ConT ''MySubParam) "getMySubParam") [] True
]
resParent = ResourceParent
"ParentR"
True
[ Static "foo"
, Dynamic $ ConT ''Text
]
[ ResourceLeaf $ Resource "ChildR" [] (Methods Nothing ["GET"]) ["child"] True
]
ress = resParent : resLeaves
rrinst <- mkRenderRouteInstance (ConT ''MyApp) ress
rainst <- mkRouteAttrsInstance (ConT ''MyApp) ress
prinst <- mkParseRouteInstance (ConT ''MyApp) ress
dispatch <- mkDispatchClause MkDispatchSettings
{ mdsRunHandler = [|runHandler|]
, mdsSubDispatcher = [|subDispatch dispatcher|]
, mdsGetPathInfo = [|fst|]
, mdsMethod = [|snd|]
, mdsSetPathInfo = [|\p (_, m) -> (p, m)|]
, mds404 = [|pack "404"|]
, mds405 = [|pack "405"|]
, mdsGetHandler = defaultGetHandler
, mdsUnwrapper = return
} ress
return
$ InstanceD
[]
(ConT ''Dispatcher
`AppT` ConT ''MyApp
`AppT` ConT ''MyApp)
[FunD (mkName "dispatcher") [dispatch]]
: prinst
: rainst
: rrinst
instance Dispatcher MySub master where
dispatcher env (pieces, _method) =
( pack $ "subsite: " ++ show pieces
, Just $ envToMaster env route
)
where
route = MySubRoute (pieces, [])
instance Dispatcher MySubParam master where
dispatcher env (pieces, method) =
case map unpack pieces of
[[c]] ->
let route = ParamRoute c
toMaster = envToMaster env
MySubParam i = envSub env
in ( pack $ "subparam " ++ show i ++ ' ' : [c]
, Just $ toMaster route
)
_ -> (pack "404", Nothing)
{-
thDispatchAlias
:: (master ~ MyApp, sub ~ MyApp, handler ~ String, app ~ (String, Maybe (YRC.Route MyApp)))
=> master
-> sub
-> (YRC.Route sub -> YRC.Route master)
-> app -- ^ 404 page
-> handler -- ^ 405 page
-> Text -- ^ method
-> [Text]
-> app
--thDispatchAlias = thDispatch
thDispatchAlias master sub toMaster app404 handler405 method0 pieces0 =
case dispatch pieces0 of
Just f -> f master sub toMaster app404 handler405 method0
Nothing -> app404
where
dispatch = toDispatch
[ Route [] False $ \pieces ->
case pieces of
[] -> do
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsRootR of
Just f -> f
Nothing -> handler405'
in runHandler handler master' sub' RootR toMaster'
_ -> error "Invariant violated"
, Route [D.Static "blog", D.Dynamic] False $ \pieces ->
case pieces of
[_, x2] -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' _app404' handler405' method ->
let handler =
case Map.lookup method methodsBlogPostR of
Just f -> f y2
Nothing -> handler405'
in runHandler handler master' sub' (BlogPostR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "wiki"] True $ \pieces ->
case pieces of
_:x2 -> do
y2 <- fromPathMultiPiece x2
Just $ \master' sub' toMaster' _app404' _handler405' _method ->
let handler = handleWikiR y2
in runHandler handler master' sub' (WikiR y2) toMaster'
_ -> error "Invariant violated"
, Route [D.Static "subsite"] True $ \pieces ->
case pieces of
_:x2 -> do
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySub sub') (toMaster' . SubsiteR) app404' handler405' method x2
_ -> error "Invariant violated"
, Route [D.Static "subparam", D.Dynamic] True $ \pieces ->
case pieces of
_:x2:x3 -> do
y2 <- fromPathPiece x2
Just $ \master' sub' toMaster' app404' handler405' method ->
dispatcher master' (getMySubParam sub' y2) (toMaster' . SubparamR y2) app404' handler405' method x3
_ -> error "Invariant violated"
]
methodsRootR = Map.fromList [("GET", getRootR)]
methodsBlogPostR = Map.fromList [("GET", getBlogPostR), ("POST", postBlogPostR)]
-}
main :: IO ()
main = hspec $ do
describe "RenderRoute instance" $ do
it "renders root correctly" $ renderRoute RootR @?= ([], [])
it "renders blog post correctly" $ renderRoute (BlogPostR $ pack "foo") @?= (map pack ["blog", "foo"], [])
it "renders wiki correctly" $ renderRoute (WikiR $ map pack ["foo", "bar"]) @?= (map pack ["wiki", "foo", "bar"], [])
it "renders subsite correctly" $ renderRoute (SubsiteR $ MySubRoute (map pack ["foo", "bar"], [(pack "baz", pack "bin")]))
@?= (map pack ["subsite", "foo", "bar"], [(pack "baz", pack "bin")])
it "renders subsite param correctly" $ renderRoute (SubparamR 6 $ ParamRoute 'c')
@?= (map pack ["subparam", "6", "c"], [])
describe "thDispatch" $ do
let disp m ps = dispatcher
(Env
{ envToMaster = id
, envMaster = MyApp
, envSub = MyApp
})
(map pack ps, S8.pack m)
it "routes to root" $ disp "GET" [] @?= (pack "this is the root", Just RootR)
it "POST root is 405" $ disp "POST" [] @?= (pack "405", Just RootR)
it "invalid page is a 404" $ disp "GET" ["not-found"] @?= (pack "404", Nothing :: Maybe (YRC.Route MyApp))
it "routes to blog post" $ disp "GET" ["blog", "somepost"]
@?= (pack "some blog post: somepost", Just $ BlogPostR $ pack "somepost")
it "routes to blog post, POST method" $ disp "POST" ["blog", "somepost2"]
@?= (pack "POST some blog post: somepost2", Just $ BlogPostR $ pack "somepost2")
it "routes to wiki" $ disp "DELETE" ["wiki", "foo", "bar"]
@?= (pack "the wiki: [\"foo\",\"bar\"]", Just $ WikiR $ map pack ["foo", "bar"])
it "routes to subsite" $ disp "PUT" ["subsite", "baz"]
@?= (pack "subsite: [\"baz\"]", Just $ SubsiteR $ MySubRoute ([pack "baz"], []))
it "routes to subparam" $ disp "PUT" ["subparam", "6", "q"]
@?= (pack "subparam 6 q", Just $ SubparamR 6 $ ParamRoute 'q')
describe "parsing" $ do
it "subsites work" $ do
parseRoute ([pack "subsite", pack "foo"], [(pack "bar", pack "baz")]) @?=
Just (SubsiteR $ MySubRoute ([pack "foo"], [(pack "bar", pack "baz")]))
describe "overlap checking" $ do
it "catches overlapping statics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping dynamics" $ do
let routes = [parseRoutesNoCheck|
/#Int Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping statics and dynamics" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#String Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping multi" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/##*Strings Foo2
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "catches overlapping subsite" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/foo Foo2 Subsite getSubsite
|]
findOverlapNames routes @?= [("Foo1", "Foo2")]
it "no false positives" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/bar/#String Foo2
|]
findOverlapNames routes @?= []
it "obeys ignore rules" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/#!String Foo2
/!foo Foo3
|]
findOverlapNames routes @?= []
it "obeys multipiece ignore rules #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
/+![String] Foo2
|]
findOverlapNames routes @?= []
it "ignore rules for entire route #779" $ do
let routes = [parseRoutesNoCheck|
/foo Foo1
!/+[String] Foo2
!/#String Foo3
!/foo Foo4
|]
findOverlapNames routes @?= []
it "ignore rules for hierarchy" $ do
let routes = [parseRoutesNoCheck|
/+[String] Foo1
!/foo Foo2:
/foo Foo3
/foo Foo4:
/!#foo Foo5
|]
findOverlapNames routes @?= []
it "proper boolean logic" $ do
let routes = [parseRoutesNoCheck|
/foo/bar Foo1
/foo/baz Foo2
/bar/baz Foo3
|]
findOverlapNames routes @?= []
describe "routeAttrs" $ do
it "works" $ do
routeAttrs RootR @?= Set.fromList [pack "foo", pack "bar"]
it "hierarchy" $ do
routeAttrs (ParentR (pack "ignored") ChildR) @?= Set.singleton (pack "child")
hierarchy
describe "parseRouteTyoe" $ do
let success s t = it s $ parseTypeTree s @?= Just t
failure s = it s $ parseTypeTree s @?= Nothing
success "Int" $ TTTerm "Int"
success "(Int)" $ TTTerm "Int"
failure "(Int"
failure "(Int))"
failure "[Int"
failure "[Int]]"
success "[Int]" $ TTList $ TTTerm "Int"
success "Foo-Bar" $ TTApp (TTTerm "Foo") (TTTerm "Bar")
success "Foo-Bar-Baz" $ TTApp (TTTerm "Foo") (TTTerm "Bar") `TTApp` TTTerm "Baz"
getRootR :: Text
getRootR = pack "this is the root"
getBlogPostR :: Text -> String
getBlogPostR t = "some blog post: " ++ unpack t
postBlogPostR :: Text -> Text
postBlogPostR t = pack $ "POST some blog post: " ++ unpack t
handleWikiR :: [Text] -> String
handleWikiR ts = "the wiki: " ++ show ts
getChildR :: Text -> Text
getChildR = id
|
MaxGabriel/yesod
|
yesod-core/test/RouteSpec.hs
|
mit
| 12,651 | 0 | 22 | 4,007 | 2,809 | 1,450 | 1,359 | 200 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Database.Persist.Redis.Store
( execRedisT
, RedisBackend
)where
import Control.Monad.IO.Class (MonadIO (..))
import Data.Aeson(FromJSON(..), ToJSON(..))
import Data.Text (Text, pack)
import qualified Database.Redis as R
import Web.HttpApiData (ToHttpApiData (..), FromHttpApiData (..), parseUrlPieceMaybe)
import Web.PathPieces (PathPiece(..))
import Database.Persist
import Database.Persist.Redis.Config (RedisT, thisConnection)
import Database.Persist.Redis.Internal
import Database.Persist.Redis.Update
import qualified Database.Persist.Sql as Sql
type RedisBackend = R.Connection
-- | Fetches a next key from <object>_id record
createKey :: (R.RedisCtx m f, PersistEntity val) => val -> m (f Integer)
createKey val = do
let keyId = toKeyId val
R.incr keyId
desugar :: R.TxResult a -> Either String a
desugar (R.TxSuccess x) = Right x
desugar R.TxAborted = Left "Transaction aborted!"
desugar (R.TxError string) = Left string
-- | Execute Redis transaction inside RedisT monad transformer
execRedisT :: (MonadIO m) => R.RedisTx (R.Queued a) -> RedisT m a
execRedisT action = do
conn <- thisConnection
result <- liftIO $ R.runRedis conn $ R.multiExec action -- this is the question if we should support transaction here
let r = desugar result
case r of
(Right x) -> return x
(Left x) -> liftIO $ fail x
instance HasPersistBackend R.Connection where
type BaseBackend R.Connection = R.Connection
persistBackend = id
instance PersistCore R.Connection where
newtype BackendKey R.Connection = RedisKey Text
deriving (Show, Read, Eq, Ord, PersistField, FromJSON, ToJSON)
instance PersistStoreRead R.Connection where
get k = do
r <- execRedisT $ R.hgetall (unKey k)
if null r
then return Nothing
else do
Entity _ val <- liftIO $ mkEntity k r
return $ Just val
instance PersistStoreWrite R.Connection where
insert val = do
keyId <- execRedisT $ createKey val
let textKey = toKeyText val keyId
key <- liftIO $ toKey textKey
insertKey key val
return key
insertKey k val = do
let fields = toInsertFields val
-- Inserts a hash map into <object>_<id> record
_ <- execRedisT $ R.hmset (unKey k) fields
return ()
repsert k val = do
_ <- execRedisT $ R.del [unKey k]
insertKey k val
return ()
replace k val = do
delete k
insertKey k val
return ()
delete k = do
r <- execRedisT $ R.del [unKey k]
case r of
0 -> liftIO $ fail "there is no such key!"
1 -> return ()
_ -> liftIO $ fail "there are a lot of such keys!"
update _ [] = return ()
update k upds = do
r <- execRedisT $ R.hgetall (unKey k)
if null r
then pure ()
else do
v <- liftIO $ mkEntity k r
let (Entity _ val) = cmdUpdate v upds
insertKey k val
return()
instance ToHttpApiData (BackendKey RedisBackend) where
toUrlPiece (RedisKey txt) = txt
instance FromHttpApiData (BackendKey RedisBackend) where
parseUrlPiece = return . RedisKey
-- some checking that entity exists and it is in format of entityname_id is omitted
instance PathPiece (BackendKey RedisBackend) where
toPathPiece = toUrlPiece
fromPathPiece = parseUrlPieceMaybe
instance Sql.PersistFieldSql (BackendKey RedisBackend) where
sqlType _ = Sql.SqlOther (pack "doesn't make much sense for Redis backend")
|
yesodweb/persistent
|
persistent-redis/Database/Persist/Redis/Store.hs
|
mit
| 3,745 | 0 | 15 | 976 | 1,122 | 561 | 561 | 93 | 2 |
module HAHP.Validation.Alternatives where
import Control.Parallel.Strategies
import Data.Map (notMember)
import Data.Maybe
import HAHP.Data
import HAHP.Data.Core
import HAHP.Data.Errors
import HAHP.Data.Utils
import HAHP.Validation.Unique
validateAlternatives :: AHPDataSet
-> [AlternativesError]
validateAlternatives dataSet = validate' dataSet testsList
validate' :: AHPDataSet
-> [AHPDataSet -> Maybe AlternativesError]
-> [AlternativesError]
validate' dataSet checks = catMaybes $ parMap rseq (\check -> check dataSet) checks
testsList :: [AHPDataSet -> Maybe AlternativesError]
testsList = [ noAlternativesTest
, alternativesUnicityTest
, indicatorsValuesExistenceTest
]
noAlternativesTest :: AHPDataSet
-> Maybe AlternativesError
noAlternativesTest (_, alts) =
if not . null $ alts
then Nothing
else Just NoAlternativesError
alternativesUnicityTest :: AHPDataSet
-> Maybe AlternativesError
alternativesUnicityTest (_, alts) =
if null repeatedAlternativesNames
then Nothing
else Just AlternativesUnicityError {repeatedAlternativesNames = repeatedAlternativesNames}
where repeatedAlternativesNames = repeated . map altName $ alts
indicatorsValuesExistenceTest :: AHPDataSet
-> Maybe AlternativesError
indicatorsValuesExistenceTest (ahpTree, alts) =
if null errors
then Nothing
else Just IndicatorsValuesExistenceError { indValuesErrors = errors}
where indicatorsNames = map name (getTreeLeaves ahpTree)
errors = [ (alt, ind)
| alt <- alts
, ind <- indicatorsNames
, notMember ind . indValues $ alt
]
|
jpierre03/hahp
|
src/HAHP/Validation/Alternatives.hs
|
gpl-3.0
| 1,894 | 0 | 11 | 560 | 391 | 215 | 176 | 44 | 2 |
{-# LANGUAGE Rank2Types, ImpredicativeTypes #-}
module Language.Java.Paragon.TypeCheck.Constraints where
import qualified Data.Map as Map
--import Language.Java.Paragon.Syntax (Ident) -- get rid of!
import Language.Java.Paragon.Error
import Language.Java.Paragon.TypeCheck.Policy
--import Language.Java.Paragon.TypeCheck.Containment
import Language.Java.Paragon.TypeCheck.Locks
--import Language.Java.Paragon.TypeCheck.Monad.TcCont
import Language.Java.Paragon.Interaction
import Data.List (union)
import qualified Data.ByteString.Char8 as B
--import Language.Java.Paragon.Syntax (Ident)
constraintsModule :: String
constraintsModule = typeCheckerBase ++ ".Constraints"
data Constraint =
LRT [(B.ByteString, ActorPolicy)]
[TcClause TcAtom] [TcLock] (TcPolicy TcActor) (TcPolicy TcActor)
deriving (Show, Eq)
type ConstraintWMsg = (Constraint, Error)
splitCstrs :: Constraint -> [Constraint]
splitCstrs (LRT bs g ls p q) = [ LRT bs g ls x y | x <- disjoin p, y <- dismeet q ]
where disjoin, dismeet :: (TcPolicy TcActor) -> [TcPolicy TcActor]
disjoin (Join p1 p2) = (disjoin p1)++(disjoin p2)
disjoin (Meet p1 _p2) = disjoin p1 -- TODO: Ugly strategy!!
disjoin p' = [p']
dismeet (Meet p1 p2) = (dismeet p1)++(dismeet p2)
dismeet (Join p1 _p2) = dismeet p1 -- TODO: Ugly strategy!!
dismeet p' = [p']
--Check if a given constraint p<=q verifies that q is an unknown policy of a variable
isCstrVar :: Constraint -> Bool
isCstrVar (LRT _ _ _ _ (RealPolicy _)) = False
isCstrVar (LRT _ _ _ _ (VarPolicy (TcMetaVar _ _))) = True
isCstrVar (LRT _ _ _ _ _)
= panic (constraintsModule ++ ".isCstrVar")
"Right-side of a constraint shouldn't be a join or meet!"
--Check if a given constraint p<=q verifies that q is an unknown policy of a variable
noVarLeft :: Constraint -> Bool
noVarLeft (LRT _ _ _ (RealPolicy _) _) = True
noVarLeft (LRT _ _ _ (VarPolicy (TcMetaVar _ _)) _) = False
noVarLeft (LRT bs g ls (Join p q) r) =
noVarLeft (LRT bs g ls p r) || noVarLeft (LRT bs g ls q r)
noVarLeft (LRT bs g ls (Meet p q) r) =
noVarLeft (LRT bs g ls p r) || noVarLeft (LRT bs g ls q r)
{-
partitionM :: (Constraint -> IO Bool) -> [Constraint] -> IO([Constraint], [Constraint])
partitionM f xs = do
xs' <- mapM (\x -> do
b <- f x
return (b, x))
xs
xs'' <- return $ partition fst xs'
return $ ((map snd $ fst xs''), (map snd $ snd xs''))
-}
{-
filterM :: (Constraint -> IO Bool) -> [Constraint] -> IO([Constraint])
filterM f xs = do
xs' <- mapM (\x -> do
b <- f x
return (b, x))
xs
xs'' <- return $ filter fst xs'
return $ (map snd $ xs'')
-}
linker :: (Map.Map (TcMetaVar TcActor) [([TcLock], (TcPolicy TcActor))]) -> Constraint -> (Map.Map (TcMetaVar TcActor) [([TcLock], (TcPolicy TcActor))])
linker m (LRT _ _ ls p (VarPolicy x)) = case (Map.lookup x m) of
Nothing -> Map.insert x [(ls, p)] m
Just ps -> Map.insert x ((ls, p):ps) m
linker _ _ = panic "linker shouldn't be called on a non-variable constraint" ""
-- Given (ls, p) and (ls',q) s.t. (ls, p) <= X, returns (ls `union` ls', p) if q=X, (ls, p) either
substPol :: (TcMetaVar TcActor) -> ([TcLock], (TcPolicy TcActor)) -> (([TcLock], TcPolicy TcActor)) -> ([TcLock], (TcPolicy TcActor))
substPol x (ls, px) (ls', p@(VarPolicy y)) =
case (x == y) of
True -> ((ls `union` ls'), px)
False -> (ls', p)
substPol _ _ (_, (Join _ _)) = panic "substPol called on a Join !" ""
substPol _ _ p = p
-- Add to a set of constraints the ones obtained by substituting a policy to a MetaVariable
substitution :: (TcMetaVar TcActor) -> ([TcLock], (TcPolicy TcActor)) -> [Constraint] -> [Constraint]
substitution _ _ [] = []
substitution x (ls, px) ((c@(LRT bs g ls' p q)):cs) =
let (ls'', psubst) = substPol x (ls, px) (ls',p) in
case ((psubst == p) && (ls'' == ls')) of
True -> c:(substitution x (ls, px) cs)
False -> (LRT bs g ls'' psubst q):c:(substitution x (ls, px) cs)
|
bvdelft/parac2
|
src/Language/Java/Paragon/PolicyLang/Constraints.hs
|
bsd-3-clause
| 4,198 | 0 | 13 | 1,035 | 1,320 | 716 | 604 | 57 | 5 |
{-# LANGUAGE OverloadedStrings, Rank2Types, PatternGuards #-}
module Haste.Config (
Config (..), AppStart, defaultConfig, stdJSLibs, startCustom, fastMultiply,
safeMultiply, strictly32Bits, debugLib) where
import Haste.AST.PP.Opts
import Haste.AST.Syntax
import Haste.AST.Constructors
import Haste.AST.Op
import Control.Shell (replaceExtension, (</>))
import Data.ByteString.Builder
import Data.Monoid
import Haste.Environment
import Outputable (Outputable)
import Data.List (stripPrefix, nub)
type AppStart = Builder -> Builder
stdJSLibs :: [FilePath]
stdJSLibs = map (jsDir </>) [
"rts.js", "floatdecode.js", "stdlib.js", "endian.js", "bn.js",
"MVar.js", "StableName.js", "Integer.js", "long.js", "md5.js", "array.js",
"pointers.js", "cheap-unicode.js", "Handle.js", "Weak.js",
"Foreign.js"
]
debugLib :: FilePath
debugLib = jsDir </> "debug.js"
-- | Execute the program as soon as it's loaded into memory.
-- Evaluate the result of applying main, as we might get a thunk back if
-- we're doing TCE. This is so cheap, small and non-intrusive we might
-- as well always do it this way, to simplify the config a bit.
startASAP :: AppStart
startASAP mainSym =
mainSym <> "();"
-- | Launch the application using a custom command.
startCustom :: String -> AppStart
startCustom "onload" = startOnLoadComplete
startCustom "asap" = startASAP
startCustom "onexec" = startASAP
startCustom str = insertSym str
-- | Replace the first occurrence of $HASTE_MAIN with Haste's entry point
-- symbol.
insertSym :: String -> AppStart
insertSym [] _ = stringUtf8 ""
insertSym str sym
| Just r <- stripPrefix "$HASTE_MAIN" str = sym <> stringUtf8 r
| (l,r) <- span (/= '$') str = stringUtf8 l <> insertSym r sym
-- | Execute the program when the document has finished loading.
startOnLoadComplete :: AppStart
startOnLoadComplete mainSym =
"window.onload = " <> mainSym <> ";"
-- | Int op wrapper for strictly 32 bit (|0).
strictly32Bits :: Exp -> Exp
strictly32Bits = flip (binOp BitOr) (litN 0)
-- | Safe Int multiplication.
safeMultiply :: Exp -> Exp -> Exp
safeMultiply a b = callForeign "imul" [a, b]
-- | Fast but unsafe Int multiplication.
fastMultiply :: Exp -> Exp -> Exp
fastMultiply = binOp Mul
-- | Compiler configuration.
data Config = Config {
-- | Runtime files to dump into the JS blob.
rtsLibs :: [FilePath],
-- | Path to directory where system jsmods are located.
libPaths :: [FilePath],
-- | Write all jsmods to this path.
targetLibPath :: FilePath,
-- | A function that takes the main symbol as its input and outputs the
-- code that starts the program.
appStart :: AppStart,
-- | Wrap the program in its own namespace?
wrapProg :: Bool,
-- | Options to the pretty printer.
ppOpts :: PPOpts,
-- | A function that takes the name of the a target as its input and
-- outputs the name of the file its JS blob should be written to.
outFile :: Config -> String -> String,
-- | Link the program?
performLink :: Bool,
-- | Link as jslib file, instead of executable?
linkJSLib :: Bool,
-- | Output file name when linking jslib.
linkJSLibFile :: Maybe FilePath,
-- | A function to call on each Int arithmetic primop.
wrapIntMath :: Exp -> Exp,
-- | Operation to use for Int multiplication.
multiplyIntOp :: Exp -> Exp -> Exp,
-- | Be verbose about warnings, etc.?
verbose :: Bool,
-- | Perform optimizations over the whole program at link time?
wholeProgramOpts :: Bool,
-- | Perform comprehensive whole program flow analysis optimizations at
-- link time?
flowAnalysisOpts :: Bool,
-- | Allow the possibility that some tail recursion may not be optimized
-- in order to gain slightly smaller code?
sloppyTCE :: Bool,
-- | Turn on run-time tracing of primops?
tracePrimops :: Bool,
-- | Run the entire thing through Google Closure when done?
useGoogleClosure :: Maybe FilePath,
-- | Extra flags for Google Closure to take?
useGoogleClosureFlags :: [String],
-- | Any external Javascript to link into the JS bundle.
jsExternals :: [FilePath],
-- | Produce a skeleton HTML file containing the program rather than a
-- JS file.
outputHTML :: Bool,
-- | GHC DynFlags used for STG generation.
-- Currently only used for printing StgSyn values.
showOutputable :: forall a. Outputable a => a -> String,
-- | Which module contains the program's main function?
-- Defaults to Just ("main", "Main")
mainMod :: Maybe (String, String),
-- | Perform optimizations.
-- Defaults to True.
optimize :: Bool,
-- | Enable tail loop transformation?
-- Defaults to True.
enableTailLoops :: Bool,
-- | Enable proper tailcalls?
-- Defaults to True.
enableProperTailcalls :: Bool,
-- | Inline @JSLit@ values?
-- Defaults to False.
inlineJSPrim :: Bool,
-- | Remove tailcalls and trampolines for tail call cycles provably
-- shorter than @N@ calls.
-- Defaults to 3.
detrampolineThreshold :: Int,
-- | Bound tail call chains at @n@ stack frames.
-- Defaults to 10.
tailChainBound :: Int,
-- | Overwrite scrutinees when evaluated instead of allocating a new local.
-- Defaults to False.
overwriteScrutinees :: Bool,
-- | Annotate all external symbols and JS literals with /* EXTERNAL */ in
-- generated code.
-- Defaults to False.
annotateExternals :: Bool,
-- | Annotate all non-local Haskell symbols and with their qualified
-- names.
-- Defaults to False.
annotateSymbols :: Bool,
-- | Emit @"use strict";@ declaration. Does not affect minification, but
-- *does* affect any external JS.
-- Defaults to True.
useStrict :: Bool,
-- | Use classy objects for small ADTs?
-- Defaults to True.
useClassyObjects :: Bool
}
-- | Default compiler configuration.
defaultConfig :: Config
defaultConfig = Config {
rtsLibs = stdJSLibs,
libPaths = nub [jsmodUserDir, jsmodSysDir],
targetLibPath = ".",
appStart = startOnLoadComplete,
wrapProg = False,
ppOpts = defaultPPOpts,
outFile = \cfg f -> let ext = if outputHTML cfg
then "html"
else "js"
in replaceExtension f ext,
performLink = True,
linkJSLib = False,
linkJSLibFile = Nothing,
wrapIntMath = strictly32Bits,
multiplyIntOp = safeMultiply,
verbose = False,
wholeProgramOpts = False,
flowAnalysisOpts = False,
sloppyTCE = False,
tracePrimops = False,
useGoogleClosure = Nothing,
useGoogleClosureFlags = [],
jsExternals = [],
outputHTML = False,
showOutputable = const "No showOutputable defined in config!",
mainMod = Just ("main", "Main"),
optimize = True,
enableTailLoops = True,
enableProperTailcalls = True,
inlineJSPrim = False,
detrampolineThreshold = 3,
tailChainBound = 0,
overwriteScrutinees = False,
annotateExternals = False,
annotateSymbols = False,
useStrict = True,
useClassyObjects = True
}
|
kranich/haste-compiler
|
src/Haste/Config.hs
|
bsd-3-clause
| 7,625 | 0 | 13 | 2,130 | 1,098 | 686 | 412 | 119 | 2 |
{-# LANGUAGE Haskell98 #-}
{-# LINE 1 "Data/Map/Lazy/Merge.hs" #-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Map.Lazy.Merge
-- Copyright : (c) David Feuer 2016
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : portable
--
-- This module defines an API for writing functions that merge two
-- maps. The key functions are 'merge' and 'mergeA'.
-- Each of these can be used with several different "merge tactics".
--
-- The 'merge' and 'mergeA' functions are shared by
-- the lazy and strict modules. Only the choice of merge tactics
-- determines strictness. If you use 'Data.Map.Strict.Merge.mapMissing'
-- from "Data.Map.Strict.Merge" then the results will be forced before
-- they are inserted. If you use 'Data.Map.Lazy.Merge.mapMissing' from
-- this module then they will not.
--
-- == Efficiency note
--
-- The 'Category', 'Applicative', and 'Monad' instances for 'WhenMissing'
-- tactics are included because they are valid. However, they are
-- inefficient in many cases and should usually be avoided. The instances
-- for 'WhenMatched' tactics should not pose any major efficiency problems.
module Data.Map.Lazy.Merge {-# DEPRECATED "Use \"Data.Map.Merge.Lazy\"." #-}
( module Data.Map.Merge.Lazy ) where
import Data.Map.Merge.Lazy
|
phischu/fragnix
|
tests/packages/scotty/Data.Map.Lazy.Merge.hs
|
bsd-3-clause
| 1,841 | 0 | 5 | 643 | 56 | 49 | 7 | 8 | 0 |
module Main where
import Data.Char as Char hiding (isSymbol)
import Data.List as List (nub, isPrefixOf, sortBy)
import Data.Maybe as Maybe (catMaybes)
import Control.Monad (unless)
import System.Environment (getArgs)
main = do
[name, original, modified] <- getArgs
diff name original modified
diff :: String -> FilePath -> FilePath -> IO ()
diff moduleName originalFile modifiedFile = do
original <- readFile originalFile
modified <- readFile modifiedFile
let (added, removed, changed) =
classify (extractFunctionsFromHi original)
(extractFunctionsFromHi modified)
-- putStrLn "Functions added:"
-- mapM_ putStrLn added
unless (null removed && null changed) $
putStrLn ("module " ++ moduleName)
unless (null removed) $ do
putStrLn " functions removed:"
mapM_ (putStrLn . (" "++)) removed
putStrLn ""
unless (null changed) $ do
putStrLn " functions changed:"
mapM_ putStrLn [ " " ++ name ++ " changed from"
++ "\n :: " ++ originalType
++ "\n to :: " ++ modifiedType
| (name, originalType, modifiedType) <- changed ]
putStrLn ""
classify :: [(String, String)] -> [(String, String)] -> ([String], [String], [(String, String, String)])
classify originalFuns modifiedFuns =
( [ originalName | (originalName, originalType) <- added ]
, [ modifiedName | (modifiedName, modifiedType) <- removed
, not $ "lvl" `isPrefixOf` modifiedName
, not $ "gtk_" `isPrefixOf` modifiedName ]
, [ (originalName, originalType, modifiedType)
| ((originalName, originalType), (modifiedName, modifiedType)) <- changed
, canonicaliseQuantifiedVars originalType
/= canonicaliseQuantifiedVars modifiedType] )
where (removed, changed, added) =
mergeBy (comparing fst)
(sortBy (comparing fst) originalFuns)
(sortBy (comparing fst) modifiedFuns)
canonicaliseQuantifiedVars :: String -> String
canonicaliseQuantifiedVars ty =
unwords [ case lookup w varMapping of
Nothing -> w
Just w' -> w'
| w <- words ty ]
where quantifiedVars = [ w | w@(c:_) <- words ty, Char.isLower c ]
varMapping = zip (List.nub quantifiedVars) (map (\c -> [c]) ['a'..'z'])
-- mergeBy cmp xs ys = (only_in_xs, in_both, only_in_ys)
mergeBy :: (a -> b -> Ordering) -> [a] -> [b] -> ([a], [(a, b)], [b])
mergeBy cmp = merge [] [] []
where merge l m r [] ys = (reverse l, reverse m, reverse (ys++r))
merge l m r xs [] = (reverse (xs++l), reverse m, reverse r)
merge l m r (x:xs) (y:ys) =
case x `cmp` y of
GT -> merge l m (y:r) (x:xs) ys
EQ -> merge l ((x,y):m) r xs ys
LT -> merge (x:l) m r xs (y:ys)
comparing :: (Ord a) => (b -> a) -> b -> b -> Ordering
comparing p x y = compare (p x) (p y)
-- returns a list of function names with their types
extractFunctionsFromHi :: String -> [(String, String)]
extractFunctionsFromHi = catMaybes . map (eval . lexer) . init . parse
ignore = ["module", "__interface", "__export", "package", "orphans",
";", "$", "import", ":", "infixr", "infixl", "infix", "("]
eval :: [String] -> Maybe (String, String)
eval (x:_) | x `elem` ignore = Nothing
eval ("instance":ls) = Nothing
eval ("type":ls) = Nothing
eval ("data":ls) = Nothing
-- functions
eval ls@(name:"::":type_) = Just (name, respace (filterBraces type_))
eval xs = Nothing
filterBraces ("{":"}":xs) = filterBraces xs
filterBraces (x:xs) = x : filterBraces xs
filterBraces [] = []
respace :: [String] -> String
respace x = f (filter (/= ";") x)
where
f [] = ""
f [x] = x
f (x1:x2:xs) = if shouldspace x1 x2
then x1 ++ " " ++ f (x2:xs)
else x1 ++ f (x2:xs)
lBrack = "({["
rBrack = ")}]"
isRight [x] = x `elem` rBrack
isRight _ = False
isLeft [x] = x `elem` lBrack
isLeft _ = False
shouldspace l r = not $
isRight r || isLeft l || r == ","
splitTerms :: [String] -> [[String]]
splitTerms xs@(x:_) | isLeft x = left : splitTerms (drop (length left) xs)
where
left = readBrack 0 xs
readBrack 1 (x:xs) | isRight x = [x]
readBrack n (x:xs) | isRight x = x : readBrack (n-1) xs
| isLeft x = x : readBrack (n+1) xs
| otherwise = x : readBrack n xs
splitTerms (x:xs) = [x] : splitTerms xs
splitTerms [] = []
splitOn :: Eq a => a -> [a] -> [[a]]
splitOn x [] = []
splitOn x as = takeWhile (/= x) as : splitOn x (safeTail (dropWhile (/= x) as))
safeTail (x:xs) = xs
safeTail [] = []
parse :: String -> [String]
parse xs = rejoin (lines xs)
where
rejoin (x1:x2@(x2h:x2t):xs) | isSpace x2h = rejoin ((x1 ++ " " ++ dropWhile isSpace x2) : xs)
rejoin (x:xs) = x : rejoin xs
rejoin [] = []
lexer :: String -> [String]
lexer = demodule . lexRaw
demodule :: [String] -> [String]
demodule ("(":".":xs) = "(":".": demodule xs
demodule (x:".":xs) = demodule xs
demodule (x:xs) = x : demodule xs
demodule [] = []
-- Chunks taken from NHC's lexer, with modifications
lexRaw :: String -> [String]
lexRaw "" = []
lexRaw (x:xs) | isSpace x = lexRaw xs
lexRaw (x:xs) | x == '\'' || x == '\"' = f [x] xs
where
f done [] = [reverse done]
f done ('\\':x:xs) = f (x:'\\':done) xs
f done (a:xs) | a == x = reverse (a:done) : lexRaw xs
| otherwise = f (a:done) xs
lexRaw ('{':'-':x) = f x
where
f ('-':'}':x) = lexRaw x
f (x:xs) = f xs
f [] = []
lexRaw ('[':']':xs) = "[]" : lexRaw xs
lexRaw ('(':')':xs) = "()" : lexRaw xs
lexRaw ('(':x:xs) | isSymbol x && b == ')' = a : lexRaw bs
where (a, b:bs) = span isSymbol (x:xs)
lexRaw (x:xs) | x `elem` ",;()[]{}`" = [x] : lexRaw xs
| isDigit x = lexRaw xs -- drop digits, not needed -- continue isDigit
| isSymbol x = continue isSymbol
| isIdFirst x = continue isIdAny
where
isIdFirst c = isAlpha c || c == '_'
isIdAny c = isAlphaNum c || c `elem` "_'#"
continue f = a : lexRaw b
where (a, b) = span f (x:xs)
isSymbol c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
{-
lex (c:s) | isSingle c = [([c],s)]
| isSym c = [(c:sym,t) | (sym,t) <- [span isSym s]]
| isIdInit c = [(c:nam,t) | (nam,t) <- [span isIdChar s]]
| isDigit c = [(c:ds++fe,t) | (ds,s) <- [span isDigit s],
(fe,t) <- lexFracExp s ]
| otherwise = [] -- bad character
where
isSingle c = c `elem` ",;()[]{}`"
isSym c = c `elem` "!@#$%&*+./<=>?\\^|:-~"
isIdInit c =
isIdChar c = isAlphaNum c || c `elem` "_'"
lexFracExp ('.':c:s) | isDigit c
= [('.':ds++e,u) | (ds,t) <- lexDigits (c:s),
(e,u) <- lexExp t ]
lexFracExp s = lexExp s
lexExp (e:s) | e `elem` "eE"
= [(e:c:ds,u) | (c:t) <- [s], c `elem` "+-",
(ds,u) <- lexDigits t] ++
[(e:ds,t) | (ds,t) <- lexDigits s]
lexExp s = [("",s)]
lexRaw "" = []
lexRaw (' ':x) = lexRaw x
lexRaw (';':x) = lexRaw x
-- to make up for Hugs being wrong
lexRaw ('_':x) = lexRaw x
lexRaw ('{':'-':x) = f x
where
f ('-':'}':x) = lexRaw x
f (x:xs) = f xs
f [] = []
lexRaw x = a : lexRaw b
where [(a, b)] = lex x
-}
|
k0001/gtk2hs
|
tools/apidiff/HiDiff.hs
|
gpl-3.0
| 7,619 | 0 | 17 | 2,348 | 2,797 | 1,458 | 1,339 | 142 | 5 |
{- File mode utilities.
-
- Copyright 2010-2012 Joey Hess <[email protected]>
-
- License: BSD-2-clause
-}
{-# LANGUAGE CPP #-}
module Utility.FileMode where
import System.IO
import Control.Monad
import Control.Exception (bracket)
import System.PosixCompat.Types
import Utility.PosixFiles
#ifndef mingw32_HOST_OS
import System.Posix.Files
#endif
import Foreign (complement)
import Utility.Exception
{- Applies a conversion function to a file's mode. -}
modifyFileMode :: FilePath -> (FileMode -> FileMode) -> IO ()
modifyFileMode f convert = void $ modifyFileMode' f convert
modifyFileMode' :: FilePath -> (FileMode -> FileMode) -> IO FileMode
modifyFileMode' f convert = do
s <- getFileStatus f
let old = fileMode s
let new = convert old
when (new /= old) $
setFileMode f new
return old
{- Adds the specified FileModes to the input mode, leaving the rest
- unchanged. -}
addModes :: [FileMode] -> FileMode -> FileMode
addModes ms m = combineModes (m:ms)
{- Removes the specified FileModes from the input mode. -}
removeModes :: [FileMode] -> FileMode -> FileMode
removeModes ms m = m `intersectFileModes` complement (combineModes ms)
{- Runs an action after changing a file's mode, then restores the old mode. -}
withModifiedFileMode :: FilePath -> (FileMode -> FileMode) -> IO a -> IO a
withModifiedFileMode file convert a = bracket setup cleanup go
where
setup = modifyFileMode' file convert
cleanup oldmode = modifyFileMode file (const oldmode)
go _ = a
writeModes :: [FileMode]
writeModes = [ownerWriteMode, groupWriteMode, otherWriteMode]
readModes :: [FileMode]
readModes = [ownerReadMode, groupReadMode, otherReadMode]
executeModes :: [FileMode]
executeModes = [ownerExecuteMode, groupExecuteMode, otherExecuteMode]
otherGroupModes :: [FileMode]
otherGroupModes =
[ groupReadMode, otherReadMode
, groupWriteMode, otherWriteMode
]
{- Removes the write bits from a file. -}
preventWrite :: FilePath -> IO ()
preventWrite f = modifyFileMode f $ removeModes writeModes
{- Turns a file's owner write bit back on. -}
allowWrite :: FilePath -> IO ()
allowWrite f = modifyFileMode f $ addModes [ownerWriteMode]
{- Turns a file's owner read bit back on. -}
allowRead :: FilePath -> IO ()
allowRead f = modifyFileMode f $ addModes [ownerReadMode]
{- Allows owner and group to read and write to a file. -}
groupSharedModes :: [FileMode]
groupSharedModes =
[ ownerWriteMode, groupWriteMode
, ownerReadMode, groupReadMode
]
groupWriteRead :: FilePath -> IO ()
groupWriteRead f = modifyFileMode f $ addModes groupSharedModes
checkMode :: FileMode -> FileMode -> Bool
checkMode checkfor mode = checkfor `intersectFileModes` mode == checkfor
{- Checks if a file mode indicates it's a symlink. -}
isSymLink :: FileMode -> Bool
#ifdef mingw32_HOST_OS
isSymLink _ = False
#else
isSymLink = checkMode symbolicLinkMode
#endif
{- Checks if a file has any executable bits set. -}
isExecutable :: FileMode -> Bool
isExecutable mode = combineModes executeModes `intersectFileModes` mode /= 0
{- Runs an action without that pesky umask influencing it, unless the
- passed FileMode is the standard one. -}
noUmask :: FileMode -> IO a -> IO a
#ifndef mingw32_HOST_OS
noUmask mode a
| mode == stdFileMode = a
| otherwise = withUmask nullFileMode a
#else
noUmask _ a = a
#endif
withUmask :: FileMode -> IO a -> IO a
#ifndef mingw32_HOST_OS
withUmask umask a = bracket setup cleanup go
where
setup = setFileCreationMask umask
cleanup = setFileCreationMask
go _ = a
#else
withUmask _ a = a
#endif
combineModes :: [FileMode] -> FileMode
combineModes [] = undefined
combineModes [m] = m
combineModes (m:ms) = foldl unionFileModes m ms
isSticky :: FileMode -> Bool
#ifdef mingw32_HOST_OS
isSticky _ = False
#else
isSticky = checkMode stickyMode
stickyMode :: FileMode
stickyMode = 512
setSticky :: FilePath -> IO ()
setSticky f = modifyFileMode f $ addModes [stickyMode]
#endif
{- Writes a file, ensuring that its modes do not allow it to be read
- or written by anyone other than the current user,
- before any content is written.
-
- When possible, this is done using the umask.
-
- On a filesystem that does not support file permissions, this is the same
- as writeFile.
-}
writeFileProtected :: FilePath -> String -> IO ()
writeFileProtected file content = withUmask 0o0077 $
withFile file WriteMode $ \h -> do
void $ tryIO $ modifyFileMode file $ removeModes otherGroupModes
hPutStr h content
|
avengerpenguin/propellor
|
src/Utility/FileMode.hs
|
bsd-2-clause
| 4,440 | 12 | 11 | 750 | 992 | 526 | 466 | 81 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module : Aws.DynamoDb.Commands.Scan
-- Copyright : Soostone Inc
-- License : BSD3
--
-- Maintainer : Ozgun Ataman <[email protected]>
-- Stability : experimental
--
-- Implementation of Amazon DynamoDb Scan command.
--
-- See: @http:\/\/docs.aws.amazon.com\/amazondynamodb\/latest\/APIReference\/API_Scan.html@
----------------------------------------------------------------------------
module Aws.DynamoDb.Commands.Scan
( Scan (..)
, scan
, ScanResponse (..)
) where
-------------------------------------------------------------------------------
import Control.Applicative
import Data.Aeson
import Data.Default
import Data.Maybe
import qualified Data.Text as T
import Data.Typeable
import qualified Data.Vector as V
-------------------------------------------------------------------------------
import Aws.Core
import Aws.DynamoDb.Core
-------------------------------------------------------------------------------
-- | A Scan command that uses primary keys for an expedient scan.
data Scan = Scan {
sTableName :: T.Text
-- ^ Required.
, sFilter :: Conditions
-- ^ Whether to filter results before returning to client
, sStartKey :: Maybe [Attribute]
-- ^ Exclusive start key to resume a previous query.
, sLimit :: Maybe Int
-- ^ Whether to limit result set size
, sIndex :: Maybe T.Text
-- ^ Optional. Index to 'Scan'
, sSelect :: QuerySelect
-- ^ What to return from 'Scan'
, sRetCons :: ReturnConsumption
, sSegment :: Int
-- ^ Segment number, starting at 0, for parallel queries.
, sTotalSegments :: Int
-- ^ Total number of parallel segments. 1 means sequential scan.
} deriving (Eq,Show,Read,Ord,Typeable)
-- | Construct a minimal 'Scan' request.
scan :: T.Text -- ^ Table name
-> Scan
scan tn = Scan tn def Nothing Nothing Nothing def def 0 1
-- | Response to a 'Scan' query.
data ScanResponse = ScanResponse {
srItems :: V.Vector Item
, srLastKey :: Maybe [Attribute]
, srCount :: Int
, srScanned :: Int
, srConsumed :: Maybe ConsumedCapacity
} deriving (Eq,Show,Read,Ord)
-------------------------------------------------------------------------------
instance ToJSON Scan where
toJSON Scan{..} = object $
catMaybes
[ (("ExclusiveStartKey" .= ) . attributesJson) <$> sStartKey
, ("Limit" .= ) <$> sLimit
, ("IndexName" .= ) <$> sIndex
] ++
conditionsJson "ScanFilter" sFilter ++
querySelectJson sSelect ++
[ "TableName".= sTableName
, "ReturnConsumedCapacity" .= sRetCons
, "Segment" .= sSegment
, "TotalSegments" .= sTotalSegments
]
instance FromJSON ScanResponse where
parseJSON (Object v) = ScanResponse
<$> v .:? "Items" .!= V.empty
<*> ((do o <- v .: "LastEvaluatedKey"
Just <$> parseAttributeJson o)
<|> pure Nothing)
<*> v .: "Count"
<*> v .: "ScannedCount"
<*> v .:? "ConsumedCapacity"
parseJSON _ = fail "ScanResponse must be an object."
instance Transaction Scan ScanResponse
instance SignQuery Scan where
type ServiceConfiguration Scan = DdbConfiguration
signQuery gi = ddbSignQuery "Scan" gi
instance ResponseConsumer r ScanResponse where
type ResponseMetadata ScanResponse = DdbResponse
responseConsumer _ ref resp = ddbResponseConsumer ref resp
instance AsMemoryResponse ScanResponse where
type MemoryResponse ScanResponse = ScanResponse
loadToMemory = return
instance ListResponse ScanResponse Item where
listResponse = V.toList . srItems
instance IteratedTransaction Scan ScanResponse where
nextIteratedRequest request response =
case srLastKey response of
Nothing -> Nothing
key -> Just request { sStartKey = key }
|
romanb/aws
|
Aws/DynamoDb/Commands/Scan.hs
|
bsd-3-clause
| 4,163 | 1 | 19 | 1,026 | 717 | 406 | 311 | -1 | -1 |
{-# LANGUAGE TypeApplications #-}
module Bug where
foo = notInScope @Bool True
|
sdiehl/ghc
|
testsuite/tests/typecheck/should_fail/T13834.hs
|
bsd-3-clause
| 82 | 0 | 6 | 15 | 17 | 10 | 7 | 3 | 1 |
import Test.Cabal.Prelude
main = cabalTest $ do
withRepo "repo" . withSourceCopy $ do
-- TODO: test this with a sandbox-installed package
-- that is not depended upon
cabal "freeze" []
cwd <- fmap testCurrentDir getTestEnv
assertFileDoesNotContain (cwd </> "cabal.config") "exceptions"
assertFileDoesNotContain (cwd </> "cabal.config") "my"
assertFileDoesContain (cwd </> "cabal.config") "base"
|
mydaum/cabal
|
cabal-testsuite/PackageTests/Freeze/freeze.test.hs
|
bsd-3-clause
| 455 | 0 | 13 | 110 | 99 | 47 | 52 | 8 | 1 |
module Main where
import Snap.Http.Server.Config
import Snap.Snaplet
import Blackbox.App
main :: IO ()
main = serveSnaplet defaultConfig app
|
sopvop/snap
|
test/suite/AppMain.hs
|
bsd-3-clause
| 174 | 0 | 6 | 51 | 41 | 24 | 17 | 6 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-- !!! Functional dependencies and existentials
-- Hugs (February 2000) doesn't like it. It says
-- Variable "e" in constraint is not locally bound
module ShouldCompile where
class Collection c e | c -> e where
empty :: c
put :: c -> e -> c
data SomeCollection e = forall c . Collection c e => MakeSomeCollection c
|
hvr/jhc
|
regress/tests/1_typecheck/2_pass/ghc/tc119.hs
|
mit
| 360 | 0 | 8 | 77 | 67 | 39 | 28 | -1 | -1 |
--------------------------------------------------------------------------------
-- | A module containing various file utility functions
module Hakyll.Core.Util.File
( makeDirectories
, getRecursiveContents
, removeDirectory
) where
--------------------------------------------------------------------------------
import Control.Applicative ((<$>))
import Control.Monad (filterM, forM, when)
import System.Directory (createDirectoryIfMissing,
doesDirectoryExist, getDirectoryContents,
removeDirectoryRecursive)
import System.FilePath (takeDirectory, (</>))
--------------------------------------------------------------------------------
-- | Given a path to a file, try to make the path writable by making
-- all directories on the path.
makeDirectories :: FilePath -> IO ()
makeDirectories = createDirectoryIfMissing True . takeDirectory
--------------------------------------------------------------------------------
-- | Get all contents of a directory.
getRecursiveContents :: (FilePath -> IO Bool) -- ^ Ignore this file/directory
-> FilePath -- ^ Directory to search
-> IO [FilePath] -- ^ List of files found
getRecursiveContents ignore top = go ""
where
isProper x
| x `elem` [".", ".."] = return False
| otherwise = not <$> ignore x
go dir = do
dirExists <- doesDirectoryExist (top </> dir)
if not dirExists
then return []
else do
names <- filterM isProper =<< getDirectoryContents (top </> dir)
paths <- forM names $ \name -> do
let rel = dir </> name
isDirectory <- doesDirectoryExist (top </> rel)
if isDirectory
then go rel
else return [rel]
return $ concat paths
--------------------------------------------------------------------------------
removeDirectory :: FilePath -> IO ()
removeDirectory fp = do
e <- doesDirectoryExist fp
when e $ removeDirectoryRecursive fp
|
Javran/hakyll
|
src/Hakyll/Core/Util/File.hs
|
bsd-3-clause
| 2,251 | 0 | 20 | 681 | 400 | 211 | 189 | 36 | 3 |
{-# LANGUAGE TemplateHaskell,ForeignFunctionInterface #-}
module T3319 where
import Foreign.Ptr
import Language.Haskell.TH
$(return [ForeignD (ImportF CCall Unsafe "&" (mkName "foo") (AppT (ConT ''Ptr) (ConT ''())))])
-- Should generate the same as this:
foreign import ccall unsafe "&" foo1 :: Ptr ()
|
urbanslug/ghc
|
testsuite/tests/th/T3319.hs
|
bsd-3-clause
| 306 | 0 | 17 | 44 | 98 | 52 | 46 | 6 | 0 |
module PetParser where
import Control.Applicative
import Data.Time.Calendar
import Data.Time.Calendar.MonthDay
import Data.Char
import Parser
import qualified Expense as E
type Location = (Int, Int)
monthName :: Int -> String
monthName i = ["January", "February", "March",
"April", "May", "June", "July",
"August", "September", "October",
"November", "December"] !! i
errInvalidMonth :: Int -> String
errInvalidMonth m = unwords ["| Invalid month value", show m]
errInvalidDay :: Int -> Int -> String
errInvalidDay d m = unwords ["| Invalid day value", show d, "of", monthName m]
errInvalidTagSep :: Char -> String
errInvalidTagSep s = unwords ["| Invalid tag separator", show s]
newline :: Char
newline = '\n'
space :: Char -> Bool
space c = isSpace c && c /= newline
locUpd :: Char -> Location -> Location
locUpd e (l, c) = if e == newline then (l + 1, 1) else (l, c + 1)
spaces :: String -> Parser Char Location String
spaces e = some $ satisfy space e
newlines :: String -> Parser Char Location String
newlines e = some $ satisfy (== newline) e
whites :: String -> Parser Char Location String
whites e = some $ satisfy isSpace e
optionalSpaces :: String -> Parser Char Location String
optionalSpaces e = many $ satisfy space e
optionalNewlines :: String -> Parser Char Location String
optionalNewlines e = many $ satisfy (== newline) e
optionalWhites :: String -> Parser Char Location String
optionalWhites e = many $ satisfy isSpace e
int :: String -> Parser Char Location Int
int e = rawInt e >>= \r -> return (read r :: Int)
intAsDouble :: Parser Char Location Double
intAsDouble = rawInt "an integer value" >>= \r -> return (read r :: Double)
rawInt :: String -> Parser Char Location String
rawInt e = some $ satisfy isDigit e
onlyDouble :: Parser Char Location Double
onlyDouble = do
d <- rawInt "the decimal part of a double value"
p <- satisfy (== '.') "the floating-point of a double value"
f <- rawInt "the fractional part of a double value"
return (read (d ++ [p] ++ f) :: Double)
amount :: Parser Char Location Double
amount = onlyDouble <|> intAsDouble
year :: Parser Char Location Int
year = do a <- satisfy isDigit "the millenia digit of year"
b <- satisfy isDigit "the century digit of year"
c <- satisfy isDigit "the decade digit of year"
d <- satisfy isDigit "the yearly digit of year"
return (read [a, b, c, d] :: Int)
month :: Parser Char Location Int
month = do l <- loc
a <- satisfy isDigit "the first digit of month"
b <- satisfy isDigit "the second digit of month"
let m = read [a, b] :: Int
if m > 12
then err (Just l) $ errInvalidMonth m
else return m
day :: Parser Char Location Int
day = do a <- satisfy isDigit "the first digit of day"
b <- satisfy isDigit "the second digit of day"
return (read [a, b] :: Int)
date :: Parser Char Location (Int, Int, Int)
date = do y <- year ; _ <- satisfy (== '-') "the first date separator"
m <- month ; _ <- satisfy (== '-') "the second date separator"
l <- loc
d <- day
if d > monthLength (isLeapYear (toInteger y)) m
then err (Just l) $ errInvalidDay m d
else return (y, m, d)
name :: String -> Parser Char Location String
name e = some $ satisfy (not . isSpace) e
person :: Parser Char Location String
person = name "a person name"
shop :: Parser Char Location String
shop = name "a shop name"
tag :: Parser Char Location String
tag = some $ satisfy (\c -> not (isSpace c) && c /= ',') "a tag name"
tags :: Parser Char Location [String]
tags = tags_ [] >>= \ts -> return $ reverse ts
where tags_ a = do t <- tag
e <- eof
if e then return $ t:a
else do p <- peek "a spacing"
if isSpace p then return $ t:a
else if p == ',' then item >> tags_ (t:a)
else err Nothing $ errInvalidTagSep p
note :: Parser Char Location (Maybe String)
note = do r <- many $ satisfy (/= newline) "anything until a newline"
return $ if null r then Nothing else Just r
expense :: Parser Char Location E.Expense
expense = do a <- amount <|> err Nothing "Error parsing Amount"
_ <- spaces "the spacing after the amount"
d <- date <|> err Nothing "Error parsing Date"
_ <- spaces "the spacing after the date"
p <- person <|> err Nothing "Error parsing Person Name"
_ <- spaces "the spacing after the person name"
s <- shop <|> err Nothing "Error parsing Shop Name"
_ <- spaces "the spacing after the shop name"
t <- tags <|> err Nothing "Error parsing Tags"
_ <- optionalSpaces "the spacing after the tags"
n <- note <|> err Nothing "Error parsing Note"
return E.Expense { E.amount = a , E.date = d
, E.person = p , E.shop = s
, E.tags = t , E.note = n
}
expenses :: Parser Char Location [E.Expense]
expenses = expenses_ [] >>= \es -> return $ reverse es
where optWhites = optionalWhites "a spacing between expenses"
expenses_ a = optWhites >> eof >>= \e ->
if e then return a else expense >>= \i ->
optionalWhites "a spacing between expenses" >> expenses_ (i:a)
|
fredmorcos/attic
|
projects/pet/archive/pet_haskell_cli/cli/PetParser.hs
|
isc
| 5,529 | 0 | 17 | 1,628 | 1,825 | 925 | 900 | 118 | 4 |
import Data.List
sudoku puzzle = if length (filter (==0) (concat puzzle)) == 0
then puzzle
else sudoku [[if val x y == 0 then solve x y puzzle else val x y | x <- [0..8]] | y <-[0..8]]
where val x y = (puzzle !! y) !! x
cellList n = [start..end]
where cell = n `div` 3
start = cell * 3
end = (cell+1) * 3 - 1
solve x y puzzle = if length candidate == 1 then head candidate else 0
where celld = filter (/=0) [val c r | c <- xcell, r <- ycell]
xd = filter (/=0) [val c y | c <- [0..8]]
yd = filter (/=0) [val x r | r <- [0..8]]
duple = nub $ sort (celld ++ xd ++ yd)
candidate = [1..9] \\ duple
val x y = (puzzle !! y) !! x
xcell = cellList x
ycell = cellList y
|
jwvg0425/HaskellScratchPad
|
src/sdoku_easy.hs
|
mit
| 787 | 0 | 11 | 282 | 403 | 214 | 189 | 18 | 3 |
{-# htermination (unlines :: (List (List Char)) -> (List Char)) #-}
import qualified Prelude
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Char = Char MyInt ;
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
psPs :: (List a) -> (List a) -> (List a);
psPs Nil ys = ys;
psPs (Cons x xs) ys = Cons x (psPs xs ys);
unlines :: (List (List Char)) -> (List Char);
unlines Nil = Nil;
unlines (Cons l ls) = psPs l (Cons (Char (Pos (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))) (unlines ls));
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/basic_haskell/unlines_1.hs
|
mit
| 572 | 0 | 31 | 133 | 295 | 158 | 137 | 12 | 1 |
{-# htermination group :: [Char] -> [[Char]] #-}
import List
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/List_group_3.hs
|
mit
| 61 | 0 | 3 | 10 | 5 | 3 | 2 | 1 | 0 |
-- dave = ("Dave",100,["tejer","escribirPoesia"],[ardilla,libroPedKing])
-- nombre barbaro = (n,_,_,_)
-- fuerza barbaro = (_,f,_,_)
--listaHabilidades barbaro = (_,_,lsHab,_)
--listaObjetos barbaro = (_,_,_,lsObj)
sinRepetidos [] = []
sinRepetidos (x:xs) | elem x xs = sinRepetidos xs
| otherwise = x : sinRepetidos xs
|
mnicoletti/pdep-utn-frba
|
funcional/guia-ejercicios/parcial-barbaros.hs
|
mit
| 327 | 0 | 8 | 49 | 63 | 31 | 32 | 3 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Network.Wreq
import Control.Lens hiding (deep, Review)
import Text.XML.HXT.Core
import Text.XML.HXT.DOM.FormatXmlTree
import Text.XML.HXT.Arrow.Pickle
import Text.XML.HXT.Arrow.Edit
import Text.XML.HXT.Arrow.Pickle.Schema
import qualified Data.ByteString.Lazy.Char8 as LB
import Data.Time.Clock
import Data.Time.Format
import qualified Data.Text as T
type DevKey = String
type UserId = String
type GoodreadsURL = String
type Page = Int
data Review = Review {
rBook :: Book,
rRating :: Int,
rRead :: Maybe UTCTime,
rAdded :: UTCTime,
rReviewText :: String,
rLink :: String
} deriving (Eq,Ord,Show)
instance XmlPickler Review where
xpickle = xpReview
data Book = Book {
bTitle :: String,
bImageUrl :: String,
bLink :: String,
bNumPages :: Maybe Int
} deriving (Eq,Ord,Show)
instance XmlPickler Book where
xpickle = xpBook
data GRRequestConfig = GRRequestConfig {
grDevKey :: DevKey,
grUserId :: UserId
}
-- A list of your book reviews up to the specified page (20 per page)
reviewsUpToPage :: GRRequestConfig -> Page -> IO [Either String Review]
reviewsUpToPage config n = do
responses <- downloadPagesData config 1 n
let responseBodies = fmap (\r -> r ^. responseBody) responses
return $ readXmlReviews $ concatMap parseGRResponse responseBodies
mkReadShelfURL :: UserId -> GoodreadsURL
mkReadShelfURL uid = grBaseURL ++ uid
where grBaseURL = "https://www.goodreads.com/review/list/"
mkReadShelfRequestParams :: DevKey -> Page -> Options
mkReadShelfRequestParams key page = defaults & params .~ paramList
where
paramList = [("shelf","read"),
("key",T.pack key),
("v","2"),
("format","xml"),
("per_page","20"), -- 20 is the goodreads limit
("page", (T.pack . show $ page))]
parseGRResponse rBody = parsed
where
isReview = hasName "review"
bookTags = ["title", "image_url", "link", "num_pages"]
reviewTags = ["book", "rating", "date_added", "read_at", "body", "link"]
bookFilter = foldl1 (<+>) (fmap hasName bookTags)
reviewFilter = foldl1 (<+>) (fmap hasName reviewTags)
parsed = runLA (
xreadDoc >>>
deep isReview >>>
transfAllCdata >>>
processChildren reviewFilter >>>
processChildren (processChildren bookFilter `when` hasName "book")
) $ (LB.unpack rBody)
readXmlReviews :: [XmlTree] -> [Either String Review]
readXmlReviews = fmap readXmlReview
readXmlReview :: XmlTree -> Either String Review
readXmlReview = (unpickleDoc' xpickle)
downloadPagesData :: GRRequestConfig -> Page -> Page -> IO [Response LB.ByteString]
downloadPagesData conf from to = sequence actions
where
opts = map (mkReadShelfRequestParams $ grDevKey conf) [from..to]
url = mkReadShelfURL (grUserId conf)
actions = zipWith getWith opts (repeat url)
uncurry6 fx = \(a,b,c,d,e,f) -> fx a b c d e f
xpTime = xpWrapEither (timeParse, show) xpText
where
timeParse = parseTimeM True defaultTimeLocale timeFormatString
timeFormatString = "%a %b %d %X %z %Y"
xpReview = xpElem "review" $
xpWrap (uncurry6 Review, \r -> (rBook r, rRating r, rRead r, rAdded r, rReviewText r, rLink r)) $
xp6Tuple
xpBook
(xpElem "rating" $ xpInt)
(xpElem "read_at" $ xpOption xpTime)
(xpElem "date_added" $ xpTime)
(xpElem "body" $ xpText)
(xpElem "link" $ xpText)
xpBook = xpElem "book" $
xpWrap (uncurry4 Book, \b -> (bTitle b, bImageUrl b, bLink b, bNumPages b)) $
xp4Tuple
(xpElem "title" $ xpText)
(xpElem "image_url" $ xpText)
(xpElem "link" $ xpText)
(xpElem "num_pages" $ xpOption xpInt)
|
rafalio/goodreadsHaskell
|
goodreadsHaskell.hs
|
mit
| 3,774 | 0 | 14 | 843 | 1,148 | 636 | 512 | 96 | 1 |
module Main where
import Criterion.Main
import Data.Bits
import Data.String
import Network.MQTT.Message
import Network.MQTT.Trie as R
main :: IO ()
main = filterTree `seq` defaultMain [benchmark]
benchmark :: Benchmark
benchmark = bench "Matching 512 topics against 20000 permissions." $ whnf (foldr (\topic accum-> accum `xor` R.matchTopic topic filterTree) False) topics
filterTree :: Trie ()
filterTree = foldr (\f t-> R.insert (fromString f) () t) mempty filters
filters :: [String]
filters = [ [x1,x2,x3,'/',x4,x5,x6,'/',x7,x8,x9] | x1<-r,x2<-r,x3<-r,x4<-r,x5<-r,x6<-r,x7<-r,x8<-r,x9<-r]
where
r = ['a'..'c']
topics :: [Topic]
topics = fromString <$> f filters
where
f [] = []
f xs = head xs : f (drop 36 xs)
|
lpeterse/haskell-mqtt
|
benchmark/TopicMatching.hs
|
mit
| 792 | 0 | 13 | 180 | 355 | 195 | 160 | 19 | 2 |
import Control.Monad
data Context = Home | Mobile | Business
deriving (Eq, Show)
type Phone = String
albulena = [(Home, "+355-652-55512")]
nils = [(Mobile, "+47-922-55-512"), (Business, "+47-922-12-121"),
(Home, "+47-925-55-121"), (Business, "+47-922-25-551")]
twalumba = [(Business, "+260-02-55-5121")]
onePersnalPhone :: [(Context, Phone)] -> Maybe Phone
onePersnalPhone alist =
lookup Home alist `mplus` lookup Mobile alist
allBusinessPhones :: [(Context, Phone)] -> [Phone]
allBusinessPhones ps = map snd $ filter (contextIs Business) ps
`mplus` filter (contextIs Mobile) ps
contextIs a (b,_) = a == b
lookupM :: (MonadPlus m, Eq a) => a -> [(a,b)] -> m b
lookupM _ [] = mzero
lookupM key ((x,y):xys)
| key == x = return y `mplus` lookupM key xys
| otherwise = lookupM key xys
|
zhangjiji/real-world-haskell
|
ch15/VCard.hs
|
mit
| 841 | 0 | 9 | 178 | 347 | 193 | 154 | 20 | 1 |
-- Binary sXORe
-- http://www.codewars.com/kata/56d3e702fc231fdf72001779
module Kata.BinarySxore where
sxore :: Integer -> Integer
sxore n | even n && n `mod` 4 == 0 = n
| even n = succ n
| n `mod` 4 == 1 = 1
| otherwise = 0
|
gafiatulin/codewars
|
src/7 kyu/BinarySxore.hs
|
mit
| 251 | 0 | 11 | 70 | 91 | 46 | 45 | 6 | 1 |
-- | Access to @RealAddress@ from within the @GBA@ monad.
module Game.GBA.Memory.Real
( RealAddress
, Segment
, SegmentOffset
, readReal8
, readReal16
, readReal32
, writeReal8
, writeReal16
, writeReal32
, virtual
)
where
import Control.Applicative
import Control.Monad.Base
import Data.Bits
import Data.Word
import Game.GBA.MemoryMap
import Game.GBA.Monad
-- | Write to a real address. (in 8-bit mode)
writeReal8 :: RealAddress -> Word8 -> GBA s ()
writeReal8 addr val = do
mem <- viewLens gbaMemoryMap
liftBase $ writeRaw mem addr val
-- | Write to a real address. (in 16-bit mode)
--
-- Uses little-endian.
writeReal16 :: RealAddress -> Word16 -> GBA s ()
writeReal16 (seg, off) val = do
writeReal8 (seg, off) . fromIntegral $ shiftR (shiftL val 8) 8
writeReal8 (seg, off+1) . fromIntegral $ shiftR val 8
-- | Write to a real address. (in 32-bit mode)
--
-- Uses little-endian.
writeReal32 :: RealAddress -> Word32 -> GBA s ()
writeReal32 (seg, off) val = do
writeReal16 (seg, off) . fromIntegral $ shiftR (shiftL val 16) 16
writeReal16 (seg, off+2) . fromIntegral $ shiftR val 16
-- | Read from a real address. (in 8-bit mode)
readReal8 :: RealAddress -> GBA s Word8
readReal8 addr = do
mem <- viewLens gbaMemoryMap
liftBase $ readRaw mem addr
-- | Read from a real address. (in 16-bit mode)
--
-- Uses little-endian.
readReal16 :: RealAddress -> GBA s Word16
readReal16 (seg, off) = do
ms <- fromIntegral <$> readReal8 (seg, off+1)
ls <- fromIntegral <$> readReal8 (seg, off)
return $ shiftL ms 8 `xor` ls
-- | Read from a real address. (in 32-bit mode)
--
-- Uses little-endian.
readReal32 :: RealAddress -> GBA s Word32
readReal32 (seg, off) = do
ms <- fromIntegral <$> readReal16 (seg, off+2)
ls <- fromIntegral <$> readReal16 (seg, off)
return $ shiftL ms 16 `xor` ls
|
jhance/gba-hs
|
src/Game/GBA/Memory/Real.hs
|
mit
| 1,945 | 0 | 11 | 469 | 562 | 298 | 264 | 43 | 1 |
module Web.TSBot.ClientQuery.TelnetSpec (spec) where
import Web.TSBot.ClientQuery.Telnet ()
import Test.Hspec
spec :: Spec
spec = it "is" pending
|
taktoa/TSBot
|
test-suite/Web/TSBot/ClientQuery/TelnetSpec.hs
|
mit
| 149 | 0 | 5 | 20 | 43 | 27 | 16 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Monoid
import Control.Monad
import Control.Exception
import Control.Concurrent
import System.Socket
import System.Socket.Family.Inet as Inet
import System.Socket.Protocol.SCTP as SCTP
main :: IO ()
main = do
server <- socket `onException` p 0 :: IO (Socket Inet SequentialPacket SCTP)
client <- socket `onException` p 1 :: IO (Socket Inet SequentialPacket SCTP)
bind server addr `onException` p 3
listen server 5 `onException` p 4
connect client addr `onException` p 5
setSocketOption
server
(mempty { dataIOEvent = True }) `onException` p 6
SCTP.sendMessage
client
"hallo"
addr
( 2342 :: PayloadProtocolIdentifier )
( mempty :: MessageFlags )
( 2 :: StreamNumber )
( 3 :: TimeToLive )
( 4 :: Context ) `onException` p 7
(msg, adr, sinfo, flags) <- SCTP.receiveMessage server 4096 mempty
`onException` p 8
when (sinfoPayloadProtocolIdentifier sinfo /= 2342) (e 9)
when (sinfoStreamNumber sinfo /= 2) (e 10)
when (msg /= "hallo") (e 11)
when (flags /= msgEndOfRecord) (e 12)
addr :: SocketAddressInet
addr = SocketAddressInet Inet.loopback 7777
p :: Int -> IO ()
p i = print i
e :: Int -> IO ()
e i = error (show i)
|
nh2/haskell-socket-sctp
|
tests/SendReceiveMessage.hs
|
mit
| 1,399 | 0 | 11 | 405 | 467 | 245 | 222 | 40 | 1 |
{-# OPTIONS_GHC -F -pgmF htfpp #-}
module Main where
import Test.Framework
import {-@ HTF_TESTS @-} Web.DataUrlTest
main :: IO ()
main = htfMain htf_importedTests
|
agrafix/dataurl
|
test/Test.hs
|
mit
| 165 | 0 | 6 | 26 | 34 | 20 | 14 | 6 | 1 |
euler015 :: Int -> Integer
euler015 x = let x' = fromIntegral x in (2*x') `choose` x'
where
choose _ 0 = 1
choose 0 _ = 0
choose n k = ((n-1) `choose` (k-1)) * n `div` k
main :: IO ()
main = print $ euler015 20
|
marknsikora/euler
|
euler015/euler015.hs
|
mit
| 226 | 0 | 12 | 64 | 132 | 70 | 62 | 7 | 3 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module GitMail.Time
( Time(..)
, unsafeFromLocalTime
) where
import Control.Applicative
import Data.Aeson
import Data.Aeson.Parser
import Data.Maybe ( fromMaybe )
import Data.String
import qualified Data.Time as T
import Data.Text ( pack, unpack )
-- | A wrapper around a "T.UTCTime" with instances for "ToJSON", "FromJSON",
-- and "IsString".
newtype Time = Time { unTime :: T.UTCTime
}
deriving (Show, Ord, Eq)
instance ToJSON Time where
toJSON (Time { unTime = t }) = String $ formatTime t
instance FromJSON Time where
parseJSON (String t) = Time <$> parseTime (unpack t)
parseJSON _ = fail "failed to parse time (not a string)"
instance IsString Time where
fromString = Time . fromMaybe (error "invalid time string literal") . parseTime
-- | Convert a "LocalTime" into a HackSignal "Time", ignoring timezones.
unsafeFromLocalTime :: T.LocalTime -> Time
unsafeFromLocalTime = Time . T.localTimeToUTC T.utc
iso8601 = T.iso8601DateFormat (Just "%H:%M:%S%Q%Z")
formatTime = pack . T.formatTime T.defaultTimeLocale iso8601
parseTime :: (Monad m, T.ParseTime s) => String -> m s
parseTime = T.parseTimeM False T.defaultTimeLocale iso8601
|
ShivanKaul/gitmail
|
github/src/GitMail/Time.hs
|
mit
| 1,334 | 0 | 10 | 325 | 321 | 176 | 145 | 26 | 1 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_HADDOCK show-extensions #-}
-- |
-- Module : Yi.Tag
-- License : GPL-2
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- A module for CTags integration. Note that this reads the ‘tags’
-- file produced by @hasktags@, not the ‘TAGS’ file which uses a
-- different format (etags).
module Yi.Tag ( lookupTag
, importTagTable
, hintTags
, completeTag
, Tag(..)
, mkTag
, unTag'
, TagTable(..)
, getTags
, setTags
, resetTags
, tagsFileList
) where
import Control.Applicative
import Control.Lens
import Data.Binary
import qualified Data.ByteString as BS
import qualified Data.ByteString.UTF8 as BS8
#if __GLASGOW_HASKELL__ < 708
import Data.DeriveTH
#else
import GHC.Generics (Generic)
#endif
import Data.Default
import qualified Data.Foldable as F
import Data.List (isPrefixOf)
import Data.Map (Map, fromListWith, lookup, keys)
import Data.Maybe (mapMaybe)
import qualified Data.Text as T
import qualified Data.Text.Encoding as E
import qualified Data.Trie as Trie
import Data.Typeable
import System.FilePath (takeFileName, takeDirectory, (</>))
import System.FriendlyPath
import Yi.Editor
import Yi.Config.Simple.Types (Field, customVariable)
import Yi.Types (YiVariable, YiConfigVariable)
newtype TagsFileList = TagsFileList { _unTagsFileList :: [FilePath] }
deriving Typeable
instance Default TagsFileList where
def = TagsFileList ["tags"]
instance YiConfigVariable TagsFileList
makeLenses ''TagsFileList
tagsFileList :: Field [FilePath]
tagsFileList = customVariable . unTagsFileList
newtype Tags = Tags (Maybe TagTable) deriving Typeable
instance Default Tags where
def = Tags Nothing
instance YiVariable Tags
newtype Tag = Tag { _unTag :: T.Text } deriving (Show, Eq, Ord)
-- | Helper
mkTag :: String -> Tag
mkTag = Tag . T.pack
unTag' :: Tag -> String
unTag' = T.unpack . _unTag
instance Binary Tag where
put (Tag t) = put (E.encodeUtf8 t)
get = Tag . E.decodeUtf8 <$> get
data TagTable = TagTable { tagFileName :: FilePath
-- ^ local name of the tag file
-- TODO: reload if this file is changed
, tagBaseDir :: FilePath
-- ^ path to the tag file directory
-- tags are relative to this path
, tagFileMap :: Map Tag [(FilePath, Int)]
-- ^ map from tags to files
, tagTrie :: Trie.Trie
-- ^ trie to speed up tag hinting
} deriving Typeable
-- | Find the location of a tag using the tag table.
-- Returns a full path and line number
lookupTag :: Tag -> TagTable -> [(FilePath, Int)]
lookupTag tag tagTable = do
(file, line) <- F.concat . Data.Map.lookup tag $ tagFileMap tagTable
return (tagBaseDir tagTable </> file, line)
-- | Super simple parsing CTag format 1 parsing algorithm
-- TODO: support search patterns in addition to lineno
readCTags :: String -> Map Tag [(FilePath, Int)]
readCTags =
fromListWith (++) . mapMaybe (parseTagLine . words) . lines
where parseTagLine (tag:tagfile:lineno:_) =
-- remove ctag control lines
if "!_TAG_" `isPrefixOf` tag then Nothing
else Just (mkTag tag, [(tagfile, fst . head . reads $ lineno)])
parseTagLine _ = Nothing
-- | Read in a tag file from the system
importTagTable :: FilePath -> IO TagTable
importTagTable filename = do
friendlyName <- expandTilda filename
tagStr <- fmap BS8.toString $ BS.readFile friendlyName
let cts = readCTags tagStr
return TagTable { tagFileName = takeFileName filename
, tagBaseDir = takeDirectory filename
, tagFileMap = cts
-- TODO either change word-trie to use Text or
-- figure out a better way all together for this
, tagTrie = Trie.fromList . map (T.unpack . _unTag) $ keys cts
}
-- | Gives all the possible expanded tags that could match a given @prefix@
hintTags :: TagTable -> T.Text -> [T.Text]
hintTags tags prefix = map (T.append prefix . T.pack) sufs
where
sufs = Trie.possibleSuffixes (T.unpack prefix) $ tagTrie tags
-- | Extends the string to the longest certain length
completeTag :: TagTable -> T.Text -> T.Text
completeTag tags prefix =
prefix `T.append` T.pack (Trie.certainSuffix (T.unpack prefix) (tagTrie tags))
-- ---------------------------------------------------------------------
-- Direct access interface to TagTable.
-- | Set a new TagTable
setTags :: TagTable -> EditorM ()
setTags = putEditorDyn . Tags . Just
-- | Reset the TagTable
resetTags :: EditorM ()
resetTags = putEditorDyn $ Tags Nothing
-- | Get the currently registered tag table
getTags :: EditorM (Maybe TagTable)
getTags = do
Tags t <- getEditorDyn
return t
#if __GLASGOW_HASKELL__ < 708
$(derive makeBinary ''Tags)
$(derive makeBinary ''TagTable)
$(derive makeBinary ''TagsFileList)
#else
deriving instance Generic Tags
deriving instance Generic TagTable
deriving instance Generic TagsFileList
instance Binary Tags
instance Binary TagTable
instance Binary TagsFileList
#endif
|
atsukotakahashi/wi
|
src/library/Yi/Tag.hs
|
gpl-2.0
| 5,763 | 0 | 15 | 1,583 | 1,161 | 659 | 502 | 101 | 3 |
module Game
where
import qualified Control.Monad.State as S
--https://www.haskell.org/haskellwiki/Arrays#Immutable_arrays_.28module_Data.Array.IArray.29
--https://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-IArray.html
--https://www.haskell.org/ghc/docs/latest/html/libraries/array/Data-Array-IArray.html#t:Array
import qualified Data.Array.IArray as IA
import qualified Gen as G
import qualified Func as F
type GameState = F.Grid
type GameValue = G.Point
type GameResult = F.Progress
{-
playGame :: String -> S.State GameState GameValue
playGame [] = do
s <- S.get
return s
step :: F.Grid -> G.Point -> F.Grid
step g p@(G.Point x y)
| F.progress g /= InProgress = g
| F.marking item in [QuestionMark, Normal] = g IA.// [((x,y),item')]
where
item :: GridCell
item = IA.! g (x y)
item' :: GridCell
item' = F.MineCell (mine item) Revealed
-}
--runGame :: S.State [Int] Int
--runGame s a = a:s
main :: IO ()
main = undefined
|
AaronShiny/minesweeper
|
src/Game.hs
|
gpl-2.0
| 974 | 0 | 6 | 153 | 79 | 56 | 23 | 10 | 1 |
---- linecount.hs
---- Counts the number of lines in a file.
import System.Environment (getArgs)
import System.Exit (exitFailure)
import System.IO (readFile)
import System.IO.Error
( catchIOError
, ioeGetFileName
, ioError
, isDoesNotExistError
, isPermissionError
)
countLines :: String -> String
countLines x = "The file has " ++ lineCount ++ " lines!"
where lineCount = show . length . lines $ x
errorHandler :: IOError -> IO ()
errorHandler e
| isDoesNotExistError e = putStrLn $ "File does not exist: " ++ path
| isPermissionError e = putStrLn $ "Permission denied: " ++ path
| otherwise = ioError e
where
path = case ioeGetFileName e of
Just path -> path
Nothing -> "unknown path"
main :: IO ()
main = catchIOError main' (\e -> errorHandler e >> exitFailure)
main' :: IO ()
main' = putStrLn . countLines =<< readFile . head =<< getArgs
|
friedbrice/Haskell
|
ch09/linecount.hs
|
gpl-2.0
| 881 | 4 | 10 | 180 | 270 | 140 | 130 | 24 | 2 |
module PropT17 where
import Prelude(Bool(..))
import Zeno
-- Definitions
True && x = x
_ && _ = False
False || x = x
_ || _ = True
not True = False
not False = True
-- Nats
data Nat = S Nat | Z
(+) :: Nat -> Nat -> Nat
Z + y = y
(S x) + y = S (x + y)
(*) :: Nat -> Nat -> Nat
Z * _ = Z
(S x) * y = y + (x * y)
(==),(/=) :: Nat -> Nat -> Bool
Z == Z = True
Z == _ = False
S _ == Z = False
S x == S y = x == y
x /= y = not (x == y)
(<=) :: Nat -> Nat -> Bool
Z <= _ = True
_ <= Z = False
S x <= S y = x <= y
one, zero :: Nat
zero = Z
one = S Z
double :: Nat -> Nat
double Z = Z
double (S x) = S (S (double x))
even :: Nat -> Bool
even Z = True
even (S Z) = False
even (S (S x)) = even x
half :: Nat -> Nat
half Z = Z
half (S Z) = Z
half (S (S x)) = S (half x)
mult :: Nat -> Nat -> Nat -> Nat
mult Z _ acc = acc
mult (S x) y acc = mult x y (y + acc)
fac :: Nat -> Nat
fac Z = S Z
fac (S x) = S x * fac x
qfac :: Nat -> Nat -> Nat
qfac Z acc = acc
qfac (S x) acc = qfac x (S x * acc)
exp :: Nat -> Nat -> Nat
exp _ Z = S Z
exp x (S n) = x * exp x n
qexp :: Nat -> Nat -> Nat -> Nat
qexp x Z acc = acc
qexp x (S n) acc = qexp x n (x * acc)
-- Lists
length :: [a] -> Nat
length [] = Z
length (_:xs) = S (length xs)
(++) :: [a] -> [a] -> [a]
[] ++ ys = ys
(x:xs) ++ ys = x : (xs ++ ys)
drop :: Nat -> [a] -> [a]
drop Z xs = xs
drop _ [] = []
drop (S x) (_:xs) = drop x xs
rev :: [a] -> [a]
rev [] = []
rev (x:xs) = rev xs ++ [x]
qrev :: [a] -> [a] -> [a]
qrev [] acc = acc
qrev (x:xs) acc = qrev xs (x:acc)
revflat :: [[a]] -> [a]
revflat [] = []
revflat ([]:xss) = revflat xss
revflat ((x:xs):xss) = revflat (xs:xss) ++ [x]
qrevflat :: [[a]] -> [a] -> [a]
qrevflat [] acc = acc
qrevflat ([]:xss) acc = qrevflat xss acc
qrevflat ((x:xs):xss) acc = qrevflat (xs:xss) (x:acc)
rotate :: Nat -> [a] -> [a]
rotate Z xs = xs
rotate _ [] = []
rotate (S n) (x:xs) = rotate n (xs ++ [x])
elem :: Nat -> [Nat] -> Bool
elem _ [] = False
elem n (x:xs) = n == x || elem n xs
subset :: [Nat] -> [Nat] -> Bool
subset [] ys = True
subset (x:xs) ys = x `elem` xs && subset xs ys
intersect,union :: [Nat] -> [Nat] -> [Nat]
(x:xs) `intersect` ys | x `elem` ys = x:(xs `intersect` ys)
| otherwise = xs `intersect` ys
[] `intersect` ys = []
union (x:xs) ys | x `elem` ys = union xs ys
| otherwise = x:(union xs ys)
union [] ys = ys
isort :: [Nat] -> [Nat]
isort [] = []
isort (x:xs) = insert x (isort xs)
insert :: Nat -> [Nat] -> [Nat]
insert n [] = [n]
insert n (x:xs) =
case n <= x of
True -> n : x : xs
False -> x : (insert n xs)
count :: Nat -> [Nat] -> Nat
count n (x:xs) | n == x = S (count n xs)
| otherwise = count n xs
count n [] = Z
sorted :: [Nat] -> Bool
sorted (x:y:xs) = x <= y && sorted (y:xs)
sorted _ = True
-- Theorem
prop_T17 :: [a] -> [a] -> Prop
prop_T17 x y = prove (rev (rev (x ++ y)) :=: rev (rev x) ++ rev (rev y))
|
danr/hipspec
|
testsuite/prod/zeno_version/PropT17.hs
|
gpl-3.0
| 2,998 | 0 | 13 | 924 | 2,027 | 1,054 | 973 | 114 | 2 |
{-
The Code Of Life - Renders a 3D interactive model of DNA (a double helix) in a recursive manner in which the bonds of the DNA are made up of more double helices and so on. Be Warned! This program can be very tasking for you PC
Copyright (C) 2013 Euan Hunter
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 <http://www.gnu.org/licenses/>.
-}
module DoubleHelix(DoubleHelixModel, genDHelix, renderDHelix, DoubleHelix.extractHeight) where
import Graphics.UI.GLUT
import Helix
type DoubleHelixModel = (HelixModel, HelixModel, GLdouble)
genDHelix :: Helix GLdouble GLdouble -> GLdouble -> DoubleHelixModel
genDHelix mhelix d = (hel 0.0 ,hel pi, Helix.extractHeight mhelix)
where
hel = genHelix mhelix d
renderDHelix :: DoubleHelixModel -> Int -> IO ()
renderDHelix (h1,h2, _) mode = renderHelix h1 mode >> renderHelix h2 mode
extractHeight :: DoubleHelixModel -> GLdouble
extractHeight (_,_,h) = h
|
SamLex/TheCodeOfLife
|
src/DoubleHelix.hs
|
gpl-3.0
| 1,546 | 0 | 8 | 345 | 182 | 101 | 81 | 11 | 1 |
module GtkBlast.Captcha
(CaptchaMode(..)
,addCaptcha
,killAllCaptcha
,captchaModeEnvPart
,maintainCaptcha
) where
import Import hiding (on, mod)
import GtkBlast.MuVar
import GtkBlast.Environment
import GtkBlast.Log
import GtkBlast.Conf
import GtkBlast.EnvPart
import GtkBlast.GuiCaptcha
import GtkBlast.AntigateCaptcha
import GtkBlast.Types
import BlastItWithPiss
import Graphics.UI.Gtk hiding (get, set)
cmToBool :: CaptchaMode -> Bool
cmToBool Gui = False
cmToBool Antigate = True
cmFromBool :: Bool -> CaptchaMode
cmFromBool False = Gui
cmFromBool True = Antigate
addCaptcha :: (CaptchaOrigin, CaptchaRequest) -> E ()
addCaptcha sp = do
cm <- get =<< asks captchaMode
case cm of
Gui -> addGuiCaptcha sp
Antigate -> addAntigateCaptcha sp
-- | 'killAllCaptcha' should only be called when all the threads blocking on captcha are dead
killAllCaptcha :: E ()
killAllCaptcha = do
cm <- get =<< asks captchaMode
case cm of
Gui -> killGuiCaptcha
Antigate -> killAntigateCaptcha
deactivateCaptcha :: CaptchaMode -> E [(CaptchaOrigin, CaptchaRequest)]
deactivateCaptcha Gui = deactivateGuiCaptcha
deactivateCaptcha Antigate = deactivateAntigateCaptcha
migrateCaptcha :: CaptchaMode -> CaptchaMode -> E ()
migrateCaptcha ocm ncm = do
writeLog $ "Migrating captchas from " ++ show ocm ++ " to " ++ show ncm
captchas <- deactivateCaptcha ocm
writeLog $ "Got " ++ show (length captchas) ++ " for migration"
addCaptchas ncm captchas
where
addCaptchas Gui = addGuiCaptchas
addCaptchas Antigate = addAntigateCaptchas
captchaModeEnvPart :: Builder -> EnvPart
captchaModeEnvPart b = EP
(\e c -> do
wcheckantigate <- setir ((cmToBool . coCaptchaMode) c)
=<< builderGetObject b castToCheckButton "checkantigate"
captchaMode <- newIORef (coCaptchaMode c)
void $ on wcheckantigate buttonActivated $ do
oldMode <- get captchaMode
let newMode = cmFromBool $ not $ cmToBool oldMode
set captchaMode newMode
runE e $ migrateCaptcha oldMode newMode
return captchaMode
)
(\v c -> get v <&> \a -> c{coCaptchaMode=a})
(\v e -> e{captchaMode=v})
maintainCaptcha :: [(Board, [BlastProxy])] -> E ()
maintainCaptcha blacklist = do
cm <- get =<< asks captchaMode
case cm of
Gui -> maintainGuiCaptcha blacklist
Antigate -> maintainAntigateCaptcha blacklist
|
exbb2/BlastItWithPiss
|
src/GtkBlast/Captcha.hs
|
gpl-3.0
| 2,466 | 0 | 17 | 548 | 693 | 352 | 341 | 66 | 2 |
module Frame.Continuation
( Payload
, endHeadersF
, isEndHeaders
, mkPayload
, getHeaderFragment
, getPayload
, putPayload
, toString
) where
import Data.ByteString.Lazy (ByteString)
import Data.Binary.Get (Get)
import qualified Data.Binary.Get as Get
import Control.Monad.Except (ExceptT, lift)
import qualified Data.Binary.Put as Put
import Data.Binary.Put (Put)
import ProjectPrelude
import ErrorCodes
data Payload = Payload ByteString
endHeadersF :: FrameFlags
endHeadersF = 0x4
isEndHeaders :: FrameFlags -> Bool
isEndHeaders f = testFlag f endHeadersF
getHeaderFragment :: Payload -> ByteString
getHeaderFragment (Payload bs) = bs
mkPayload :: ByteString -> Payload
mkPayload bs = Payload bs
getPayload :: FrameLength -> FrameFlags -> StreamId -> ExceptT ConnError Get Payload
getPayload fLength _ _ = do
fmap Payload $ lift $ Get.getLazyByteString $ fromIntegral fLength
putPayload :: Payload -> Put
putPayload (Payload bs) = Put.putLazyByteString bs
toString :: String -> Payload -> String
toString prefix (Payload bs) =
prefix ++ "fragment: " ++ show bs
|
authchir/SoSe17-FFP-haskell-http2-server
|
src/Frame/Continuation.hs
|
gpl-3.0
| 1,132 | 0 | 10 | 215 | 314 | 175 | 139 | 34 | 1 |
module Schnizle.Config
( config
, pandocOptions
, feedConfig
) where
import Hakyll
import qualified Text.Pandoc.Options as O
import Text.Highlighting.Kate.Styles (pygments)
config :: Configuration
config = defaultConfiguration
{ deployCommand = "rsync -avz -e ssh ./_site/ schnizle.in:/home/felixsch/html/" }
pandocOptions :: O.WriterOptions
pandocOptions = defaultHakyllWriterOptions
{ O.writerHtml5 = True
, O.writerHtmlQTags = True
, O.writerSectionDivs = True
, O.writerTableOfContents = True
, O.writerHighlight = True
, O.writerHighlightStyle = pygments
, O.writerExtensions = O.githubMarkdownExtensions
}
feedConfig :: FeedConfiguration
feedConfig
= FeedConfiguration
{ feedTitle = "schnizle.in - What ever comes to mind"
, feedDescription = "Blog of felixsch"
, feedAuthorName = "Felix S."
, feedAuthorEmail = "[email protected]"
, feedRoot = "http://schnizle.in"
}
|
felixsch/schnizle
|
Schnizle/Config.hs
|
gpl-3.0
| 973 | 0 | 7 | 207 | 173 | 110 | 63 | 27 | 1 |
module DL3051 (tests) where
import qualified Data.Map as Map
import qualified Hadolint.Process
import qualified Hadolint.Rule as Rule
import Helpers
import Test.Hspec
tests :: SpecWith ()
tests = do
let ?rulesConfig = Hadolint.Process.RulesConfig [] (Map.fromList [("emptylabel", Rule.RawText)]) False
describe "DL3051 - Label `<label>` is empty." $ do
it "not ok with label empty" $ do
ruleCatches "DL3051" "LABEL emptylabel=\"\""
onBuildRuleCatches "DL3051" "LABEL emptylabel=\"\""
it "ok with label not empty" $ do
ruleCatchesNot "DL3051" "LABEL emptylabel=\"foo\""
onBuildRuleCatchesNot "DL3051" "LABEL emptylabel=\"bar\""
it "ok with other label empty" $ do
ruleCatchesNot "DL3051" "LABEL other=\"\""
onBuildRuleCatchesNot "DL3051" "LABEL other=\"\""
|
lukasmartinelli/hadolint
|
test/DL3051.hs
|
gpl-3.0
| 811 | 0 | 15 | 149 | 182 | 90 | 92 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.Content.Datafeeds.Delete
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes a datafeed from your Merchant Center account. This method can
-- only be called for non-multi-client accounts.
--
-- /See:/ <https://developers.google.com/shopping-content Content API for Shopping Reference> for @content.datafeeds.delete@.
module Network.Google.Resource.Content.Datafeeds.Delete
(
-- * REST Resource
DatafeedsDeleteResource
-- * Creating a Request
, datafeedsDelete
, DatafeedsDelete
-- * Request Lenses
, ddMerchantId
, ddDatafeedId
, ddDryRun
) where
import Network.Google.Prelude
import Network.Google.ShoppingContent.Types
-- | A resource alias for @content.datafeeds.delete@ method which the
-- 'DatafeedsDelete' request conforms to.
type DatafeedsDeleteResource =
"content" :>
"v2" :>
Capture "merchantId" (Textual Word64) :>
"datafeeds" :>
Capture "datafeedId" (Textual Word64) :>
QueryParam "dryRun" Bool :>
QueryParam "alt" AltJSON :> Delete '[JSON] ()
-- | Deletes a datafeed from your Merchant Center account. This method can
-- only be called for non-multi-client accounts.
--
-- /See:/ 'datafeedsDelete' smart constructor.
data DatafeedsDelete = DatafeedsDelete'
{ _ddMerchantId :: !(Textual Word64)
, _ddDatafeedId :: !(Textual Word64)
, _ddDryRun :: !(Maybe Bool)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'DatafeedsDelete' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ddMerchantId'
--
-- * 'ddDatafeedId'
--
-- * 'ddDryRun'
datafeedsDelete
:: Word64 -- ^ 'ddMerchantId'
-> Word64 -- ^ 'ddDatafeedId'
-> DatafeedsDelete
datafeedsDelete pDdMerchantId_ pDdDatafeedId_ =
DatafeedsDelete'
{ _ddMerchantId = _Coerce # pDdMerchantId_
, _ddDatafeedId = _Coerce # pDdDatafeedId_
, _ddDryRun = Nothing
}
ddMerchantId :: Lens' DatafeedsDelete Word64
ddMerchantId
= lens _ddMerchantId (\ s a -> s{_ddMerchantId = a})
. _Coerce
ddDatafeedId :: Lens' DatafeedsDelete Word64
ddDatafeedId
= lens _ddDatafeedId (\ s a -> s{_ddDatafeedId = a})
. _Coerce
-- | Flag to run the request in dry-run mode.
ddDryRun :: Lens' DatafeedsDelete (Maybe Bool)
ddDryRun = lens _ddDryRun (\ s a -> s{_ddDryRun = a})
instance GoogleRequest DatafeedsDelete where
type Rs DatafeedsDelete = ()
type Scopes DatafeedsDelete =
'["https://www.googleapis.com/auth/content"]
requestClient DatafeedsDelete'{..}
= go _ddMerchantId _ddDatafeedId _ddDryRun
(Just AltJSON)
shoppingContentService
where go
= buildClient
(Proxy :: Proxy DatafeedsDeleteResource)
mempty
|
rueshyna/gogol
|
gogol-shopping-content/gen/Network/Google/Resource/Content/Datafeeds/Delete.hs
|
mpl-2.0
| 3,615 | 0 | 14 | 838 | 501 | 294 | 207 | 72 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.BigtableAdmin.Projects.Instances.Clusters.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets information about a cluster.
--
-- /See:/ <https://cloud.google.com/bigtable/ Cloud Bigtable Admin API Reference> for @bigtableadmin.projects.instances.clusters.get@.
module Network.Google.Resource.BigtableAdmin.Projects.Instances.Clusters.Get
(
-- * REST Resource
ProjectsInstancesClustersGetResource
-- * Creating a Request
, projectsInstancesClustersGet
, ProjectsInstancesClustersGet
-- * Request Lenses
, picgXgafv
, picgUploadProtocol
, picgAccessToken
, picgUploadType
, picgName
, picgCallback
) where
import Network.Google.BigtableAdmin.Types
import Network.Google.Prelude
-- | A resource alias for @bigtableadmin.projects.instances.clusters.get@ method which the
-- 'ProjectsInstancesClustersGet' request conforms to.
type ProjectsInstancesClustersGetResource =
"v2" :>
Capture "name" Text :>
QueryParam "$.xgafv" Xgafv :>
QueryParam "upload_protocol" Text :>
QueryParam "access_token" Text :>
QueryParam "uploadType" Text :>
QueryParam "callback" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] Cluster
-- | Gets information about a cluster.
--
-- /See:/ 'projectsInstancesClustersGet' smart constructor.
data ProjectsInstancesClustersGet =
ProjectsInstancesClustersGet'
{ _picgXgafv :: !(Maybe Xgafv)
, _picgUploadProtocol :: !(Maybe Text)
, _picgAccessToken :: !(Maybe Text)
, _picgUploadType :: !(Maybe Text)
, _picgName :: !Text
, _picgCallback :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ProjectsInstancesClustersGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'picgXgafv'
--
-- * 'picgUploadProtocol'
--
-- * 'picgAccessToken'
--
-- * 'picgUploadType'
--
-- * 'picgName'
--
-- * 'picgCallback'
projectsInstancesClustersGet
:: Text -- ^ 'picgName'
-> ProjectsInstancesClustersGet
projectsInstancesClustersGet pPicgName_ =
ProjectsInstancesClustersGet'
{ _picgXgafv = Nothing
, _picgUploadProtocol = Nothing
, _picgAccessToken = Nothing
, _picgUploadType = Nothing
, _picgName = pPicgName_
, _picgCallback = Nothing
}
-- | V1 error format.
picgXgafv :: Lens' ProjectsInstancesClustersGet (Maybe Xgafv)
picgXgafv
= lens _picgXgafv (\ s a -> s{_picgXgafv = a})
-- | Upload protocol for media (e.g. \"raw\", \"multipart\").
picgUploadProtocol :: Lens' ProjectsInstancesClustersGet (Maybe Text)
picgUploadProtocol
= lens _picgUploadProtocol
(\ s a -> s{_picgUploadProtocol = a})
-- | OAuth access token.
picgAccessToken :: Lens' ProjectsInstancesClustersGet (Maybe Text)
picgAccessToken
= lens _picgAccessToken
(\ s a -> s{_picgAccessToken = a})
-- | Legacy upload protocol for media (e.g. \"media\", \"multipart\").
picgUploadType :: Lens' ProjectsInstancesClustersGet (Maybe Text)
picgUploadType
= lens _picgUploadType
(\ s a -> s{_picgUploadType = a})
-- | Required. The unique name of the requested cluster. Values are of the
-- form
-- \`projects\/{project}\/instances\/{instance}\/clusters\/{cluster}\`.
picgName :: Lens' ProjectsInstancesClustersGet Text
picgName = lens _picgName (\ s a -> s{_picgName = a})
-- | JSONP
picgCallback :: Lens' ProjectsInstancesClustersGet (Maybe Text)
picgCallback
= lens _picgCallback (\ s a -> s{_picgCallback = a})
instance GoogleRequest ProjectsInstancesClustersGet
where
type Rs ProjectsInstancesClustersGet = Cluster
type Scopes ProjectsInstancesClustersGet =
'["https://www.googleapis.com/auth/bigtable.admin",
"https://www.googleapis.com/auth/bigtable.admin.cluster",
"https://www.googleapis.com/auth/bigtable.admin.instance",
"https://www.googleapis.com/auth/cloud-bigtable.admin",
"https://www.googleapis.com/auth/cloud-bigtable.admin.cluster",
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/cloud-platform.read-only"]
requestClient ProjectsInstancesClustersGet'{..}
= go _picgName _picgXgafv _picgUploadProtocol
_picgAccessToken
_picgUploadType
_picgCallback
(Just AltJSON)
bigtableAdminService
where go
= buildClient
(Proxy :: Proxy ProjectsInstancesClustersGetResource)
mempty
|
brendanhay/gogol
|
gogol-bigtableadmin/gen/Network/Google/Resource/BigtableAdmin/Projects/Instances/Clusters/Get.hs
|
mpl-2.0
| 5,365 | 0 | 15 | 1,140 | 716 | 421 | 295 | 107 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.DFAReporting.Countries.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Gets one country by ID.
--
-- /See:/ <https://developers.google.com/doubleclick-advertisers/ DCM/DFA Reporting And Trafficking API Reference> for @dfareporting.countries.get@.
module Network.Google.Resource.DFAReporting.Countries.Get
(
-- * REST Resource
CountriesGetResource
-- * Creating a Request
, countriesGet
, CountriesGet
-- * Request Lenses
, cgProFileId
, cgDartId
) where
import Network.Google.DFAReporting.Types
import Network.Google.Prelude
-- | A resource alias for @dfareporting.countries.get@ method which the
-- 'CountriesGet' request conforms to.
type CountriesGetResource =
"dfareporting" :>
"v2.7" :>
"userprofiles" :>
Capture "profileId" (Textual Int64) :>
"countries" :>
Capture "dartId" (Textual Int64) :>
QueryParam "alt" AltJSON :> Get '[JSON] Country
-- | Gets one country by ID.
--
-- /See:/ 'countriesGet' smart constructor.
data CountriesGet = CountriesGet'
{ _cgProFileId :: !(Textual Int64)
, _cgDartId :: !(Textual Int64)
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'CountriesGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cgProFileId'
--
-- * 'cgDartId'
countriesGet
:: Int64 -- ^ 'cgProFileId'
-> Int64 -- ^ 'cgDartId'
-> CountriesGet
countriesGet pCgProFileId_ pCgDartId_ =
CountriesGet'
{ _cgProFileId = _Coerce # pCgProFileId_
, _cgDartId = _Coerce # pCgDartId_
}
-- | User profile ID associated with this request.
cgProFileId :: Lens' CountriesGet Int64
cgProFileId
= lens _cgProFileId (\ s a -> s{_cgProFileId = a}) .
_Coerce
-- | Country DART ID.
cgDartId :: Lens' CountriesGet Int64
cgDartId
= lens _cgDartId (\ s a -> s{_cgDartId = a}) .
_Coerce
instance GoogleRequest CountriesGet where
type Rs CountriesGet = Country
type Scopes CountriesGet =
'["https://www.googleapis.com/auth/dfatrafficking"]
requestClient CountriesGet'{..}
= go _cgProFileId _cgDartId (Just AltJSON)
dFAReportingService
where go
= buildClient (Proxy :: Proxy CountriesGetResource)
mempty
|
rueshyna/gogol
|
gogol-dfareporting/gen/Network/Google/Resource/DFAReporting/Countries/Get.hs
|
mpl-2.0
| 3,111 | 0 | 14 | 732 | 421 | 249 | 172 | 63 | 1 |
buildG bounds0 edges0 = accumArray (flip (:)) [] bounds0 (map reassoc edges0)
where reassoc (v, e, w) = (v, (e, w))
|
lspitzner/brittany
|
data/Test277.hs
|
agpl-3.0
| 118 | 0 | 8 | 23 | 69 | 38 | 31 | 2 | 1 |
gcd' :: Int -> Int -> Int
gcd' x 0 = x
gcd' x y = gcd' y (x `mod` y)
ans :: Int -> Int -> Int
ans x y =
if x >= y
then gcd' x y
else gcd' y x
main = do
l <- getLine
let i = map read $ words l :: [Int]
o = ans (i!!0) (i!!1)
putStrLn $ show o
|
a143753/AOJ
|
ALDS1_1_B.hs
|
apache-2.0
| 263 | 0 | 12 | 91 | 164 | 83 | 81 | 13 | 2 |
lend amount balance = let reserve = 100
newBalance = balance - amount
in if balance < reserve
then Nothing
else Just newBalance
|
hungaikev/learning-haskell
|
Lending.hs
|
apache-2.0
| 230 | 0 | 9 | 125 | 46 | 23 | 23 | 5 | 2 |
module AIM.OService where
import qualified Data.ByteString.Lazy as BS
import qualified Data.ByteString.Lazy.Char8 as BSC
import Data.Word
import Data.Char
import Data.Binary.Put
import Data.Binary.Get
import AIM.Snac
import AIM.Tlv
data NickwInfo = NickwInfo {displayId :: String, evil :: Word16, userAttr :: [TLV]}
instance Show NickwInfo where
show x = "Display ID: " ++ (displayId x) ++ ", Evil: " ++ (show $ evil x) ++ ", TLVs: " ++ (show $ userAttr x)
oservice_nick_info :: BS.ByteString -> (NickwInfo, BS.ByteString)
oservice_nick_info stuff = do
runGet f stuff
where
f = do
nickLength <- getWord8
name <- getLazyByteString (fromIntegral nickLength)
evil <- getWord16be
numTLV <- getWord16be
stuff <- getRemainingLazyByteString
let (tlvs, rest) = tlv_extract_block (fromIntegral numTLV) stuff
return $ (NickwInfo (BSC.unpack name) evil tlvs, rest)
|
chrismoos/haskell-aim-client
|
src/AIM/oservice.hs
|
apache-2.0
| 898 | 2 | 14 | 163 | 292 | 158 | 134 | 23 | 1 |
module Delahaye.A338033 (a338033_list, a338033) where
import Delahaye.A337656 (a337656)
import Helpers.Delahaye (rowTable)
a338033 :: Int -> Integer
a338033 n = a338033_list !! (n-1)
a338033_list :: [Integer]
a338033_list = rowTable (*) a337656
|
peterokagey/haskellOEIS
|
src/Delahaye/A338033.hs
|
apache-2.0
| 247 | 0 | 7 | 32 | 82 | 48 | 34 | 7 | 1 |
-- Copyright 2020-2021 Google 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
--
-- http://www.apache.org/licenses/LICENSE-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.
-- | Type-level 'Integer'.
--
-- Import Integer qualified as K and refer to it as K.Integer.
--
-- It turns out this is approximately identical to an in-progress GHC change
-- https://github.com/ghc-proposals/ghc-proposals/pull/154, right down to the
-- particulars of how to encode kind-classes. Apparently I was on the right
-- track! TODO(awpr): when that thing is merged and readily available, remove
-- this or turn it into a compat package.
--
-- Once that proposal is complete, we can migrate by replacing K.Integer with
-- just Integer.
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE NoStarIsType #-}
{-# LANGUAGE PolyKinds #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Kinds.Integer
( -- * Type-level Integers
Integer(..), ToInteger
-- ** Runtime Values
, KnownInteger(..)
-- ** Specialized Arithmetic and Comparison
, AddInteger, SubInteger, CmpInteger, MulInteger
, type (-#)
-- * Axioms
, plusMinusInverseL, plusMinusInverseR
, mulCommutes
) where
import Prelude hiding (Integer)
import qualified Prelude as P
import Data.Type.Equality ((:~:)(..))
import GHC.Exts (proxy#)
import GHC.TypeNats (KnownNat, Nat, natVal')
import Unsafe.Coerce (unsafeCoerce)
import Kinds.Num (type (+), type (-), type (*), FromNat, ToInteger)
import Kinds.Ord (Compare, OrdCond)
-- | Type-level signed numbers
data Integer = Pos Nat | Neg Nat
-- | Mostly internal; the "snumber" package provides more useful functionality.
class KnownInteger (n :: Integer) where
integerVal :: P.Integer
instance KnownNat n => KnownInteger ('Pos n) where
integerVal = toInteger $ natVal' @n proxy#
instance KnownNat n => KnownInteger ('Neg n) where
integerVal =
let x = natVal' @n proxy#
in if x == 0
then error "illegal KnownInteger (-0)"
else negate $ toInteger x
type instance Compare {- k=Integer -} x y = CmpInteger x y
type instance FromNat {- k=Integer -} n = 'Pos n
type instance ToInteger {- k=Integer -} n = n
type instance x + y = AddInteger x y
type instance x - y = SubInteger x y
type instance x * y = MulInteger x y
-- | Comparison of type-level integers.
type family CmpInteger m n where
CmpInteger ('Pos m) ('Pos n) = Compare m n
CmpInteger ('Pos 0) ('Neg 0) = 'EQ
CmpInteger ('Pos m) ('Neg n) = 'GT
CmpInteger ('Neg 0) ('Pos 0) = 'EQ
CmpInteger ('Neg m) ('Pos n) = 'LT
CmpInteger ('Neg m) ('Neg n) = Compare n m -- Note: reversed
-- | Given two 'Nat's @m@ and @n@, computes @m - n@ as an 'Integer'.
type family (m :: Nat) -# (n :: Nat) where
-- Redundant cases solely to make sure we get stuck reducing '-#' rather
-- than reducing @OrdCond (Compare m n) tons of junk@ when the magnitude is
-- a type variable. This is similar to adding a bang pattern or case
-- statement to a term-level function to make it strict in its arguments; but
-- we don't have case statements or bang patterns in type families, so we add
-- clauses instead.
n -# 0 = 'Pos n -- Order matters: 0 -# 0 should be 'Pos 0
0 -# n = 'Neg n
m -# n = OrdCond (Compare m n)
('Neg (n - m))
('Pos 0)
('Pos (m - n))
-- | Addition of type-level integers.
type family AddInteger m n where
AddInteger ('Pos m) ('Pos n) = 'Pos (m + n)
AddInteger ('Pos m) ('Neg n) = m -# n
AddInteger ('Neg m) ('Pos n) = n -# m
AddInteger ('Neg m) ('Neg n) = 'Neg (m + n)
-- | Subtraction of type-level integers.
type family SubInteger m n where
-- Note we could define this as @AddInteger m (Negate n)@, but then GHC would
-- reduce eagerly to this when the parameters are type variables, and
-- irreducible calls to 'SubInteger' would appear in error messages as
-- @AddInteger m (Negate n)@ rather than the more readable @SubInteger m n@.
-- So, we tolerate some duplicated code in order to make sure we get stuck on
-- 'SubInteger' rather than later.
SubInteger ('Pos m) ('Pos n) = m -# n
SubInteger ('Pos m) ('Neg n) = 'Pos (m + n)
SubInteger ('Neg m) ('Pos n) = 'Neg (m + n)
SubInteger ('Neg m) ('Neg n) = n -# m
-- | Multiplication of type-level integers.
type family MulInteger m n where
MulInteger ('Pos m) ('Pos n) = 'Pos (m * n)
MulInteger ('Pos m) ('Neg n) = 0 -# (m * n)
MulInteger ('Neg m) ('Pos n) = 0 -# (m * n)
MulInteger ('Neg m) ('Neg n) = 'Pos (m * n)
unsafeAxiom :: a :~: b
unsafeAxiom = unsafeCoerce Refl
-- | Subtracting the right summand gives back the left summand.
plusMinusInverseR :: (m + n) -# n :~: 'Pos m
plusMinusInverseR = unsafeAxiom
-- | Subtracting the left summand gives back the right summand.
plusMinusInverseL :: (m + n) -# m :~: 'Pos n
plusMinusInverseL = unsafeAxiom
-- | Multiplication of integers is commutative.
mulCommutes :: MulInteger m n :~: MulInteger n m
mulCommutes = unsafeAxiom
|
google/hs-dependent-literals
|
numeric-kinds/src/Kinds/Integer.hs
|
apache-2.0
| 5,669 | 5 | 11 | 1,202 | 1,321 | 738 | 583 | -1 | -1 |
move :: String -> [Int] -> [Int]
move cmd (a:b:c:d:e:f:_) =
case cmd of
"North" -> [f,b,e,d,a,c]
"East" -> [d,a,b,c,e,f]
"West" -> [b,c,d,a,e,f]
"South" -> [e,b,f,d,c,a]
"Right" -> [a,e,c,f,d,b]
"Left" -> [a,f,c,e,b,d]
move _ _ = []
ans' :: Int -> [Int] -> [String] -> Int
ans' s _ [] = s
ans' s d (c:cs) =
let d' = move c d
s' = head d'
in
ans' (s+s') d' cs
ans :: [String] -> [Int]
ans [] = []
ans ("0":_) = []
ans (n:x) =
let n' = read n :: Int
d = take n' x
r = drop n' x
in
(ans' 1 [1,3,6,4,5,2] d):(ans r)
main = do
c <- getContents
let i = map head $ map words $ lines c
o = ans i
mapM_ print o
|
a143753/AOJ
|
0502.hs
|
apache-2.0
| 683 | 0 | 12 | 216 | 499 | 272 | 227 | 29 | 6 |
{-# LANGUAGE OverloadedStrings #-}
module Text.Named.TeiNCP
( ID
, Cert (..)
, Ptr (..)
, Deriv (..)
, Para (..)
, Sent (..)
, NE (..)
, parseNamed
, readNamed
) where
import System.FilePath (takeBaseName)
import qualified Data.Text.Lazy as L
import qualified Data.Text.Lazy.Encoding as L
import qualified Data.ByteString.Lazy as BS
import qualified Codec.Compression.GZip as GZip
import qualified Codec.Archive.Tar as Tar
import Text.XML.PolySoup
import qualified Data.Named as Cano
type ID = L.Text
data Cert
= High
| Medium
| Low
deriving (Show)
data Ptr
-- | Of "#id" form
= Local
{ target :: ID }
-- | Of "loc#id" form
| Global
{ target :: ID
, location :: L.Text }
deriving (Show)
data Deriv = Deriv
{ derivType :: L.Text
, derivFrom :: L.Text }
deriving (Show)
-- | Paragraph.
data Para = Para
{ paraID :: ID
, sentences :: [Sent] }
deriving (Show)
-- | Sentence.
data Sent = Sent
{ sentID :: ID
, names :: [NE] }
deriving (Show)
-- | A Seg element in a file.
data NE = NE
{ neID :: ID
, derived :: Maybe Deriv
, neType :: L.Text
, subType :: Maybe L.Text
, orth :: L.Text
-- | Left base or Right when.
, base :: Either L.Text L.Text
, cert :: Cert
, certComment :: Maybe L.Text
, ptrs :: [Ptr] }
deriving (Show)
-- | TEI NKJP ann_morphosyntax parser.
type P a = XmlParser L.Text a
namedP :: P [Para]
namedP = true //> paraP
paraP :: P Para
paraP = uncurry Para <$> (tag "p" *> getAttr "xml:id" </> sentP)
sentP :: P Sent
sentP = uncurry Sent <$> (tag "s" *> getAttr "xml:id" </> nameP)
nameP :: P NE
nameP = (tag "seg" *> getAttr "xml:id") `join` \neID -> do
ne <- nameBodyP
ptrs <- some namePtrP
<|> failBad ("no targets specified for " ++ L.unpack neID)
return $ ne { neID = neID, ptrs = ptrs }
nameBodyP :: P NE
nameBodyP = (tag "fs" *> hasAttr "type" "named") `joinR` do
deriv <- optional derivP
neType <- fSymP "type"
subType <- optional (fSymP "subtype")
orth <- fStrP "orth"
base <- (Left <$> fStrP "base")
<|> (Right <$> fStrP "when")
cert <- certP
certComment <- optional (fStrP "comment")
return $ NE { neType = neType, subType = subType, orth = orth, base = base
, derived = deriv, cert = cert, certComment = certComment
, neID = "", ptrs = [] } -- ^ Should be supplied outside
derivP :: P Deriv
derivP = fP "derived" `joinR` ( fsP "derivation" `joinR` do
Deriv <$> fSymP "derivType" <*> fStrP "derivedFrom" )
fP x = tag "f" *> hasAttr "name" x
fsP x = tag "fs" *> hasAttr "type" x
certP :: P Cert
certP =
mkCert <$> fSymP "certainty"
where
mkCert "high" = High
mkCert "medium" = Medium
mkCert "low" = Low
mkCert _ = Medium -- ^ It should not happen!
namePtrP :: P Ptr
namePtrP = cut (tag "ptr" *> getAttr "target") >>= \x -> return $
case L.break (=='#') x of
(ptr, "") -> Local ptr
(loc, ptr) -> Global
{ location = loc
, target = (L.tail ptr) }
fStrP :: L.Text -> P L.Text
fStrP x =
let checkName = tag "f" *> hasAttr "name" x
-- | Body sometimes is empty.
safeHead [] = ""
safeHead xs = head xs
in safeHead <$> (checkName #> tag "string" /> text)
fSymP :: L.Text -> P L.Text
fSymP x =
let checkName = tag "f" *> hasAttr "name" x
p = cut (tag "symbol" *> getAttr "value")
in head <$> (checkName /> p)
parseNamed :: L.Text -> [Para]
parseNamed = parseXML namedP
-- | NKJP .tar.gz handling. TODO: Move NCP parsing utilities
-- to another, common module. It should also allow parsing
-- plain directories.
-- | Parse NCP .tar.gz corpus.
readNamed :: FilePath -> IO [(FilePath, [Para])]
readNamed tarPath = do
map parseEntry . withBase "ann_named" <$> readTar tarPath
readTar :: FilePath -> IO [Tar.Entry]
readTar tar
= Tar.foldEntries (:) [] error
. Tar.read . GZip.decompress
<$> BS.readFile tar
parseEntry :: Tar.Entry -> (FilePath, [Para])
parseEntry entry =
(Tar.entryPath entry, parseNamed content)
where
(Tar.NormalFile binary _) = Tar.entryContent entry
content = L.decodeUtf8 binary
withBase :: String -> [Tar.Entry] -> [Tar.Entry]
withBase base = filter ((==base) . takeBaseName . Tar.entryPath)
|
kawu/named
|
Text/Named/TeiNCP.hs
|
bsd-2-clause
| 4,418 | 0 | 15 | 1,213 | 1,483 | 814 | 669 | 128 | 4 |
module Main where
import Criterion.Main (bench, bgroup, defaultMain, nf)
main :: IO ()
main =
defaultMain
[ bgroup
"example1"
[ bench "plus" $ nf (1 +) (1 :: Int)
, bench "minus" $ nf (1 -) (1 :: Int)
]
]
|
cdepillabout/highlight
|
bench/Bench.hs
|
bsd-3-clause
| 250 | 0 | 11 | 86 | 99 | 56 | 43 | 9 | 1 |
{-# LANGUAGE CPP,TemplateHaskell,DeriveDataTypeable #-}
module Data.Encoding.ISO88594
(ISO88594(..)) where
import Data.Array ((!),Array)
import Data.Word (Word8)
import Data.Map (Map,lookup,member)
import Data.Encoding.Base
import Prelude hiding (lookup)
import Control.OldException (throwDyn)
import Data.Typeable
data ISO88594 = ISO88594 deriving (Eq,Show,Typeable)
enc :: Char -> Word8
enc c = case lookup c encodeMap of
Just v -> v
Nothing -> throwDyn (HasNoRepresentation c)
instance Encoding ISO88594 where
encode _ = encodeSinglebyte enc
encodeLazy _ = encodeSinglebyteLazy enc
encodable _ c = member c encodeMap
decode _ = decodeSinglebyte (decodeArr!)
decodeArr :: Array Word8 Char
#ifndef __HADDOCK__
decodeArr = $(decodingArray "8859-4.TXT")
#endif
encodeMap :: Map Char Word8
#ifndef __HADDOCK__
encodeMap = $(encodingMap "8859-4.TXT")
#endif
|
abuiles/turbinado-blog
|
tmp/dependencies/encoding-0.4.1/Data/Encoding/ISO88594.hs
|
bsd-3-clause
| 869 | 2 | 10 | 120 | 270 | 149 | 121 | 24 | 2 |
{-# LANGUAGE EmptyDataDecls #-}
module DynamicContents where
{- FAY compiled module -}
import FFI
import Prelude
import Data.Data
import JQuery hiding (filter, validate)
import Fay.JQueryUI
import Fay.Text hiding (concat)
import Bead.Domain.Shared.Evaluation
import Bead.Shared.Command
import Bead.View.Fay.Hooks
import Bead.View.Fay.HookIds
import Bead.View.Fay.JSON.ClientSide
import Bead.View.Validators
main :: Fay ()
main = addOnLoad onload
onload :: Fay ()
onload = do
hookPercentageDiv evaluationPctHook
hookEvaluationTypeForm assignmentEvTypeHook
hookDatetimePickerDiv startDateTimeHook
hookDatetimePickerDiv endDateTimeHook
connectStartEndDatePickers startDateTimeHook endDateTimeHook
connectStartEndHours startDateTimeHook endDateTimeHook
hookAssignmentForm (hookId assignmentForm) startDateTimeHook endDateTimeHook
hookRegistrationForm
hookSamePasswords (rFormId regFinalForm) (lcFieldName loginPassword) (lcFieldName regPasswordAgain)
hookPasswordField (rFormId regFinalForm) (lcFieldName loginPassword)
hookPasswordField (rFormId changePwdForm) (cpf oldPasswordField)
hookSamePasswords (rFormId changePwdForm) (cpf newPasswordField) (cpf newPasswordAgainField)
hookSamePasswords (rFormId setStudentPwdForm) (cpf studentNewPwdField) (cpf studentNewPwdAgainField)
hookLargeComments
-- hookPingButton
connectStartEndDatePickers :: DateTimePickerHook -> DateTimePickerHook -> Fay ()
connectStartEndDatePickers start end = void $ do
startId <- select . cssId $ dtDatePickerId start
endId <- select . cssId $ dtDatePickerId end
existStart <- exists startId
existEnd <- exists endId
when (existStart && existEnd) $ do
setMinDatePickers startId endId
setMaxDatePickers startId endId
putStrLn "Date pickers are connected"
connectStartEndHours :: DateTimePickerHook -> DateTimePickerHook -> Fay ()
connectStartEndHours start end = void $ do
startDate <- select . cssId $ dtDatePickerId start
startHour <- select . cssId $ dtHourPickerId start
startMin <- select . cssId $ dtMinPickerId start
endDate <- select . cssId $ dtDatePickerId end
endHour <- select . cssId $ dtHourPickerId end
endMin <- select . cssId $ dtMinPickerId end
existStartDate <- exists startDate
existStartHour <- exists startHour
existStartMin <- exists startMin
existEndDate <- exists endDate
existEndHour <- exists endHour
existEndMin <- exists endMin
let existAll = and [ existStartDate, existStartHour, existStartMin
, existEndDate, existEndHour, existEndMin
]
when existAll $ do
let times = do
sd <- getVal startDate
sh <- getVal startHour
sm <- getVal startMin
ed <- getVal endDate
eh <- getVal endHour
em <- getVal endMin
return (sd,sh,sm,ed,eh,em)
-- Check is the start date and the end date is the same
-- The start hour and minute must be before than the end hour and min
checkStart e = void $ do
(sd,sh,sm,ed,eh,em) <- times
when (sd == ed) $ do
when (less eh sh) $ void $ setVal eh startHour
when (eh == sh && less em sm) $ void $ setVal em startMin
checkEnd e = void $ do
(sd,sh,sm,ed,eh,em) <- times
when (sd == ed) $ do
when (less eh sh) $ void $ setVal sh endHour
when (eh == sh && less em sm) $ void $ setVal sm endMin
spinStop checkStart startHour
spinStop checkStart startMin
spinStop checkEnd endHour
spinStop checkEnd endMin
spinChange checkStart startHour
spinChange checkStart startMin
spinChange checkEnd endHour
spinChange checkEnd endMin
putStrLn "Synchronization of hours and mins is hooked"
-- Attaches a datepicker and hour and minute input fields
-- to the given hook
hookDatetimePickerDiv :: DateTimePickerHook -> Fay ()
hookDatetimePickerDiv hook = void $ do
let pickerDiv = dtDivId $ hook
div <- select . cssId $ pickerDiv -- dtDivId $ hook
existDiv <- exists div
when existDiv $ do
input <- select . cssId . dtHiddenInputId $ hook
date <- select . createDateInput $ dtDatePickerId hook
datepicker date
hour <- select . createTimeInput $ dtHourPickerId hook
min <- select . createTimeInput $ dtMinPickerId hook
br <- select newLine
appendTo div br
appendTo div date
appendTo div br
appendTo div hour
appendTo div min
numberField hour 0 23
numberField min 0 59
defDate <- select . cssId . dtDefaultDate $ hook
defHour <- select . cssId . dtDefaultHour $ hook
defMin <- select . cssId . dtDefaultMin $ hook
copy defDate date
copy defHour hour
copy defMin min
let createDateTime e = void $ do
d <- getVal date
h <- getVal hour
m <- getVal min
setVal (datetime d h m) input
hourSpinner createDateTime hour
minuteSpinner createDateTime min
change createDateTime date
change createDateTime hour
change createDateTime min
putStrLn $ "Date picker " ++ pickerDiv ++ " is loaded."
where
createDateInput id = fromString ("<input id=\"" ++ id ++ "\" type=\"text\" size=\"10\" required readonly />")
createTimeInput id = fromString ("<input id=\"" ++ id ++ "\" type=\"text\" size=\"2\" value=\"0\"/>")
newLine = fromString "<br/>"
datetime d h m = fromString $ (unpack d) ++ " " ++ (twoDigits (unpack h)) ++ ":" ++ (twoDigits (unpack m)) ++ ":00"
copy from to = do
x <- getVal from
setVal x to
twoDigits [d] = ['0',d]
twoDigits ds = ds
hookPercentageDiv :: PercentageHook -> Fay ()
hookPercentageDiv hook = void $ do
div <- select . cssId . ptDivId $ hook
existDiv <- exists div
when existDiv $ do
input <- select . cssId . ptHiddenInputId $ hook
checkboxMsg <- (select . cssId $ hookId evCommentOnlyText) >>= getVal
commentCheckbox <- select (fromString $ concat [ "<input type=\"checkbox\" checked=\"\">", unpack checkboxMsg, "</input>" ])
appendTo div commentCheckbox
select (fromString "<br/>") >>= appendTo div
pctInput <- select (fromString "<input type=\"text\" size=\"3\" required />")
appendTo div pctInput
pctSymbol <- select (fromString "<span class=\"evtremoveable\">%</span>")
appendTo div pctSymbol
let changeHiddenInput e = void $ do
t <- targetElement e
val <- getVal t
setVal (fromString . result . double . unpack $ val) input
let commentCheckboxChanged e = void $ do
t <- target e
c <- checked t
if c
then do
disableSpinner (Spinner pctInput)
setVal (fromString comment) input
else do
enableSpinner (Spinner pctInput)
val <- getVal pctInput
setVal (fromString . result . double . unpack $ val) input
change commentCheckboxChanged commentCheckbox
numberField pctInput 0 100
-- Comment checkbox is checked by default, the pctInput should be disabled
-- and the input field value should be a comment
pctSpinner changeHiddenInput pctInput
disableSpinner (Spinner pctInput)
setVal (fromString comment) input
putStrLn "Percentage div is loaded."
where
double "100" = "1.0"
double ds = "0." ++ twoDigits ds
-- Converts a string percentage into a JSON EvalOrComment percentage value representation
result :: String -> String
result = evalOrCommentJson . EvCmtResult . percentageResult . parseDouble
comment :: String
comment = evalOrCommentJson EvCmtComment
numberField :: JQuery -> Int -> Int -> Fay ()
numberField i min max = do
setVal (fromString . printInt $ min) i
flip keyup i $ \e -> void $ do
t <- targetElement e
val <- getVal t
setVal (fromString $ filter isDigit (unpack val)) t
flip change i $ \e -> void $ do
t <- targetElement e
val <- getVal t
case (unpack val) of
[] -> void $ setVal (fromString "0") t
v -> do let x = parseInt v
when (x < min) $ void $ setVal (fromString . show $ min) t
when (x >= max) $ void $ setVal (fromString . show $ max) t
makeMessage removable msg = select . fromString $ (
"<br class=\"" ++ removable ++ "\"><snap style=\"font-size: smaller;color: red\" class=\"" ++
removable ++ "\">"
++ msg ++
"</span>")
-- Validate a field with a given field validator, and places
-- a message with a given class, after the given place
validateField :: FieldValidator -> JQuery -> JQuery -> String -> Fay Bool
validateField validator field place removable = do
v <- getVal field
validate validator (unpack v)
(return True)
(\m -> do span <- makeMessage removable (message validator)
after span place
return False)
-- Hooks the assignment form with a validator, that runs on the submit of the
-- form. The two dates must be selected properly, otherwise the form
-- can't be submitted.
hookAssignmentForm :: String -> DateTimePickerHook -> DateTimePickerHook -> Fay ()
hookAssignmentForm formId startHook endHook = void $ do
form <- select $ cssId formId
existForm <- exists form
when existForm $ do
start <- select . cssId $ dtHiddenInputId startHook
end <- select . cssId $ dtHiddenInputId endHook
startErrMsgPos <- select . cssId $ dtDatePickerId startHook
endErrMsgPos <- select . cssId $ dtDatePickerId endHook
let validateForm = do
messages <- select . cssClass $ removeable
remove messages
start <- validateField isDateTime start startErrMsgPos removeable
end <- validateField isDateTime end endErrMsgPos removeable
return (start && end)
void $ onSubmit validateForm form
where
removeable = "datetimeerror"
-- Checks if the page contains password field
-- and hook it with the validator for submit event.
hookPasswordField :: String -> String -> Fay ()
hookPasswordField formId password = void $ do
form <- select . cssId $ formId
existForm <- exists form
when existForm $ do
pwd <- select $ cssId password
let validatorPwd = do
messages <- select . cssClass $ removable
remove messages
validateField isPassword pwd pwd removable
onSubmit validatorPwd form
putStrLn "Password field is loaded."
where
removable = "password_error"
-- Checks if the form has a password and a password again field
-- and hook that the two values must be the same for submit event.
hookSamePasswords :: String -> String -> String -> Fay ()
hookSamePasswords formId password1 password2 = void $ do
form <- select . cssId $ formId
existForm <- exists form
when existForm $ do
pwd <- select $ cssId password1
pwdAgain <- select $ cssId password2
let validator = do
messages <- select . cssClass $ removable
remove messages
password <- getVal pwd
passwordAgain <- getVal pwdAgain
case (password == passwordAgain) of
True -> return True
False -> do
span <- makeMessage removable "A jelszavak nem egyeznek!"
after span pwdAgain
return False
onSubmit validator form
putStrLn "Same password fields are loaded."
where
removable = "same_password_error"
hookRegistrationForm :: Fay ()
hookRegistrationForm = void $ do
regForm <- select . cssId . rFormId $ regForm
existForm <- exists regForm
when existForm $ do
uname <- select . cssId . lcFieldName $ loginUsername
pwd <- select . cssId . lcFieldName $ loginPassword
email <- select . cssId . rFieldName $ regEmailAddress
fname <- select . cssId . rFieldName $ regFullName
let validator = do
messages <- select . cssClass $ removable
remove messages
andM
[ validateField isUsername uname uname removable
, validateField isEmailAddress email email removable
]
onSubmit validator regForm
putStrLn "Registration form is loaded."
where
removable = "regremovable"
hookEvaluationTypeForm :: EvaluationHook -> Fay ()
hookEvaluationTypeForm hook = do
let formId = evFormId hook
form <- select . cssId $ formId
existForm <- exists form
when existForm $ do
selection <- select . cssId . evSelectionId $ hook
change (changeFormContent form) selection
setDefaultEvalConfig form selection
putStrLn $ "Evaluation form " ++ formId ++ " is loaded."
where
setDefaultEvalConfig :: JQuery -> JQuery -> Fay ()
setDefaultEvalConfig form selection = do
val <- (select . cssId $ evHiddenValueId hook) >>= getVal
dt <- convertJsonToData val
case dt of
(EvConfig (BinEval _)) -> do
setEvaluationConfig binaryConfig
setSelectionValue selection "\"BinEval\""
(EvConfig (PctEval _)) -> do
setEvaluationConfig (percentageConfig 0.0)
setSelectionValue selection "\"PctEval\""
(EvConfig (FreeEval _)) -> do
setEvaluationConfig freeFormConfig
setSelectionValue selection "\"FreeEval\""
changeFormContent :: JQuery -> Event -> Fay ()
changeFormContent form e = void $ do
t <- target e
v <- decodeEvalType <$> selectedValue t
case v of
(BinEval _) -> do
setEvaluationConfig binaryConfig
(PctEval _) -> do
setEvaluationConfig (percentageConfig 0.0)
(FreeEval _) -> do
setEvaluationConfig freeFormConfig
setEvaluationConfig :: EvConfig -> Fay ()
setEvaluationConfig c =
void $ select (cssId . evHiddenValueId $ hook) >>=
setVal (fromString . evConfigJson $ c)
hookLargeComments :: Fay ()
hookLargeComments = void $ do
moreButton <- select (fromString "a.morebutton")
click toggle moreButton
where
a_morebutton = fromString ("a." ++ hookClass moreButtonClass)
pre_more = fromString ("pre." ++ hookClass moreClass)
morebutton = fromString (hookClass moreButtonClass)
lessbutton = fromString (hookClass lessButtonClass)
span_seeless = fromString ("span." ++ hookClass seeLessClass)
span_seemore = fromString ("span." ++ hookClass seeMoreClass)
toggle :: Event -> Fay ()
toggle e = void $ do
seeMore <- (target e) >>= select
full <- (nextSelector pre_more seeMore >>= first)
slideToggle full
preview <- (prevSelector pre_more seeMore >>= first)
slideToggle preview
seeMoreClass <- hasClass morebutton seeMore
if (seeMoreClass)
then do seeLessText <- (prevAllSelector span_seeless seeMore) >>= getText
setText seeLessText seeMore
removeClass morebutton seeMore
addClass lessbutton seeMore
else do seeMoreText <- (prevAllSelector span_seemore seeMore) >>= getText
setText seeMoreText seeMore
removeClass lessbutton seeMore
addClass morebutton seeMore
{- PING EXAMPLE
hookPingButton :: Fay ()
hookPingButton = void $ do
select (fromString "#pingform") >>= submit (\e -> preventDefault e >> submitPing)
where
submitPing :: Fay ()
submitPing = void $ do
form <- select (fromString "#pingform")
json <- formJson form :: Fay Ping
jPost (fromString "/fay/ping") json (\(Pong message) -> putStrLn (unpack message))
-}
-- Converts a JSON value into fay data
convertJsonToData :: Text -> Fay (Automatic f)
convertJsonToData = ffi "JSON.parse(%1)"
formJson :: JQuery -> Fay f
formJson = ffi "Helpers.formJson(%1)"
jPost :: Text -> Automatic f -> (Automatic g -> Fay ()) -> Fay ()
jPost = ffi "jQuery.ajax(%1, { data: JSON.stringify(%2), type: 'POST', processData: false, contentType: 'text/json', success: %3 })"
cssId :: String -> Text
cssId i = fromString ('#':i)
cssClass :: String -> Text
cssClass c = fromString ('.':c)
-- * Helpers
(<$>) :: (a -> b) -> Fay a -> Fay b
f <$> m = m >>= (return . f)
andM :: [Fay Bool] -> Fay Bool
andM fs = and <$> (sequence fs)
-- * JQuery helpers
sValue :: JQuery -> Fay Int
sValue = ffi "%1.spinner(\"value\")"
targetElement :: Event -> Fay JQuery
targetElement e = (target e) >>= select
exists :: JQuery -> Fay Bool
exists = ffi "(%1.length != 0)"
-- * Javascript helpers
selectedValue :: Element -> Fay String
selectedValue = ffi "%1.options[%1.selectedIndex].value"
-- Set the selection value to the given string
setSelectionValue :: JQuery -> String -> Fay ()
setSelectionValue = ffi "%1.val(%2)"
-- Checks if the given jquery represents a checkbox, and
-- returns if it is checked or not. If the jquery is not a checkbox throws
-- an exception
checked :: Element -> Fay Bool
checked = ffi "%1.checked"
firstOptionValue :: JQuery -> Fay String
firstOptionValue selection = do
findSelector (fromString "option") selection >>= first >>= getVal >>= (return . unpack)
addOnLoad :: Fay a -> Fay ()
addOnLoad = ffi "window.addEventListener(\"load\", %1)"
value :: Element -> Fay String
value = ffi "%1.value"
parseInt :: String -> Int
parseInt = ffi "parseInt(%1)"
parseDouble :: String -> Double
parseDouble = ffi "parseFloat(%1)"
printInt :: Int -> String
printInt = ffi "%1.toString()"
-- Returns true if the first text is greater in js than the second
greater :: Text -> Text -> Bool
greater = ffi "(%1) > (%2)"
-- Returns true if the first text is less in js than the second
less :: Text -> Text -> Bool
less = ffi "(%1) < (%2)"
|
andorp/bead
|
snaplets/fay/src/DynamicContents.hs
|
bsd-3-clause
| 17,519 | 0 | 25 | 4,297 | 4,876 | 2,281 | 2,595 | 378 | 5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.