_id
stringlengths
64
64
repository
stringlengths
6
84
name
stringlengths
4
110
content
stringlengths
0
248k
license
null
download_url
stringlengths
89
454
language
stringclasses
7 values
comments
stringlengths
0
74.6k
code
stringlengths
0
248k
9052680f5357b5a4b52d5761dba8b927f57dea4d043065312021964b6b84a1b6
gstew5/snarkl
Errors.hs
# LANGUAGE GeneralizedNewtypeDeriving , DeriveDataTypeable # , DeriveDataTypeable #-} module Errors where import Data.Typeable import Control.Exception newtype ErrMsg = ErrMsg { errMsg :: String } deriving (Typeable) instance Show ErrMsg where show (ErrMsg msg) = msg instance Exception ErrMsg fail_with :: ErrMsg -> a fail_with e = throw e
null
https://raw.githubusercontent.com/gstew5/snarkl/d6ce72b13e370d2965bb226f28a1135269e7c198/src/Errors.hs
haskell
# LANGUAGE GeneralizedNewtypeDeriving , DeriveDataTypeable # , DeriveDataTypeable #-} module Errors where import Data.Typeable import Control.Exception newtype ErrMsg = ErrMsg { errMsg :: String } deriving (Typeable) instance Show ErrMsg where show (ErrMsg msg) = msg instance Exception ErrMsg fail_with :: ErrMsg -> a fail_with e = throw e
ef41970046e3bee8aae8c170c793a8d102281c7bd0df5f06aa2a64de131b34cd
racket/typed-racket
submodule-list-0.rkt
#lang typed/racket/base/optional ;; Test importing a list (module u racket/base (define x* (list 1)) (provide x*)) (require/typed 'u (x* (Listof Integer))) (+ (car x*) 1)
null
https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/submodule-list-0.rkt
racket
Test importing a list
#lang typed/racket/base/optional (module u racket/base (define x* (list 1)) (provide x*)) (require/typed 'u (x* (Listof Integer))) (+ (car x*) 1)
ffb75198a7c4866007e838b5aac13e974ad07b1c612a34f1d9486014af5f2394
ruricolist/FXML
parse.lisp
(in-package #:fxml.html5) (defun parse (input handler &key fragment (encoding :utf-8)) (let ((dom (if fragment (html5-parser:parse-html5-fragment input :encoding encoding) (html5-parser:parse-html5 input :encoding encoding)))) (serialize-dom dom handler)))
null
https://raw.githubusercontent.com/ruricolist/FXML/a0e73bb48ef03adea94a55986cc27f522074c8e1/html5/parse.lisp
lisp
(in-package #:fxml.html5) (defun parse (input handler &key fragment (encoding :utf-8)) (let ((dom (if fragment (html5-parser:parse-html5-fragment input :encoding encoding) (html5-parser:parse-html5 input :encoding encoding)))) (serialize-dom dom handler)))
fbccc06fd943d39e9a3f82d265d9040960bcb77d7a978d840a9c1814fae220d9
divipp/lensref
SevenGUIs.hs
{-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE NoMonomorphismRestriction # module LensRef.Demo.SevenGUIs where import Numeric (showFFloat) import Data.String (IsString (..)) import Data.Function (on) import Data.List (isPrefixOf, insertBy) import Data.Maybe (fromMaybe, listToMaybe, isJust, isNothing) import qualified Data.IntMap as Map import qualified Data.Map as Map' import qualified Data.IntSet as Set import Control.Applicative (pure, (<*>), (<$>), liftA2) import Control.Monad.State import Control.Monad.Reader import Control.Monad.Writer import Lens.Family2 import Lens.Family2.Stock import Lens.Family2.Unchecked import LensRef ------------------------------------------------------------------------------ 7guis # 1 | Simple counter Try in ghci : > ( click , put , get , delay ) < - run counter > click 1 > get 0 Simple counter Try in ghci: > (click, put, get, delay) <- run counter > click 1 > get 0 -} counter :: WidgetContext s => RefCreator s () counter = do -- model r <- newRef (0 :: Int) let inc = modRef r (+1) -- view horizontally $ do label "Value" $ show <$> readRef r button "Count" $ pure $ Just inc ------------------------------------------------------------------------------ 7guis # 1 version 2 counterV2 :: WidgetContext s => RefCreator s () counterV2 = counterModel >>= counterView data Counter s = Counter { counterValue :: RefReader s Int , incrementCounter :: RefWriter s () } counterModel :: RefContext s => RefCreator s (Counter s) counterModel = do r <- newRef (0 :: Int) return Counter { counterValue = readRef r , incrementCounter = modRef r (+1) } counterView :: WidgetContext s => Counter s -> RefCreator s () counterView (Counter {..}) = horizontally $ do label "Value" $ show <$> counterValue button "Count" $ pure $ Just incrementCounter ------------------------------------------------------------------------------ 7guis # 2 type Temperature = Prec2 Double temperatureConverter :: WidgetContext s => RefCreator s () temperatureConverter = do -- model celsius <- newRef (0 :: Temperature) let fahrenheit = multiplying 1.8 . adding 32 `lensMap` celsius -- view horizontally $ do void $ entryShow "Celsius" celsius void $ entryShow "Fahrenheit" fahrenheit ------------- defined in Control . Lens adding :: Num a => a -> Lens' a a adding n = iso (+n) (+(-n)) multiplying :: (Fractional a, Eq a) => a -> Lens' a a multiplying 0 = error "multiplying: factor 0" multiplying n = iso (*n) (/n) ------------------------------------------------------------------------------ 7guis # 3 type Date = NonNegative Integer flightBooker :: WidgetContext s => RefCreator s () flightBooker = do -- model booked <- newRef False startdate <- newRef (0 :: Date) maybeenddate <- newRef (Nothing :: Maybe Date) -- view void $ readRef booked `switch` \case True -> label "Notice" $ do start <- readRef startdate readRef maybeenddate <&> \case Just end -> "You have booked a return flight on " ++ show start ++ "-" ++ show end Nothing -> "You have booked a one-way flight on " ++ show start False -> do -- view model boolenddate <- extendRef maybeenddate maybeLens (False, 0) let isreturn = lensMap _1 boolenddate bookaction parseok = do ok <- parseok start <- readRef startdate end <- readRef maybeenddate return $ (ok && maybe True (start <=) end, writeRef booked True) ^. maybeLens -- view view combobox isreturn $ do item False "One-way" item True "Return" startok <- entryShow "Start" startdate endok <- entryShowActive "End" (readRef isreturn) $ lensMap _2 boolenddate button "Book" $ bookaction $ (&&) <$> startok <*> endok ---------- part of the toolkit maybeLens :: Lens' (Bool, a) (Maybe a) maybeLens = lens (\(b, a) -> mkMaybe a b) (\(_, a) ma -> maybe (False, a) (\a' -> (True, a')) ma) mkMaybe :: a -> Bool -> Maybe a mkMaybe a True = Just a mkMaybe _ False = Nothing ------------------------------------------------------------------------------ 7guis # 4 timer :: WidgetContext s => Rational -> RefCreator s () timer refresh = do -- model duration <- newRef 10 start <- newRef =<< lift currentTime timer <- join <$> onChange (readRef start + readRef duration) (mkTimer refresh) let elapsed = timer - readRef start ratio = safeDiv <$> elapsed <*> readRef duration where safeDiv _ 0 = 1 safeDiv a b = a / b reset = writeRef start =<< lift currentTime -- view vertically $ do label "Elapsed (percent)" $ (++"%") . show . (*100) . (^. convert . prec2) <$> ratio label "Elapsed" $ (++"s") . show . (^. convert . prec2) <$> elapsed void $ entryShow "Duration" $ lensMap (convert . prec2 . nonNegative) duration button "Reset" $ pure $ Just reset ---------- part of the toolkit mkTimer :: WidgetContext s => Delay -> Time -> RefCreator s (RefReader s Time) mkTimer refresh end = do t <- lift currentTime if end <= t then return $ pure end else do x <- newRef t void $ onChange (readRef x) $ \xt -> when (xt < end) $ asyncDo refresh $ writeRef x =<< lift currentTime return $ readRef x ------------------------------------------------------------------------------ 7guis # 5 crud :: WidgetContext s => RefCreator s () crud = do -- model names <- newRef [("Emil", "Hans"), ("Mustermann", "Max"), ("Tisch", "Roman")] name <- newRef ("Romba", "John") prefix <- newRef "" sel <- onChangeEq_ (readRef prefix) $ const $ return Nothing let create = do n <- readerToWriter $ readRef name modRef names (++ [n]) update s i = modRef names $ \l -> take i l ++ [s] ++ drop (i+1) l delete i = do writeRef sel Nothing modRef names $ \l -> take i l ++ drop (i+1) l filterednames = (readRef prefix <&> \p -> filter (isPrefixOf p . fst . snd)) <*> (zip [0..] <$> readRef names) -- view vertically $ do entry "Filter prefix" prefix listbox sel $ map (\(i, (s, n)) -> (i, s ++ ", " ++ n)) <$> filterednames entry "Name" $ lensMap _2 name entry "Surname" $ lensMap _1 name horizontally $ do button "Create" $ pure $ Just create button "Update" $ fmap <$> (update <$> readRef name) <*> readRef sel button "Delete" $ fmap delete <$> readRef sel ------------------------------------------------------------------------------ 7guis # 6 circleDrawer :: forall s . WidgetContext s => RefCreator s () circleDrawer = do -- model mousepos <- newRef (0, 0 :: Prec2 Double) circles <- newRef [((0,2), 1), ((0,0), 2)] selected <- onChange_ (readRef circles) $ const $ return Nothing (undo, redo) <- undoTr (==) circles sel <- extendRef selected maybeLens (False, (0, 1)) let click = do mp <- readerToWriter $ readRef mousepos l <- readerToWriter $ readRef circles head $ [ writeRef selected $ Just (i, d) | (i, (p, d)) <- zip [0..] l , distance mp p <= d + 0.01 ] ++ [ modRef circles $ insertBy (compare `on` snd) (mp, 1) ] view = maybe id f <$> readRef selected <*> (map ((,) False) <$> readRef circles) where f (i, d) l = insertBy (compare `on` snd . snd) (True, (fst $ snd $ l !! i, d)) $ take i l ++ drop (i+1) l done = readerToWriter view >>= writeRef circles . map snd -- view horizontally $ do button "Undo" undo button "Redo" redo horizontally $ do void $ entryShow "MousePos" mousepos button "MouseClick" $ mkMaybe click . not <$> readRef (lensMap _1 sel) label "Circles" $ view <&> \l -> unlines [show d ++ " at " ++ show p ++ if s then " filled" else "" | (s, (p, d)) <- l] void $ (readRef $ lensMap _1 sel) `switch` \case False -> return () True -> do label "Adjust diameter of circle at" $ show . fst <$> ((!!) <$> readRef circles <*> readRef (lensMap (_2 . _1) sel)) horizontally $ do void $ entryShow "Diameter" $ lensMap (_2 . _2 . nonNegative) sel button "Done" $ pure $ Just done distance (x1, y1) (x2, y2) = sqrt $ (x2-x1)^2 + (y2-y1)^2 ----------- part of the toolkit -- | Undo-redo state transformation. undoTr :: RefContext s => (a -> a -> Bool) -- ^ equality on state -> Ref s a -- ^ reference of state -> RefCreator s ( RefReader s (Maybe (RefWriter s ())) , RefReader s (Maybe (RefWriter s ())) ) -- ^ undo and redo actions undoTr eq r = do ku <- extendRef r (undoLens eq) ([], []) let try f = fmap (writeRef ku) . f <$> readRef ku pure (try undo, try redo) where undo (x: xs@(_:_), ys) = Just (xs, x: ys) undo _ = Nothing redo (xs, y: ys) = Just (y: xs, ys) redo _ = Nothing undoLens :: (a -> a -> Bool) -> Lens' ([a],[a]) a undoLens eq = lens get set where get = head . fst set (x' : xs, ys) x | eq x x' = (x: xs, ys) set (xs, _) x = (x : xs, []) -------------------------------------------------------------------------------- Widget API -------------------------------------------------------------------------------- type Time = Rational -- seconds elapsed from program start duration in seconds infix 1 `switch` type NamedWidgets s = WriterT [(String, RefCreator s ())] (RefCreator s) class RefContext s => WidgetContext s where label :: String -> RefReader s String -> RefCreator s () primEntry :: String -> RefReader s Bool -- ^ active (sensitive) -> RefReader s Bool -- ^ the content is correct -> Ref s String -> RefCreator s () -- | Label entry. entry :: String -> Ref s String -> RefCreator s () entry name = primEntry name (pure True) (pure True) entryShow :: (Show a, Read a) => String -> Ref s a -> RefCreator s (RefReader s Bool) entryShow name = entryShowActive name (pure True) entryShowActive :: (Show a, Read a) => String -> RefReader s Bool -> Ref s a -> RefCreator s (RefReader s Bool) entryShowActive name active r = do x <- readerToCreator $ readRef r v <- extendRef r (lens fst set') (x, Nothing) let ok = isNothing . snd <$> readRef v primEntry name active ok $ lens get set `lensMap` v return ok where set' t@(v',_) v | show v == show v' = t set' _ v = (v, Nothing) get (_, Just s) = s get (v, _) = show v set (v, _) s = case reads s of ((x,""):_) -> (x, Nothing) _ -> (v, Just s) -- | Button. button :: RefReader s String -- ^ dynamic label of the button ^ when the @Maybe@ readRef is @Nothing@ , the button is inactive -> RefCreator s () checkbox :: Ref s Bool -> RefCreator s () combobox :: Eq a => Ref s a -> Writer [(a, String)] () -> RefCreator s () listbox :: Eq a => Ref s (Maybe a) -> RefReader s [(a, String)] -> RefCreator s () padding :: RefCreator s a -> RefCreator s a vertically :: RefCreator s a -> RefCreator s a horizontally :: RefCreator s a -> RefCreator s a switch :: Eq a => RefReader s a -> (a -> RefCreator s b) -> RefCreator s (RefReader s b) asyncDoAt :: Time -> RefWriter s () -> RefCreator s () asyncDo :: Delay -> RefWriter s () -> RefCreator s () asyncDo d w = do t <- lift currentTime asyncDoAt (t + d) w currentTime :: s Time item :: MonadWriter [(a, b)] m => a -> b -> m () item s m = tell [(s, m)] -------------------------------------------------------------------------------- API implementation -------------------------------------------------------------------------------- instance RefContext m => WidgetContext (WContext m) where button s fm = primButton s (text <$> s) (isJust <$> fm) $ readerToWriter fm >>= fromMaybe (pure ()) checkbox r = primButton (show <$> readRef r) (text . show <$> readRef r) (pure True) $ modRef r not combobox i as = horizontally $ forM_ (execWriter as) $ \(n, s) -> primButton (pure s) ((bool (color green) id . (== n) <$> readRef i) <*> pure (text s)) (pure True) $ writeRef i n listbox sel as = void $ (null <$> as) `switch` \case True -> return () False -> do primButton (fromMaybe "" . fmap snd . listToMaybe <$> as) -- TODO: should work with head instead of listToMaybe (layout <$> (head <$> as) <*> readRef sel) (pure True) (writeRef sel . Just . fst . head =<< readerToWriter as) TODO : should work with tail instead of drop 1 where layout (a, s) (Just a') | a == a' = color green $ text s layout (_, s) _ = text s label name r = horizontally $ do addLayout $ pure ((), pure $ color magenta $ text name) addControl (pure name) (pure [Get $ r <&> text]) $ color bluebackground <$> ((" " `hcomp_`) . (`hcomp_` " ") . text <$> r) primEntry name active ok r = horizontally $ do addLayout $ pure ((), pure $ color magenta $ text name) addControl (pure name) (active <&> \case True -> [Put $ writeRef r, Get $ text <$> readRef r]; False -> []) $ color <$> (active >>= bool (bool greenbackground redbackground <$> ok) (pure magenta)) <*> (text . pad 7 . (++ " ") <$> readRef r) where pad n s = replicate (n - length s) ' ' ++ s padding w = addLayout $ (,) <$> w <*> (fmap padDoc <$> getLayout) vertically ms = addLayout $ (,) <$> ms <*> getLayout horizontally ms = addLayout $ (,) <$> ms <*> (fmap (foldr hcomp emptyDoc) <$> collectLayouts) switch r f = addLayout $ h <$> onChangeMemo r g where g v = return <$> ((,) <$> f v <*> getLayout) h v = (fst <$> v, join $ snd <$> v) asyncDoAt t w = do f <- lift $ asks asyncDoAtDict f t w currentTime = do t <- asks time readSimpleRef t getLayout :: (RefContext m, s ~ WContext m) => RefCreator s (RefReader s Doc) getLayout = fmap (foldr vcomp emptyDoc) <$> collectLayouts -------------------------------------------------------------------------------- data Action s = Click (RefWriter s ()) -- button and checkbox | Put (String -> RefWriter s ()) -- entry | Get (RefReader s Doc) -- entry and dynamic label type WContext m = ReaderT (WidgetContextDict m) m data WidgetContextDict m = WidgetContextDict { addControlDict :: RegisterControl (WContext m) , asyncDoAtDict :: Time -> RefWriter (WContext m) () -> RefCreator (WContext m) () , widgetCollection :: SimpleRef m (RefReader (WContext m) [Doc]) , time :: SimpleRef m Time } type RegisterControl s = RefReader s String -> RefReader s [Action s] -> RefReader s Doc -> RefCreator s () -------------------------------------------------------------------------------- addControl :: (RefContext m, s ~ WContext m) => RefReader s String -> RefReader s [Action s] -> RefReader s Doc -> RefCreator s () addControl name acts layout = do f <- lift $ asks addControlDict f name acts layout addLayout :: (RefContext m, s ~ WContext m) => RefCreator s (a, RefReader s Doc) -> RefCreator s a addLayout f = do c <- lift $ asks widgetCollection vs <- lift $ modSimpleRef c $ state $ \s -> (s, pure []) (a, v) <- f lift $ modSimpleRef c $ modify $ liftA2 (++) $ liftA2 (:) v vs return a collectLayouts :: (RefContext m, s ~ WContext m) => RefCreator s (RefReader s [Doc]) collectLayouts = do c <- lift $ asks widgetCollection lift $ modSimpleRef c $ state $ \s -> (reverse <$> s, pure []) primButton :: (RefContext m, s ~ WContext m) => RefReader s String -- ^ dynamic label of the button -> RefReader s Doc -- ^ dynamic label of the button ^ the button is active when this returns @True@ -> RefWriter s () -- ^ the action to do when the button is pressed -> RefCreator s () primButton name layout vis act = addControl name (vis <&> \case True -> [Click act, Get layout]; False -> []) $ color <$> (bool grey magenta <$> vis) <*> layout -------------------------------- run, run' :: RefCreator (WContext IO) () -> IO (String -> IO (), String -> String -> IO (), String -> IO (), Delay -> IO ()) run = runWidget putStr . padding run' = runWidget (appendFile "out") . padding runWidget :: forall m . RefContext m => (String -> m ()) -> RefCreator (WContext m) () -> m (String -> m (), String -> String -> m (), String -> m (), Delay -> m ()) runWidget out buildwidget = do delayedactions <- newSimpleRef mempty time <- newSimpleRef 0 controlmap <- newSimpleRef mempty controlnames <- newSimpleRef mempty controlcounter <- newSimpleRef 0 currentview <- newSimpleRef emptyDoc collection <- newSimpleRef $ pure [] let addControl name acts layout = do i <- lift $ modSimpleRef controlcounter $ state $ \c -> (c, succ c) let setControlActions cs = modSimpleRef controlmap $ modify $ case cs of [] -> Map.delete i _ -> Map.insert i cs f Unblock = acts f _ = pure [] void $ onChange acts $ lift . setControlActions void $ onChangeEqOld name $ \oldname name -> lift $ modSimpleRef controlnames $ modify $ Map'.insertWith Set.union name (Set.singleton i) . Map'.update (Just . Set.delete i) oldname onRegionStatusChange_ $ \msg -> setControlActions <$> f msg addLayout $ return $ (,) () $ hcomp_ <$> layout <*> (pure $ color yellow $ text $ map toSubscript $ show i) asyncDoAt t w = lift $ do ct <- readSimpleRef time if (t < ct) then fail "asyncDoAt" else modSimpleRef delayedactions $ modify $ insertBy (compare `on` fst) (t, w) delay d = do ct <- lift $ readSimpleRef time timeJump $ ct + d timeJump t = do lift (readSimpleRef delayedactions) >>= \case ((t', w): as) | t' <= t -> do lift $ writeSimpleRef delayedactions as lift $ writeSimpleRef time t' w timeJump t _ -> lift $ writeSimpleRef time t lookup_ :: String -> m [Action (WContext m)] lookup_ n = do ns <- readSimpleRef controlnames i <- case (Map'.lookup n ns, reads n) of (Just is, _) | not $ Set.null is -> return $ head $ Set.toList is (_, [(i, "")]) -> return i _ -> fail "no such control" cs <- readSimpleRef controlmap maybe (fail "control not registered") pure $ Map.lookup i cs draw = modSimpleRef currentview (state $ \d -> (show d, emptyDoc)) >>= out st = WidgetContextDict addControl asyncDoAt collection time flip runReaderT st $ runRefCreator $ \runRefWriter_ -> do buildwidget layout <- getLayout void $ onChangeEq layout $ lift . writeSimpleRef currentview lift $ lift draw let runRefWriter :: RefWriter (WContext m) b -> m b runRefWriter = flip runReaderT st . runRefWriter_ click cs = fromMaybe (fail "not a button or checkbox") $ listToMaybe [runRefWriter act | Click act <- cs] put cs s = fromMaybe (fail "not an entry") $ listToMaybe [runRefWriter $ act s | Put act <- cs] get cs = fromMaybe (fail "not an entry or label") $ listToMaybe [runRefWriter $ readerToWriter act | Get act <- cs] return ( \n -> lookup_ n >>= click >> draw , \n s -> lookup_ n >>= (`put` s) >> draw , \n -> (lookup_ n >>= get) >>= out . show , \t -> runRefWriter (delay t) >> draw ) -------------------------------------------------------------------------------- Doc data type -------------------------------------------------------------------------------- data Doc = Doc Int [String] deriving Eq instance IsString Doc where fromString = text instance Show Doc where show (Doc _ ss) = unlines ss height :: Doc -> Int height (Doc _ l) = length l emptyDoc :: Doc emptyDoc = Doc 0 [] text :: String -> Doc text = foldr vcomp emptyDoc . map f . lines where f s = Doc (length s) [s] color :: Color -> Doc -> Doc color c (Doc n ss) = Doc n ["\x1b[" ++ show c ++ "m" ++ s ++ "\x1b[0m" | s <- ss] vcomp :: Doc -> Doc -> Doc vcomp (Doc n s) (Doc m t) = Doc k $ map (pad (k-n)) s ++ map (pad (k-m)) t where k = max n m pad n l = l ++ replicate n ' ' hcomp :: Doc -> Doc -> Doc hcomp (Doc 0 _) d2 = d2 hcomp d1 d2 = d1 `hcomp_` (" " `hcomp_` d2) hcomp_ :: Doc -> Doc -> Doc hcomp_ (Doc n xs) (Doc m ys) = Doc (n + m) $ zipWith (++) (ext n xs) (ext m ys) where h = max (length xs) (length ys) ext n l = take h $ l ++ repeat (replicate n ' ') padDoc :: Doc -> Doc padDoc d = color red (foldr vcomp emptyDoc $ replicate (height d) " |") `hcomp` d ------------------------------------------ type Color = Int red, green, magenta, grey, redbackground, greenbackground, bluebackground :: Color red = 31 green = 32 yellow = 33 magenta = 35 grey = 37 redbackground = 41 greenbackground = 42 bluebackground = 44 -------------------------------------------------------------------------------- Aux -------------------------------------------------------------------------------- infixl 1 <&> (<&>) :: Functor f => f a -> (a -> b) -> f b as <&> f = f <$> as bool :: a -> a -> Bool -> a bool a _ True = a bool _ b False = b modSimpleRef :: RefContext m => SimpleRef m a -> StateT a m b -> m b modSimpleRef r s = do a <- readSimpleRef r (x, a') <- runStateT s a writeSimpleRef r a' return x --------------------- newtype Prec2 a = Prec2 { unPrec2 :: a } deriving (Eq, Ord, Num, Fractional, Floating, Real, RealFrac, RealFloat) instance RealFloat a => Show (Prec2 a) where show d = showFFloat (Just 2) d "" instance Read a => Read (Prec2 a) where readsPrec i = map f . readsPrec i where f (a, s) = (Prec2 a, s) prec2 :: Lens' a (Prec2 a) prec2 = iso Prec2 unPrec2 --------------------- newtype NonNegative a = NonNegative { unNonNegative :: a } deriving (Eq, Ord, Num, Fractional, Floating, Real, RealFrac, RealFloat) instance Show a => Show (NonNegative a) where show (NonNegative x) = show x instance (Read a, Ord a, Num a) => Read (NonNegative a) where readsPrec i = concatMap f . readsPrec i where f (a, s) = [(NonNegative a, s) | a >= 0] nonNegative :: Lens' a (NonNegative a) nonNegative = iso NonNegative unNonNegative --------------------- convert :: (RealFrac a, RealFrac b) => Lens' a b convert = iso realToFrac realToFrac --------------------- toSubscript '0' = '₀' toSubscript '1' = '₁' toSubscript '2' = '₂' toSubscript '3' = '₃' toSubscript '4' = '₄' toSubscript '5' = '₅' toSubscript '6' = '₆' toSubscript '7' = '₇' toSubscript '8' = '₈' toSubscript '9' = '₉' toSubscript _ = error "toSubscript"
null
https://raw.githubusercontent.com/divipp/lensref/2f0b9a36ac8853780e2b09ad0769464dd3837dab/src/LensRef/Demo/SevenGUIs.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE OverloadedStrings # ---------------------------------------------------------------------------- 7guis # 1 model view ---------------------------------------------------------------------------- 7guis # 1 version 2 ---------------------------------------------------------------------------- 7guis # 2 model view ----------- defined in Control . Lens ---------------------------------------------------------------------------- 7guis # 3 model view view model view view -------- part of the toolkit ---------------------------------------------------------------------------- 7guis # 4 model view -------- part of the toolkit ---------------------------------------------------------------------------- 7guis # 5 model view ---------------------------------------------------------------------------- 7guis # 6 model view --------- part of the toolkit | Undo-redo state transformation. ^ equality on state ^ reference of state ^ undo and redo actions ------------------------------------------------------------------------------ Widget API ------------------------------------------------------------------------------ seconds elapsed from program start ^ active (sensitive) ^ the content is correct | Label entry. | Button. ^ dynamic label of the button ------------------------------------------------------------------------------ API implementation ------------------------------------------------------------------------------ TODO: should work with head instead of listToMaybe ------------------------------------------------------------------------------ button and checkbox entry entry and dynamic label ------------------------------------------------------------------------------ ^ dynamic label of the button ^ dynamic label of the button ^ the action to do when the button is pressed ------------------------------ ------------------------------------------------------------------------------ Doc data type ------------------------------------------------------------------------------ ---------------------------------------- ------------------------------------------------------------------------------ Aux ------------------------------------------------------------------------------ ------------------- ------------------- ------------------- -------------------
# LANGUAGE TypeFamilies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE NoMonomorphismRestriction # module LensRef.Demo.SevenGUIs where import Numeric (showFFloat) import Data.String (IsString (..)) import Data.Function (on) import Data.List (isPrefixOf, insertBy) import Data.Maybe (fromMaybe, listToMaybe, isJust, isNothing) import qualified Data.IntMap as Map import qualified Data.Map as Map' import qualified Data.IntSet as Set import Control.Applicative (pure, (<*>), (<$>), liftA2) import Control.Monad.State import Control.Monad.Reader import Control.Monad.Writer import Lens.Family2 import Lens.Family2.Stock import Lens.Family2.Unchecked import LensRef | Simple counter Try in ghci : > ( click , put , get , delay ) < - run counter > click 1 > get 0 Simple counter Try in ghci: > (click, put, get, delay) <- run counter > click 1 > get 0 -} counter :: WidgetContext s => RefCreator s () counter = do r <- newRef (0 :: Int) let inc = modRef r (+1) horizontally $ do label "Value" $ show <$> readRef r button "Count" $ pure $ Just inc counterV2 :: WidgetContext s => RefCreator s () counterV2 = counterModel >>= counterView data Counter s = Counter { counterValue :: RefReader s Int , incrementCounter :: RefWriter s () } counterModel :: RefContext s => RefCreator s (Counter s) counterModel = do r <- newRef (0 :: Int) return Counter { counterValue = readRef r , incrementCounter = modRef r (+1) } counterView :: WidgetContext s => Counter s -> RefCreator s () counterView (Counter {..}) = horizontally $ do label "Value" $ show <$> counterValue button "Count" $ pure $ Just incrementCounter type Temperature = Prec2 Double temperatureConverter :: WidgetContext s => RefCreator s () temperatureConverter = do celsius <- newRef (0 :: Temperature) let fahrenheit = multiplying 1.8 . adding 32 `lensMap` celsius horizontally $ do void $ entryShow "Celsius" celsius void $ entryShow "Fahrenheit" fahrenheit adding :: Num a => a -> Lens' a a adding n = iso (+n) (+(-n)) multiplying :: (Fractional a, Eq a) => a -> Lens' a a multiplying 0 = error "multiplying: factor 0" multiplying n = iso (*n) (/n) type Date = NonNegative Integer flightBooker :: WidgetContext s => RefCreator s () flightBooker = do booked <- newRef False startdate <- newRef (0 :: Date) maybeenddate <- newRef (Nothing :: Maybe Date) void $ readRef booked `switch` \case True -> label "Notice" $ do start <- readRef startdate readRef maybeenddate <&> \case Just end -> "You have booked a return flight on " ++ show start ++ "-" ++ show end Nothing -> "You have booked a one-way flight on " ++ show start False -> do boolenddate <- extendRef maybeenddate maybeLens (False, 0) let isreturn = lensMap _1 boolenddate bookaction parseok = do ok <- parseok start <- readRef startdate end <- readRef maybeenddate return $ (ok && maybe True (start <=) end, writeRef booked True) ^. maybeLens combobox isreturn $ do item False "One-way" item True "Return" startok <- entryShow "Start" startdate endok <- entryShowActive "End" (readRef isreturn) $ lensMap _2 boolenddate button "Book" $ bookaction $ (&&) <$> startok <*> endok maybeLens :: Lens' (Bool, a) (Maybe a) maybeLens = lens (\(b, a) -> mkMaybe a b) (\(_, a) ma -> maybe (False, a) (\a' -> (True, a')) ma) mkMaybe :: a -> Bool -> Maybe a mkMaybe a True = Just a mkMaybe _ False = Nothing timer :: WidgetContext s => Rational -> RefCreator s () timer refresh = do duration <- newRef 10 start <- newRef =<< lift currentTime timer <- join <$> onChange (readRef start + readRef duration) (mkTimer refresh) let elapsed = timer - readRef start ratio = safeDiv <$> elapsed <*> readRef duration where safeDiv _ 0 = 1 safeDiv a b = a / b reset = writeRef start =<< lift currentTime vertically $ do label "Elapsed (percent)" $ (++"%") . show . (*100) . (^. convert . prec2) <$> ratio label "Elapsed" $ (++"s") . show . (^. convert . prec2) <$> elapsed void $ entryShow "Duration" $ lensMap (convert . prec2 . nonNegative) duration button "Reset" $ pure $ Just reset mkTimer :: WidgetContext s => Delay -> Time -> RefCreator s (RefReader s Time) mkTimer refresh end = do t <- lift currentTime if end <= t then return $ pure end else do x <- newRef t void $ onChange (readRef x) $ \xt -> when (xt < end) $ asyncDo refresh $ writeRef x =<< lift currentTime return $ readRef x crud :: WidgetContext s => RefCreator s () crud = do names <- newRef [("Emil", "Hans"), ("Mustermann", "Max"), ("Tisch", "Roman")] name <- newRef ("Romba", "John") prefix <- newRef "" sel <- onChangeEq_ (readRef prefix) $ const $ return Nothing let create = do n <- readerToWriter $ readRef name modRef names (++ [n]) update s i = modRef names $ \l -> take i l ++ [s] ++ drop (i+1) l delete i = do writeRef sel Nothing modRef names $ \l -> take i l ++ drop (i+1) l filterednames = (readRef prefix <&> \p -> filter (isPrefixOf p . fst . snd)) <*> (zip [0..] <$> readRef names) vertically $ do entry "Filter prefix" prefix listbox sel $ map (\(i, (s, n)) -> (i, s ++ ", " ++ n)) <$> filterednames entry "Name" $ lensMap _2 name entry "Surname" $ lensMap _1 name horizontally $ do button "Create" $ pure $ Just create button "Update" $ fmap <$> (update <$> readRef name) <*> readRef sel button "Delete" $ fmap delete <$> readRef sel circleDrawer :: forall s . WidgetContext s => RefCreator s () circleDrawer = do mousepos <- newRef (0, 0 :: Prec2 Double) circles <- newRef [((0,2), 1), ((0,0), 2)] selected <- onChange_ (readRef circles) $ const $ return Nothing (undo, redo) <- undoTr (==) circles sel <- extendRef selected maybeLens (False, (0, 1)) let click = do mp <- readerToWriter $ readRef mousepos l <- readerToWriter $ readRef circles head $ [ writeRef selected $ Just (i, d) | (i, (p, d)) <- zip [0..] l , distance mp p <= d + 0.01 ] ++ [ modRef circles $ insertBy (compare `on` snd) (mp, 1) ] view = maybe id f <$> readRef selected <*> (map ((,) False) <$> readRef circles) where f (i, d) l = insertBy (compare `on` snd . snd) (True, (fst $ snd $ l !! i, d)) $ take i l ++ drop (i+1) l done = readerToWriter view >>= writeRef circles . map snd horizontally $ do button "Undo" undo button "Redo" redo horizontally $ do void $ entryShow "MousePos" mousepos button "MouseClick" $ mkMaybe click . not <$> readRef (lensMap _1 sel) label "Circles" $ view <&> \l -> unlines [show d ++ " at " ++ show p ++ if s then " filled" else "" | (s, (p, d)) <- l] void $ (readRef $ lensMap _1 sel) `switch` \case False -> return () True -> do label "Adjust diameter of circle at" $ show . fst <$> ((!!) <$> readRef circles <*> readRef (lensMap (_2 . _1) sel)) horizontally $ do void $ entryShow "Diameter" $ lensMap (_2 . _2 . nonNegative) sel button "Done" $ pure $ Just done distance (x1, y1) (x2, y2) = sqrt $ (x2-x1)^2 + (y2-y1)^2 undoTr :: RefContext s -> RefCreator s ( RefReader s (Maybe (RefWriter s ())) , RefReader s (Maybe (RefWriter s ())) undoTr eq r = do ku <- extendRef r (undoLens eq) ([], []) let try f = fmap (writeRef ku) . f <$> readRef ku pure (try undo, try redo) where undo (x: xs@(_:_), ys) = Just (xs, x: ys) undo _ = Nothing redo (xs, y: ys) = Just (y: xs, ys) redo _ = Nothing undoLens :: (a -> a -> Bool) -> Lens' ([a],[a]) a undoLens eq = lens get set where get = head . fst set (x' : xs, ys) x | eq x x' = (x: xs, ys) set (xs, _) x = (x : xs, []) duration in seconds infix 1 `switch` type NamedWidgets s = WriterT [(String, RefCreator s ())] (RefCreator s) class RefContext s => WidgetContext s where label :: String -> RefReader s String -> RefCreator s () primEntry :: String -> Ref s String -> RefCreator s () entry :: String -> Ref s String -> RefCreator s () entry name = primEntry name (pure True) (pure True) entryShow :: (Show a, Read a) => String -> Ref s a -> RefCreator s (RefReader s Bool) entryShow name = entryShowActive name (pure True) entryShowActive :: (Show a, Read a) => String -> RefReader s Bool -> Ref s a -> RefCreator s (RefReader s Bool) entryShowActive name active r = do x <- readerToCreator $ readRef r v <- extendRef r (lens fst set') (x, Nothing) let ok = isNothing . snd <$> readRef v primEntry name active ok $ lens get set `lensMap` v return ok where set' t@(v',_) v | show v == show v' = t set' _ v = (v, Nothing) get (_, Just s) = s get (v, _) = show v set (v, _) s = case reads s of ((x,""):_) -> (x, Nothing) _ -> (v, Just s) button ^ when the @Maybe@ readRef is @Nothing@ , the button is inactive -> RefCreator s () checkbox :: Ref s Bool -> RefCreator s () combobox :: Eq a => Ref s a -> Writer [(a, String)] () -> RefCreator s () listbox :: Eq a => Ref s (Maybe a) -> RefReader s [(a, String)] -> RefCreator s () padding :: RefCreator s a -> RefCreator s a vertically :: RefCreator s a -> RefCreator s a horizontally :: RefCreator s a -> RefCreator s a switch :: Eq a => RefReader s a -> (a -> RefCreator s b) -> RefCreator s (RefReader s b) asyncDoAt :: Time -> RefWriter s () -> RefCreator s () asyncDo :: Delay -> RefWriter s () -> RefCreator s () asyncDo d w = do t <- lift currentTime asyncDoAt (t + d) w currentTime :: s Time item :: MonadWriter [(a, b)] m => a -> b -> m () item s m = tell [(s, m)] instance RefContext m => WidgetContext (WContext m) where button s fm = primButton s (text <$> s) (isJust <$> fm) $ readerToWriter fm >>= fromMaybe (pure ()) checkbox r = primButton (show <$> readRef r) (text . show <$> readRef r) (pure True) $ modRef r not combobox i as = horizontally $ forM_ (execWriter as) $ \(n, s) -> primButton (pure s) ((bool (color green) id . (== n) <$> readRef i) <*> pure (text s)) (pure True) $ writeRef i n listbox sel as = void $ (null <$> as) `switch` \case True -> return () False -> do (layout <$> (head <$> as) <*> readRef sel) (pure True) (writeRef sel . Just . fst . head =<< readerToWriter as) TODO : should work with tail instead of drop 1 where layout (a, s) (Just a') | a == a' = color green $ text s layout (_, s) _ = text s label name r = horizontally $ do addLayout $ pure ((), pure $ color magenta $ text name) addControl (pure name) (pure [Get $ r <&> text]) $ color bluebackground <$> ((" " `hcomp_`) . (`hcomp_` " ") . text <$> r) primEntry name active ok r = horizontally $ do addLayout $ pure ((), pure $ color magenta $ text name) addControl (pure name) (active <&> \case True -> [Put $ writeRef r, Get $ text <$> readRef r]; False -> []) $ color <$> (active >>= bool (bool greenbackground redbackground <$> ok) (pure magenta)) <*> (text . pad 7 . (++ " ") <$> readRef r) where pad n s = replicate (n - length s) ' ' ++ s padding w = addLayout $ (,) <$> w <*> (fmap padDoc <$> getLayout) vertically ms = addLayout $ (,) <$> ms <*> getLayout horizontally ms = addLayout $ (,) <$> ms <*> (fmap (foldr hcomp emptyDoc) <$> collectLayouts) switch r f = addLayout $ h <$> onChangeMemo r g where g v = return <$> ((,) <$> f v <*> getLayout) h v = (fst <$> v, join $ snd <$> v) asyncDoAt t w = do f <- lift $ asks asyncDoAtDict f t w currentTime = do t <- asks time readSimpleRef t getLayout :: (RefContext m, s ~ WContext m) => RefCreator s (RefReader s Doc) getLayout = fmap (foldr vcomp emptyDoc) <$> collectLayouts data Action s type WContext m = ReaderT (WidgetContextDict m) m data WidgetContextDict m = WidgetContextDict { addControlDict :: RegisterControl (WContext m) , asyncDoAtDict :: Time -> RefWriter (WContext m) () -> RefCreator (WContext m) () , widgetCollection :: SimpleRef m (RefReader (WContext m) [Doc]) , time :: SimpleRef m Time } type RegisterControl s = RefReader s String -> RefReader s [Action s] -> RefReader s Doc -> RefCreator s () addControl :: (RefContext m, s ~ WContext m) => RefReader s String -> RefReader s [Action s] -> RefReader s Doc -> RefCreator s () addControl name acts layout = do f <- lift $ asks addControlDict f name acts layout addLayout :: (RefContext m, s ~ WContext m) => RefCreator s (a, RefReader s Doc) -> RefCreator s a addLayout f = do c <- lift $ asks widgetCollection vs <- lift $ modSimpleRef c $ state $ \s -> (s, pure []) (a, v) <- f lift $ modSimpleRef c $ modify $ liftA2 (++) $ liftA2 (:) v vs return a collectLayouts :: (RefContext m, s ~ WContext m) => RefCreator s (RefReader s [Doc]) collectLayouts = do c <- lift $ asks widgetCollection lift $ modSimpleRef c $ state $ \s -> (reverse <$> s, pure []) primButton :: (RefContext m, s ~ WContext m) ^ the button is active when this returns @True@ -> RefCreator s () primButton name layout vis act = addControl name (vis <&> \case True -> [Click act, Get layout]; False -> []) $ color <$> (bool grey magenta <$> vis) <*> layout run, run' :: RefCreator (WContext IO) () -> IO (String -> IO (), String -> String -> IO (), String -> IO (), Delay -> IO ()) run = runWidget putStr . padding run' = runWidget (appendFile "out") . padding runWidget :: forall m . RefContext m => (String -> m ()) -> RefCreator (WContext m) () -> m (String -> m (), String -> String -> m (), String -> m (), Delay -> m ()) runWidget out buildwidget = do delayedactions <- newSimpleRef mempty time <- newSimpleRef 0 controlmap <- newSimpleRef mempty controlnames <- newSimpleRef mempty controlcounter <- newSimpleRef 0 currentview <- newSimpleRef emptyDoc collection <- newSimpleRef $ pure [] let addControl name acts layout = do i <- lift $ modSimpleRef controlcounter $ state $ \c -> (c, succ c) let setControlActions cs = modSimpleRef controlmap $ modify $ case cs of [] -> Map.delete i _ -> Map.insert i cs f Unblock = acts f _ = pure [] void $ onChange acts $ lift . setControlActions void $ onChangeEqOld name $ \oldname name -> lift $ modSimpleRef controlnames $ modify $ Map'.insertWith Set.union name (Set.singleton i) . Map'.update (Just . Set.delete i) oldname onRegionStatusChange_ $ \msg -> setControlActions <$> f msg addLayout $ return $ (,) () $ hcomp_ <$> layout <*> (pure $ color yellow $ text $ map toSubscript $ show i) asyncDoAt t w = lift $ do ct <- readSimpleRef time if (t < ct) then fail "asyncDoAt" else modSimpleRef delayedactions $ modify $ insertBy (compare `on` fst) (t, w) delay d = do ct <- lift $ readSimpleRef time timeJump $ ct + d timeJump t = do lift (readSimpleRef delayedactions) >>= \case ((t', w): as) | t' <= t -> do lift $ writeSimpleRef delayedactions as lift $ writeSimpleRef time t' w timeJump t _ -> lift $ writeSimpleRef time t lookup_ :: String -> m [Action (WContext m)] lookup_ n = do ns <- readSimpleRef controlnames i <- case (Map'.lookup n ns, reads n) of (Just is, _) | not $ Set.null is -> return $ head $ Set.toList is (_, [(i, "")]) -> return i _ -> fail "no such control" cs <- readSimpleRef controlmap maybe (fail "control not registered") pure $ Map.lookup i cs draw = modSimpleRef currentview (state $ \d -> (show d, emptyDoc)) >>= out st = WidgetContextDict addControl asyncDoAt collection time flip runReaderT st $ runRefCreator $ \runRefWriter_ -> do buildwidget layout <- getLayout void $ onChangeEq layout $ lift . writeSimpleRef currentview lift $ lift draw let runRefWriter :: RefWriter (WContext m) b -> m b runRefWriter = flip runReaderT st . runRefWriter_ click cs = fromMaybe (fail "not a button or checkbox") $ listToMaybe [runRefWriter act | Click act <- cs] put cs s = fromMaybe (fail "not an entry") $ listToMaybe [runRefWriter $ act s | Put act <- cs] get cs = fromMaybe (fail "not an entry or label") $ listToMaybe [runRefWriter $ readerToWriter act | Get act <- cs] return ( \n -> lookup_ n >>= click >> draw , \n s -> lookup_ n >>= (`put` s) >> draw , \n -> (lookup_ n >>= get) >>= out . show , \t -> runRefWriter (delay t) >> draw ) data Doc = Doc Int [String] deriving Eq instance IsString Doc where fromString = text instance Show Doc where show (Doc _ ss) = unlines ss height :: Doc -> Int height (Doc _ l) = length l emptyDoc :: Doc emptyDoc = Doc 0 [] text :: String -> Doc text = foldr vcomp emptyDoc . map f . lines where f s = Doc (length s) [s] color :: Color -> Doc -> Doc color c (Doc n ss) = Doc n ["\x1b[" ++ show c ++ "m" ++ s ++ "\x1b[0m" | s <- ss] vcomp :: Doc -> Doc -> Doc vcomp (Doc n s) (Doc m t) = Doc k $ map (pad (k-n)) s ++ map (pad (k-m)) t where k = max n m pad n l = l ++ replicate n ' ' hcomp :: Doc -> Doc -> Doc hcomp (Doc 0 _) d2 = d2 hcomp d1 d2 = d1 `hcomp_` (" " `hcomp_` d2) hcomp_ :: Doc -> Doc -> Doc hcomp_ (Doc n xs) (Doc m ys) = Doc (n + m) $ zipWith (++) (ext n xs) (ext m ys) where h = max (length xs) (length ys) ext n l = take h $ l ++ repeat (replicate n ' ') padDoc :: Doc -> Doc padDoc d = color red (foldr vcomp emptyDoc $ replicate (height d) " |") `hcomp` d type Color = Int red, green, magenta, grey, redbackground, greenbackground, bluebackground :: Color red = 31 green = 32 yellow = 33 magenta = 35 grey = 37 redbackground = 41 greenbackground = 42 bluebackground = 44 infixl 1 <&> (<&>) :: Functor f => f a -> (a -> b) -> f b as <&> f = f <$> as bool :: a -> a -> Bool -> a bool a _ True = a bool _ b False = b modSimpleRef :: RefContext m => SimpleRef m a -> StateT a m b -> m b modSimpleRef r s = do a <- readSimpleRef r (x, a') <- runStateT s a writeSimpleRef r a' return x newtype Prec2 a = Prec2 { unPrec2 :: a } deriving (Eq, Ord, Num, Fractional, Floating, Real, RealFrac, RealFloat) instance RealFloat a => Show (Prec2 a) where show d = showFFloat (Just 2) d "" instance Read a => Read (Prec2 a) where readsPrec i = map f . readsPrec i where f (a, s) = (Prec2 a, s) prec2 :: Lens' a (Prec2 a) prec2 = iso Prec2 unPrec2 newtype NonNegative a = NonNegative { unNonNegative :: a } deriving (Eq, Ord, Num, Fractional, Floating, Real, RealFrac, RealFloat) instance Show a => Show (NonNegative a) where show (NonNegative x) = show x instance (Read a, Ord a, Num a) => Read (NonNegative a) where readsPrec i = concatMap f . readsPrec i where f (a, s) = [(NonNegative a, s) | a >= 0] nonNegative :: Lens' a (NonNegative a) nonNegative = iso NonNegative unNonNegative convert :: (RealFrac a, RealFrac b) => Lens' a b convert = iso realToFrac realToFrac toSubscript '0' = '₀' toSubscript '1' = '₁' toSubscript '2' = '₂' toSubscript '3' = '₃' toSubscript '4' = '₄' toSubscript '5' = '₅' toSubscript '6' = '₆' toSubscript '7' = '₇' toSubscript '8' = '₈' toSubscript '9' = '₉' toSubscript _ = error "toSubscript"
17aa1ed735c5aa79219a9bbaadd42398a7f3443ffe0fb6904636801282aa73f8
AdaCore/why3
ast.ml
(** {1 Abstract syntax trees} *) (* open Why3 *) (* to comment out when inside Why3 *) type var_type = | Tint | Tbool type label = Here | Old type expression = | Evar of Abstract.why_var * label | Ecst of string | Eadd of expression * expression | Esub of expression * expression | Emul of expression * expression | Ediv of expression * expression | Emod of expression * expression | Ebwtrue | Ebwfalse | Ebwnot of expression | Ebwand of expression * expression | Ebwor of expression * expression let e_var v lab = Evar(v,lab) let e_cst c = Ecst c let e_add e1 e2 = Eadd(e1,e2) let e_sub e1 e2 = Esub(e1,e2) let e_mul e1 e2 = Emul(e1,e2) let e_div e1 e2 = Ediv(e1,e2) let e_mod e1 e2 = Emod(e1,e2) let e_bwtrue = Ebwtrue let e_bwfalse = Ebwfalse let bwnot_simp e = match e with | Ebwtrue -> Ebwfalse | Ebwfalse -> Ebwtrue | Ebwnot e -> e | _ -> Ebwnot e let bwor_simp e1 e2 = match e1, e2 with | Ebwtrue,_ | _,Ebwtrue -> Ebwtrue | Ebwfalse,_ -> e2 | _,Ebwfalse -> e1 | _ -> Ebwor(e1,e2) let bwand_simp e1 e2 = match e1, e2 with | Ebwfalse,_ | _,Ebwfalse -> Ebwfalse | Ebwtrue,_ -> e2 | _,Ebwtrue -> e1 | _ -> Ebwand(e1,e2) let rec subst_e (x:Abstract.why_var) (t:expression) (e:expression) : expression = match e with | Evar (var, Here) -> if var = x then t else e | Evar (_, Old) -> assert false | Eadd (e1, e2) -> Eadd(subst_e x t e1, subst_e x t e2) | Esub (e1, e2) -> Esub(subst_e x t e1, subst_e x t e2) | Emul (e1, e2) -> Emul(subst_e x t e1, subst_e x t e2) | Ediv (e1, e2) -> Ediv(subst_e x t e1, subst_e x t e2) | Emod (e1, e2) -> Emod(subst_e x t e1, subst_e x t e2) | Ebwnot e -> Ebwnot(subst_e x t e) | Ebwand (e1, e2) -> Ebwand(subst_e x t e1, subst_e x t e2) | Ebwor (e1, e2) -> Ebwor(subst_e x t e1, subst_e x t e2) | Ecst _ | Ebwtrue | Ebwfalse -> e let e_let_in_expression v e1 e2 = subst_e v e1 e2 type atomic_condition = | Ceq of expression * expression | Cne of expression * expression | Ceq_bool of expression * expression | Cne_bool of expression * expression | Clt of expression * expression | Cle of expression * expression | Cgt of expression * expression | Cge of expression * expression | C_is_true of expression | C_is_false of expression let c_eq_int e1 e2 = Ceq(e1,e2) let c_ne_int e1 e2 = Cne(e1,e2) let c_eq_bool e1 e2 = Ceq_bool(e1,e2) let c_ne_bool e1 e2 = Cne_bool(e1,e2) let c_le e1 e2 = Cle(e1,e2) let c_lt e1 e2 = Clt(e1,e2) let c_ge e1 e2 = Cge(e1,e2) let c_gt e1 e2 = Cgt(e1,e2) let c_is_true e = match e with | Ebwnot e -> C_is_false e | _ -> C_is_true e let c_is_false e = match e with | Ebwnot e -> C_is_true e | _ -> C_is_false e type condition = | BTrue | BFalse | BAnd of condition * condition | BOr of condition * condition | BAtomic of atomic_condition let neg_atomic_cond : atomic_condition -> atomic_condition = fun c -> match c with | Ceq (e1, e2) -> Cne (e1, e2) | Cne (e1, e2) -> Ceq (e1, e2) | Ceq_bool (e1, e2) -> Cne_bool (e1, e2) | Cne_bool (e1, e2) -> Ceq_bool (e1, e2) | Clt (e1, e2) -> Cge (e1, e2) | Cle (e1, e2) -> Cgt (e1, e2) | Cgt (e1, e2) -> Cle (e1, e2) | Cge (e1, e2) -> Clt (e1, e2) | C_is_true e -> C_is_false e | C_is_false e -> C_is_true e let true_cond = BTrue let false_cond = BFalse let atomic_cond c = BAtomic c let rec neg_cond : condition -> condition = fun c -> match c with | BTrue -> BFalse | BFalse -> BTrue | BAnd (c1, c2) -> BOr (neg_cond c1, neg_cond c2) | BOr (c1, c2) -> BAnd (neg_cond c1, neg_cond c2) | BAtomic c -> BAtomic (neg_atomic_cond c) let or_cond c1 c2 = match c1, c2 with | BTrue,_ | _,BTrue -> BTrue | BFalse,_ -> c2 | _,BFalse -> c1 | _ -> BOr(c1, c2) let and_cond c1 c2 = match c1, c2 with | BTrue,_ -> c2 | _,BTrue -> c1 | BFalse,_ | _,BFalse -> BFalse | _ -> BAnd(c1,c2) let rec subst_c (x:Abstract.why_var) (t:expression) (c:condition) : condition = match c with | BTrue -> BTrue | BFalse -> BFalse | BAnd (c1, c2) -> and_cond (subst_c x t c1) (subst_c x t c2) | BOr (c1, c2) -> or_cond (subst_c x t c1) (subst_c x t c2) | BAtomic a -> let a' = match a with | Ceq (e1, e2) -> Ceq (subst_e x t e1, subst_e x t e2) | Cne (e1, e2) -> Cne (subst_e x t e1, subst_e x t e2) | Ceq_bool (e1, e2) -> Ceq_bool (subst_e x t e1, subst_e x t e2) | Cne_bool (e1, e2) -> Cne_bool (subst_e x t e1, subst_e x t e2) | Clt (e1, e2) -> Clt (subst_e x t e1, subst_e x t e2) | Cle (e1, e2) -> Cle (subst_e x t e1, subst_e x t e2) | Cgt (e1, e2) -> Cgt (subst_e x t e1, subst_e x t e2) | Cge (e1, e2) -> Cge (subst_e x t e1, subst_e x t e2) | C_is_true e -> C_is_true (subst_e x t e) | C_is_false e -> C_is_false (subst_e x t e) in BAtomic a' let e_let_in_condition v e c = subst_c v e c let ternary_condition c c1 c2 = ` if c then c1 else c2 ` is equivalent to ` ( c /\ c1 ) \/ ( not c /\ c2 ) ` `(c /\ c1) \/ (not c /\ c2)` *) or_cond (and_cond c c1) (and_cond (neg_cond c) c2) (** {2 Statements} *) type fun_id = { fun_name : string; fun_tag : int; } let print_fun_id fmt id = Format.fprintf fmt "%s" id.fun_name let create_fun_id = let c = ref 0 in fun name -> incr c; { fun_name = name; fun_tag = !c; } type statement_node = | Sassign of Abstract.why_var * expression | Sassign_bool of Abstract.why_var * Bdd.variable * expression | Swhile of condition * (string option * condition) list * statement | Sfcall of (Abstract.why_var * statement * Abstract.var_value) option * fun_id * expression list | Site of condition * statement * statement | Sblock of statement list | Sassert of condition | Sassume of condition | Shavoc of Abstract.why_env * condition | Sletin of Abstract.why_var * Abstract.var_value * expression * statement | Sdrop of Abstract.why_var * statement | Sbreak and statement = { stmt_tag : string; stmt_node : statement_node; } let mk_stmt tag n = { stmt_tag = tag; stmt_node = n } let calling_fresh_allowed = ref true let fresh_var ty = assert !calling_fresh_allowed; let open Abstract in match ty with | Tint -> IntValue (fresh_apron_var ()) | Tbool -> BoolValue (fresh_bdd_var ()) let s_assign tag ty v e = let n = match ty with | Tint -> Sassign(v,e) | Tbool -> let b = Abstract.fresh_bdd_var () in Sassign_bool(v,b,e) in mk_stmt tag n let s_assert tag c = mk_stmt tag (Sassert c) let s_assume tag c = mk_stmt tag (Sassume c) let s_sequence tag s1 s2 = match s1.stmt_node, s2.stmt_node with | Sblock [],_ -> s2 | _,Sblock [] -> s1 | Sblock l1, Sblock l2 -> { s2 with stmt_node = Sblock (l1 @ l2) } | Sblock l1, _ -> { s1 with stmt_node = Sblock (l1 @ [s2]) } | _,Sblock l2 -> { s2 with stmt_node = Sblock (s1 :: l2) } | _,_ -> { stmt_tag = tag ; stmt_node = Sblock [s1;s2] } let s_block tag sl = mk_stmt tag (Sblock sl) let s_ite tag c e1 e2 = mk_stmt tag (Site(c,e1,e2)) let s_while tag cond invs body = mk_stmt tag (Swhile(cond, invs, body)) let s_call tag ret f el = let n = match ret with | None -> Sfcall(None,f,el) | Some (ty,v,e) -> let ab = fresh_var ty in Sfcall(Some(v,e,ab),f,el) in mk_stmt tag n let s_havoc tag writes c = let open Abstract in let m = VarMap.fold (fun v ty acc -> VarMap.add v (fresh_var ty) acc) writes VarMap.empty in mk_stmt tag (Shavoc(m,c)) let s_let_in tag ty v e s = let av = fresh_var ty in mk_stmt tag (Sletin(v,av,e,s)) let s_drop tag v s = mk_stmt tag (Sdrop(v,s)) let s_break tag = mk_stmt tag Sbreak type fun_kind = | Fun_let of statement * expression option (** functions defined with a body and possibly a returned expression *) | Fun_val of Abstract.why_env * (Abstract.why_var * Abstract.var_value) option * condition (** functions declared with a contract: a writes clause, an optional result variable, and a post-condition *) type param_value = Param_ref of var_type | Param_noref of Abstract.var_value type func = { func_name : fun_id; func_params : (Abstract.why_var * param_value) list; func_def : fun_kind } (** function declarations. *) let declare_function_let ~(name:fun_id) ~(params:(bool * var_type * Abstract.why_var) list) ~(body:statement) ~(return:(var_type * expression) option) : func = let func_params = List.map (fun (is_ref,ty,v) -> let av = if is_ref then Param_ref ty else Param_noref (fresh_var ty) in (v,av)) params in let return = match return with | Some (_,e) -> Some e | None -> None in let func_def = Fun_let(body,return) in { func_name = name; func_params; func_def; } let declare_function_val ~(name:fun_id) ~(params:(bool * var_type * Abstract.why_var) list) ~(writes:var_type Abstract.VarMap.t) ~(result:(var_type * Abstract.why_var) option) ~(post:condition) : func = let open Abstract in let func_params = List.map (fun (is_ref,ty,v) -> let av = if is_ref then Param_ref ty else Param_noref(fresh_var ty) in (v,av)) params in let writes = VarMap.fold (fun v ty acc -> VarMap.add v (fresh_var ty) acc) writes VarMap.empty in let result = match result with | None -> None | Some (ty,v) -> Some (v, fresh_var ty) in let func_def = Fun_val(writes,result,post) in { func_name = name; func_params; func_def; } type why1program = { name : string; vars : Abstract.var_value Abstract.VarMap.t; functions : func list; statements : statement } let map_to_varmap (map: var_type Abstract.VarMap.t) : Abstract.var_value Abstract.VarMap.t = let open Abstract in let to_abstract v t varmap = let var = match t with | Tint -> IntValue (fresh_apron_var ()) | Tbool -> BoolValue (fresh_bdd_var ()) in VarMap.add v var varmap in VarMap.fold to_abstract map VarMap.empty let mk_program ~name ~variables ~functions ~main = calling_fresh_allowed := false; { name = name; vars = map_to_varmap variables; functions; statements = main; } let reset_ast_generation () = Abstract.reset_fresh_var_generators (); calling_fresh_allowed := true * { 2 Printing } let print_type fmt t = match t with | Tint -> Format.fprintf fmt "int" | Tbool -> Format.fprintf fmt "bool" let rec print_expression fmt e = match e with | Evar (v, Here) -> Format.fprintf fmt "%a" Abstract.print_var v | Evar (v, Old) -> Format.fprintf fmt "@@%a" Abstract.print_var v | Ecst i -> Format.fprintf fmt "%s" i | Eadd(e1, e2) -> Format.fprintf fmt "(%a + %a)" print_expression e1 print_expression e2 | Esub(e1, e2) -> Format.fprintf fmt "(%a - %a)" print_expression e1 print_expression e2 | Emul(e1, e2) -> Format.fprintf fmt "(%a * %a)" print_expression e1 print_expression e2 | Ediv(e1, e2) -> Format.fprintf fmt "(%a / %a)" print_expression e1 print_expression e2 | Emod(e1, e2) -> Format.fprintf fmt "(%a %% %a)" print_expression e1 print_expression e2 | Ebwtrue -> Format.fprintf fmt "True" | Ebwfalse -> Format.fprintf fmt "False" | Ebwnot e' -> Format.fprintf fmt "~%a" print_expression e' | Ebwand(e1, e2) -> Format.fprintf fmt "(%a & %a)" print_expression e1 print_expression e2 | Ebwor(e1, e2) -> Format.fprintf fmt "(%a | %a)" print_expression e1 print_expression e2 let rec print_condition fmt c = match c with | BTrue -> Format.fprintf fmt "T" | BFalse -> Format.fprintf fmt "F" | BAnd (c1, c2) -> Format.fprintf fmt "@[(%a@ && %a)@]" print_condition c1 print_condition c2 | BOr (c1, c2) -> Format.fprintf fmt "(%a || %a)" print_condition c1 print_condition c2 | BAtomic a -> match a with | Ceq(e1, e2) -> Format.fprintf fmt "%a = %a" print_expression e1 print_expression e2 | Cne(e1, e2) -> Format.fprintf fmt "%a <> %a" print_expression e1 print_expression e2 | Ceq_bool(e1, e2) -> Format.fprintf fmt "%a == %a" print_expression e1 print_expression e2 | Cne_bool(e1, e2) -> Format.fprintf fmt "%a =/= %a" print_expression e1 print_expression e2 | Clt(e1, e2) -> Format.fprintf fmt "%a < %a" print_expression e1 print_expression e2 | Cle(e1, e2) -> Format.fprintf fmt "%a <= %a" print_expression e1 print_expression e2 | Cgt(e1, e2) -> Format.fprintf fmt "%a > %a" print_expression e1 print_expression e2 | Cge(e1, e2) -> Format.fprintf fmt "%a >= %a" print_expression e1 print_expression e2 | C_is_true e' -> Format.fprintf fmt "%a" print_expression e' | C_is_false e' -> Format.fprintf fmt "~%a" print_expression e' let rec print_statement_node fmt s = let open Format in match s with | Sassign(v,e) -> fprintf fmt "@[<hv 2>%a <-@ @[%a@]@]" Abstract.print_var v print_expression e | Sassign_bool(v,_,e) -> fprintf fmt "@[<hv 2>%a <-@ @[%a@]@]" Abstract.print_var v print_expression e | Sfcall(None,id,el) -> fprintf fmt "@[%a(%a)@]" print_fun_id id (Pp.print_list Pp.comma print_expression) el | Sfcall(Some (x,s,_),id,el) -> fprintf fmt "@[<hv 0>letcall %a <- @[%a(%a)@]@ in@ @[%a@]@ endletcall@]" Abstract.print_var x print_fun_id id (Pp.print_list Pp.comma print_expression) el print_statement s | Swhile(c,invs,s) -> fprintf fmt "@[<hv 2>while @[%a@] do@ " print_condition c; List.iter (fun (n, c) -> match n with | None -> fprintf fmt "@[invariant @[%a@]@]@ " print_condition c | Some(n) -> fprintf fmt "@[invariant @[@%s] @[%a@]@]@ " n print_condition c) invs; fprintf fmt "@[%a@]@]" print_statement s | Site(c,s1,s2) -> fprintf fmt "@[<hv 2>if @[%a@]@ then@ @[%a@]@ else@ @[%a@]@ endif@]" print_condition c print_statement s1 print_statement s2 | Sassert c -> fprintf fmt "@[<hv 2>assert @[%a@]@]" print_condition c | Sassume c -> fprintf fmt "@[<hv 2>assume @[%a@]@]" print_condition c | Sblock (s::sl) -> fprintf fmt "@[<hv 2>{ @[%a@]" print_statement s; List.iter (function s -> fprintf fmt ";@ @[%a@]" print_statement s) sl; fprintf fmt " }@]" | Sblock [] -> fprintf fmt "skip"; | Shavoc (m, c) -> fprintf fmt "@[<hv 2>havoc writes {%a} @]" Abstract.print_env m; fprintf fmt "@[<hv 2>ensures @[%a@]@]" print_condition c | Sletin(v,_,e,s) -> fprintf fmt "@[<hv 0>let @[<hv 0>%a =@ @[%a@]@]@ in@ @[%a@]@ endlet@]" Abstract.print_var v print_expression e print_statement s | Sdrop(v,s) -> fprintf fmt "@[<hv 0>drop %a in@ @[%a@]@ enddrop@]" Abstract.print_var v print_statement s | Sbreak -> fprintf fmt "break" and print_statement fmt s = match s.stmt_tag with | "" -> print_statement_node fmt s.stmt_node | atr -> Format.fprintf fmt "@[[%s]@ %a@]" atr print_statement_node s.stmt_node let print_param fmt (v, av) = match av with | Param_ref ty -> Format.fprintf fmt "ref %a: %a" Abstract.print_var v print_type ty | Param_noref av -> Format.fprintf fmt "%a(%a)" Abstract.print_var v Abstract.print_var_value av let print_func_def fmt (_d: fun_kind) : unit = Format.fprintf fmt "<funcdef>" let print_func fmt (f : func) : unit = Format.fprintf fmt "@[<hv 2>{ func_name = %a ;@ func_params = [ @[%a@] ] ;@ func_def = @[%a@]@ }@]" print_fun_id f.func_name Pp.(print_list semi print_param) f.func_params print_func_def f.func_def let print_program fmt p = Format.fprintf fmt "@[<hv 2>{ vars = @[%a@] ;@ functions = @[%a@] ;@ main = @[%a@]@ }@]" Abstract.print_env p.vars Pp.(print_list semi print_func) p.functions print_statement p.statements
null
https://raw.githubusercontent.com/AdaCore/why3/be1023970d48869285e68f12d32858c3383958e0/src/bddinfer/ast.ml
ocaml
* {1 Abstract syntax trees} open Why3 to comment out when inside Why3 * {2 Statements} * functions defined with a body and possibly a returned expression * functions declared with a contract: a writes clause, an optional result variable, and a post-condition * function declarations.
type var_type = | Tint | Tbool type label = Here | Old type expression = | Evar of Abstract.why_var * label | Ecst of string | Eadd of expression * expression | Esub of expression * expression | Emul of expression * expression | Ediv of expression * expression | Emod of expression * expression | Ebwtrue | Ebwfalse | Ebwnot of expression | Ebwand of expression * expression | Ebwor of expression * expression let e_var v lab = Evar(v,lab) let e_cst c = Ecst c let e_add e1 e2 = Eadd(e1,e2) let e_sub e1 e2 = Esub(e1,e2) let e_mul e1 e2 = Emul(e1,e2) let e_div e1 e2 = Ediv(e1,e2) let e_mod e1 e2 = Emod(e1,e2) let e_bwtrue = Ebwtrue let e_bwfalse = Ebwfalse let bwnot_simp e = match e with | Ebwtrue -> Ebwfalse | Ebwfalse -> Ebwtrue | Ebwnot e -> e | _ -> Ebwnot e let bwor_simp e1 e2 = match e1, e2 with | Ebwtrue,_ | _,Ebwtrue -> Ebwtrue | Ebwfalse,_ -> e2 | _,Ebwfalse -> e1 | _ -> Ebwor(e1,e2) let bwand_simp e1 e2 = match e1, e2 with | Ebwfalse,_ | _,Ebwfalse -> Ebwfalse | Ebwtrue,_ -> e2 | _,Ebwtrue -> e1 | _ -> Ebwand(e1,e2) let rec subst_e (x:Abstract.why_var) (t:expression) (e:expression) : expression = match e with | Evar (var, Here) -> if var = x then t else e | Evar (_, Old) -> assert false | Eadd (e1, e2) -> Eadd(subst_e x t e1, subst_e x t e2) | Esub (e1, e2) -> Esub(subst_e x t e1, subst_e x t e2) | Emul (e1, e2) -> Emul(subst_e x t e1, subst_e x t e2) | Ediv (e1, e2) -> Ediv(subst_e x t e1, subst_e x t e2) | Emod (e1, e2) -> Emod(subst_e x t e1, subst_e x t e2) | Ebwnot e -> Ebwnot(subst_e x t e) | Ebwand (e1, e2) -> Ebwand(subst_e x t e1, subst_e x t e2) | Ebwor (e1, e2) -> Ebwor(subst_e x t e1, subst_e x t e2) | Ecst _ | Ebwtrue | Ebwfalse -> e let e_let_in_expression v e1 e2 = subst_e v e1 e2 type atomic_condition = | Ceq of expression * expression | Cne of expression * expression | Ceq_bool of expression * expression | Cne_bool of expression * expression | Clt of expression * expression | Cle of expression * expression | Cgt of expression * expression | Cge of expression * expression | C_is_true of expression | C_is_false of expression let c_eq_int e1 e2 = Ceq(e1,e2) let c_ne_int e1 e2 = Cne(e1,e2) let c_eq_bool e1 e2 = Ceq_bool(e1,e2) let c_ne_bool e1 e2 = Cne_bool(e1,e2) let c_le e1 e2 = Cle(e1,e2) let c_lt e1 e2 = Clt(e1,e2) let c_ge e1 e2 = Cge(e1,e2) let c_gt e1 e2 = Cgt(e1,e2) let c_is_true e = match e with | Ebwnot e -> C_is_false e | _ -> C_is_true e let c_is_false e = match e with | Ebwnot e -> C_is_true e | _ -> C_is_false e type condition = | BTrue | BFalse | BAnd of condition * condition | BOr of condition * condition | BAtomic of atomic_condition let neg_atomic_cond : atomic_condition -> atomic_condition = fun c -> match c with | Ceq (e1, e2) -> Cne (e1, e2) | Cne (e1, e2) -> Ceq (e1, e2) | Ceq_bool (e1, e2) -> Cne_bool (e1, e2) | Cne_bool (e1, e2) -> Ceq_bool (e1, e2) | Clt (e1, e2) -> Cge (e1, e2) | Cle (e1, e2) -> Cgt (e1, e2) | Cgt (e1, e2) -> Cle (e1, e2) | Cge (e1, e2) -> Clt (e1, e2) | C_is_true e -> C_is_false e | C_is_false e -> C_is_true e let true_cond = BTrue let false_cond = BFalse let atomic_cond c = BAtomic c let rec neg_cond : condition -> condition = fun c -> match c with | BTrue -> BFalse | BFalse -> BTrue | BAnd (c1, c2) -> BOr (neg_cond c1, neg_cond c2) | BOr (c1, c2) -> BAnd (neg_cond c1, neg_cond c2) | BAtomic c -> BAtomic (neg_atomic_cond c) let or_cond c1 c2 = match c1, c2 with | BTrue,_ | _,BTrue -> BTrue | BFalse,_ -> c2 | _,BFalse -> c1 | _ -> BOr(c1, c2) let and_cond c1 c2 = match c1, c2 with | BTrue,_ -> c2 | _,BTrue -> c1 | BFalse,_ | _,BFalse -> BFalse | _ -> BAnd(c1,c2) let rec subst_c (x:Abstract.why_var) (t:expression) (c:condition) : condition = match c with | BTrue -> BTrue | BFalse -> BFalse | BAnd (c1, c2) -> and_cond (subst_c x t c1) (subst_c x t c2) | BOr (c1, c2) -> or_cond (subst_c x t c1) (subst_c x t c2) | BAtomic a -> let a' = match a with | Ceq (e1, e2) -> Ceq (subst_e x t e1, subst_e x t e2) | Cne (e1, e2) -> Cne (subst_e x t e1, subst_e x t e2) | Ceq_bool (e1, e2) -> Ceq_bool (subst_e x t e1, subst_e x t e2) | Cne_bool (e1, e2) -> Cne_bool (subst_e x t e1, subst_e x t e2) | Clt (e1, e2) -> Clt (subst_e x t e1, subst_e x t e2) | Cle (e1, e2) -> Cle (subst_e x t e1, subst_e x t e2) | Cgt (e1, e2) -> Cgt (subst_e x t e1, subst_e x t e2) | Cge (e1, e2) -> Cge (subst_e x t e1, subst_e x t e2) | C_is_true e -> C_is_true (subst_e x t e) | C_is_false e -> C_is_false (subst_e x t e) in BAtomic a' let e_let_in_condition v e c = subst_c v e c let ternary_condition c c1 c2 = ` if c then c1 else c2 ` is equivalent to ` ( c /\ c1 ) \/ ( not c /\ c2 ) ` `(c /\ c1) \/ (not c /\ c2)` *) or_cond (and_cond c c1) (and_cond (neg_cond c) c2) type fun_id = { fun_name : string; fun_tag : int; } let print_fun_id fmt id = Format.fprintf fmt "%s" id.fun_name let create_fun_id = let c = ref 0 in fun name -> incr c; { fun_name = name; fun_tag = !c; } type statement_node = | Sassign of Abstract.why_var * expression | Sassign_bool of Abstract.why_var * Bdd.variable * expression | Swhile of condition * (string option * condition) list * statement | Sfcall of (Abstract.why_var * statement * Abstract.var_value) option * fun_id * expression list | Site of condition * statement * statement | Sblock of statement list | Sassert of condition | Sassume of condition | Shavoc of Abstract.why_env * condition | Sletin of Abstract.why_var * Abstract.var_value * expression * statement | Sdrop of Abstract.why_var * statement | Sbreak and statement = { stmt_tag : string; stmt_node : statement_node; } let mk_stmt tag n = { stmt_tag = tag; stmt_node = n } let calling_fresh_allowed = ref true let fresh_var ty = assert !calling_fresh_allowed; let open Abstract in match ty with | Tint -> IntValue (fresh_apron_var ()) | Tbool -> BoolValue (fresh_bdd_var ()) let s_assign tag ty v e = let n = match ty with | Tint -> Sassign(v,e) | Tbool -> let b = Abstract.fresh_bdd_var () in Sassign_bool(v,b,e) in mk_stmt tag n let s_assert tag c = mk_stmt tag (Sassert c) let s_assume tag c = mk_stmt tag (Sassume c) let s_sequence tag s1 s2 = match s1.stmt_node, s2.stmt_node with | Sblock [],_ -> s2 | _,Sblock [] -> s1 | Sblock l1, Sblock l2 -> { s2 with stmt_node = Sblock (l1 @ l2) } | Sblock l1, _ -> { s1 with stmt_node = Sblock (l1 @ [s2]) } | _,Sblock l2 -> { s2 with stmt_node = Sblock (s1 :: l2) } | _,_ -> { stmt_tag = tag ; stmt_node = Sblock [s1;s2] } let s_block tag sl = mk_stmt tag (Sblock sl) let s_ite tag c e1 e2 = mk_stmt tag (Site(c,e1,e2)) let s_while tag cond invs body = mk_stmt tag (Swhile(cond, invs, body)) let s_call tag ret f el = let n = match ret with | None -> Sfcall(None,f,el) | Some (ty,v,e) -> let ab = fresh_var ty in Sfcall(Some(v,e,ab),f,el) in mk_stmt tag n let s_havoc tag writes c = let open Abstract in let m = VarMap.fold (fun v ty acc -> VarMap.add v (fresh_var ty) acc) writes VarMap.empty in mk_stmt tag (Shavoc(m,c)) let s_let_in tag ty v e s = let av = fresh_var ty in mk_stmt tag (Sletin(v,av,e,s)) let s_drop tag v s = mk_stmt tag (Sdrop(v,s)) let s_break tag = mk_stmt tag Sbreak type fun_kind = | Fun_let of statement * expression option | Fun_val of Abstract.why_env * (Abstract.why_var * Abstract.var_value) option * condition type param_value = Param_ref of var_type | Param_noref of Abstract.var_value type func = { func_name : fun_id; func_params : (Abstract.why_var * param_value) list; func_def : fun_kind } let declare_function_let ~(name:fun_id) ~(params:(bool * var_type * Abstract.why_var) list) ~(body:statement) ~(return:(var_type * expression) option) : func = let func_params = List.map (fun (is_ref,ty,v) -> let av = if is_ref then Param_ref ty else Param_noref (fresh_var ty) in (v,av)) params in let return = match return with | Some (_,e) -> Some e | None -> None in let func_def = Fun_let(body,return) in { func_name = name; func_params; func_def; } let declare_function_val ~(name:fun_id) ~(params:(bool * var_type * Abstract.why_var) list) ~(writes:var_type Abstract.VarMap.t) ~(result:(var_type * Abstract.why_var) option) ~(post:condition) : func = let open Abstract in let func_params = List.map (fun (is_ref,ty,v) -> let av = if is_ref then Param_ref ty else Param_noref(fresh_var ty) in (v,av)) params in let writes = VarMap.fold (fun v ty acc -> VarMap.add v (fresh_var ty) acc) writes VarMap.empty in let result = match result with | None -> None | Some (ty,v) -> Some (v, fresh_var ty) in let func_def = Fun_val(writes,result,post) in { func_name = name; func_params; func_def; } type why1program = { name : string; vars : Abstract.var_value Abstract.VarMap.t; functions : func list; statements : statement } let map_to_varmap (map: var_type Abstract.VarMap.t) : Abstract.var_value Abstract.VarMap.t = let open Abstract in let to_abstract v t varmap = let var = match t with | Tint -> IntValue (fresh_apron_var ()) | Tbool -> BoolValue (fresh_bdd_var ()) in VarMap.add v var varmap in VarMap.fold to_abstract map VarMap.empty let mk_program ~name ~variables ~functions ~main = calling_fresh_allowed := false; { name = name; vars = map_to_varmap variables; functions; statements = main; } let reset_ast_generation () = Abstract.reset_fresh_var_generators (); calling_fresh_allowed := true * { 2 Printing } let print_type fmt t = match t with | Tint -> Format.fprintf fmt "int" | Tbool -> Format.fprintf fmt "bool" let rec print_expression fmt e = match e with | Evar (v, Here) -> Format.fprintf fmt "%a" Abstract.print_var v | Evar (v, Old) -> Format.fprintf fmt "@@%a" Abstract.print_var v | Ecst i -> Format.fprintf fmt "%s" i | Eadd(e1, e2) -> Format.fprintf fmt "(%a + %a)" print_expression e1 print_expression e2 | Esub(e1, e2) -> Format.fprintf fmt "(%a - %a)" print_expression e1 print_expression e2 | Emul(e1, e2) -> Format.fprintf fmt "(%a * %a)" print_expression e1 print_expression e2 | Ediv(e1, e2) -> Format.fprintf fmt "(%a / %a)" print_expression e1 print_expression e2 | Emod(e1, e2) -> Format.fprintf fmt "(%a %% %a)" print_expression e1 print_expression e2 | Ebwtrue -> Format.fprintf fmt "True" | Ebwfalse -> Format.fprintf fmt "False" | Ebwnot e' -> Format.fprintf fmt "~%a" print_expression e' | Ebwand(e1, e2) -> Format.fprintf fmt "(%a & %a)" print_expression e1 print_expression e2 | Ebwor(e1, e2) -> Format.fprintf fmt "(%a | %a)" print_expression e1 print_expression e2 let rec print_condition fmt c = match c with | BTrue -> Format.fprintf fmt "T" | BFalse -> Format.fprintf fmt "F" | BAnd (c1, c2) -> Format.fprintf fmt "@[(%a@ && %a)@]" print_condition c1 print_condition c2 | BOr (c1, c2) -> Format.fprintf fmt "(%a || %a)" print_condition c1 print_condition c2 | BAtomic a -> match a with | Ceq(e1, e2) -> Format.fprintf fmt "%a = %a" print_expression e1 print_expression e2 | Cne(e1, e2) -> Format.fprintf fmt "%a <> %a" print_expression e1 print_expression e2 | Ceq_bool(e1, e2) -> Format.fprintf fmt "%a == %a" print_expression e1 print_expression e2 | Cne_bool(e1, e2) -> Format.fprintf fmt "%a =/= %a" print_expression e1 print_expression e2 | Clt(e1, e2) -> Format.fprintf fmt "%a < %a" print_expression e1 print_expression e2 | Cle(e1, e2) -> Format.fprintf fmt "%a <= %a" print_expression e1 print_expression e2 | Cgt(e1, e2) -> Format.fprintf fmt "%a > %a" print_expression e1 print_expression e2 | Cge(e1, e2) -> Format.fprintf fmt "%a >= %a" print_expression e1 print_expression e2 | C_is_true e' -> Format.fprintf fmt "%a" print_expression e' | C_is_false e' -> Format.fprintf fmt "~%a" print_expression e' let rec print_statement_node fmt s = let open Format in match s with | Sassign(v,e) -> fprintf fmt "@[<hv 2>%a <-@ @[%a@]@]" Abstract.print_var v print_expression e | Sassign_bool(v,_,e) -> fprintf fmt "@[<hv 2>%a <-@ @[%a@]@]" Abstract.print_var v print_expression e | Sfcall(None,id,el) -> fprintf fmt "@[%a(%a)@]" print_fun_id id (Pp.print_list Pp.comma print_expression) el | Sfcall(Some (x,s,_),id,el) -> fprintf fmt "@[<hv 0>letcall %a <- @[%a(%a)@]@ in@ @[%a@]@ endletcall@]" Abstract.print_var x print_fun_id id (Pp.print_list Pp.comma print_expression) el print_statement s | Swhile(c,invs,s) -> fprintf fmt "@[<hv 2>while @[%a@] do@ " print_condition c; List.iter (fun (n, c) -> match n with | None -> fprintf fmt "@[invariant @[%a@]@]@ " print_condition c | Some(n) -> fprintf fmt "@[invariant @[@%s] @[%a@]@]@ " n print_condition c) invs; fprintf fmt "@[%a@]@]" print_statement s | Site(c,s1,s2) -> fprintf fmt "@[<hv 2>if @[%a@]@ then@ @[%a@]@ else@ @[%a@]@ endif@]" print_condition c print_statement s1 print_statement s2 | Sassert c -> fprintf fmt "@[<hv 2>assert @[%a@]@]" print_condition c | Sassume c -> fprintf fmt "@[<hv 2>assume @[%a@]@]" print_condition c | Sblock (s::sl) -> fprintf fmt "@[<hv 2>{ @[%a@]" print_statement s; List.iter (function s -> fprintf fmt ";@ @[%a@]" print_statement s) sl; fprintf fmt " }@]" | Sblock [] -> fprintf fmt "skip"; | Shavoc (m, c) -> fprintf fmt "@[<hv 2>havoc writes {%a} @]" Abstract.print_env m; fprintf fmt "@[<hv 2>ensures @[%a@]@]" print_condition c | Sletin(v,_,e,s) -> fprintf fmt "@[<hv 0>let @[<hv 0>%a =@ @[%a@]@]@ in@ @[%a@]@ endlet@]" Abstract.print_var v print_expression e print_statement s | Sdrop(v,s) -> fprintf fmt "@[<hv 0>drop %a in@ @[%a@]@ enddrop@]" Abstract.print_var v print_statement s | Sbreak -> fprintf fmt "break" and print_statement fmt s = match s.stmt_tag with | "" -> print_statement_node fmt s.stmt_node | atr -> Format.fprintf fmt "@[[%s]@ %a@]" atr print_statement_node s.stmt_node let print_param fmt (v, av) = match av with | Param_ref ty -> Format.fprintf fmt "ref %a: %a" Abstract.print_var v print_type ty | Param_noref av -> Format.fprintf fmt "%a(%a)" Abstract.print_var v Abstract.print_var_value av let print_func_def fmt (_d: fun_kind) : unit = Format.fprintf fmt "<funcdef>" let print_func fmt (f : func) : unit = Format.fprintf fmt "@[<hv 2>{ func_name = %a ;@ func_params = [ @[%a@] ] ;@ func_def = @[%a@]@ }@]" print_fun_id f.func_name Pp.(print_list semi print_param) f.func_params print_func_def f.func_def let print_program fmt p = Format.fprintf fmt "@[<hv 2>{ vars = @[%a@] ;@ functions = @[%a@] ;@ main = @[%a@]@ }@]" Abstract.print_env p.vars Pp.(print_list semi print_func) p.functions print_statement p.statements
cb55180de2329e71a34e96769e65735c92835037e7fde05aa26b165bb525b516
tweag/ormolu
strictness-out.hs
data Foo a where Foo1 :: !Int -> {-# UNPACK #-} !Bool -> Foo Int Foo2 :: {-# UNPACK #-} Maybe Int && Bool -> Foo Int
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/data/gadt/strictness-out.hs
haskell
# UNPACK # # UNPACK #
data Foo a where
780bbef44f88b87da6014125639e45d3562d305f8abd1d1bd17f5e2a49939e20
SimulaVR/godot-haskell
ImmediateGeometry.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.ImmediateGeometry (Godot.Core.ImmediateGeometry.add_sphere, Godot.Core.ImmediateGeometry.add_vertex, Godot.Core.ImmediateGeometry.begin, Godot.Core.ImmediateGeometry.clear, Godot.Core.ImmediateGeometry.end, Godot.Core.ImmediateGeometry.set_color, Godot.Core.ImmediateGeometry.set_normal, Godot.Core.ImmediateGeometry.set_tangent, Godot.Core.ImmediateGeometry.set_uv, Godot.Core.ImmediateGeometry.set_uv2) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.GeometryInstance() # NOINLINE bindImmediateGeometry_add_sphere # -- | Simple helper to draw an UV sphere with given latitude, longitude and radius. bindImmediateGeometry_add_sphere :: MethodBind bindImmediateGeometry_add_sphere = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "add_sphere" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Simple helper to draw an UV sphere with given latitude, longitude and radius. add_sphere :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Int -> Int -> Float -> Maybe Bool -> IO () add_sphere cls arg1 arg2 arg3 arg4 = withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3, maybe (VariantBool True) toVariant arg4] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_add_sphere (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "add_sphere" '[Int, Int, Float, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.add_sphere # NOINLINE bindImmediateGeometry_add_vertex # -- | Adds a vertex in local coordinate space with the currently set color/uv/etc. bindImmediateGeometry_add_vertex :: MethodBind bindImmediateGeometry_add_vertex = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "add_vertex" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Adds a vertex in local coordinate space with the currently set color/uv/etc. add_vertex :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector3 -> IO () add_vertex cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_add_vertex (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "add_vertex" '[Vector3] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.add_vertex # NOINLINE bindImmediateGeometry_begin # -- | Begin drawing (and optionally pass a texture override). When done call @method end@. For more information on how this works, search for @glBegin()@ and @glEnd()@ references. -- For the type of primitive, see the @enum Mesh.PrimitiveType@ enum. bindImmediateGeometry_begin :: MethodBind bindImmediateGeometry_begin = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "begin" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Begin drawing (and optionally pass a texture override). When done call @method end@. For more information on how this works, search for @glBegin()@ and @glEnd()@ references. -- For the type of primitive, see the @enum Mesh.PrimitiveType@ enum. begin :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Int -> Maybe Texture -> IO () begin cls arg1 arg2 = withVariantArray [toVariant arg1, maybe VariantNil toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_begin (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "begin" '[Int, Maybe Texture] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.begin # NOINLINE bindImmediateGeometry_clear # -- | Clears everything that was drawn using begin/end. bindImmediateGeometry_clear :: MethodBind bindImmediateGeometry_clear = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Clears everything that was drawn using begin/end. clear :: (ImmediateGeometry :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "clear" '[] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.clear # NOINLINE bindImmediateGeometry_end # -- | Ends a drawing context and displays the results. bindImmediateGeometry_end :: MethodBind bindImmediateGeometry_end = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "end" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Ends a drawing context and displays the results. end :: (ImmediateGeometry :< cls, Object :< cls) => cls -> IO () end cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_end (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "end" '[] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.end # NOINLINE bindImmediateGeometry_set_color # -- | The current drawing color. bindImmediateGeometry_set_color :: MethodBind bindImmediateGeometry_set_color = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The current drawing color. set_color :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Color -> IO () set_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_color" '[Color] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_color # NOINLINE bindImmediateGeometry_set_normal # -- | The next vertex's normal. bindImmediateGeometry_set_normal :: MethodBind bindImmediateGeometry_set_normal = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_normal" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The next vertex's normal. set_normal :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector3 -> IO () set_normal cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_normal (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_normal" '[Vector3] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_normal # NOINLINE bindImmediateGeometry_set_tangent # -- | The next vertex's tangent (and binormal facing). bindImmediateGeometry_set_tangent :: MethodBind bindImmediateGeometry_set_tangent = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_tangent" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The next vertex's tangent (and binormal facing). set_tangent :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Plane -> IO () set_tangent cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_tangent (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_tangent" '[Plane] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_tangent # NOINLINE bindImmediateGeometry_set_uv # -- | The next vertex's UV. bindImmediateGeometry_set_uv :: MethodBind bindImmediateGeometry_set_uv = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_uv" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | The next vertex's UV. set_uv :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector2 -> IO () set_uv cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_uv (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_uv" '[Vector2] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_uv # NOINLINE bindImmediateGeometry_set_uv2 # | The next vertex 's second layer UV . bindImmediateGeometry_set_uv2 :: MethodBind bindImmediateGeometry_set_uv2 = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_uv2" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The next vertex 's second layer UV . set_uv2 :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector2 -> IO () set_uv2 cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_uv2 (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_uv2" '[Vector2] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_uv2
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/ImmediateGeometry.hs
haskell
| Simple helper to draw an UV sphere with given latitude, longitude and radius. | Simple helper to draw an UV sphere with given latitude, longitude and radius. | Adds a vertex in local coordinate space with the currently set color/uv/etc. | Adds a vertex in local coordinate space with the currently set color/uv/etc. | Begin drawing (and optionally pass a texture override). When done call @method end@. For more information on how this works, search for @glBegin()@ and @glEnd()@ references. For the type of primitive, see the @enum Mesh.PrimitiveType@ enum. | Begin drawing (and optionally pass a texture override). When done call @method end@. For more information on how this works, search for @glBegin()@ and @glEnd()@ references. For the type of primitive, see the @enum Mesh.PrimitiveType@ enum. | Clears everything that was drawn using begin/end. | Clears everything that was drawn using begin/end. | Ends a drawing context and displays the results. | Ends a drawing context and displays the results. | The current drawing color. | The current drawing color. | The next vertex's normal. | The next vertex's normal. | The next vertex's tangent (and binormal facing). | The next vertex's tangent (and binormal facing). | The next vertex's UV. | The next vertex's UV.
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.ImmediateGeometry (Godot.Core.ImmediateGeometry.add_sphere, Godot.Core.ImmediateGeometry.add_vertex, Godot.Core.ImmediateGeometry.begin, Godot.Core.ImmediateGeometry.clear, Godot.Core.ImmediateGeometry.end, Godot.Core.ImmediateGeometry.set_color, Godot.Core.ImmediateGeometry.set_normal, Godot.Core.ImmediateGeometry.set_tangent, Godot.Core.ImmediateGeometry.set_uv, Godot.Core.ImmediateGeometry.set_uv2) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.GeometryInstance() # NOINLINE bindImmediateGeometry_add_sphere # bindImmediateGeometry_add_sphere :: MethodBind bindImmediateGeometry_add_sphere = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "add_sphere" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr add_sphere :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Int -> Int -> Float -> Maybe Bool -> IO () add_sphere cls arg1 arg2 arg3 arg4 = withVariantArray [toVariant arg1, toVariant arg2, toVariant arg3, maybe (VariantBool True) toVariant arg4] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_add_sphere (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "add_sphere" '[Int, Int, Float, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.add_sphere # NOINLINE bindImmediateGeometry_add_vertex # bindImmediateGeometry_add_vertex :: MethodBind bindImmediateGeometry_add_vertex = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "add_vertex" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr add_vertex :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector3 -> IO () add_vertex cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_add_vertex (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "add_vertex" '[Vector3] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.add_vertex # NOINLINE bindImmediateGeometry_begin # bindImmediateGeometry_begin :: MethodBind bindImmediateGeometry_begin = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "begin" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr begin :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Int -> Maybe Texture -> IO () begin cls arg1 arg2 = withVariantArray [toVariant arg1, maybe VariantNil toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_begin (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "begin" '[Int, Maybe Texture] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.begin # NOINLINE bindImmediateGeometry_clear # bindImmediateGeometry_clear :: MethodBind bindImmediateGeometry_clear = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr clear :: (ImmediateGeometry :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "clear" '[] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.clear # NOINLINE bindImmediateGeometry_end # bindImmediateGeometry_end :: MethodBind bindImmediateGeometry_end = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "end" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr end :: (ImmediateGeometry :< cls, Object :< cls) => cls -> IO () end cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_end (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "end" '[] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.end # NOINLINE bindImmediateGeometry_set_color # bindImmediateGeometry_set_color :: MethodBind bindImmediateGeometry_set_color = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_color" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_color :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Color -> IO () set_color cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_color (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_color" '[Color] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_color # NOINLINE bindImmediateGeometry_set_normal # bindImmediateGeometry_set_normal :: MethodBind bindImmediateGeometry_set_normal = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_normal" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_normal :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector3 -> IO () set_normal cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_normal (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_normal" '[Vector3] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_normal # NOINLINE bindImmediateGeometry_set_tangent # bindImmediateGeometry_set_tangent :: MethodBind bindImmediateGeometry_set_tangent = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_tangent" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_tangent :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Plane -> IO () set_tangent cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_tangent (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_tangent" '[Plane] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_tangent # NOINLINE bindImmediateGeometry_set_uv # bindImmediateGeometry_set_uv :: MethodBind bindImmediateGeometry_set_uv = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_uv" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_uv :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector2 -> IO () set_uv cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_uv (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_uv" '[Vector2] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_uv # NOINLINE bindImmediateGeometry_set_uv2 # | The next vertex 's second layer UV . bindImmediateGeometry_set_uv2 :: MethodBind bindImmediateGeometry_set_uv2 = unsafePerformIO $ withCString "ImmediateGeometry" $ \ clsNamePtr -> withCString "set_uv2" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | The next vertex 's second layer UV . set_uv2 :: (ImmediateGeometry :< cls, Object :< cls) => cls -> Vector2 -> IO () set_uv2 cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindImmediateGeometry_set_uv2 (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod ImmediateGeometry "set_uv2" '[Vector2] (IO ()) where nodeMethod = Godot.Core.ImmediateGeometry.set_uv2
4c438279d52853f0aacfc9f181909fd46201d4b1a753ccaa299c2de6e628b97d
multimodalrouting/osm-fulcro
geofeatures.cljc
(ns app.model.geofeatures (:require [com.fulcrologic.fulcro.components :refer [defsc get-query]])) (defsc GeoFeature [this {::keys [id] :as props}] {:ident (fn [] [::id id]) :query [::id ::source ::geojson]}) (defsc GeoFeaturesAll [this props] {:ident ::all :query [{::all (get-query GeoFeature)}]})
null
https://raw.githubusercontent.com/multimodalrouting/osm-fulcro/dedbf40686a18238349603021687694e5a4c31b6/src/main/app/model/geofeatures.cljc
clojure
(ns app.model.geofeatures (:require [com.fulcrologic.fulcro.components :refer [defsc get-query]])) (defsc GeoFeature [this {::keys [id] :as props}] {:ident (fn [] [::id id]) :query [::id ::source ::geojson]}) (defsc GeoFeaturesAll [this props] {:ident ::all :query [{::all (get-query GeoFeature)}]})
e4eebcc8e5529c6c210e7c6183e247835a507424e465461e187b85f9b24a013a
jship/opentelemetry-haskell
Errors.hs
# LANGUAGE DuplicateRecordFields # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DerivingStrategies # {-# LANGUAGE StrictData #-} module OTel.API.Trace.Core.TraceState.Errors ( TraceStateErrors(..) , TraceStateError(..) , TraceStateSimpleKeyIsEmptyError(..) , TraceStateSimpleKeyContainsInvalidCharsError(..) , TraceStateTenantIdIsEmptyError(..) , TraceStateTenantIdContainsInvalidCharsError(..) , TraceStateSystemIdIsEmptyError(..) , TraceStateSystemIdContainsInvalidCharsError(..) , TraceStateSimpleKeyTooLongError(..) , TraceStateTenantIdTooLongError(..) , TraceStateSystemIdTooLongError(..) , TraceStateKeyTypeUnknownError(..) , TraceStateValueIsEmptyError(..) , TraceStateValueContainsInvalidCharsError(..) , TraceStateValueTooLongError(..) ) where import Control.Monad.Catch (Exception) import Data.Text (Text) import OTel.API.Common (Key) import Prelude newtype TraceStateErrors = TraceStateErrors { unTraceStateErrors :: [TraceStateError] } deriving stock (Eq, Show) deriving anyclass (Exception) data TraceStateError = TraceStateSimpleKeyIsEmpty TraceStateSimpleKeyIsEmptyError | TraceStateSimpleKeyContainsInvalidChars TraceStateSimpleKeyContainsInvalidCharsError | TraceStateTenantIdIsEmpty TraceStateTenantIdIsEmptyError | TraceStateTenantIdContainsInvalidChars TraceStateTenantIdContainsInvalidCharsError | TraceStateSystemIdIsEmpty TraceStateSystemIdIsEmptyError | TraceStateSystemIdContainsInvalidChars TraceStateSystemIdContainsInvalidCharsError | TraceStateSimpleKeyTooLong TraceStateSimpleKeyTooLongError | TraceStateTenantIdTooLong TraceStateTenantIdTooLongError | TraceStateSystemIdTooLong TraceStateSystemIdTooLongError | TraceStateKeyTypeUnknown TraceStateKeyTypeUnknownError | TraceStateValueIsEmpty TraceStateValueIsEmptyError | TraceStateValueContainsInvalidChars TraceStateValueContainsInvalidCharsError | TraceStateValueTooLong TraceStateValueTooLongError deriving stock (Eq, Show) newtype TraceStateSimpleKeyIsEmptyError = TraceStateSimpleKeyIsEmptyError { rawValue :: Text } deriving stock (Eq, Show) data TraceStateSimpleKeyContainsInvalidCharsError = TraceStateSimpleKeyContainsInvalidCharsError { rawKey :: Key Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateTenantIdIsEmptyError = TraceStateTenantIdIsEmptyError { rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateTenantIdContainsInvalidCharsError = TraceStateTenantIdContainsInvalidCharsError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateSystemIdIsEmptyError = TraceStateSystemIdIsEmptyError { rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateSystemIdContainsInvalidCharsError = TraceStateSystemIdContainsInvalidCharsError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateSimpleKeyTooLongError = TraceStateSimpleKeyTooLongError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateTenantIdTooLongError = TraceStateTenantIdTooLongError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateSystemIdTooLongError = TraceStateSystemIdTooLongError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateKeyTypeUnknownError = TraceStateKeyTypeUnknownError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show) newtype TraceStateValueIsEmptyError = TraceStateValueIsEmptyError { rawKey :: Key Text } deriving stock (Eq, Show) data TraceStateValueContainsInvalidCharsError = TraceStateValueContainsInvalidCharsError { rawKey :: Key Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateValueTooLongError = TraceStateValueTooLongError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show)
null
https://raw.githubusercontent.com/jship/opentelemetry-haskell/468b7df49226bb6a478180300dab8d1a214c213f/otel-api-trace-core/library/OTel/API/Trace/Core/TraceState/Errors.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE StrictData #
# LANGUAGE DuplicateRecordFields # # LANGUAGE DerivingStrategies # module OTel.API.Trace.Core.TraceState.Errors ( TraceStateErrors(..) , TraceStateError(..) , TraceStateSimpleKeyIsEmptyError(..) , TraceStateSimpleKeyContainsInvalidCharsError(..) , TraceStateTenantIdIsEmptyError(..) , TraceStateTenantIdContainsInvalidCharsError(..) , TraceStateSystemIdIsEmptyError(..) , TraceStateSystemIdContainsInvalidCharsError(..) , TraceStateSimpleKeyTooLongError(..) , TraceStateTenantIdTooLongError(..) , TraceStateSystemIdTooLongError(..) , TraceStateKeyTypeUnknownError(..) , TraceStateValueIsEmptyError(..) , TraceStateValueContainsInvalidCharsError(..) , TraceStateValueTooLongError(..) ) where import Control.Monad.Catch (Exception) import Data.Text (Text) import OTel.API.Common (Key) import Prelude newtype TraceStateErrors = TraceStateErrors { unTraceStateErrors :: [TraceStateError] } deriving stock (Eq, Show) deriving anyclass (Exception) data TraceStateError = TraceStateSimpleKeyIsEmpty TraceStateSimpleKeyIsEmptyError | TraceStateSimpleKeyContainsInvalidChars TraceStateSimpleKeyContainsInvalidCharsError | TraceStateTenantIdIsEmpty TraceStateTenantIdIsEmptyError | TraceStateTenantIdContainsInvalidChars TraceStateTenantIdContainsInvalidCharsError | TraceStateSystemIdIsEmpty TraceStateSystemIdIsEmptyError | TraceStateSystemIdContainsInvalidChars TraceStateSystemIdContainsInvalidCharsError | TraceStateSimpleKeyTooLong TraceStateSimpleKeyTooLongError | TraceStateTenantIdTooLong TraceStateTenantIdTooLongError | TraceStateSystemIdTooLong TraceStateSystemIdTooLongError | TraceStateKeyTypeUnknown TraceStateKeyTypeUnknownError | TraceStateValueIsEmpty TraceStateValueIsEmptyError | TraceStateValueContainsInvalidChars TraceStateValueContainsInvalidCharsError | TraceStateValueTooLong TraceStateValueTooLongError deriving stock (Eq, Show) newtype TraceStateSimpleKeyIsEmptyError = TraceStateSimpleKeyIsEmptyError { rawValue :: Text } deriving stock (Eq, Show) data TraceStateSimpleKeyContainsInvalidCharsError = TraceStateSimpleKeyContainsInvalidCharsError { rawKey :: Key Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateTenantIdIsEmptyError = TraceStateTenantIdIsEmptyError { rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateTenantIdContainsInvalidCharsError = TraceStateTenantIdContainsInvalidCharsError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateSystemIdIsEmptyError = TraceStateSystemIdIsEmptyError { rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateSystemIdContainsInvalidCharsError = TraceStateSystemIdContainsInvalidCharsError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateSimpleKeyTooLongError = TraceStateSimpleKeyTooLongError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateTenantIdTooLongError = TraceStateTenantIdTooLongError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateSystemIdTooLongError = TraceStateSystemIdTooLongError { rawTenantId :: Text , rawSystemId :: Text , rawValue :: Text } deriving stock (Eq, Show) data TraceStateKeyTypeUnknownError = TraceStateKeyTypeUnknownError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show) newtype TraceStateValueIsEmptyError = TraceStateValueIsEmptyError { rawKey :: Key Text } deriving stock (Eq, Show) data TraceStateValueContainsInvalidCharsError = TraceStateValueContainsInvalidCharsError { rawKey :: Key Text , rawValue :: Text , invalidChars :: Text } deriving stock (Eq, Show) data TraceStateValueTooLongError = TraceStateValueTooLongError { rawKey :: Key Text , rawValue :: Text } deriving stock (Eq, Show)
fa3dff4aa3c09be05517605617b065688396508eb6c2496ce2ce4163d08a86bb
digitallyinduced/ihp-forum
Show.hs
module Web.View.Threads.Show where import Web.View.Prelude import Application.Helper.View (badgeMap) data ShowView = ShowView { thread :: Include "userId" Thread , comments :: [Include "userId" Comment] , badges :: [Include "userId" UserBadge] } instance View ShowView where beforeRender ShowView { .. } = do setTitle (thread.title <> " - IHP Forum") html ShowView { .. } = [hsx| <div class="row thread mb-5"> <div class="col-3 user-col"> <a class="user-col" href={ShowUserAction author.id}> {renderPicture author} {author.name} </a> <tr> {forEach badges (renderBadges author)} </tr> {when (Just thread.userId.id == fmap (.id) currentUserOrNothing) threadOptions} </div> <div class="col-9 thread-content"> <div class="text-muted thread-created-at"> {timeAgo thread.createdAt} </div> <h1 class="thread-title">{thread.title}</h1> <div class="thread-body">{renderMarkdown thread.body}</div> </div> </div> {forEach comments renderComment} <div class="row new-comment"> <div class="col-3"> </div> <div class="col-9 mb-5 text-center"> <a class="btn btn-primary" href={NewCommentAction thread.id}>Add Comment</a> </div> </div> |] where threadOptions = [hsx| <p class="mt-3"> <a href={EditThreadAction thread.id} class="text-muted d-block">Edit thread</a> <a href={DeleteThreadAction thread.id} class="text-muted js-delete d-block">Delete this thread</a> </p> |] author = thread.userId renderBadges author userbadge | (author == userbadge.userId) = [hsx| <span class={snd badgeTuple}> {fst badgeTuple} </span> |] where badgeTuple = fromMaybe ("", "") (lookup userbadge.badge badgeMap) renderBadges _ _ = [hsx||] renderComment comment = [hsx| <div class="row comment"> <div class="col-3 user-col"> {renderPicture comment.userId} {comment.userId.name} <tr> {forEach badges (renderBadges comment.userId)} </tr> </div> <div class="col-9"> <div class="comment-meta"> {timeAgo comment.createdAt} {when currentUserIsAuthor commentActions} </div> <div class="comment-body">{renderMarkdown comment.body}</div> </div> </div> |] where currentUserIsAuthor = Just comment.userId.id == (fmap (.id) currentUserOrNothing) commentActions = [hsx| <a href={EditCommentAction comment.id}>Edit Comment</a> <a href={DeleteCommentAction comment.id} class="js-delete">Delete Comment</a> |]
null
https://raw.githubusercontent.com/digitallyinduced/ihp-forum/d71975ffd0439d27a69acb184431fb1b48796b15/Web/View/Threads/Show.hs
haskell
module Web.View.Threads.Show where import Web.View.Prelude import Application.Helper.View (badgeMap) data ShowView = ShowView { thread :: Include "userId" Thread , comments :: [Include "userId" Comment] , badges :: [Include "userId" UserBadge] } instance View ShowView where beforeRender ShowView { .. } = do setTitle (thread.title <> " - IHP Forum") html ShowView { .. } = [hsx| <div class="row thread mb-5"> <div class="col-3 user-col"> <a class="user-col" href={ShowUserAction author.id}> {renderPicture author} {author.name} </a> <tr> {forEach badges (renderBadges author)} </tr> {when (Just thread.userId.id == fmap (.id) currentUserOrNothing) threadOptions} </div> <div class="col-9 thread-content"> <div class="text-muted thread-created-at"> {timeAgo thread.createdAt} </div> <h1 class="thread-title">{thread.title}</h1> <div class="thread-body">{renderMarkdown thread.body}</div> </div> </div> {forEach comments renderComment} <div class="row new-comment"> <div class="col-3"> </div> <div class="col-9 mb-5 text-center"> <a class="btn btn-primary" href={NewCommentAction thread.id}>Add Comment</a> </div> </div> |] where threadOptions = [hsx| <p class="mt-3"> <a href={EditThreadAction thread.id} class="text-muted d-block">Edit thread</a> <a href={DeleteThreadAction thread.id} class="text-muted js-delete d-block">Delete this thread</a> </p> |] author = thread.userId renderBadges author userbadge | (author == userbadge.userId) = [hsx| <span class={snd badgeTuple}> {fst badgeTuple} </span> |] where badgeTuple = fromMaybe ("", "") (lookup userbadge.badge badgeMap) renderBadges _ _ = [hsx||] renderComment comment = [hsx| <div class="row comment"> <div class="col-3 user-col"> {renderPicture comment.userId} {comment.userId.name} <tr> {forEach badges (renderBadges comment.userId)} </tr> </div> <div class="col-9"> <div class="comment-meta"> {timeAgo comment.createdAt} {when currentUserIsAuthor commentActions} </div> <div class="comment-body">{renderMarkdown comment.body}</div> </div> </div> |] where currentUserIsAuthor = Just comment.userId.id == (fmap (.id) currentUserOrNothing) commentActions = [hsx| <a href={EditCommentAction comment.id}>Edit Comment</a> <a href={DeleteCommentAction comment.id} class="js-delete">Delete Comment</a> |]
dd569502c544dc6f58bbc330ead45cd26ea3e8c13f8254e635e1808a5a827f27
input-output-hk/plutus-apps
Escrow5.hs
{-# LANGUAGE DataKinds #-} # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE StandaloneDeriving # {-# LANGUAGE TemplateHaskell #-} # LANGUAGE TupleSections # # LANGUAGE TypeApplications # {-# LANGUAGE TypeFamilies #-} # OPTIONS_GHC -fno - warn - name - shadowing # -- This module contains a contract model for positive testing of the simplified escrow contract in . Contracts . Tutorial . Escrow , with generated escrow targets . See the " Parameterising Models and -- Dynamic Contract Instances" section of the tutorial. module Spec.Tutorial.Escrow5(prop_Escrow, prop_FinishEscrow, prop_FinishFast, prop_NoLockedFunds, prop_NoLockedFundsFast, check_propEscrowWithCoverage, EscrowModel) where import Control.Lens hiding (both, elements) import Control.Monad (void, when) import Data.Default import Data.Foldable import Data.Map (Map) import Data.Map qualified as Map import Cardano.Node.Emulator.TimeSlot (SlotConfig (..)) import Ledger (Slot (..), minAdaTxOutEstimated) import Plutus.Contract (Contract, selectList) import Plutus.Contract.Test import Plutus.Contract.Test.ContractModel import Plutus.Script.Utils.Ada qualified as Ada import Plutus.Script.Utils.Value (Value, geq) import Plutus.V2.Ledger.Api (Datum, POSIXTime (POSIXTime)) import Plutus.Contracts.Escrow hiding (Action (..)) import Plutus.Trace.Emulator qualified as Trace import PlutusTx.Monoid (inv) import Test.QuickCheck data EscrowModel = EscrowModel { _contributions :: Map Wallet Value , _targets :: Map Wallet Value , _refundSlot :: Slot , _phase :: Phase } deriving (Eq, Show, Generic) data Phase = Initial | Running | Refunding deriving (Eq, Show, Generic) makeLenses ''EscrowModel deriving instance Eq (ContractInstanceKey EscrowModel w s e params) deriving instance Show (ContractInstanceKey EscrowModel w s e params) instance ContractModel EscrowModel where data Action EscrowModel = Init Slot [(Wallet, Integer)] | Redeem Wallet | Pay Wallet Integer | Refund Wallet deriving (Eq, Show, Generic) data ContractInstanceKey EscrowModel w s e params where WalletKey :: Wallet -> ContractInstanceKey EscrowModel () EscrowSchema EscrowError (EscrowParams Datum) initialState = EscrowModel { _contributions = Map.empty , _targets = Map.empty , _refundSlot = 0 , _phase = Initial } initialInstances = [] startInstances _ (Init s wns) = [StartContract (WalletKey w) (escrowParams s wns) | w <- testWallets] startInstances _ _ = [] instanceWallet (WalletKey w) = w instanceContract _ WalletKey{} params = testContract params nextState a = case a of Init s wns -> do phase .= Running targets .= Map.fromList [(w, Ada.adaValueOf (fromInteger n)) | (w,n) <- wns] refundSlot .= s Pay w v -> do withdraw w (Ada.adaValueOf $ fromInteger v) contributions %= Map.insertWith (<>) w (Ada.adaValueOf $ fromInteger v) wait 1 Redeem w -> do targets <- viewContractState targets contribs <- viewContractState contributions sequence_ [ deposit w v | (w, v) <- Map.toList targets ] let leftoverValue = fold contribs <> inv (fold targets) deposit w leftoverValue contributions .= Map.empty wait 1 Refund w -> do v <- viewContractState $ contributions . at w . to fold contributions %= Map.delete w deposit w v wait 1 nextReactiveState slot = do deadline <- viewContractState refundSlot when (slot >= deadline) $ phase .= Refunding precondition s a = case a of Init s tgts -> currentPhase == Initial && s > 1 && and [Ada.adaValueOf (fromInteger n) `geq` Ada.toValue minAdaTxOutEstimated | (_,n) <- tgts] Redeem _ -> currentPhase == Running && fold (s ^. contractState . contributions) `geq` fold (s ^. contractState . targets) Pay _ v -> currentPhase == Running && Ada.adaValueOf (fromInteger v) `geq` Ada.toValue minAdaTxOutEstimated Refund w -> currentPhase == Refunding && w `Map.member` (s ^. contractState . contributions) where currentPhase = s ^. contractState . phase perform h _ _ a = case a of Init _ _ -> do return () Pay w v -> do Trace.callEndpoint @"pay-escrow" (h $ WalletKey w) (Ada.adaValueOf $ fromInteger v) delay 1 Redeem w -> do Trace.callEndpoint @"redeem-escrow" (h $ WalletKey w) () delay 1 Refund w -> do Trace.callEndpoint @"refund-escrow" (h $ WalletKey w) () delay 1 arbitraryAction s | s ^.contractState . phase == Initial = Init <$> (Slot . getPositive <$> scale (*10) arbitrary) <*> arbitraryTargets | otherwise = frequency $ [ (3, Pay <$> elements testWallets <*> choose (1, 30)) ] ++ [ (1, Redeem <$> elements testWallets) | (s ^. contractState . contributions . to fold) `geq` (s ^. contractState . targets . to fold) ] ++ [ (1, Refund <$> elements testWallets) ] shrinkAction _ (Init s tgts) = map (Init s) (shrinkList (\(w,n)->(w,)<$>shrink n) tgts) ++ map (`Init` tgts) (map Slot . shrink . getSlot $ s) shrinkAction _ (Pay w n) = [Pay w n' | n' <- shrink n] shrinkAction _ _ = [] arbitraryTargets :: Gen [(Wallet,Integer)] arbitraryTargets = do ws <- sublistOf testWallets vs <- infiniteListOf $ choose (1,30) return $ zip ws vs testWallets :: [Wallet] testWallets = [w1, w2, w3, w4, w5] testContract :: EscrowParams Datum -> Contract () EscrowSchema EscrowError () testContract params = selectList [ void $ payEp params , void $ redeemEp params , void $ refundEp params ] >> testContract params prop_Escrow :: Actions EscrowModel -> Property prop_Escrow = propRunActions_ escrowParams :: Slot -> [(Wallet, Integer)] -> EscrowParams d escrowParams s tgts = EscrowParams { escrowTargets = [ payToPaymentPubKeyTarget (mockWalletPaymentPubKeyHash w) (Ada.adaValueOf (fromInteger n)) | (w,n) <- tgts ] , escrowDeadline = scSlotZeroTime def + POSIXTime (getSlot s * scSlotLength def) } finishEscrow :: DL EscrowModel () finishEscrow = do anyActions_ finishingStrategy assertModel "Locked funds are not zero" (symIsZero . lockedValue) finishingStrategy :: DL EscrowModel () finishingStrategy = do contribs <- viewContractState contributions monitor (tabulate "Refunded wallets" [show . Map.size $ contribs]) phase <- viewContractState phase monitor $ tabulate "Phase" [show phase] waitUntilDeadline sequence_ [action $ Refund w | w <- testWallets, w `Map.member` contribs] walletStrategy :: Wallet -> DL EscrowModel () walletStrategy w = do contribs <- viewContractState contributions --waitUntilDeadline when (w `Map.member` contribs) $ do action $ Refund w waitUntilDeadline :: DL EscrowModel () waitUntilDeadline = do deadline <- viewContractState refundSlot slot <- viewModelState currentSlot when (slot < deadline) $ waitUntilDL deadline noLockProof :: NoLockedFundsProof EscrowModel noLockProof = defaultNLFP { nlfpMainStrategy = finishingStrategy , nlfpWalletStrategy = walletStrategy } prop_FinishEscrow :: Property prop_FinishEscrow = forAllDL finishEscrow prop_Escrow prop_FinishFast :: Property prop_FinishFast = forAllDL finishEscrow $ const True prop_NoLockedFunds :: Property prop_NoLockedFunds = checkNoLockedFundsProof noLockProof prop_NoLockedFundsFast :: Property prop_NoLockedFundsFast = checkNoLockedFundsProofFast noLockProof check_propEscrowWithCoverage :: IO () check_propEscrowWithCoverage = do cr <- quickCheckWithCoverage stdArgs (set coverageIndex covIdx $ defaultCoverageOptions) $ \covopts -> withMaxSuccess 1000 $ propRunActionsWithOptions @EscrowModel defaultCheckOptionsContractModel covopts (const (pure True)) writeCoverageReport "Escrow" cr
null
https://raw.githubusercontent.com/input-output-hk/plutus-apps/362e824c83b77df23805f1e718ea0893f5fcae56/plutus-use-cases/test/Spec/Tutorial/Escrow5.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE GADTs # # LANGUAGE TemplateHaskell # # LANGUAGE TypeFamilies # This module contains a contract model for positive testing of the Dynamic Contract Instances" section of the tutorial. waitUntilDeadline
# LANGUAGE DeriveGeneric # # LANGUAGE FlexibleInstances # # LANGUAGE StandaloneDeriving # # LANGUAGE TupleSections # # LANGUAGE TypeApplications # # OPTIONS_GHC -fno - warn - name - shadowing # simplified escrow contract in . Contracts . Tutorial . Escrow , with generated escrow targets . See the " Parameterising Models and module Spec.Tutorial.Escrow5(prop_Escrow, prop_FinishEscrow, prop_FinishFast, prop_NoLockedFunds, prop_NoLockedFundsFast, check_propEscrowWithCoverage, EscrowModel) where import Control.Lens hiding (both, elements) import Control.Monad (void, when) import Data.Default import Data.Foldable import Data.Map (Map) import Data.Map qualified as Map import Cardano.Node.Emulator.TimeSlot (SlotConfig (..)) import Ledger (Slot (..), minAdaTxOutEstimated) import Plutus.Contract (Contract, selectList) import Plutus.Contract.Test import Plutus.Contract.Test.ContractModel import Plutus.Script.Utils.Ada qualified as Ada import Plutus.Script.Utils.Value (Value, geq) import Plutus.V2.Ledger.Api (Datum, POSIXTime (POSIXTime)) import Plutus.Contracts.Escrow hiding (Action (..)) import Plutus.Trace.Emulator qualified as Trace import PlutusTx.Monoid (inv) import Test.QuickCheck data EscrowModel = EscrowModel { _contributions :: Map Wallet Value , _targets :: Map Wallet Value , _refundSlot :: Slot , _phase :: Phase } deriving (Eq, Show, Generic) data Phase = Initial | Running | Refunding deriving (Eq, Show, Generic) makeLenses ''EscrowModel deriving instance Eq (ContractInstanceKey EscrowModel w s e params) deriving instance Show (ContractInstanceKey EscrowModel w s e params) instance ContractModel EscrowModel where data Action EscrowModel = Init Slot [(Wallet, Integer)] | Redeem Wallet | Pay Wallet Integer | Refund Wallet deriving (Eq, Show, Generic) data ContractInstanceKey EscrowModel w s e params where WalletKey :: Wallet -> ContractInstanceKey EscrowModel () EscrowSchema EscrowError (EscrowParams Datum) initialState = EscrowModel { _contributions = Map.empty , _targets = Map.empty , _refundSlot = 0 , _phase = Initial } initialInstances = [] startInstances _ (Init s wns) = [StartContract (WalletKey w) (escrowParams s wns) | w <- testWallets] startInstances _ _ = [] instanceWallet (WalletKey w) = w instanceContract _ WalletKey{} params = testContract params nextState a = case a of Init s wns -> do phase .= Running targets .= Map.fromList [(w, Ada.adaValueOf (fromInteger n)) | (w,n) <- wns] refundSlot .= s Pay w v -> do withdraw w (Ada.adaValueOf $ fromInteger v) contributions %= Map.insertWith (<>) w (Ada.adaValueOf $ fromInteger v) wait 1 Redeem w -> do targets <- viewContractState targets contribs <- viewContractState contributions sequence_ [ deposit w v | (w, v) <- Map.toList targets ] let leftoverValue = fold contribs <> inv (fold targets) deposit w leftoverValue contributions .= Map.empty wait 1 Refund w -> do v <- viewContractState $ contributions . at w . to fold contributions %= Map.delete w deposit w v wait 1 nextReactiveState slot = do deadline <- viewContractState refundSlot when (slot >= deadline) $ phase .= Refunding precondition s a = case a of Init s tgts -> currentPhase == Initial && s > 1 && and [Ada.adaValueOf (fromInteger n) `geq` Ada.toValue minAdaTxOutEstimated | (_,n) <- tgts] Redeem _ -> currentPhase == Running && fold (s ^. contractState . contributions) `geq` fold (s ^. contractState . targets) Pay _ v -> currentPhase == Running && Ada.adaValueOf (fromInteger v) `geq` Ada.toValue minAdaTxOutEstimated Refund w -> currentPhase == Refunding && w `Map.member` (s ^. contractState . contributions) where currentPhase = s ^. contractState . phase perform h _ _ a = case a of Init _ _ -> do return () Pay w v -> do Trace.callEndpoint @"pay-escrow" (h $ WalletKey w) (Ada.adaValueOf $ fromInteger v) delay 1 Redeem w -> do Trace.callEndpoint @"redeem-escrow" (h $ WalletKey w) () delay 1 Refund w -> do Trace.callEndpoint @"refund-escrow" (h $ WalletKey w) () delay 1 arbitraryAction s | s ^.contractState . phase == Initial = Init <$> (Slot . getPositive <$> scale (*10) arbitrary) <*> arbitraryTargets | otherwise = frequency $ [ (3, Pay <$> elements testWallets <*> choose (1, 30)) ] ++ [ (1, Redeem <$> elements testWallets) | (s ^. contractState . contributions . to fold) `geq` (s ^. contractState . targets . to fold) ] ++ [ (1, Refund <$> elements testWallets) ] shrinkAction _ (Init s tgts) = map (Init s) (shrinkList (\(w,n)->(w,)<$>shrink n) tgts) ++ map (`Init` tgts) (map Slot . shrink . getSlot $ s) shrinkAction _ (Pay w n) = [Pay w n' | n' <- shrink n] shrinkAction _ _ = [] arbitraryTargets :: Gen [(Wallet,Integer)] arbitraryTargets = do ws <- sublistOf testWallets vs <- infiniteListOf $ choose (1,30) return $ zip ws vs testWallets :: [Wallet] testWallets = [w1, w2, w3, w4, w5] testContract :: EscrowParams Datum -> Contract () EscrowSchema EscrowError () testContract params = selectList [ void $ payEp params , void $ redeemEp params , void $ refundEp params ] >> testContract params prop_Escrow :: Actions EscrowModel -> Property prop_Escrow = propRunActions_ escrowParams :: Slot -> [(Wallet, Integer)] -> EscrowParams d escrowParams s tgts = EscrowParams { escrowTargets = [ payToPaymentPubKeyTarget (mockWalletPaymentPubKeyHash w) (Ada.adaValueOf (fromInteger n)) | (w,n) <- tgts ] , escrowDeadline = scSlotZeroTime def + POSIXTime (getSlot s * scSlotLength def) } finishEscrow :: DL EscrowModel () finishEscrow = do anyActions_ finishingStrategy assertModel "Locked funds are not zero" (symIsZero . lockedValue) finishingStrategy :: DL EscrowModel () finishingStrategy = do contribs <- viewContractState contributions monitor (tabulate "Refunded wallets" [show . Map.size $ contribs]) phase <- viewContractState phase monitor $ tabulate "Phase" [show phase] waitUntilDeadline sequence_ [action $ Refund w | w <- testWallets, w `Map.member` contribs] walletStrategy :: Wallet -> DL EscrowModel () walletStrategy w = do contribs <- viewContractState contributions when (w `Map.member` contribs) $ do action $ Refund w waitUntilDeadline :: DL EscrowModel () waitUntilDeadline = do deadline <- viewContractState refundSlot slot <- viewModelState currentSlot when (slot < deadline) $ waitUntilDL deadline noLockProof :: NoLockedFundsProof EscrowModel noLockProof = defaultNLFP { nlfpMainStrategy = finishingStrategy , nlfpWalletStrategy = walletStrategy } prop_FinishEscrow :: Property prop_FinishEscrow = forAllDL finishEscrow prop_Escrow prop_FinishFast :: Property prop_FinishFast = forAllDL finishEscrow $ const True prop_NoLockedFunds :: Property prop_NoLockedFunds = checkNoLockedFundsProof noLockProof prop_NoLockedFundsFast :: Property prop_NoLockedFundsFast = checkNoLockedFundsProofFast noLockProof check_propEscrowWithCoverage :: IO () check_propEscrowWithCoverage = do cr <- quickCheckWithCoverage stdArgs (set coverageIndex covIdx $ defaultCoverageOptions) $ \covopts -> withMaxSuccess 1000 $ propRunActionsWithOptions @EscrowModel defaultCheckOptionsContractModel covopts (const (pure True)) writeCoverageReport "Escrow" cr
37d439e0d8e7df86e6d8270f17fe3f18f829d8dbb619961572c1f8bd3553296e
schibsted/spid-tech-docs
content_shells.clj
(ns spid-docs.cultivate.content-shells) (defn http-method [& [m]] (merge {:name "!" :optional [] :required [] :responses [{:status 200 :description "!" :type "!"}] :filters [] :defaultFilters [] :accessTokenTypes []} m)) (defn endpoint [& [m]] (merge {:category ["!" "!"] :name "!" :description "!" :path "!" :pathParameters [] :method "!" :url "!" :controller "!" :defaultOutputFormat "!" :validOutputFormats [] :httpMethods {:GET (http-method)} :parameterDescriptions {}} m))
null
https://raw.githubusercontent.com/schibsted/spid-tech-docs/ee6a4394e9732572e97fc3a55506b2d6b9a9fe2b/test/spid_docs/cultivate/content_shells.clj
clojure
(ns spid-docs.cultivate.content-shells) (defn http-method [& [m]] (merge {:name "!" :optional [] :required [] :responses [{:status 200 :description "!" :type "!"}] :filters [] :defaultFilters [] :accessTokenTypes []} m)) (defn endpoint [& [m]] (merge {:category ["!" "!"] :name "!" :description "!" :path "!" :pathParameters [] :method "!" :url "!" :controller "!" :defaultOutputFormat "!" :validOutputFormats [] :httpMethods {:GET (http-method)} :parameterDescriptions {}} m))
39230653846ee178fa1d6a38ba792e01d730b1bacb5db7600736138a6b7769e1
josephwilk/musical-creativity
recombinance.clj
(ns musical-creativity.composers.recombinance (:require [clojure.math.numeric-tower :as math] [data.bach :as bach] [musical-creativity.util :refer :all] [musical-creativity.events :refer [pitch-of velocity-of timepoint-of channel-of midi-to-event]] [clojure.string :as str])) (def beats-store (atom {})) (def lexicon-store (atom {})) (def lexicons (atom ())) (def history (atom ())) (def mix-names ()) (def the-mixes ()) (def end? (atom false)) (def early-exit? (atom false)) (def compose-number 0) (def tonic (atom 'major)) (def previous-beat (atom nil)) (def beat-size 1000) (def number-of-beats 4) (def current-composer 'bach) (def start-beats-store (atom ())) (def compose-beats-store (atom ())) (def rules-store (atom ())) (defn remove-from-list [remove-items coll] (remove (set remove-items) coll)) (defn implode [list] (str/join "" list)) (defn explode [atom] (vec atom)) (defn a-thousand? [number] "Returns the number under 1000." (zero? (mod number 1000))) (defn make-lists-equal-length [list1 list2] (let [equal-pairs (map vector list1 list2)] (list (map first equal-pairs) (map second equal-pairs)))) (defn sort-by-first-element [lists] (sort (fn [[x & _] [y & _]] (< x y)) lists)) (defn all-members? [arrows target] (every? #(some #{%} target) arrows)) (defn positions "Shows the positions of number in list." [number list] (let [indexed-list (map-indexed vector list)] (for [[index element] indexed-list :when (= number element)] index))) (defn find-closest "finds the closest number in list to number." [number list] (let [test (map (fn [item] (math/abs (- number item))) list)] (nth list (choose-one (positions (first (sort <= test)) test))))) (defn all? "Tests for presence of all of first arg in second arg." [list1 list2] (empty? (clojure.set/difference (set list1) (set list2)))) (defn remove-all [stuff other-stuff] (vec (clojure.set/difference (set other-stuff) (set stuff)))) (defn hyphenate [numbers] (str/join "-" numbers)) (defn get-onset-notes "Gets the onset pitches for its arg." [events] (let [onbeat (ffirst events) onbeat-events (filter (fn [event] (= (timepoint-of event) onbeat)) events)] (map second onbeat-events))) (defn set-to-zero "Sets the events to zero." ([events] (set-to-zero events (ffirst events))) ([events subtract] (map (fn [event] (assoc (vec event) 0 (- (timepoint-of event) subtract))) events))) (defn make-name "Simple synonym for imploding the database name and number." [db-name counter] (symbol (str (name db-name) "-" counter))) (defn reduce-interval "Reduces the interval mod 12." [interval] (cond (<= (math/abs interval) 12) interval (neg? interval) (reduce-interval (+ interval 12)) :else (reduce-interval (- interval 12)))) (defn get-rule "Gets the rule between first two args." [voice start-note start-notes destination-notes name] (if (or (empty? (rest start-notes)) (empty? destination-notes)) () (cons (list (reduce-interval (- (second start-notes) start-note)) voice (- (second destination-notes) (second start-notes)) name) (get-rule voice start-note (rest start-notes) (rest destination-notes) name)))) (defn build-rules-for [start-notes destination-notes name] (loop [rules [] start-notes start-notes destination-notes destination-notes] (if (or (empty? (rest start-notes)) (empty? (rest destination-notes))) (reverse rules) (let [new-rule (reverse (get-rule (- (first destination-notes) (first start-notes)) (first start-notes) start-notes destination-notes name))] (recur (concat new-rule rules) (rest start-notes) (rest destination-notes)))))) (defn get-rules "Gets the intervals between adjacent sets of the two args." [start-notes destination-notes name] (let [test (make-lists-equal-length start-notes destination-notes) test-start-notes (first test) test-destination-notes (second test)] (build-rules-for test-start-notes test-destination-notes name))) (defn swap-unless-includes! [reference data] (when-not (some #{data} @reference) (swap! reference conj data))) (defn find-beat [name] (@beats-store name)) (defn find-in-lexicon [name] (@lexicon-store name)) (defn lexicon-contains? "Sees if the lexicon exists." [lexicon-name] (contains? @lexicon-store lexicon-name)) (defn make-lexicon-name "Creates the appropriate lexicon name for the object." ([note-numbers] (make-lexicon-name note-numbers mix-names)) ([note-numbers names] (cond (empty? the-mixes) (str current-composer "-" (hyphenate note-numbers)) (empty? names) (str current-composer "-" (hyphenate note-numbers)) (bound? (str (first names) "-" (hyphenate note-numbers))) (str (first names) "-" (hyphenate note-numbers)) :else (make-lexicon-name note-numbers (shuffle (rest names)))))) (defn add-beat-to-lexicon! [beat-name] (let [beat (find-beat beat-name) lexicon-name (make-lexicon-name (:start-notes beat))] (if (and (lexicon-contains? lexicon-name) (not (member beat-name (:beats (find-in-lexicon lexicon-name))))) (reset! lexicon-store (update-in @lexicon-store [lexicon-name :beats] conj beat-name)) (do (reset! lexicon-store (assoc @lexicon-store lexicon-name {:beats (list beat-name)})) (swap-unless-includes! lexicons lexicon-name))) lexicon-name)) (defn return-beat "Returns the beat number of the initiating event." ([channel-events] (return-beat channel-events (ffirst channel-events))) ([channel-events start-time] (some (fn [event] (when (and (a-thousand? (timepoint-of event)) (not= start-time (timepoint-of event))) (/ (- (timepoint-of event) start-time) 1000))) channel-events))) (defn create-pitch-class-set "Sorts and gets a full pc-set." [pitches] (let [pitch-classes (map #(mod % 12) pitches)] (sort < (distinct pitch-classes)))) (defn get-channel-numbers-from-events ([events] (get-channel-numbers-from-events events [])) ([events channels] (filtermap (fn [event] (when-not (member (channel-of event) channels) (channel-of event))) (reverse events)))) (defn find-alignment [point channel] (and (a-thousand? point) (some #(= point (second %)) channel))) (defn find-alignment-in-all-channels [point channels] (when (and point (every? #(find-alignment point %) channels)) point)) (defn all-together "Returns the appropriate channel timing." [channels all-channels] (let [together-timepoint (some (fn [[_ timepoint]] (find-alignment-in-all-channels timepoint all-channels)) channels)] (or together-timepoint (second (last-first all-channels))))) (defn collect-timings-by-channel [timings channel] (filter #(= (first %) channel) timings)) (defn plot-timings-of-each-beat [events] (map (fn [event] (list (channel-of event) (+ (timepoint-of event) (velocity-of event)))) events)) (defn first-place-where-all-together "This looks ahead to get the first time they end together" [events] (let [test (plot-timings-of-each-beat events) channels (get-channel-numbers-from-events events) ordered-timings-by-channel (map (fn [channel] (collect-timings-by-channel test channel)) channels)] (all-together (first ordered-timings-by-channel) (rest ordered-timings-by-channel)))) (defn collect-by-timing "Collects the events accoring to timing." [timing events] (filter (fn [[timepoint _ _ channel _]] (<= (+ timepoint channel) timing)) events)) (defn collect-beats [events] (if (empty? events) () (let [sync-time (first-place-where-all-together events) events-by-time (collect-by-timing sync-time events) reduced-events (drop (count events-by-time) events)] (cons events-by-time (collect-beats reduced-events))))) (defn make-beat [name beats] (let [start-notes (get-onset-notes (first beats)) destination-notes (get-onset-notes (second beats)) events (first beats) rules (cons (get-rules start-notes destination-notes name) (list name (ffirst (sort-by-first-element events))))] (swap! rules-store conj rules) {:start-notes start-notes :destination-notes destination-notes :events events :voice-leading (first rules)})) (defn start-beats [db-name] (remove nil? (collect-beats (set-to-zero (sort-by-first-element (bach/find-db db-name)))))) (defn- create-database-from-beats [db-name] (loop [beats (start-beats db-name) counter 1 start true] (when (seq beats) (let [name (make-name db-name counter) instance (make-beat name beats)] (reset! beats-store (assoc @beats-store name instance)) (add-beat-to-lexicon! name) (swap! compose-beats-store conj name) (when start (swap! start-beats-store conj name)) (recur (rest beats) (inc counter) nil))))) (defn create-database-from [db-names] (doall (map create-database-from-beats db-names))) (defn on-beat? "Returns true if the events conform to ontime." [events ontime] (every? (fn [event] (and (a-thousand? (timepoint-of event)) (= (timepoint-of event) ontime))) events)) (defn get-on-beat "Returns the on beat from the events." [events ontime] (cond (empty? events) () (and (a-thousand? (ffirst events)) (= (ffirst events) ontime)) (cons (first events) (get-on-beat (rest events) ontime)) :else ())) (defn get-pitches "Gets the pitches from its arg." [events] (map pitch-of events)) (defn get-interval "Returns the intervals between set members." [set] (if (empty? (rest set)) () (cons (- (second set) (first set)) (get-interval (rest set))))) (defn get-intervals "Returns the intervals in the sets." [sets] (map (fn [set] (math/abs (apply + (get-interval set)))) sets)) (defn project "Projects the pc-set through its inversions." ([set] (project set (count set) 0)) ([set length times] (if (= length times) () (cons set (project (concat (rest set) (list (+ 12 (first set)))) length (inc times)))))) (defn get-smallest-set "Returns the set with the smallest outer boundaries." [set] (let [projected-sets (project set) set-differentials (get-intervals projected-sets) sorted-differentials (sort < set-differentials)] (nth projected-sets (position (first sorted-differentials) set-differentials)))) (defn triad? "Checks to see if the events are a triad." [events] (when (seq events) (let [pitches (get-pitches events) pitches-class-set (create-pitch-class-set pitches) pitch-classes (get-smallest-set pitches-class-set)] (and (= (count pitch-classes) 3) (and (> (- (second pitch-classes) (first pitch-classes)) 2) (< (- (second pitch-classes) (first pitch-classes)) 5)) (and (> (- (third pitch-classes) (second pitch-classes)) 2) (< (- (third pitch-classes) (second pitch-classes)) 5)))))) (defn find-triad-beginning "Returns the db with a triad beginning." [] (let [test (choose-one @compose-beats-store) beat (find-beat test) on-beat (get-on-beat (:events beat) (ffirst (:events beat))) pitch-class-set (create-pitch-class-set (get-pitches on-beat))] (if (and (triad? on-beat) (or (all-members? '(0 4 8) pitch-class-set) (all-members? '(0 4 7) pitch-class-set) (all-members? '(0 5 8) pitch-class-set) (all-members? '(2 7 11) pitch-class-set)) (<= (velocity-of (first (:events beat))) 1000) (= (count (:events beat)) number-of-beats)) test (recur)))) (defn remainder "Returns the remainder of the beat." ([event] (remainder event (timepoint-of event) (velocity-of event))) ([event begin-time duration] (cond (empty? event) () (= duration 1000) () (< duration 1000) (list (concat (list begin-time) (list (pitch-of event)) (list duration) (drop 3 event))) :else (remainder event (+ begin-time 1000) (- duration 1000))))) (defn get-full-beat "Returns one full beat of the music." ([events] (get-full-beat events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (= (+ duration (velocity-of (first events))) 1000) (list (first events)) (> (+ duration (velocity-of (first events))) 1000) (list (concat (take 2 (first events)) (list (- 1000 duration)) (drop 3 (first events)))) :else (let [event (first events)] (cons event (get-full-beat (rest events) (+ begin-time (velocity-of event)) (+ (velocity-of event) duration))))))) (defn remainders "Returns remainders of beats." ([events] (remainders events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (= (+ duration (velocity-of (first events))) 1000) () (> (+ duration (velocity-of (first events))) 1000) (list (concat (list (+ begin-time (- 1000 duration))) (list (pitch-of (first events))) (list (- (velocity-of (first events)) (- 1000 duration))) (drop 3 (first events)))) :else (remainders (rest events) (+ begin-time (velocity-of (first events))) (+ (velocity-of (first events)) duration))))) (defn remove-full-beat "Removes one full beat from the events arg." ([events] (remove-full-beat events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (>= (+ duration (velocity-of (first events))) 1000) (rest events) :else (remove-full-beat (rest events) (+ begin-time (velocity-of (first events))) (+ (velocity-of (first events)) duration))))) (defn get-other-channels "Returns all but the first arg channeled events." [channel-not-to-get events] (cond (empty? events) () (= (channel-of (first events)) channel-not-to-get) (get-other-channels channel-not-to-get (rest events)) :else (cons (first events) (get-other-channels channel-not-to-get (rest events))))) (defn chop "Chops beats over 1000 into beat-sized pieces." ([event] (chop event (timepoint-of event) (velocity-of event))) ([event begin-time duration] (if (< duration 1000) () (cons (concat (list begin-time) (list (pitch-of event)) '(1000) (drop 3 event)) (chop event (+ begin-time 1000) (- duration 1000)))))) (defn events-with-channel "Gets the nth channel of the music." [channel events] (filter #(= (channel-of %) channel) events)) (defn chop-into-bites "Chops beats into groupings." [events] (cond (empty? events) () (and (= (velocity-of (first events)) 1000) (a-thousand? (ffirst events))) (cons (list (timepoint-of events)) (chop-into-bites (rest events))) (> (velocity-of (first events)) 1000) (cons (chop (first events)) (chop-into-bites (concat (remainder (first events)) (rest events)))) :else (let [event (first events) channel (channel-of event) events-for-channel (events-with-channel channel events)] (cons (get-full-beat events-for-channel) (chop-into-bites (concat (remainders events-for-channel) (concat (remove-full-beat events-for-channel) (get-other-channels channel events)))))))) (defn break-into-beats "Breaks events into beat-sized groupings." [events] (sort-by-first-element (apply concat (chop-into-bites (sort-by-first-element events))))) (defn get-long-phrases "Returns phrases of greater than 120000 duration." [distances] (remove nil? (map (fn [start stop] (when (> (- stop start) 12000) [start stop])) distances (rest distances)))) (defn get-region "Returns the region boardered by begin and end times." [begin-time end-time events] (filter (fn [event] (and (>= (timepoint-of event) begin-time) (< (timepoint-of event) end-time))) events)) (defn not-beyond? [channel-events] (if (not (> (apply + (map third channel-events)) 1000)) true)) (defn not-beyond-1000? "Returns true if the beat does not contain events beyond the incept time." [beat] (every? (fn [channel] (not-beyond? (events-with-channel channel beat))) (range 1 5))) (defn- cadence-place? [beat] (and (on-beat? (take number-of-beats beat) (ffirst beat)) (triad? (take number-of-beats beat)) (not-beyond-1000? beat))) (defn find-cadence-place "Returns the best place for a first cadence." [ordered-events] (let [beats (collect-beats ordered-events)] (seq (map ffirst (filter cadence-place? beats))))) (defn find-best-on-time [on-times] (find-closest (+ (/ (- (last on-times) (first on-times)) 2) (first on-times)) on-times)) (defn remove-region "Removes the region boardered by begin and end times." [begin-time end-time events] (concat (filter (fn [event] (or (< (timepoint-of event) begin-time) (>= (timepoint-of event) end-time))) events))) (defn- build-suitable-event [event] (if (>= (velocity-of event) 1000) event (concat (take 2 event) '(1000) (drop 3 event)))) (defn resolve-beat "Resolves the beat if necessary." ([beat] (resolve-beat beat (ffirst beat))) ([beat on-time] (cond (nil? (seq beat)) () (= (velocity-of (first beat)) 1000) (cons (first beat) (resolve-beat (rest beat) on-time)) :else (let [on-beat-candidate (get-on-beat (events-with-channel (channel-of (first beat)) beat) on-time) on-beat-event (first on-beat-candidate)] (cons (build-suitable-event on-beat-event) (resolve-beat (remove-all (events-with-channel (channel-of (first beat)) beat) beat) on-time)))))) (defn discover-cadence "Discovers an appropriate cadence." [missing-cadence-locations ordered-events] (let [relevant-events (get-region (first missing-cadence-locations) (second missing-cadence-locations) ordered-events) places-for-cadence (find-cadence-place relevant-events) best-location-for-new-cadence (when places-for-cadence (find-best-on-time places-for-cadence))] (if-not best-location-for-new-cadence ordered-events (sort-by-first-element (concat (resolve-beat (get-region best-location-for-new-cadence (+ best-location-for-new-cadence 1000) relevant-events)) (remove-region best-location-for-new-cadence (+ best-location-for-new-cadence 1000) ordered-events)))))) (defn all-match-velocity? [velocity ordered-events start-time] (and (let [channel-1-event (first (events-with-channel 1 ordered-events))] (and (= (velocity-of channel-1-event) velocity) (= start-time (timepoint-of channel-1-event)))) (let [channel-2-event (first (events-with-channel 2 ordered-events))] (and (= (velocity-of channel-2-event) velocity) (= start-time (timepoint-of channel-2-event)))) (let [channel-3-event (first (events-with-channel 3 ordered-events))] (and (= (velocity-of channel-3-event) velocity) (= start-time (timepoint-of channel-3-event)))) (let [channel-4-event (first (events-with-channel 4 ordered-events))] (and (= (velocity-of channel-4-event) velocity) (= start-time (timepoint-of channel-4-event)))))) (defn find-1000s "Returns the ontime if the ordered events are all duration 1000." ([ordered-events] (find-1000s ordered-events (ffirst ordered-events))) ([ordered-events start-time] (cond (empty? ordered-events) nil (all-match-velocity? 1000 ordered-events start-time) start-time :else (find-1000s (rest ordered-events))))) (defn find-2000s "Returns events of 2000 duration." ([ordered-events] (find-2000s ordered-events (ffirst ordered-events))) ([ordered-events start-time] (cond (empty? ordered-events) nil (all-match-velocity? 2000 ordered-events start-time) start-time :else (find-2000s (rest ordered-events))))) (defn discover-cadences "Makes an appropriate cadence possible." [missing-cadence-locations ordered-events] (reduce (fn [events location] (discover-cadence location events)) ordered-events missing-cadence-locations)) (defn distance-to-cadence [ordered-events] "Returns the distance tocadence of the arg." (let [quarter-note-distance (find-1000s ordered-events) half-note-distance (find-2000s ordered-events)] (cond (and (nil? quarter-note-distance) (nil? half-note-distance)) nil (nil? quarter-note-distance) half-note-distance (nil? half-note-distance) quarter-note-distance :else (if (> quarter-note-distance half-note-distance) half-note-distance quarter-note-distance)))) (defn clear-to "Clears the events up to the cadence." [distance-to-cadence ordered-events] (filter (fn [event] (> (timepoint-of event) distance-to-cadence)) ordered-events)) (defn find-cadence-start-times "Finds the cadence start times." [ordered-events] (let [distance-to-cadence (distance-to-cadence ordered-events)] (cond (empty? ordered-events) () (nil? distance-to-cadence) (find-cadence-start-times (rest ordered-events)) :else (cons distance-to-cadence (find-cadence-start-times (clear-to distance-to-cadence ordered-events)))))) (defn transpose "Transposes the events according to its first arg." [amt events] (filter (fn [event] (not (zero? (pitch-of event))) (concat (list (timepoint-of event)) (list (+ (pitch-of event) amt)) (drop 2 event))) events)) (defn get-note-timing "grunt work for get-beat-length" [event time] (- (+ (timepoint-of event) (velocity-of event)) time)) (defn get-beat-length [events] (let [time (ffirst events)] (first (sort > (map #(get-note-timing % time) events))))) (defn match-chord? "Matches the chord with the list of pitches within the allowance." [chord full-chord allowance] (cond (empty? chord) true (and (not (member (first chord) full-chord)) (zero? allowance)) nil (not (member (first chord) full-chord)) (match-chord? (rest chord) full-chord (dec allowance)) :else (match-chord? (rest chord) full-chord allowance))) (defn reduce-it "Reduces its first arg mod12 below its second arg." [note base] (if (< note base) note (reduce-it (- note 12) base))) (defn project-octaves "Projects its arg through a series of octaves." [note] (let [base-note (reduce-it note 20)] (loop [results [] current-note (reduce-it note 20)] (if (> current-note 120) results (recur (conj results (+ 12 current-note)) (+ 12 current-note)))))) (defn match-harmony? "Checks to see if its args match mod-12." [one two] (match-chord? (sort < one) (mapcat project-octaves two) (math/floor (/ (count one) 4)))) (defn all-members? "Checks to see if its first arg members are present in second arg." [list target] (clojure.set/superset? (set target) (set list))) (defn get-all-events-with-start-time-of [start-time events] (filter (fn [event] (= (timepoint-of event) start-time)) events)) (defn get-last-beat-events [events] (let [sorted-events (sort-by-first-element events) last-event (last sorted-events) begin-time (first last-event) last-beat (get-all-events-with-start-time-of begin-time events)] (if (and (= (count last-beat) number-of-beats) (a-thousand? (velocity-of (first last-beat)))) last-beat))) (defn get-db-name "Returns the database name." [lexicon] (first (str/split lexicon #"-"))) (defn inc-beat-number [beat] (when beat (let [beat (str beat) last-beat-digit (Integer/parseInt (str (last (explode beat))))] (str (get-db-name beat) "-" (inc last-beat-digit))))) (defn find-events-duration "Returns the events duration." ([events] (find-events-duration events 0)) ([events duration] (cond (empty? events) duration (= (channel-of (first events)) 1) (find-events-duration (rest events) (+ duration (velocity-of (first events)))) :else (find-events-duration (rest events) duration)))) (defn- retimed-events [events current-time] (map (fn [event] (cons (+ (timepoint-of event) current-time) (rest event))) (set-to-zero (first events)))) (defn re-time "Re-times the beats to fit together." ([event-lists] (re-time event-lists 0)) ([event-lists current-time] (if (empty? event-lists) () (cons (retimed-events event-lists current-time) (re-time (rest event-lists) (+ current-time (get-beat-length (first event-lists)))))))) (defn highest-lowest-notes "Returns the highest and lowest pitches of its arg." [events] (list (first (sort > (map pitch-of (events-with-channel 1 events)))) (first (sort < (map pitch-of (let [test (events-with-channel 4 events)] (if (empty? test) (events-with-channel 2 events) test))))))) (defn put-it-in-the-middle [extremes] "Gets the average." (math/round (/ (+ (second extremes) (first extremes)) 2))) (defn transpose-to-bach-range [events] (let [high-low (highest-lowest-notes events) intervals-off (list (- 83 (first high-low)) (- 40 (second high-low))) middle (put-it-in-the-middle intervals-off)] (transpose middle events))) (defn make-1000s "Makes all of the beat's durations into 1000s." [beat] (map (fn [event] (concat (take 2 event) '(1000) (drop 3 event))) beat)) (defn reset-beats "Resets the beats appropriately." [beats subtraction] (if (empty? beats)() (cons (map (fn [event] (concat (list (- (timepoint-of event) subtraction)) (rest event))) (first beats)) (reset-beats (rest beats) subtraction)))) (defn collapse "Collapses the final cadence." [beats] (cond (empty? beats) () (and (= (count (first beats)) number-of-beats) (= (third (ffirst beats)) 2000)) (cons (make-1000s (first beats)) (collapse (reset-beats (rest beats) 1000))) :else (cons (first beats) (collapse (rest beats))))) (defn cadence-collapse "Ensures the final chord will not have offbeats." [events] (apply concat (collapse (collect-beats (sort-by-first-element events))))) (defn reset-events-to "Resets the events for the delayed beat." [events begin-time] (map (fn [event] (cons (+ begin-time (timepoint-of event)) (rest event))) (set-to-zero events))) (defn delay-for-upbeat [events] (reset-events-to events 3000)) (defn ensure-necessary-cadences "Ensures the cadences are proper." [ordered-events] (let [cadence-start-times (find-cadence-start-times ordered-events) cadence-start-times (if-not (zero? (first cadence-start-times)) (cons 0 cadence-start-times) cadence-start-times) long-phrases (get-long-phrases cadence-start-times)] (discover-cadences long-phrases ordered-events))) (defn- sorted-by-beat [beats] (map (fn [beat] (get-pitches (get-on-beat beat (ffirst beat)))) beats)) (defn parallel? [events] (let [beats (collect-beats (take 30 (sort-by-first-element events))) sorted-pitches-by-beat (sorted-by-beat beats)] (and (= (count (first sorted-pitches-by-beat)) number-of-beats) (= (count (second sorted-pitches-by-beat)) number-of-beats) (or (and (pos? (- (ffirst sorted-pitches-by-beat) (first (second sorted-pitches-by-beat)))) (pos? (- (second (first sorted-pitches-by-beat)) (second (second sorted-pitches-by-beat)))) (pos? (- (third (first sorted-pitches-by-beat)) (third (second sorted-pitches-by-beat)))) (pos? (- (fourth (first sorted-pitches-by-beat)) (fourth (second sorted-pitches-by-beat))))) (and (neg? (- (ffirst sorted-pitches-by-beat) (first (second sorted-pitches-by-beat)))) (neg? (- (second (first sorted-pitches-by-beat)) (second (second sorted-pitches-by-beat)))) (neg? (- (third (first sorted-pitches-by-beat)) (third (second sorted-pitches-by-beat)))) (neg? (- (fourth (first sorted-pitches-by-beat)) (fourth (second sorted-pitches-by-beat))))))))) (defn wait-for-cadence? "Ensures the cadence is the proper length." ([events] (wait-for-cadence? events (ffirst events))) ([events start-time] (cond (empty? events) false (> (timepoint-of (first events)) (+ start-time 4000)) true (> (velocity-of (first events)) 1000) false :else (wait-for-cadence? (rest events) start-time)))) (defn- match-tonic? "Returns true if the events are tonic." [last-beat-events projected-octaves small large] (when (seq last-beat-events) (and (all-members? (map second last-beat-events) projected-octaves) (match-harmony? (sort < (map second last-beat-events)) small ) (match-harmony? (sort > (map second last-beat-events)) large)))) (defn match-bach-tonic? [events] (let [last-beat-events (get-last-beat-events (break-into-beats events)) projected-octaves (mapcat project-octaves '(60 64 67))] (match-tonic? last-beat-events projected-octaves '(60 64 67) '(60 64 67)))) (defn match-tonic-minor? [events] (let [last-beat-events (get-last-beat-events (break-into-beats events)) projected-octaves (mapcat project-octaves '(60 63 67))] (match-tonic? last-beat-events projected-octaves '(60 63 67) '(60 63 67)))) (defn match-major-tonic? [events] (let [pitches (get-pitches events) channel-4-events (events-with-channel 4 (sort-by-first-element events))] (and (or (all? (create-pitch-class-set pitches) '(0 4 7)) (all? (create-pitch-class-set pitches) '(0 3 7))) (zero? (first (create-pitch-class-set (get-pitches channel-4-events))))))) (defn- skip-generating-new-events? [counter current-beat] (reset! early-exit? (empty? (:destination-notes (find-beat current-beat)))) (or @early-exit? (when (and (> counter 36) (if (= tonic 'minor) (and (> (find-events-duration (:events (find-beat current-beat))) beat-size) (match-tonic-minor? (:events (find-beat current-beat)))) (and (> (find-events-duration (:events (find-beat current-beat))) beat-size) (match-bach-tonic? (:events (find-beat current-beat)))))) (reset! end? true)))) (defn build-events-for-beat [counter current-beat] (loop [events [] counter counter current-beat current-beat] (if (skip-generating-new-events? counter current-beat) events (let [beat (find-beat current-beat) new-events (:events beat) destination-notes (:destination-notes beat) lexicon-name (make-lexicon-name destination-notes) beat-in-lexicon (find-in-lexicon lexicon-name) beat-choices (:beats beat-in-lexicon) new-beat (choose-one (if (empty? (rest beat-choices)) beat-choices (remove-from-list (list @previous-beat (inc-beat-number @previous-beat)) beat-choices)))] (swap! history conj current-beat) (reset! previous-beat current-beat) (recur (concat events new-events) (inc counter) new-beat))))) (defn- build-events [counter] (let [current-beat (find-triad-beginning) current-beat-events (:events (find-beat current-beat))] (if (match-tonic-minor? (take number-of-beats current-beat-events)) (reset! tonic 'minor) (reset! tonic 'major)) (let [events (build-events-for-beat counter current-beat) events-list (list current-beat-events) all-events (if-not (empty? events) (concat (list events) events-list) events-list)] (swap! history conj current-beat) (apply concat (re-time all-events))))) (defn compose-events ([] (compose-events 0)) ([counter] (reset! end? false) (reset! history ()) (let [events (build-events counter)] (reset! history (reverse @history)) (when @end? (swap! history conj (list (inc compose-number)))) (if (or @early-exit? (not= current-composer 'bach)) () events)))) (defn valid-solution? [events] (if (empty? events) false (let [last-event (last (sort-by-first-element events)) event-sum (+ (timepoint-of last-event) (velocity-of last-event))] (and (>= event-sum 15000) (<= event-sum 200000) (wait-for-cadence? events) (not (parallel? events)))))) (defn prepare-events [events early-exit?] (let [events (ensure-necessary-cadences (sort-by-first-element events)) events (if-not (match-major-tonic? (get-on-beat events (ffirst events))) (delay-for-upbeat events) events) events (if (and (not early-exit?) (= current-composer 'bach)) (cadence-collapse (transpose-to-bach-range events)) events)] events)) (defn recombinance [] (let [events (compose-events)] (if (and (valid-solution? events) @end?) (prepare-events events @early-exit?) (recombinance)))) (defn compose [] (let [events (recombinance) sorted-events (sort (fn [e1 e2] (< (timepoint-of e1) (timepoint-of e2))) events)] (println @history) (map midi-to-event sorted-events))) (defn compose-original [] (map midi-to-event (mapcat bach/find-db (list (first bach/chorale-140-data) (second bach/chorale-140-data) (third bach/chorale-140-data)))))
null
https://raw.githubusercontent.com/josephwilk/musical-creativity/c2e6aab2a26d69ee2e51f4fad84fa3a71805e6ca/src/musical_creativity/composers/recombinance.clj
clojure
(ns musical-creativity.composers.recombinance (:require [clojure.math.numeric-tower :as math] [data.bach :as bach] [musical-creativity.util :refer :all] [musical-creativity.events :refer [pitch-of velocity-of timepoint-of channel-of midi-to-event]] [clojure.string :as str])) (def beats-store (atom {})) (def lexicon-store (atom {})) (def lexicons (atom ())) (def history (atom ())) (def mix-names ()) (def the-mixes ()) (def end? (atom false)) (def early-exit? (atom false)) (def compose-number 0) (def tonic (atom 'major)) (def previous-beat (atom nil)) (def beat-size 1000) (def number-of-beats 4) (def current-composer 'bach) (def start-beats-store (atom ())) (def compose-beats-store (atom ())) (def rules-store (atom ())) (defn remove-from-list [remove-items coll] (remove (set remove-items) coll)) (defn implode [list] (str/join "" list)) (defn explode [atom] (vec atom)) (defn a-thousand? [number] "Returns the number under 1000." (zero? (mod number 1000))) (defn make-lists-equal-length [list1 list2] (let [equal-pairs (map vector list1 list2)] (list (map first equal-pairs) (map second equal-pairs)))) (defn sort-by-first-element [lists] (sort (fn [[x & _] [y & _]] (< x y)) lists)) (defn all-members? [arrows target] (every? #(some #{%} target) arrows)) (defn positions "Shows the positions of number in list." [number list] (let [indexed-list (map-indexed vector list)] (for [[index element] indexed-list :when (= number element)] index))) (defn find-closest "finds the closest number in list to number." [number list] (let [test (map (fn [item] (math/abs (- number item))) list)] (nth list (choose-one (positions (first (sort <= test)) test))))) (defn all? "Tests for presence of all of first arg in second arg." [list1 list2] (empty? (clojure.set/difference (set list1) (set list2)))) (defn remove-all [stuff other-stuff] (vec (clojure.set/difference (set other-stuff) (set stuff)))) (defn hyphenate [numbers] (str/join "-" numbers)) (defn get-onset-notes "Gets the onset pitches for its arg." [events] (let [onbeat (ffirst events) onbeat-events (filter (fn [event] (= (timepoint-of event) onbeat)) events)] (map second onbeat-events))) (defn set-to-zero "Sets the events to zero." ([events] (set-to-zero events (ffirst events))) ([events subtract] (map (fn [event] (assoc (vec event) 0 (- (timepoint-of event) subtract))) events))) (defn make-name "Simple synonym for imploding the database name and number." [db-name counter] (symbol (str (name db-name) "-" counter))) (defn reduce-interval "Reduces the interval mod 12." [interval] (cond (<= (math/abs interval) 12) interval (neg? interval) (reduce-interval (+ interval 12)) :else (reduce-interval (- interval 12)))) (defn get-rule "Gets the rule between first two args." [voice start-note start-notes destination-notes name] (if (or (empty? (rest start-notes)) (empty? destination-notes)) () (cons (list (reduce-interval (- (second start-notes) start-note)) voice (- (second destination-notes) (second start-notes)) name) (get-rule voice start-note (rest start-notes) (rest destination-notes) name)))) (defn build-rules-for [start-notes destination-notes name] (loop [rules [] start-notes start-notes destination-notes destination-notes] (if (or (empty? (rest start-notes)) (empty? (rest destination-notes))) (reverse rules) (let [new-rule (reverse (get-rule (- (first destination-notes) (first start-notes)) (first start-notes) start-notes destination-notes name))] (recur (concat new-rule rules) (rest start-notes) (rest destination-notes)))))) (defn get-rules "Gets the intervals between adjacent sets of the two args." [start-notes destination-notes name] (let [test (make-lists-equal-length start-notes destination-notes) test-start-notes (first test) test-destination-notes (second test)] (build-rules-for test-start-notes test-destination-notes name))) (defn swap-unless-includes! [reference data] (when-not (some #{data} @reference) (swap! reference conj data))) (defn find-beat [name] (@beats-store name)) (defn find-in-lexicon [name] (@lexicon-store name)) (defn lexicon-contains? "Sees if the lexicon exists." [lexicon-name] (contains? @lexicon-store lexicon-name)) (defn make-lexicon-name "Creates the appropriate lexicon name for the object." ([note-numbers] (make-lexicon-name note-numbers mix-names)) ([note-numbers names] (cond (empty? the-mixes) (str current-composer "-" (hyphenate note-numbers)) (empty? names) (str current-composer "-" (hyphenate note-numbers)) (bound? (str (first names) "-" (hyphenate note-numbers))) (str (first names) "-" (hyphenate note-numbers)) :else (make-lexicon-name note-numbers (shuffle (rest names)))))) (defn add-beat-to-lexicon! [beat-name] (let [beat (find-beat beat-name) lexicon-name (make-lexicon-name (:start-notes beat))] (if (and (lexicon-contains? lexicon-name) (not (member beat-name (:beats (find-in-lexicon lexicon-name))))) (reset! lexicon-store (update-in @lexicon-store [lexicon-name :beats] conj beat-name)) (do (reset! lexicon-store (assoc @lexicon-store lexicon-name {:beats (list beat-name)})) (swap-unless-includes! lexicons lexicon-name))) lexicon-name)) (defn return-beat "Returns the beat number of the initiating event." ([channel-events] (return-beat channel-events (ffirst channel-events))) ([channel-events start-time] (some (fn [event] (when (and (a-thousand? (timepoint-of event)) (not= start-time (timepoint-of event))) (/ (- (timepoint-of event) start-time) 1000))) channel-events))) (defn create-pitch-class-set "Sorts and gets a full pc-set." [pitches] (let [pitch-classes (map #(mod % 12) pitches)] (sort < (distinct pitch-classes)))) (defn get-channel-numbers-from-events ([events] (get-channel-numbers-from-events events [])) ([events channels] (filtermap (fn [event] (when-not (member (channel-of event) channels) (channel-of event))) (reverse events)))) (defn find-alignment [point channel] (and (a-thousand? point) (some #(= point (second %)) channel))) (defn find-alignment-in-all-channels [point channels] (when (and point (every? #(find-alignment point %) channels)) point)) (defn all-together "Returns the appropriate channel timing." [channels all-channels] (let [together-timepoint (some (fn [[_ timepoint]] (find-alignment-in-all-channels timepoint all-channels)) channels)] (or together-timepoint (second (last-first all-channels))))) (defn collect-timings-by-channel [timings channel] (filter #(= (first %) channel) timings)) (defn plot-timings-of-each-beat [events] (map (fn [event] (list (channel-of event) (+ (timepoint-of event) (velocity-of event)))) events)) (defn first-place-where-all-together "This looks ahead to get the first time they end together" [events] (let [test (plot-timings-of-each-beat events) channels (get-channel-numbers-from-events events) ordered-timings-by-channel (map (fn [channel] (collect-timings-by-channel test channel)) channels)] (all-together (first ordered-timings-by-channel) (rest ordered-timings-by-channel)))) (defn collect-by-timing "Collects the events accoring to timing." [timing events] (filter (fn [[timepoint _ _ channel _]] (<= (+ timepoint channel) timing)) events)) (defn collect-beats [events] (if (empty? events) () (let [sync-time (first-place-where-all-together events) events-by-time (collect-by-timing sync-time events) reduced-events (drop (count events-by-time) events)] (cons events-by-time (collect-beats reduced-events))))) (defn make-beat [name beats] (let [start-notes (get-onset-notes (first beats)) destination-notes (get-onset-notes (second beats)) events (first beats) rules (cons (get-rules start-notes destination-notes name) (list name (ffirst (sort-by-first-element events))))] (swap! rules-store conj rules) {:start-notes start-notes :destination-notes destination-notes :events events :voice-leading (first rules)})) (defn start-beats [db-name] (remove nil? (collect-beats (set-to-zero (sort-by-first-element (bach/find-db db-name)))))) (defn- create-database-from-beats [db-name] (loop [beats (start-beats db-name) counter 1 start true] (when (seq beats) (let [name (make-name db-name counter) instance (make-beat name beats)] (reset! beats-store (assoc @beats-store name instance)) (add-beat-to-lexicon! name) (swap! compose-beats-store conj name) (when start (swap! start-beats-store conj name)) (recur (rest beats) (inc counter) nil))))) (defn create-database-from [db-names] (doall (map create-database-from-beats db-names))) (defn on-beat? "Returns true if the events conform to ontime." [events ontime] (every? (fn [event] (and (a-thousand? (timepoint-of event)) (= (timepoint-of event) ontime))) events)) (defn get-on-beat "Returns the on beat from the events." [events ontime] (cond (empty? events) () (and (a-thousand? (ffirst events)) (= (ffirst events) ontime)) (cons (first events) (get-on-beat (rest events) ontime)) :else ())) (defn get-pitches "Gets the pitches from its arg." [events] (map pitch-of events)) (defn get-interval "Returns the intervals between set members." [set] (if (empty? (rest set)) () (cons (- (second set) (first set)) (get-interval (rest set))))) (defn get-intervals "Returns the intervals in the sets." [sets] (map (fn [set] (math/abs (apply + (get-interval set)))) sets)) (defn project "Projects the pc-set through its inversions." ([set] (project set (count set) 0)) ([set length times] (if (= length times) () (cons set (project (concat (rest set) (list (+ 12 (first set)))) length (inc times)))))) (defn get-smallest-set "Returns the set with the smallest outer boundaries." [set] (let [projected-sets (project set) set-differentials (get-intervals projected-sets) sorted-differentials (sort < set-differentials)] (nth projected-sets (position (first sorted-differentials) set-differentials)))) (defn triad? "Checks to see if the events are a triad." [events] (when (seq events) (let [pitches (get-pitches events) pitches-class-set (create-pitch-class-set pitches) pitch-classes (get-smallest-set pitches-class-set)] (and (= (count pitch-classes) 3) (and (> (- (second pitch-classes) (first pitch-classes)) 2) (< (- (second pitch-classes) (first pitch-classes)) 5)) (and (> (- (third pitch-classes) (second pitch-classes)) 2) (< (- (third pitch-classes) (second pitch-classes)) 5)))))) (defn find-triad-beginning "Returns the db with a triad beginning." [] (let [test (choose-one @compose-beats-store) beat (find-beat test) on-beat (get-on-beat (:events beat) (ffirst (:events beat))) pitch-class-set (create-pitch-class-set (get-pitches on-beat))] (if (and (triad? on-beat) (or (all-members? '(0 4 8) pitch-class-set) (all-members? '(0 4 7) pitch-class-set) (all-members? '(0 5 8) pitch-class-set) (all-members? '(2 7 11) pitch-class-set)) (<= (velocity-of (first (:events beat))) 1000) (= (count (:events beat)) number-of-beats)) test (recur)))) (defn remainder "Returns the remainder of the beat." ([event] (remainder event (timepoint-of event) (velocity-of event))) ([event begin-time duration] (cond (empty? event) () (= duration 1000) () (< duration 1000) (list (concat (list begin-time) (list (pitch-of event)) (list duration) (drop 3 event))) :else (remainder event (+ begin-time 1000) (- duration 1000))))) (defn get-full-beat "Returns one full beat of the music." ([events] (get-full-beat events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (= (+ duration (velocity-of (first events))) 1000) (list (first events)) (> (+ duration (velocity-of (first events))) 1000) (list (concat (take 2 (first events)) (list (- 1000 duration)) (drop 3 (first events)))) :else (let [event (first events)] (cons event (get-full-beat (rest events) (+ begin-time (velocity-of event)) (+ (velocity-of event) duration))))))) (defn remainders "Returns remainders of beats." ([events] (remainders events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (= (+ duration (velocity-of (first events))) 1000) () (> (+ duration (velocity-of (first events))) 1000) (list (concat (list (+ begin-time (- 1000 duration))) (list (pitch-of (first events))) (list (- (velocity-of (first events)) (- 1000 duration))) (drop 3 (first events)))) :else (remainders (rest events) (+ begin-time (velocity-of (first events))) (+ (velocity-of (first events)) duration))))) (defn remove-full-beat "Removes one full beat from the events arg." ([events] (remove-full-beat events (ffirst events) 0)) ([events begin-time duration] (cond (empty? events) () (>= (+ duration (velocity-of (first events))) 1000) (rest events) :else (remove-full-beat (rest events) (+ begin-time (velocity-of (first events))) (+ (velocity-of (first events)) duration))))) (defn get-other-channels "Returns all but the first arg channeled events." [channel-not-to-get events] (cond (empty? events) () (= (channel-of (first events)) channel-not-to-get) (get-other-channels channel-not-to-get (rest events)) :else (cons (first events) (get-other-channels channel-not-to-get (rest events))))) (defn chop "Chops beats over 1000 into beat-sized pieces." ([event] (chop event (timepoint-of event) (velocity-of event))) ([event begin-time duration] (if (< duration 1000) () (cons (concat (list begin-time) (list (pitch-of event)) '(1000) (drop 3 event)) (chop event (+ begin-time 1000) (- duration 1000)))))) (defn events-with-channel "Gets the nth channel of the music." [channel events] (filter #(= (channel-of %) channel) events)) (defn chop-into-bites "Chops beats into groupings." [events] (cond (empty? events) () (and (= (velocity-of (first events)) 1000) (a-thousand? (ffirst events))) (cons (list (timepoint-of events)) (chop-into-bites (rest events))) (> (velocity-of (first events)) 1000) (cons (chop (first events)) (chop-into-bites (concat (remainder (first events)) (rest events)))) :else (let [event (first events) channel (channel-of event) events-for-channel (events-with-channel channel events)] (cons (get-full-beat events-for-channel) (chop-into-bites (concat (remainders events-for-channel) (concat (remove-full-beat events-for-channel) (get-other-channels channel events)))))))) (defn break-into-beats "Breaks events into beat-sized groupings." [events] (sort-by-first-element (apply concat (chop-into-bites (sort-by-first-element events))))) (defn get-long-phrases "Returns phrases of greater than 120000 duration." [distances] (remove nil? (map (fn [start stop] (when (> (- stop start) 12000) [start stop])) distances (rest distances)))) (defn get-region "Returns the region boardered by begin and end times." [begin-time end-time events] (filter (fn [event] (and (>= (timepoint-of event) begin-time) (< (timepoint-of event) end-time))) events)) (defn not-beyond? [channel-events] (if (not (> (apply + (map third channel-events)) 1000)) true)) (defn not-beyond-1000? "Returns true if the beat does not contain events beyond the incept time." [beat] (every? (fn [channel] (not-beyond? (events-with-channel channel beat))) (range 1 5))) (defn- cadence-place? [beat] (and (on-beat? (take number-of-beats beat) (ffirst beat)) (triad? (take number-of-beats beat)) (not-beyond-1000? beat))) (defn find-cadence-place "Returns the best place for a first cadence." [ordered-events] (let [beats (collect-beats ordered-events)] (seq (map ffirst (filter cadence-place? beats))))) (defn find-best-on-time [on-times] (find-closest (+ (/ (- (last on-times) (first on-times)) 2) (first on-times)) on-times)) (defn remove-region "Removes the region boardered by begin and end times." [begin-time end-time events] (concat (filter (fn [event] (or (< (timepoint-of event) begin-time) (>= (timepoint-of event) end-time))) events))) (defn- build-suitable-event [event] (if (>= (velocity-of event) 1000) event (concat (take 2 event) '(1000) (drop 3 event)))) (defn resolve-beat "Resolves the beat if necessary." ([beat] (resolve-beat beat (ffirst beat))) ([beat on-time] (cond (nil? (seq beat)) () (= (velocity-of (first beat)) 1000) (cons (first beat) (resolve-beat (rest beat) on-time)) :else (let [on-beat-candidate (get-on-beat (events-with-channel (channel-of (first beat)) beat) on-time) on-beat-event (first on-beat-candidate)] (cons (build-suitable-event on-beat-event) (resolve-beat (remove-all (events-with-channel (channel-of (first beat)) beat) beat) on-time)))))) (defn discover-cadence "Discovers an appropriate cadence." [missing-cadence-locations ordered-events] (let [relevant-events (get-region (first missing-cadence-locations) (second missing-cadence-locations) ordered-events) places-for-cadence (find-cadence-place relevant-events) best-location-for-new-cadence (when places-for-cadence (find-best-on-time places-for-cadence))] (if-not best-location-for-new-cadence ordered-events (sort-by-first-element (concat (resolve-beat (get-region best-location-for-new-cadence (+ best-location-for-new-cadence 1000) relevant-events)) (remove-region best-location-for-new-cadence (+ best-location-for-new-cadence 1000) ordered-events)))))) (defn all-match-velocity? [velocity ordered-events start-time] (and (let [channel-1-event (first (events-with-channel 1 ordered-events))] (and (= (velocity-of channel-1-event) velocity) (= start-time (timepoint-of channel-1-event)))) (let [channel-2-event (first (events-with-channel 2 ordered-events))] (and (= (velocity-of channel-2-event) velocity) (= start-time (timepoint-of channel-2-event)))) (let [channel-3-event (first (events-with-channel 3 ordered-events))] (and (= (velocity-of channel-3-event) velocity) (= start-time (timepoint-of channel-3-event)))) (let [channel-4-event (first (events-with-channel 4 ordered-events))] (and (= (velocity-of channel-4-event) velocity) (= start-time (timepoint-of channel-4-event)))))) (defn find-1000s "Returns the ontime if the ordered events are all duration 1000." ([ordered-events] (find-1000s ordered-events (ffirst ordered-events))) ([ordered-events start-time] (cond (empty? ordered-events) nil (all-match-velocity? 1000 ordered-events start-time) start-time :else (find-1000s (rest ordered-events))))) (defn find-2000s "Returns events of 2000 duration." ([ordered-events] (find-2000s ordered-events (ffirst ordered-events))) ([ordered-events start-time] (cond (empty? ordered-events) nil (all-match-velocity? 2000 ordered-events start-time) start-time :else (find-2000s (rest ordered-events))))) (defn discover-cadences "Makes an appropriate cadence possible." [missing-cadence-locations ordered-events] (reduce (fn [events location] (discover-cadence location events)) ordered-events missing-cadence-locations)) (defn distance-to-cadence [ordered-events] "Returns the distance tocadence of the arg." (let [quarter-note-distance (find-1000s ordered-events) half-note-distance (find-2000s ordered-events)] (cond (and (nil? quarter-note-distance) (nil? half-note-distance)) nil (nil? quarter-note-distance) half-note-distance (nil? half-note-distance) quarter-note-distance :else (if (> quarter-note-distance half-note-distance) half-note-distance quarter-note-distance)))) (defn clear-to "Clears the events up to the cadence." [distance-to-cadence ordered-events] (filter (fn [event] (> (timepoint-of event) distance-to-cadence)) ordered-events)) (defn find-cadence-start-times "Finds the cadence start times." [ordered-events] (let [distance-to-cadence (distance-to-cadence ordered-events)] (cond (empty? ordered-events) () (nil? distance-to-cadence) (find-cadence-start-times (rest ordered-events)) :else (cons distance-to-cadence (find-cadence-start-times (clear-to distance-to-cadence ordered-events)))))) (defn transpose "Transposes the events according to its first arg." [amt events] (filter (fn [event] (not (zero? (pitch-of event))) (concat (list (timepoint-of event)) (list (+ (pitch-of event) amt)) (drop 2 event))) events)) (defn get-note-timing "grunt work for get-beat-length" [event time] (- (+ (timepoint-of event) (velocity-of event)) time)) (defn get-beat-length [events] (let [time (ffirst events)] (first (sort > (map #(get-note-timing % time) events))))) (defn match-chord? "Matches the chord with the list of pitches within the allowance." [chord full-chord allowance] (cond (empty? chord) true (and (not (member (first chord) full-chord)) (zero? allowance)) nil (not (member (first chord) full-chord)) (match-chord? (rest chord) full-chord (dec allowance)) :else (match-chord? (rest chord) full-chord allowance))) (defn reduce-it "Reduces its first arg mod12 below its second arg." [note base] (if (< note base) note (reduce-it (- note 12) base))) (defn project-octaves "Projects its arg through a series of octaves." [note] (let [base-note (reduce-it note 20)] (loop [results [] current-note (reduce-it note 20)] (if (> current-note 120) results (recur (conj results (+ 12 current-note)) (+ 12 current-note)))))) (defn match-harmony? "Checks to see if its args match mod-12." [one two] (match-chord? (sort < one) (mapcat project-octaves two) (math/floor (/ (count one) 4)))) (defn all-members? "Checks to see if its first arg members are present in second arg." [list target] (clojure.set/superset? (set target) (set list))) (defn get-all-events-with-start-time-of [start-time events] (filter (fn [event] (= (timepoint-of event) start-time)) events)) (defn get-last-beat-events [events] (let [sorted-events (sort-by-first-element events) last-event (last sorted-events) begin-time (first last-event) last-beat (get-all-events-with-start-time-of begin-time events)] (if (and (= (count last-beat) number-of-beats) (a-thousand? (velocity-of (first last-beat)))) last-beat))) (defn get-db-name "Returns the database name." [lexicon] (first (str/split lexicon #"-"))) (defn inc-beat-number [beat] (when beat (let [beat (str beat) last-beat-digit (Integer/parseInt (str (last (explode beat))))] (str (get-db-name beat) "-" (inc last-beat-digit))))) (defn find-events-duration "Returns the events duration." ([events] (find-events-duration events 0)) ([events duration] (cond (empty? events) duration (= (channel-of (first events)) 1) (find-events-duration (rest events) (+ duration (velocity-of (first events)))) :else (find-events-duration (rest events) duration)))) (defn- retimed-events [events current-time] (map (fn [event] (cons (+ (timepoint-of event) current-time) (rest event))) (set-to-zero (first events)))) (defn re-time "Re-times the beats to fit together." ([event-lists] (re-time event-lists 0)) ([event-lists current-time] (if (empty? event-lists) () (cons (retimed-events event-lists current-time) (re-time (rest event-lists) (+ current-time (get-beat-length (first event-lists)))))))) (defn highest-lowest-notes "Returns the highest and lowest pitches of its arg." [events] (list (first (sort > (map pitch-of (events-with-channel 1 events)))) (first (sort < (map pitch-of (let [test (events-with-channel 4 events)] (if (empty? test) (events-with-channel 2 events) test))))))) (defn put-it-in-the-middle [extremes] "Gets the average." (math/round (/ (+ (second extremes) (first extremes)) 2))) (defn transpose-to-bach-range [events] (let [high-low (highest-lowest-notes events) intervals-off (list (- 83 (first high-low)) (- 40 (second high-low))) middle (put-it-in-the-middle intervals-off)] (transpose middle events))) (defn make-1000s "Makes all of the beat's durations into 1000s." [beat] (map (fn [event] (concat (take 2 event) '(1000) (drop 3 event))) beat)) (defn reset-beats "Resets the beats appropriately." [beats subtraction] (if (empty? beats)() (cons (map (fn [event] (concat (list (- (timepoint-of event) subtraction)) (rest event))) (first beats)) (reset-beats (rest beats) subtraction)))) (defn collapse "Collapses the final cadence." [beats] (cond (empty? beats) () (and (= (count (first beats)) number-of-beats) (= (third (ffirst beats)) 2000)) (cons (make-1000s (first beats)) (collapse (reset-beats (rest beats) 1000))) :else (cons (first beats) (collapse (rest beats))))) (defn cadence-collapse "Ensures the final chord will not have offbeats." [events] (apply concat (collapse (collect-beats (sort-by-first-element events))))) (defn reset-events-to "Resets the events for the delayed beat." [events begin-time] (map (fn [event] (cons (+ begin-time (timepoint-of event)) (rest event))) (set-to-zero events))) (defn delay-for-upbeat [events] (reset-events-to events 3000)) (defn ensure-necessary-cadences "Ensures the cadences are proper." [ordered-events] (let [cadence-start-times (find-cadence-start-times ordered-events) cadence-start-times (if-not (zero? (first cadence-start-times)) (cons 0 cadence-start-times) cadence-start-times) long-phrases (get-long-phrases cadence-start-times)] (discover-cadences long-phrases ordered-events))) (defn- sorted-by-beat [beats] (map (fn [beat] (get-pitches (get-on-beat beat (ffirst beat)))) beats)) (defn parallel? [events] (let [beats (collect-beats (take 30 (sort-by-first-element events))) sorted-pitches-by-beat (sorted-by-beat beats)] (and (= (count (first sorted-pitches-by-beat)) number-of-beats) (= (count (second sorted-pitches-by-beat)) number-of-beats) (or (and (pos? (- (ffirst sorted-pitches-by-beat) (first (second sorted-pitches-by-beat)))) (pos? (- (second (first sorted-pitches-by-beat)) (second (second sorted-pitches-by-beat)))) (pos? (- (third (first sorted-pitches-by-beat)) (third (second sorted-pitches-by-beat)))) (pos? (- (fourth (first sorted-pitches-by-beat)) (fourth (second sorted-pitches-by-beat))))) (and (neg? (- (ffirst sorted-pitches-by-beat) (first (second sorted-pitches-by-beat)))) (neg? (- (second (first sorted-pitches-by-beat)) (second (second sorted-pitches-by-beat)))) (neg? (- (third (first sorted-pitches-by-beat)) (third (second sorted-pitches-by-beat)))) (neg? (- (fourth (first sorted-pitches-by-beat)) (fourth (second sorted-pitches-by-beat))))))))) (defn wait-for-cadence? "Ensures the cadence is the proper length." ([events] (wait-for-cadence? events (ffirst events))) ([events start-time] (cond (empty? events) false (> (timepoint-of (first events)) (+ start-time 4000)) true (> (velocity-of (first events)) 1000) false :else (wait-for-cadence? (rest events) start-time)))) (defn- match-tonic? "Returns true if the events are tonic." [last-beat-events projected-octaves small large] (when (seq last-beat-events) (and (all-members? (map second last-beat-events) projected-octaves) (match-harmony? (sort < (map second last-beat-events)) small ) (match-harmony? (sort > (map second last-beat-events)) large)))) (defn match-bach-tonic? [events] (let [last-beat-events (get-last-beat-events (break-into-beats events)) projected-octaves (mapcat project-octaves '(60 64 67))] (match-tonic? last-beat-events projected-octaves '(60 64 67) '(60 64 67)))) (defn match-tonic-minor? [events] (let [last-beat-events (get-last-beat-events (break-into-beats events)) projected-octaves (mapcat project-octaves '(60 63 67))] (match-tonic? last-beat-events projected-octaves '(60 63 67) '(60 63 67)))) (defn match-major-tonic? [events] (let [pitches (get-pitches events) channel-4-events (events-with-channel 4 (sort-by-first-element events))] (and (or (all? (create-pitch-class-set pitches) '(0 4 7)) (all? (create-pitch-class-set pitches) '(0 3 7))) (zero? (first (create-pitch-class-set (get-pitches channel-4-events))))))) (defn- skip-generating-new-events? [counter current-beat] (reset! early-exit? (empty? (:destination-notes (find-beat current-beat)))) (or @early-exit? (when (and (> counter 36) (if (= tonic 'minor) (and (> (find-events-duration (:events (find-beat current-beat))) beat-size) (match-tonic-minor? (:events (find-beat current-beat)))) (and (> (find-events-duration (:events (find-beat current-beat))) beat-size) (match-bach-tonic? (:events (find-beat current-beat)))))) (reset! end? true)))) (defn build-events-for-beat [counter current-beat] (loop [events [] counter counter current-beat current-beat] (if (skip-generating-new-events? counter current-beat) events (let [beat (find-beat current-beat) new-events (:events beat) destination-notes (:destination-notes beat) lexicon-name (make-lexicon-name destination-notes) beat-in-lexicon (find-in-lexicon lexicon-name) beat-choices (:beats beat-in-lexicon) new-beat (choose-one (if (empty? (rest beat-choices)) beat-choices (remove-from-list (list @previous-beat (inc-beat-number @previous-beat)) beat-choices)))] (swap! history conj current-beat) (reset! previous-beat current-beat) (recur (concat events new-events) (inc counter) new-beat))))) (defn- build-events [counter] (let [current-beat (find-triad-beginning) current-beat-events (:events (find-beat current-beat))] (if (match-tonic-minor? (take number-of-beats current-beat-events)) (reset! tonic 'minor) (reset! tonic 'major)) (let [events (build-events-for-beat counter current-beat) events-list (list current-beat-events) all-events (if-not (empty? events) (concat (list events) events-list) events-list)] (swap! history conj current-beat) (apply concat (re-time all-events))))) (defn compose-events ([] (compose-events 0)) ([counter] (reset! end? false) (reset! history ()) (let [events (build-events counter)] (reset! history (reverse @history)) (when @end? (swap! history conj (list (inc compose-number)))) (if (or @early-exit? (not= current-composer 'bach)) () events)))) (defn valid-solution? [events] (if (empty? events) false (let [last-event (last (sort-by-first-element events)) event-sum (+ (timepoint-of last-event) (velocity-of last-event))] (and (>= event-sum 15000) (<= event-sum 200000) (wait-for-cadence? events) (not (parallel? events)))))) (defn prepare-events [events early-exit?] (let [events (ensure-necessary-cadences (sort-by-first-element events)) events (if-not (match-major-tonic? (get-on-beat events (ffirst events))) (delay-for-upbeat events) events) events (if (and (not early-exit?) (= current-composer 'bach)) (cadence-collapse (transpose-to-bach-range events)) events)] events)) (defn recombinance [] (let [events (compose-events)] (if (and (valid-solution? events) @end?) (prepare-events events @early-exit?) (recombinance)))) (defn compose [] (let [events (recombinance) sorted-events (sort (fn [e1 e2] (< (timepoint-of e1) (timepoint-of e2))) events)] (println @history) (map midi-to-event sorted-events))) (defn compose-original [] (map midi-to-event (mapcat bach/find-db (list (first bach/chorale-140-data) (second bach/chorale-140-data) (third bach/chorale-140-data)))))
87c517502f2483c081419df5e3b6a270ea05484b8aa0248bd13fab69a4d11056
laosb/SvelteNova
highlights.scm
; This query file is adopted from -sitter-svelte/blob/master/queries/highlights.scm. Nova 's highlight captures are different from the original one . ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.title ) ( # match ? @_tag " ^(h[0 - 9]|title)$ " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.strong ) ( # match ? @_tag " ^(strong|b)$ " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.emphasis ) ( # match ? @_tag " ^(em|i)$ " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.strike ) ( # match ? @_tag " ^(s|del)$ " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.underline ) ( # eq ? @_tag " u " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.literal ) ( # match ? @_tag " ^(code|kbd)$ " ) ) ; ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.uri ) ( # eq ? @_tag " a " ) ) ((attribute (attribute_name) @_attr (quoted_attribute_value (attribute_value) @tag.attribute.value.link)) (#match? @_attr "^(href|src)$")) ((attribute (attribute_name) @tag.attribute.name ["="]? @tag.attribute.operator [ (attribute_value) @tag.attribute.value (quoted_attribute_value ["\"" "'"] @tag.attribute.value.delimiter.left (_)? @tag.attribute.value ["\"" "'"] @tag.attribute.value.delimiter.right ) ]? ) (#not-match? @tag.attribute.name "(?i)^(src|href)$") ) (tag_name) @tag.name (erroneous_end_tag_name) @invalid (comment) @comment (if_start_expr (special_block_keyword) @keyword.condition) (else_expr (special_block_keyword) @keyword.condition) (else_if_expr (special_block_keyword) @keyword.condition) (if_end_expr (special_block_keyword) @keyword.condition) [ (special_block_keyword) (then) (as) ] @keyword [ "{" "}" ("{" "#") ("{" ":") ("{" "/") ("{" "@") ] @tag.framework.bracket [ "<" ">" "</" "/>" ] @tag.bracket
null
https://raw.githubusercontent.com/laosb/SvelteNova/7c813791aaed07396e6bd3dc7574b259b5b32036/SvelteNova.novaextension/Queries/highlights.scm
scheme
This query file is adopted from -sitter-svelte/blob/master/queries/highlights.scm.
Nova 's highlight captures are different from the original one . ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.title ) ( # match ? @_tag " ^(h[0 - 9]|title)$ " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.strong ) ( # match ? @_tag " ^(strong|b)$ " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.emphasis ) ( # match ? @_tag " ^(em|i)$ " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.strike ) ( # match ? @_tag " ^(s|del)$ " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.underline ) ( # eq ? @_tag " u " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.literal ) ( # match ? @_tag " ^(code|kbd)$ " ) ) ( ( element ( start_tag ( tag_name ) @_tag ) ( text ) @text.uri ) ( # eq ? @_tag " a " ) ) ((attribute (attribute_name) @_attr (quoted_attribute_value (attribute_value) @tag.attribute.value.link)) (#match? @_attr "^(href|src)$")) ((attribute (attribute_name) @tag.attribute.name ["="]? @tag.attribute.operator [ (attribute_value) @tag.attribute.value (quoted_attribute_value ["\"" "'"] @tag.attribute.value.delimiter.left (_)? @tag.attribute.value ["\"" "'"] @tag.attribute.value.delimiter.right ) ]? ) (#not-match? @tag.attribute.name "(?i)^(src|href)$") ) (tag_name) @tag.name (erroneous_end_tag_name) @invalid (comment) @comment (if_start_expr (special_block_keyword) @keyword.condition) (else_expr (special_block_keyword) @keyword.condition) (else_if_expr (special_block_keyword) @keyword.condition) (if_end_expr (special_block_keyword) @keyword.condition) [ (special_block_keyword) (then) (as) ] @keyword [ "{" "}" ("{" "#") ("{" ":") ("{" "/") ("{" "@") ] @tag.framework.bracket [ "<" ">" "</" "/>" ] @tag.bracket
dc51f3f6785c9e8b0bd4edc02ec137e11b15828e28d522fb66a5caa61b6f4b32
atgreen/red-light-green-light
db-sqlite.lisp
-*- Mode : LISP ; Syntax : COMMON - LISP ; Package : RLGL.DB ; Base : 10 -*- ;;; Copyright ( C ) 2018 , 2019 , 2020 , 2021 , 2022 < > ;;; ;;; This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . ;;; ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;; Affero General Public License for more details. ;;; You should have received a copy of the GNU Affero General Public ;;; License along with this program. If not, see ;;; </>. ;; Matcher routines (in-package #:rlgl.db) (defclass db/sqlite (db-backend) ((sqlite-db-filename :initarg :filename :reader filename) (fresh :initarg :fresh :initform nil :reader fresh)) (:default-initargs :sql-insert-log-statement "insert into log(version, colour, report, signature, client_signature, unixtimestamp) values ('~A', '~A', '~A', '~A', '~A', strftime('%s','now'));" :filename (error "Must supply a filename."))) (defmethod initialize-instance :after ((db db/sqlite) &key) (let ((dbc (connect-cached db))) (mapc (lambda (command) (dbi:do-sql dbc command)) '("create table if not exists users (puk integer primary key autoincrement, user_uuid char(36) not null, created_at integer, unique(user_uuid));")))) (defmethod connect-cached ((db db/sqlite)) (dbi:connect-cached :sqlite3 :database-name (filename db)))
null
https://raw.githubusercontent.com/atgreen/red-light-green-light/b7677851364b5fb87774b8674596a38c6c01a9d7/db/db-sqlite.lisp
lisp
Syntax : COMMON - LISP ; Package : RLGL.DB ; Base : 10 -*- This program is free software: you can redistribute it and/or This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. License along with this program. If not, see </>. Matcher routines
Copyright ( C ) 2018 , 2019 , 2020 , 2021 , 2022 < > modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Affero General Public (in-package #:rlgl.db) (defclass db/sqlite (db-backend) ((sqlite-db-filename :initarg :filename :reader filename) (fresh :initarg :fresh :initform nil :reader fresh)) (:default-initargs :sql-insert-log-statement "insert into log(version, colour, report, signature, client_signature, unixtimestamp) values ('~A', '~A', '~A', '~A', '~A', strftime('%s','now'));" :filename (error "Must supply a filename."))) (defmethod initialize-instance :after ((db db/sqlite) &key) (let ((dbc (connect-cached db))) (mapc (lambda (command) (dbi:do-sql dbc command)) '("create table if not exists users (puk integer primary key autoincrement, user_uuid char(36) not null, created_at integer, unique(user_uuid));")))) (defmethod connect-cached ((db db/sqlite)) (dbi:connect-cached :sqlite3 :database-name (filename db)))
6281229a720054754aa9ddcfa5ae45dc5252278a6ea42fff4595cec9c6ea622e
SKA-ScienceDataProcessor/RC
test.hs
{-# LANGUAGE GADTs #-} import DNA.Actor import DNA.AST import DNA import DNA.Compiler.CH ---------------------------------------------------------------- -- Print actor ---------------------------------------------------------------- exprPrint :: Expr () (() -> Int -> ((),Out)) exprPrint = Lam $ Lam $ Tup ( Scalar () `Cons` Out [PrintInt $ Var ZeroIdx] `Cons` Nil) actorPrint :: Actor () actorPrint = actor $ do rule $ exprPrint startingState $ Scalar () return () ---------------------------------------------------------------- -- Source actor ---------------------------------------------------------------- exprSrcInt :: Conn Int -> Expr () (Int -> (Int,Out)) exprSrcInt i = Lam $ Tup ( Ap (Ap Add (Var ZeroIdx)) (Scalar (1 :: Int)) `Cons` Out [Outbound i (Var ZeroIdx)] `Cons` Nil) actorSrcInt :: Actor (Conn Int) actorSrcInt = actor $ do c <- simpleOut ConnOne producer $ exprSrcInt c startingState $ Scalar 0 return c program = do (aPr, ()) <- use actorPrint (_ , c ) <- use actorSrcInt connect c aPr main :: IO () main = compile compileToCH (saveProject "dir") 2 program
null
https://raw.githubusercontent.com/SKA-ScienceDataProcessor/RC/1b5e25baf9204a9f7ef40ed8ee94a86cc6c674af/MS1/dna-examples/test.hs
haskell
# LANGUAGE GADTs # -------------------------------------------------------------- Print actor -------------------------------------------------------------- -------------------------------------------------------------- Source actor --------------------------------------------------------------
import DNA.Actor import DNA.AST import DNA import DNA.Compiler.CH exprPrint :: Expr () (() -> Int -> ((),Out)) exprPrint = Lam $ Lam $ Tup ( Scalar () `Cons` Out [PrintInt $ Var ZeroIdx] `Cons` Nil) actorPrint :: Actor () actorPrint = actor $ do rule $ exprPrint startingState $ Scalar () return () exprSrcInt :: Conn Int -> Expr () (Int -> (Int,Out)) exprSrcInt i = Lam $ Tup ( Ap (Ap Add (Var ZeroIdx)) (Scalar (1 :: Int)) `Cons` Out [Outbound i (Var ZeroIdx)] `Cons` Nil) actorSrcInt :: Actor (Conn Int) actorSrcInt = actor $ do c <- simpleOut ConnOne producer $ exprSrcInt c startingState $ Scalar 0 return c program = do (aPr, ()) <- use actorPrint (_ , c ) <- use actorSrcInt connect c aPr main :: IO () main = compile compileToCH (saveProject "dir") 2 program
8bb2dd62edb79aace5020e1246002567f236e9eaad5ce520adc2924209258c90
tiagodalloca/city-weather-clj
config.clj
(ns city-weather-clj.system.config (:require [city-weather-clj.http.server :as http-server] [city-weather-clj.http.handler :as http-handler] [city-weather-clj.api-client.open-weather :refer [make-open-weather-client]] [city-weather-clj.cache :refer [make-weather-cache]] [integrant.core :as ig])) (defmethod ig/init-key :http/server [_ {:keys [handler] {:keys [port]} :opts}] (http-server/start-server {:handler handler :port port})) (defmethod ig/halt-key! :http/server [_ server] (when server (.stop server))) #_{:clj-kondo/ignore [:unused-binding]} (defmethod ig/init-key :http/handler [_ deps] (http-handler/get-handler deps)) (defmethod ig/init-key :api-client/weather [_ {:keys [endpoint api-key]}] (when-not (some? api-key) (throw (ex-info "Missing api-key" {:api-key api-key}))) (make-open-weather-client endpoint api-key)) (defmethod ig/init-key :system/cache [_ _] (make-weather-cache))
null
https://raw.githubusercontent.com/tiagodalloca/city-weather-clj/606745f64a1b58366b04060248afa4b15d99b6d7/src/city_weather_clj/system/config.clj
clojure
(ns city-weather-clj.system.config (:require [city-weather-clj.http.server :as http-server] [city-weather-clj.http.handler :as http-handler] [city-weather-clj.api-client.open-weather :refer [make-open-weather-client]] [city-weather-clj.cache :refer [make-weather-cache]] [integrant.core :as ig])) (defmethod ig/init-key :http/server [_ {:keys [handler] {:keys [port]} :opts}] (http-server/start-server {:handler handler :port port})) (defmethod ig/halt-key! :http/server [_ server] (when server (.stop server))) #_{:clj-kondo/ignore [:unused-binding]} (defmethod ig/init-key :http/handler [_ deps] (http-handler/get-handler deps)) (defmethod ig/init-key :api-client/weather [_ {:keys [endpoint api-key]}] (when-not (some? api-key) (throw (ex-info "Missing api-key" {:api-key api-key}))) (make-open-weather-client endpoint api-key)) (defmethod ig/init-key :system/cache [_ _] (make-weather-cache))
daacab98b3387a50230e3da625e4177edeccbae04503e75617c814073c62941f
sacerdot/CovidMonitoring
ospedale.erl
%%%------------------------------------------------------------------- @author ( C ) 2020 , < COMPANY > %%% @doc %%% %%% @end Created : 01 . May 2020 11:11 %%%------------------------------------------------------------------- -module(ospedale). -author("Federico Bertani"). %% API -export([start/0, hospital_loop/0]). hospital_loop()-> receive % an user wants to be tested {test_me, PID} -> io:format("USER ~p WANTS TO BE TESTED ~n",[PID]), answer with probability 25 % to be positive case (rand:uniform(4)=<1) of true -> PID ! positive; false -> PID ! negative end, hospital_loop() end. start() -> io:format("Hospital started~n"), global:register_name(ospedale,self()), hospital_loop().
null
https://raw.githubusercontent.com/sacerdot/CovidMonitoring/fe969cd51869bbe6479da509c9a6ab21d43e6d11/BertaniSignatiStacchio/ospedale.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- API an user wants to be tested to be positive
@author ( C ) 2020 , < COMPANY > Created : 01 . May 2020 11:11 -module(ospedale). -author("Federico Bertani"). -export([start/0, hospital_loop/0]). hospital_loop()-> receive {test_me, PID} -> io:format("USER ~p WANTS TO BE TESTED ~n",[PID]), case (rand:uniform(4)=<1) of true -> PID ! positive; false -> PID ! negative end, hospital_loop() end. start() -> io:format("Hospital started~n"), global:register_name(ospedale,self()), hospital_loop().
e1fb54c6bbb2b73851b73de36d3644d6ed799b763389b191b3a24cb646ab0b70
facebookarchive/lex-pass
Lex.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE DeriveGeneric # module Lang.Php.Ast.Lex where import qualified Data.Set as Set import Text.PrettyPrint.GenericPretty import Lang.Php.Ast.Common data StrLit = StrLit String deriving (Data, Eq, Generic, Show, Typeable) instance Parse StrLit where parse = StrLit <$> ( liftM2 (:) (char '"') (strLitRestParserCurly '"' False) <|> liftM2 (:) (char '\'') (strLitRestParser '\'') ) instance Unparse StrLit where unparse (StrLit a) = a strLitRestParser :: Char -> Parser String strLitRestParser end = anyChar >>= \ c -> (c:) <$> if c == end then return [] else if c == '\\' then liftM2 (:) anyChar (strLitRestParser end) else strLitRestParser end -- "{$a["{$a}"]}" e.g. is a legal single string literal in php.. strLitRestParserCurly :: Char -> Bool -> Parser String strLitRestParserCurly end haveCurly = anyChar >>= \ c -> (c:) <$> if c == end then return [] else if c == '\\' then liftM2 (:) anyChar (strLitRestParserCurly end False) else if c == '{' then strLitRestParserCurly end True else if haveCurly && c == '$' then liftM2 (++) (strLitRestParserCurly '}' False) (strLitRestParserCurly end False) else strLitRestParserCurly end False backticksParser :: Parser String backticksParser = liftM2 (:) (char '`') (strLitRestParserCurly '`' False) data NumLit = NumLit String deriving (Data, Eq, Generic, Show, Typeable) instance Parse NumLit where -- could be tighter parse = NumLit <$> (liftM2 (++) numStart (ptAndRest <|> return "") <|> ptAndRest) where numStart = liftM2 (:) (oneOf ['0'..'9']) noDecPt ptAndRest = liftM2 (:) (char '.') noDecPt noDecPt = many . oneOf $ 'x':['0'..'9'] ++ ['a'..'f'] ++ ['A'..'F'] instance Unparse NumLit where unparse (NumLit a) = a data HereDoc = HereDoc String deriving (Data, Eq, Generic, Show, Typeable) wsNoNLParser :: Parser String wsNoNLParser = many (satisfy (\ x -> isSpace x && x /= '\n')) instance Parse HereDoc where parse = HereDoc <$> do ws <- tokHereDocP >> wsNoNLParser s <- genIdentifierParser nl <- newline rest <- hereDocRestParser s return (ws ++ s ++ [nl] ++ rest) instance Unparse HereDoc where unparse (HereDoc a) = tokHereDoc ++ a hereDocRestParser :: String -> Parser String hereDocRestParser s = try (string s <* notFollowedBy (satisfy (\ c -> c /= '\n' && c /= ';'))) <|> liftM2 (++) lineParser (hereDocRestParser s) lineParser :: Parser String lineParser = liftM2 (++) (many $ satisfy (/= '\n')) ((:[]) <$> newline) identStartChars :: String identStartChars = ['\\'] ++ ['a'..'z'] ++ ['A'..'Z'] ++ ['_'] identEndChars :: String identEndChars = identStartChars ++ ['0'..'9'] identXmlChars :: String identXmlChars = identStartChars ++ ['0'..'9'] ++ ['-'] genIdentifierParser :: Parser String genIdentifierParser = liftM2 (:) (oneOf identStartChars) (many $ oneOf identEndChars) <|> concat <$> many1 (liftM2 (++) tokColonP . many1 $ oneOf identXmlChars) xmlIdentifierParser :: Parser String xmlIdentifierParser = many1 $ oneOf identXmlChars identifierParser :: Parser String identifierParser = try $ do i <- genIdentifierParser when (map toLower i `Set.member` reservedWords) $ fail "Found reserved word when expecting identifier." return i -- must be given lowercase charCI :: Char -> Parser Char charCI c = satisfy ((== c) . toLower) -- must be given lowercase stringCI :: String -> Parser String stringCI = mapM charCI -- idk why but we need an explicit specialized type instead of using (string) -- directly str :: String -> Parser String str = string nc t cs = try $ str t <* notFollowedBy (oneOf cs) -- ugly, redo this.. maybe have a minimal lexer stage after all? tokNot = "!" tokNotP = nc tokNot "=" tokNE = "!=" tokNEP = nc tokNE "=" tokNI = "!==" tokNIP = try $ str tokNI tokDollar = "$" tokDollarP = str tokDollar tokMod = "%" tokModP = nc tokMod "=" tokModBy = "%=" tokModByP = try $ str tokModBy tokAmp = "&" tokAmpP = nc tokAmp "&=" tokAnd = "&&" tokAndP = try $ str tokAnd tokBitAndBy = "&=" tokBitAndByP = try $ str tokBitAndBy tokLParen = "(" tokLParenP = str tokLParen tokRParen = ")" tokRParenP = str tokRParen tokMul = "*" tokMulP = nc tokMul "=/" tokMulBy = "*=" tokMulByP = try $ str tokMulBy tokPlus = "+" tokPlusP = nc tokPlus "+=" tokIncr = "++" tokIncrP = try $ str tokIncr tokPlusBy = "+=" tokPlusByP = try $ str tokPlusBy tokComma = "," tokCommaP = str tokComma tokMinus = "-" tokMinusP = nc tokMinus "-=>" tokDecr = "--" tokDecrP = try $ str tokDecr tokMinusBy = "-=" tokMinusByP = try $ str tokMinusBy tokArrow = "->" tokArrowP = try $ str tokArrow tokConcat = "." tokConcatP = nc tokConcat "=" tokConcatBy = ".=" tokConcatByP = try $ str tokConcatBy tokDiv = "/" tokDivP = nc tokDiv "=*/" tokDivBy = "/=" tokDivByP = try $ str tokDivBy tokColon = ":" tokColonP = nc tokColon ":" tokDubColon = "::" tokDubColonP = try $ str tokDubColon tokSemi = ";" tokSemiP = str tokSemi tokLT = "<" tokLTP = nc tokLT "<=>" tokShiftL = "<<" tokShiftLP = nc tokShiftL "<=" tokHereDoc = "<<<" tokHereDocP = try $ str tokHereDoc tokShiftLBy = "<<=" tokShiftLByP = try $ str tokShiftLBy tokLE = "<=" tokLEP = try $ str tokLE tokNEOld = "<>" tokNEOldP = try $ str tokNEOld tokOpenPhp = "<?php" tokOpenPhpP = try $ str "<?" >> optional (identCI "php") tokOpenPhpEcho = "<?=" -- no tokOpenPhpEchoP, done manually currently, has weird rules tokEquals = "=" tokEqualsP = nc tokEquals "=>" tokEQ = "==" tokEQP = nc tokEQ "=" tokID = "===" tokIDP = try $ str tokID tokDubArrow = "=>" tokDubArrowP = try $ str tokDubArrow tokGT = ">" tokGTP = nc tokGT "=>" tokGE = ">=" tokGEP = try $ str tokGE tokShiftR = ">>" tokShiftRP = nc tokShiftR "=" tokShiftRBy = ">>=" tokShiftRByP = try $ str tokShiftRBy tokQMark = "?" tokQMarkP = nc tokQMark ">" tokClosePhp = "?>" tokClosePhpP = try $ str tokClosePhp tokAt = "@" tokAtP = str tokAt tokLBracket = "[" tokLBracketP = str tokLBracket tokRBracket = "]" tokRBracketP = str tokRBracket tokXor = "^" tokXorP = nc tokXor "=" tokXorBy = "^=" tokXorByP = try $ str tokXorBy tokLBrace = "{" tokLBraceP = str tokLBrace tokBitOr = "|" tokBitOrP = nc tokBitOr "=|" tokBitOrBy = "|=" tokBitOrByP = try $ str tokBitOrBy tokOr = "||" tokOrP = try $ str tokOr tokRBrace = "}" tokRBraceP = str tokRBrace tokBitNot = "~" tokBitNotP = str tokBitNot tokAbstract = "abstract" tokAndWd = "and" tokArray = "array" tokAs = "as" tokBreak = "break" tokCase = "case" tokCatch = "catch" tokClass = "class" tokClone = "clone" tokConst = "const" tokContinue = "continue" tokDeclare = "declare" tokDefault = "default" tokDie = "die" tokDo = "do" tokEcho = "echo" tokElse = "else" tokElseif = "elseif" tokEmpty = "empty" tokEnddeclare = "enddeclare" tokEndfor = "endfor" tokEndforeach = "endforeach" tokEndif = "endif" tokEndswitch = "endswitch" tokEndwhile = "endwhile" tokEval = "eval" tokExit = "exit" tokExtends = "extends" tokFinal = "final" tokFor = "for" tokForeach = "foreach" tokFunction = "function" tokGlobal = "global" tokGoto = "goto" tokIf = "if" tokImplements = "implements" tokInclude = "include" tokIncludeOnce = "include_once" tokInstanceof = "instanceof" tokInterface = "interface" tokIsset = "isset" tokList = "list" tokNamespace = "namespace" tokNew = "new" tokOrWd = "or" tokPrint = "print" tokPrivate = "private" tokProtected = "protected" tokPublic = "public" tokRequire = "require" tokRequireOnce = "require_once" tokReturn = "return" tokStatic = "static" tokSwitch = "switch" tokThrow = "throw" tokTry = "try" tokUnset = "unset" tokUse = "use" tokVar = "var" tokWhile = "while" tokXorWd = "xor" reservedWords :: Set.Set String reservedWords = Set.fromList [ tokAbstract, tokAndWd, tokArray, tokAs, tokBreak, tokCase, tokCatch, tokClass, tokClone, tokConst, tokContinue, tokDeclare, tokDefault, tokDie, tokDo, tokEcho, tokElse, tokElseif, tokEmpty, tokEnddeclare, tokEndfor, tokEndforeach, tokEndif, tokEndswitch, tokEndwhile, tokEval, tokExit, tokExtends, tokFinal, tokFor, tokForeach, tokFunction, tokGlobal, tokGoto, tokIf, tokImplements, tokInclude, tokIncludeOnce, tokInstanceof, tokInterface, tokIsset, tokList, tokNamespace, tokNew, tokOrWd, tokPrint, tokPrivate, tokProtected, tokPublic, tokRequire, tokRequireOnce, tokReturn, tokStatic, tokSwitch, tokThrow, tokTry, tokUnset, tokUse, tokVar, tokWhile, tokXorWd] identCI w = try $ do i <- genIdentifierParser when (map toLower i /= w) $ fail "" return i identsCI w = try $ do i <- genIdentifierParser when (map toLower i `notElem` w) $ fail "" return i tokAbstractP = identCI tokAbstract tokAndWdP = identCI tokAndWd tokArrayP = identCI tokArray tokAsP = identCI tokAs tokBreakP = identCI tokBreak tokCaseP = identCI tokCase tokCatchP = identCI tokCatch tokClassP = identCI tokClass tokCloneP = identCI tokClone tokConstP = identCI tokConst tokContinueP = identCI tokContinue tokDeclareP = identCI tokDeclare tokDefaultP = identCI tokDefault tokDieP = identCI tokDie tokDoP = identCI tokDo tokEchoP = identCI tokEcho tokElseifP = identCI tokElseif tokElseP = identCI tokElse tokEmptyP = identCI tokEmpty tokEnddeclareP = identCI tokEnddeclare tokEndforeachP = identCI tokEndforeach tokEndforP = identCI tokEndfor tokEndifP = identCI tokEndif tokEndswitchP = identCI tokEndswitch tokEndwhileP = identCI tokEndwhile tokEvalP = identCI tokEval tokExitP = identCI tokExit tokExtendsP = identCI tokExtends tokFinalP = identCI tokFinal tokForP = identCI tokFor tokForeachP = identCI tokForeach tokFunctionP = identCI tokFunction tokGlobalP = identCI tokGlobal tokGotoP = identCI tokGoto tokIfP = identCI tokIf tokImplementsP = identCI tokImplements tokInstanceofP = identCI tokInstanceof tokInterfaceP = identCI tokInterface tokIssetP = identCI tokIsset tokListP = identCI tokList tokNamespaceP = identCI tokNamespace tokNewP = identCI tokNew tokOrWdP = identCI tokOrWd tokPrintP = identCI tokPrint tokPrivateP = identCI tokPrivate tokProtectedP = identCI tokProtected tokPublicP = identCI tokPublic tokReturnP = identCI tokReturn tokStaticP = identCI tokStatic tokSwitchP = identCI tokSwitch tokThrowP = identCI tokThrow tokTryP = identCI tokTry tokUnsetP = identCI tokUnset tokUseP = identCI tokUse tokVarP = identCI tokVar tokWhileP = identCI tokWhile tokXorWdP = identCI tokXorWd tokCategory = "category" tokCategoryP = identCI tokCategory tokChildren = "children" tokChildrenP = identCI tokChildren tokAttribute = "attribute" tokAttributeP = identCI tokAttribute instance Out HereDoc instance Out NumLit instance Out StrLit
null
https://raw.githubusercontent.com/facebookarchive/lex-pass/dcfa9560a95f2c1344e15493dabcc1645b1ca5e8/src/Lang/Php/Ast/Lex.hs
haskell
# LANGUAGE DeriveDataTypeable # "{$a["{$a}"]}" e.g. is a legal single string literal in php.. could be tighter must be given lowercase must be given lowercase idk why but we need an explicit specialized type instead of using (string) directly ugly, redo this.. maybe have a minimal lexer stage after all? no tokOpenPhpEchoP, done manually currently, has weird rules
# LANGUAGE DeriveGeneric # module Lang.Php.Ast.Lex where import qualified Data.Set as Set import Text.PrettyPrint.GenericPretty import Lang.Php.Ast.Common data StrLit = StrLit String deriving (Data, Eq, Generic, Show, Typeable) instance Parse StrLit where parse = StrLit <$> ( liftM2 (:) (char '"') (strLitRestParserCurly '"' False) <|> liftM2 (:) (char '\'') (strLitRestParser '\'') ) instance Unparse StrLit where unparse (StrLit a) = a strLitRestParser :: Char -> Parser String strLitRestParser end = anyChar >>= \ c -> (c:) <$> if c == end then return [] else if c == '\\' then liftM2 (:) anyChar (strLitRestParser end) else strLitRestParser end strLitRestParserCurly :: Char -> Bool -> Parser String strLitRestParserCurly end haveCurly = anyChar >>= \ c -> (c:) <$> if c == end then return [] else if c == '\\' then liftM2 (:) anyChar (strLitRestParserCurly end False) else if c == '{' then strLitRestParserCurly end True else if haveCurly && c == '$' then liftM2 (++) (strLitRestParserCurly '}' False) (strLitRestParserCurly end False) else strLitRestParserCurly end False backticksParser :: Parser String backticksParser = liftM2 (:) (char '`') (strLitRestParserCurly '`' False) data NumLit = NumLit String deriving (Data, Eq, Generic, Show, Typeable) instance Parse NumLit where parse = NumLit <$> (liftM2 (++) numStart (ptAndRest <|> return "") <|> ptAndRest) where numStart = liftM2 (:) (oneOf ['0'..'9']) noDecPt ptAndRest = liftM2 (:) (char '.') noDecPt noDecPt = many . oneOf $ 'x':['0'..'9'] ++ ['a'..'f'] ++ ['A'..'F'] instance Unparse NumLit where unparse (NumLit a) = a data HereDoc = HereDoc String deriving (Data, Eq, Generic, Show, Typeable) wsNoNLParser :: Parser String wsNoNLParser = many (satisfy (\ x -> isSpace x && x /= '\n')) instance Parse HereDoc where parse = HereDoc <$> do ws <- tokHereDocP >> wsNoNLParser s <- genIdentifierParser nl <- newline rest <- hereDocRestParser s return (ws ++ s ++ [nl] ++ rest) instance Unparse HereDoc where unparse (HereDoc a) = tokHereDoc ++ a hereDocRestParser :: String -> Parser String hereDocRestParser s = try (string s <* notFollowedBy (satisfy (\ c -> c /= '\n' && c /= ';'))) <|> liftM2 (++) lineParser (hereDocRestParser s) lineParser :: Parser String lineParser = liftM2 (++) (many $ satisfy (/= '\n')) ((:[]) <$> newline) identStartChars :: String identStartChars = ['\\'] ++ ['a'..'z'] ++ ['A'..'Z'] ++ ['_'] identEndChars :: String identEndChars = identStartChars ++ ['0'..'9'] identXmlChars :: String identXmlChars = identStartChars ++ ['0'..'9'] ++ ['-'] genIdentifierParser :: Parser String genIdentifierParser = liftM2 (:) (oneOf identStartChars) (many $ oneOf identEndChars) <|> concat <$> many1 (liftM2 (++) tokColonP . many1 $ oneOf identXmlChars) xmlIdentifierParser :: Parser String xmlIdentifierParser = many1 $ oneOf identXmlChars identifierParser :: Parser String identifierParser = try $ do i <- genIdentifierParser when (map toLower i `Set.member` reservedWords) $ fail "Found reserved word when expecting identifier." return i charCI :: Char -> Parser Char charCI c = satisfy ((== c) . toLower) stringCI :: String -> Parser String stringCI = mapM charCI str :: String -> Parser String str = string nc t cs = try $ str t <* notFollowedBy (oneOf cs) tokNot = "!" tokNotP = nc tokNot "=" tokNE = "!=" tokNEP = nc tokNE "=" tokNI = "!==" tokNIP = try $ str tokNI tokDollar = "$" tokDollarP = str tokDollar tokMod = "%" tokModP = nc tokMod "=" tokModBy = "%=" tokModByP = try $ str tokModBy tokAmp = "&" tokAmpP = nc tokAmp "&=" tokAnd = "&&" tokAndP = try $ str tokAnd tokBitAndBy = "&=" tokBitAndByP = try $ str tokBitAndBy tokLParen = "(" tokLParenP = str tokLParen tokRParen = ")" tokRParenP = str tokRParen tokMul = "*" tokMulP = nc tokMul "=/" tokMulBy = "*=" tokMulByP = try $ str tokMulBy tokPlus = "+" tokPlusP = nc tokPlus "+=" tokIncr = "++" tokIncrP = try $ str tokIncr tokPlusBy = "+=" tokPlusByP = try $ str tokPlusBy tokComma = "," tokCommaP = str tokComma tokMinus = "-" tokMinusP = nc tokMinus "-=>" tokDecr = "--" tokDecrP = try $ str tokDecr tokMinusBy = "-=" tokMinusByP = try $ str tokMinusBy tokArrow = "->" tokArrowP = try $ str tokArrow tokConcat = "." tokConcatP = nc tokConcat "=" tokConcatBy = ".=" tokConcatByP = try $ str tokConcatBy tokDiv = "/" tokDivP = nc tokDiv "=*/" tokDivBy = "/=" tokDivByP = try $ str tokDivBy tokColon = ":" tokColonP = nc tokColon ":" tokDubColon = "::" tokDubColonP = try $ str tokDubColon tokSemi = ";" tokSemiP = str tokSemi tokLT = "<" tokLTP = nc tokLT "<=>" tokShiftL = "<<" tokShiftLP = nc tokShiftL "<=" tokHereDoc = "<<<" tokHereDocP = try $ str tokHereDoc tokShiftLBy = "<<=" tokShiftLByP = try $ str tokShiftLBy tokLE = "<=" tokLEP = try $ str tokLE tokNEOld = "<>" tokNEOldP = try $ str tokNEOld tokOpenPhp = "<?php" tokOpenPhpP = try $ str "<?" >> optional (identCI "php") tokOpenPhpEcho = "<?=" tokEquals = "=" tokEqualsP = nc tokEquals "=>" tokEQ = "==" tokEQP = nc tokEQ "=" tokID = "===" tokIDP = try $ str tokID tokDubArrow = "=>" tokDubArrowP = try $ str tokDubArrow tokGT = ">" tokGTP = nc tokGT "=>" tokGE = ">=" tokGEP = try $ str tokGE tokShiftR = ">>" tokShiftRP = nc tokShiftR "=" tokShiftRBy = ">>=" tokShiftRByP = try $ str tokShiftRBy tokQMark = "?" tokQMarkP = nc tokQMark ">" tokClosePhp = "?>" tokClosePhpP = try $ str tokClosePhp tokAt = "@" tokAtP = str tokAt tokLBracket = "[" tokLBracketP = str tokLBracket tokRBracket = "]" tokRBracketP = str tokRBracket tokXor = "^" tokXorP = nc tokXor "=" tokXorBy = "^=" tokXorByP = try $ str tokXorBy tokLBrace = "{" tokLBraceP = str tokLBrace tokBitOr = "|" tokBitOrP = nc tokBitOr "=|" tokBitOrBy = "|=" tokBitOrByP = try $ str tokBitOrBy tokOr = "||" tokOrP = try $ str tokOr tokRBrace = "}" tokRBraceP = str tokRBrace tokBitNot = "~" tokBitNotP = str tokBitNot tokAbstract = "abstract" tokAndWd = "and" tokArray = "array" tokAs = "as" tokBreak = "break" tokCase = "case" tokCatch = "catch" tokClass = "class" tokClone = "clone" tokConst = "const" tokContinue = "continue" tokDeclare = "declare" tokDefault = "default" tokDie = "die" tokDo = "do" tokEcho = "echo" tokElse = "else" tokElseif = "elseif" tokEmpty = "empty" tokEnddeclare = "enddeclare" tokEndfor = "endfor" tokEndforeach = "endforeach" tokEndif = "endif" tokEndswitch = "endswitch" tokEndwhile = "endwhile" tokEval = "eval" tokExit = "exit" tokExtends = "extends" tokFinal = "final" tokFor = "for" tokForeach = "foreach" tokFunction = "function" tokGlobal = "global" tokGoto = "goto" tokIf = "if" tokImplements = "implements" tokInclude = "include" tokIncludeOnce = "include_once" tokInstanceof = "instanceof" tokInterface = "interface" tokIsset = "isset" tokList = "list" tokNamespace = "namespace" tokNew = "new" tokOrWd = "or" tokPrint = "print" tokPrivate = "private" tokProtected = "protected" tokPublic = "public" tokRequire = "require" tokRequireOnce = "require_once" tokReturn = "return" tokStatic = "static" tokSwitch = "switch" tokThrow = "throw" tokTry = "try" tokUnset = "unset" tokUse = "use" tokVar = "var" tokWhile = "while" tokXorWd = "xor" reservedWords :: Set.Set String reservedWords = Set.fromList [ tokAbstract, tokAndWd, tokArray, tokAs, tokBreak, tokCase, tokCatch, tokClass, tokClone, tokConst, tokContinue, tokDeclare, tokDefault, tokDie, tokDo, tokEcho, tokElse, tokElseif, tokEmpty, tokEnddeclare, tokEndfor, tokEndforeach, tokEndif, tokEndswitch, tokEndwhile, tokEval, tokExit, tokExtends, tokFinal, tokFor, tokForeach, tokFunction, tokGlobal, tokGoto, tokIf, tokImplements, tokInclude, tokIncludeOnce, tokInstanceof, tokInterface, tokIsset, tokList, tokNamespace, tokNew, tokOrWd, tokPrint, tokPrivate, tokProtected, tokPublic, tokRequire, tokRequireOnce, tokReturn, tokStatic, tokSwitch, tokThrow, tokTry, tokUnset, tokUse, tokVar, tokWhile, tokXorWd] identCI w = try $ do i <- genIdentifierParser when (map toLower i /= w) $ fail "" return i identsCI w = try $ do i <- genIdentifierParser when (map toLower i `notElem` w) $ fail "" return i tokAbstractP = identCI tokAbstract tokAndWdP = identCI tokAndWd tokArrayP = identCI tokArray tokAsP = identCI tokAs tokBreakP = identCI tokBreak tokCaseP = identCI tokCase tokCatchP = identCI tokCatch tokClassP = identCI tokClass tokCloneP = identCI tokClone tokConstP = identCI tokConst tokContinueP = identCI tokContinue tokDeclareP = identCI tokDeclare tokDefaultP = identCI tokDefault tokDieP = identCI tokDie tokDoP = identCI tokDo tokEchoP = identCI tokEcho tokElseifP = identCI tokElseif tokElseP = identCI tokElse tokEmptyP = identCI tokEmpty tokEnddeclareP = identCI tokEnddeclare tokEndforeachP = identCI tokEndforeach tokEndforP = identCI tokEndfor tokEndifP = identCI tokEndif tokEndswitchP = identCI tokEndswitch tokEndwhileP = identCI tokEndwhile tokEvalP = identCI tokEval tokExitP = identCI tokExit tokExtendsP = identCI tokExtends tokFinalP = identCI tokFinal tokForP = identCI tokFor tokForeachP = identCI tokForeach tokFunctionP = identCI tokFunction tokGlobalP = identCI tokGlobal tokGotoP = identCI tokGoto tokIfP = identCI tokIf tokImplementsP = identCI tokImplements tokInstanceofP = identCI tokInstanceof tokInterfaceP = identCI tokInterface tokIssetP = identCI tokIsset tokListP = identCI tokList tokNamespaceP = identCI tokNamespace tokNewP = identCI tokNew tokOrWdP = identCI tokOrWd tokPrintP = identCI tokPrint tokPrivateP = identCI tokPrivate tokProtectedP = identCI tokProtected tokPublicP = identCI tokPublic tokReturnP = identCI tokReturn tokStaticP = identCI tokStatic tokSwitchP = identCI tokSwitch tokThrowP = identCI tokThrow tokTryP = identCI tokTry tokUnsetP = identCI tokUnset tokUseP = identCI tokUse tokVarP = identCI tokVar tokWhileP = identCI tokWhile tokXorWdP = identCI tokXorWd tokCategory = "category" tokCategoryP = identCI tokCategory tokChildren = "children" tokChildrenP = identCI tokChildren tokAttribute = "attribute" tokAttributeP = identCI tokAttribute instance Out HereDoc instance Out NumLit instance Out StrLit
b34b5d51dffc7586cdb8d23e7e7effd6623b15563b277b3b9eaca8cbcadf1a0c
nberger/ring-logger
project.clj
(defproject ring-logger "1.1.1" :description "Log ring requests & responses using your favorite logging backend." :url "-logger" :license {:name "Eclipse Public License" :url "-v10.html"} :deploy-repositories [["releases" :clojars]] :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.logging "1.2.3"]] :profiles {:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :dev {:dependencies [[org.clojure/clojure "1.9.0"] [ring/ring-mock "0.2.0"] [ring/ring-core "1.6.3"] [ring/ring-codec "1.0.0"] [log4j "1.2.16"]] :resource-paths ["test-resources"]}} :plugins [[lein-codox "0.10.3"]] :codox {:source-uri "-logger/blob/master/{filepath}#L{line}"} :repositories {"sonatype-oss-public" "/"} :aliases {"test-all" ["with-profile" "dev,test,1.6:dev,test,1.7:dev,test,1.8:dev,test,1.9" "test"] "check-all" ["with-profile" "1.6:1.7:1.8:1.9" "check"]})
null
https://raw.githubusercontent.com/nberger/ring-logger/193f993ce838c4d9b29eb827c038e02489aee12f/project.clj
clojure
(defproject ring-logger "1.1.1" :description "Log ring requests & responses using your favorite logging backend." :url "-logger" :license {:name "Eclipse Public License" :url "-v10.html"} :deploy-repositories [["releases" :clojars]] :dependencies [[org.clojure/clojure "1.7.0"] [org.clojure/tools.logging "1.2.3"]] :profiles {:1.6 {:dependencies [[org.clojure/clojure "1.6.0"]]} :1.7 {:dependencies [[org.clojure/clojure "1.7.0"]]} :1.8 {:dependencies [[org.clojure/clojure "1.8.0"]]} :1.9 {:dependencies [[org.clojure/clojure "1.9.0"]]} :dev {:dependencies [[org.clojure/clojure "1.9.0"] [ring/ring-mock "0.2.0"] [ring/ring-core "1.6.3"] [ring/ring-codec "1.0.0"] [log4j "1.2.16"]] :resource-paths ["test-resources"]}} :plugins [[lein-codox "0.10.3"]] :codox {:source-uri "-logger/blob/master/{filepath}#L{line}"} :repositories {"sonatype-oss-public" "/"} :aliases {"test-all" ["with-profile" "dev,test,1.6:dev,test,1.7:dev,test,1.8:dev,test,1.9" "test"] "check-all" ["with-profile" "1.6:1.7:1.8:1.9" "check"]})
f558f6c30fa2b922a2d398b5099eed937a5bee40be5cbf0ed1c367d5f621d0af
SNePS/SNePS2
contrad.lisp
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNEBR ; Base : 10 -*- Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : contrad.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $ ;; This file is part of SNePS. $ BEGIN LICENSE$ The contents of this file are subject to the University at Buffalo Public License Version 1.0 ( the " License " ) ; you may ;;; not use this file except in compliance with the License. You ;;; may obtain a copy of the License at ;;; . edu/sneps/Downloads/ubpl.pdf. ;;; Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express ;;; or implied. See the License for the specific language gov ;;; erning rights and limitations under the License. ;;; The Original Code is SNePS 2.8 . ;;; The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . ;;; Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snebr) ; ; ; ============================================================================= ; ; ; ck-contradiction ; ---------------- ; ; ; arguments : newnode - <node> ; context - <context> ; flag - 'ASSERTION | 'SNIP ; ; returns : <node> | ----- ; ; description : Takes as arguments a node (newnode) and a context ; (context) and checks whether newnode contradicts any ; other node in the network. ; If the node contradicts a node in the network then ; the restriction of the contexts are updatted. ; If the contradicted node belongs to the belief space ; defined by context then the user is called ; to solve the contradiction. ; ; Algorithm : In order for a contradiction to exist there must exist ; a node in the network that either is negated by ; newnode node or negates newnode. ; 1 . If there exists a node that negates newnode then ; we look at the node (or nodes) that negate it. 2 . If there exists a node negated by newnode then ; we look at such node. ; ; ; written : jpm 11/09/82 ; modified: njm 10/06/88 ; modified: mrc 10/28/88 modified : flj&hi 8/18/99 modified : scs / flj 6/28/04 ; ; 6/04 Change to call sneps : contradictory - nodes.n instead of negation - or - negated - nd (defun ck-contradiction (newnode context flag) ;; Temporarily, this function calls SNeBR with only the first contradictory node it finds . ;; This agrees with the old ck-contradiction, which assumed that there was only one (let ((contr-nodes (sneps:contradictory-nodes.n newnode))) (sneps:do.ns (contr-nd contr-nodes) (when (and contr-nd (exists-contradiction contr-nd context)) (ck-contradiction-1 newnode contr-nd context flag))) newnode)) (defun ck-contradiction-1 (newnode contr-nd context flag) (let ((contrsup (sneps:ctcs-to-cts (sneps:node-asupport contr-nd)))) (update-contexts (ctcs-to-cts (sneps:node-asupport newnode)) contrsup) (sneps:mark-inconsistent context) (when (and (isassert.n newnode) (isassert.n contr-nd) (not (sneps::context-okinconsistent context))) (if (eq flag 'sneps:assertion) (sneps-contr-handler newnode contr-nd) (snip-contr-handler newnode contr-nd context))) (when (and (isassert.n newnode) (isassert.n contr-nd)) (ok-update-contexts (ctcs-to-cts (sneps:node-asupport newnode)) contrsup) (sneps:mark-okinconsistent context)))) ; ; ============================================================================= ; ; ; negation-or-negated-nd ; ---------------------- ; ; ; arguments : newnode - <node> ; ; returns : <node> | NIL ; ; description : Returns the node in the network that contradicts ; `newnode', if it exists. ; ; Algorithm : In order for a contradiction node to exist there must ; exist a node in the network that either is negated by ; newnode node or negates newnode. ; 1 . If there exists a node that negates newnode then ; we look at the node (or nodes) that negate it. 2 . If there exists a node negated by newnode then ; we look at such node. ; ; ; written : jpm 11/09/82 ; modified: njm 10/06/88 ; ; ; ; (defun negation-or-negated-nd (newnode) (cond ((is-negated newnode) (negator-of newnode)) ((is-negation newnode) (negated-by newnode)) (t nil))) ; ; ; ============================================================================= ; ; ; exists-contradiction ; -------------------- ; ; ; arguments : contr-nd - <node> ; context - <context> ; ; returns : <boolean> ; ; description : ; ; ; written : njm 10/06/88 ; modified: ; ; ; ; (defun exists-contradiction (contr-nd context) (let ((sneps:crntct context)) (declare (special sneps:crntct)) (isassert.n contr-nd))) ; ; ============================================================================= ; ; negator-of ; ---------- ; ; ; arguments : node - <node> ; ; returns : <node> | NIL ; ; description : ; ; ; ; ; written : jpm 11/30/82 ; modified: njm 10/06/88 ; ; ; (defun negator-of (node) (negator-of-1 (nodeset.n node 'arg-))) (defun negator-of-1 (ns) (cond ((isnew.ns ns) nil) ((is-negation (choose.ns ns)) (choose.ns ns)) (t (negator-of-1 (others.ns ns))))) ; ; ============================================================================= ; ; negated-by ; ---------- ; ; ; arguments : node - <node> ; ; returns : <node set> ; ; description : ; ; ; ; ; written : jpm 11/30/82 ; modified: njm 10/06/88 ; ; ; (defun negated-by (node) (choose.ns (nodeset.n node 'arg))) ; ; ============================================================================= ; ; ; is-negated ; ---------- ; ; ; arguments : node - <node> ; ; returns : <boolean> ; ; description : Takes as argument a node and returns T is the node is ; negated and returns () otherwise. ; Uses the auxiliary function is-negated-1. ; ; ; ; ; written : jpm 11/30/82 ; modified: njm 10/06/88 ; ; ; (defun is-negated (n) (is-negated-1 (nodeset.n n 'arg-))) (defun is-negated-1 (ns) (cond ((isnew.ns ns) nil) ((is-negation (choose.ns ns))) (t (is-negated-1 (others.ns ns))))) ; ; ============================================================================= ; ; ; is-negation ; ----------- ; ; ; arguments : node - <node> ; ; returns : <boolean> ; ; description : Takes as argument a node and returns T if the node is ; negating any other node and returns () otherwise. ; ; ; ; ; written : jpm 11/30/82 ; modified: njm 10/06/88 ; ; ; (defun is-negation (n) (and (nodeset.n n 'max) (eq (nodeaccess (choose.ns (nodeset.n n 'max))) 'snepsul::|0|))) ; ; ============================================================================= ; ; ; ck-context-contradiction ; ------------------------ ; ; ; arguments : newct - <context>> ; flag - 'SET-CONTEXT | 'ADD-TO-CONTEXT ; ; returns : T | NIL ; ; description : Takes as argument a context 'newct' and ; checks if it is an inconsistent context. ; If so, it reports the inconsistency to ; the user, and returns T. Otherwise, it returns NIL . ; ; written : ; ; ; (defun ck-inconsistency (newct) (if (sneps:isinconsis.ct newct) (sneps-inconsis-handler newct))) ; ; ============================================================================= ; ; sneps-inconsis-handler ; ---------------------- ; ; ; arguments : ct - <context> ; ; returns : ; ; description : This function takes as argument a context 'ct', which ; is inconsistent, reports this inconsistency to the user , and gives the user two options ( see ; sneps-inconsis-options). ; ; written : ; modified: ; ; ; ; (defun sneps-inconsis-handler (ct) (declare (special sneps:outunit sneps:crntct)) (progn (format sneps:outunit "~%~%~T The context ~S ~ ~%~T that you are trying to build is inconsistent." (context-hyps ct)) (sneps-inconsis-options))) ; ; ============================================================================= ; ; ; sneps-inconsis-options ; ---------------------- ; ; ; arguments : ---- ; ; returns : ---- ; description : Prints two options and reads the user 's choice ; (see read-sneps-inconsis-option). ; ; ; ; written : mrc 10/20/88 ; modified: ; ; ; (defun sneps-inconsis-options () (declare (special sneps:outunit)) (format sneps:outunit "~%~%~%~T You have the following options:~ ~%~T~T 1. [y]es, create the context anyway, knowing that a contradiction is ~ derivable;~ ~%~T~T 2. [n]o,don't create the context.~ ~%~T (please type y or n)") (not (user-says-yes)))
null
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/snebr/contrad.lisp
lisp
Syntax : Common - Lisp ; Package : SNEBR ; Base : 10 -*- This file is part of SNePS. you may not use this file except in compliance with the License. You may obtain a copy of the License at . edu/sneps/Downloads/ubpl.pdf. or implied. See the License for the specific language gov erning rights and limitations under the License. ============================================================================= ck-contradiction ---------------- arguments : newnode - <node> context - <context> flag - 'ASSERTION | 'SNIP returns : <node> | ----- description : Takes as arguments a node (newnode) and a context (context) and checks whether newnode contradicts any other node in the network. If the node contradicts a node in the network then the restriction of the contexts are updatted. If the contradicted node belongs to the belief space defined by context then the user is called to solve the contradiction. Algorithm : In order for a contradiction to exist there must exist a node in the network that either is negated by newnode node or negates newnode. we look at the node (or nodes) that negate it. we look at such node. written : jpm 11/09/82 modified: njm 10/06/88 modified: mrc 10/28/88 Temporarily, this function calls SNeBR with only This agrees with the old ck-contradiction, which assumed ============================================================================= negation-or-negated-nd ---------------------- arguments : newnode - <node> returns : <node> | NIL description : Returns the node in the network that contradicts `newnode', if it exists. Algorithm : In order for a contradiction node to exist there must exist a node in the network that either is negated by newnode node or negates newnode. we look at the node (or nodes) that negate it. we look at such node. written : jpm 11/09/82 modified: njm 10/06/88 ============================================================================= exists-contradiction -------------------- arguments : contr-nd - <node> context - <context> returns : <boolean> description : written : njm 10/06/88 modified: ============================================================================= negator-of ---------- arguments : node - <node> returns : <node> | NIL description : written : jpm 11/30/82 modified: njm 10/06/88 ============================================================================= negated-by ---------- arguments : node - <node> returns : <node set> description : written : jpm 11/30/82 modified: njm 10/06/88 ============================================================================= is-negated ---------- arguments : node - <node> returns : <boolean> description : Takes as argument a node and returns T is the node is negated and returns () otherwise. Uses the auxiliary function is-negated-1. written : jpm 11/30/82 modified: njm 10/06/88 ============================================================================= is-negation ----------- arguments : node - <node> returns : <boolean> description : Takes as argument a node and returns T if the node is negating any other node and returns () otherwise. written : jpm 11/30/82 modified: njm 10/06/88 ============================================================================= ck-context-contradiction ------------------------ arguments : newct - <context>> flag - 'SET-CONTEXT | 'ADD-TO-CONTEXT returns : T | NIL description : Takes as argument a context 'newct' and checks if it is an inconsistent context. If so, it reports the inconsistency to the user, and returns T. Otherwise, it ============================================================================= sneps-inconsis-handler ---------------------- arguments : ct - <context> returns : description : This function takes as argument a context 'ct', which is inconsistent, reports this inconsistency to the sneps-inconsis-options). modified: ============================================================================= sneps-inconsis-options ---------------------- arguments : ---- returns : ---- (see read-sneps-inconsis-option). modified: ~
Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : contrad.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $ $ BEGIN LICENSE$ The contents of this file are subject to the University at Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express The Original Code is SNePS 2.8 . The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snebr) 1 . If there exists a node that negates newnode then 2 . If there exists a node negated by newnode then modified : flj&hi 8/18/99 modified : scs / flj 6/28/04 6/04 Change to call sneps : contradictory - nodes.n instead of negation - or - negated - nd (defun ck-contradiction (newnode context flag) the first contradictory node it finds . that there was only one (let ((contr-nodes (sneps:contradictory-nodes.n newnode))) (sneps:do.ns (contr-nd contr-nodes) (when (and contr-nd (exists-contradiction contr-nd context)) (ck-contradiction-1 newnode contr-nd context flag))) newnode)) (defun ck-contradiction-1 (newnode contr-nd context flag) (let ((contrsup (sneps:ctcs-to-cts (sneps:node-asupport contr-nd)))) (update-contexts (ctcs-to-cts (sneps:node-asupport newnode)) contrsup) (sneps:mark-inconsistent context) (when (and (isassert.n newnode) (isassert.n contr-nd) (not (sneps::context-okinconsistent context))) (if (eq flag 'sneps:assertion) (sneps-contr-handler newnode contr-nd) (snip-contr-handler newnode contr-nd context))) (when (and (isassert.n newnode) (isassert.n contr-nd)) (ok-update-contexts (ctcs-to-cts (sneps:node-asupport newnode)) contrsup) (sneps:mark-okinconsistent context)))) 1 . If there exists a node that negates newnode then 2 . If there exists a node negated by newnode then (defun negation-or-negated-nd (newnode) (cond ((is-negated newnode) (negator-of newnode)) ((is-negation newnode) (negated-by newnode)) (t nil))) (defun exists-contradiction (contr-nd context) (let ((sneps:crntct context)) (declare (special sneps:crntct)) (isassert.n contr-nd))) (defun negator-of (node) (negator-of-1 (nodeset.n node 'arg-))) (defun negator-of-1 (ns) (cond ((isnew.ns ns) nil) ((is-negation (choose.ns ns)) (choose.ns ns)) (t (negator-of-1 (others.ns ns))))) (defun negated-by (node) (choose.ns (nodeset.n node 'arg))) (defun is-negated (n) (is-negated-1 (nodeset.n n 'arg-))) (defun is-negated-1 (ns) (cond ((isnew.ns ns) nil) ((is-negation (choose.ns ns))) (t (is-negated-1 (others.ns ns))))) (defun is-negation (n) (and (nodeset.n n 'max) (eq (nodeaccess (choose.ns (nodeset.n n 'max))) 'snepsul::|0|))) returns NIL . written : (defun ck-inconsistency (newct) (if (sneps:isinconsis.ct newct) (sneps-inconsis-handler newct))) user , and gives the user two options ( see written : (defun sneps-inconsis-handler (ct) (declare (special sneps:outunit sneps:crntct)) (progn (format sneps:outunit "~%~%~T The context ~S ~ ~%~T that you are trying to build is inconsistent." (context-hyps ct)) (sneps-inconsis-options))) description : Prints two options and reads the user 's choice written : mrc 10/20/88 (defun sneps-inconsis-options () (declare (special sneps:outunit)) (format sneps:outunit "~%~%~%~T You have the following options:~ ~%~T~T 1. [y]es, create the context anyway, knowing that a contradiction is ~ ~%~T~T 2. [n]o,don't create the context.~ ~%~T (please type y or n)") (not (user-says-yes)))
7ab724d49437729f9067c9f40b3983859a0ce022e21abdff75403df96abe9dab
trentmaetzold/cs61as
grader.rkt
#lang racket (require racket/sandbox) (provide main) (define-namespace-anchor a) (define (get-evaluator submission-file) (define e (make-module-evaluator `(module m racket (require (planet dyoo/simply-scheme)) (require rackunit rackunit/text-ui) (require (file ,submission-file))) #:allow-for-require (list '(planet dyoo/simply-scheme) 'rackunit 'rackunit/text-ui submission-file))) (e '(define test-map (make-hash))) e) (define (grade assignment-file submission-file questions) (define ns (namespace-anchor->empty-namespace a)) (parameterize ([sandbox-eval-limits '(10 20)] ;; TODO: This is horrendous, why does rackunit need to see if files exist [sandbox-path-permissions (list '(exists "/"))] [current-namespace ns]) (define create-tests (dynamic-require (simplify-path (cleanse-path assignment-file)) 'create-tests)) (define e (get-evaluator submission-file)) (define question-names (map (lambda (name) (string-append name "-tests")) questions)) (define all-names (create-tests e question-names)) (when (null? question-names) (set! question-names all-names)) (for ([q question-names]) (unless (e `(hash-has-key? test-map ,q)) (display (format "Unknown question: ~a\n" q)) (raise 'exit))) (define num-questions (length question-names)) (define num-failed (for/sum ([q question-names]) (display (format "Running tests: ~a\n" q)) (e `(run-tests (hash-ref test-map ,q) 'verbose)))) (if (= num-failed 0) (display (format "All ~a tests passed!\n" (length question-names))) (display (format "Failed ~a out of ~a tests.\n" num-failed (length question-names)))) (/ (- num-questions num-failed) num-questions))) (define (main assignment-file submission-file . args) (define (option? str) (equal? (string-ref str 0) #\-)) (define-values (options questions) (partition option? args)) (define (on-error x) (display (format "An error occurred:\n~a\nMake sure that ~a loads into Racket by typing 'racket ~a'.\n" (exn-message x) submission-file submission-file))) (if (or (member "--quiet" options) (member "-q" options)) (with-handlers ([(lambda (x) (equal? x 'exit)) (lambda (x) (display "-1\n"))] [exn:fail? (lambda (x) (display "-1\n"))]) (define out (open-output-string)) (define result (parameterize ([current-output-port out] [current-error-port out]) (exact->inexact (grade assignment-file submission-file questions)))) (close-output-port out) result) (with-handlers ([(lambda (x) (equal? x 'exit)) void] [exn:fail? on-error]) (exact->inexact (grade assignment-file submission-file questions)))))
null
https://raw.githubusercontent.com/trentmaetzold/cs61as/6e4830786e2c28a26203a4f2046776405af2c10e/homework/grader.rkt
racket
TODO: This is horrendous, why does rackunit need to see if files exist
#lang racket (require racket/sandbox) (provide main) (define-namespace-anchor a) (define (get-evaluator submission-file) (define e (make-module-evaluator `(module m racket (require (planet dyoo/simply-scheme)) (require rackunit rackunit/text-ui) (require (file ,submission-file))) #:allow-for-require (list '(planet dyoo/simply-scheme) 'rackunit 'rackunit/text-ui submission-file))) (e '(define test-map (make-hash))) e) (define (grade assignment-file submission-file questions) (define ns (namespace-anchor->empty-namespace a)) (parameterize ([sandbox-eval-limits '(10 20)] [sandbox-path-permissions (list '(exists "/"))] [current-namespace ns]) (define create-tests (dynamic-require (simplify-path (cleanse-path assignment-file)) 'create-tests)) (define e (get-evaluator submission-file)) (define question-names (map (lambda (name) (string-append name "-tests")) questions)) (define all-names (create-tests e question-names)) (when (null? question-names) (set! question-names all-names)) (for ([q question-names]) (unless (e `(hash-has-key? test-map ,q)) (display (format "Unknown question: ~a\n" q)) (raise 'exit))) (define num-questions (length question-names)) (define num-failed (for/sum ([q question-names]) (display (format "Running tests: ~a\n" q)) (e `(run-tests (hash-ref test-map ,q) 'verbose)))) (if (= num-failed 0) (display (format "All ~a tests passed!\n" (length question-names))) (display (format "Failed ~a out of ~a tests.\n" num-failed (length question-names)))) (/ (- num-questions num-failed) num-questions))) (define (main assignment-file submission-file . args) (define (option? str) (equal? (string-ref str 0) #\-)) (define-values (options questions) (partition option? args)) (define (on-error x) (display (format "An error occurred:\n~a\nMake sure that ~a loads into Racket by typing 'racket ~a'.\n" (exn-message x) submission-file submission-file))) (if (or (member "--quiet" options) (member "-q" options)) (with-handlers ([(lambda (x) (equal? x 'exit)) (lambda (x) (display "-1\n"))] [exn:fail? (lambda (x) (display "-1\n"))]) (define out (open-output-string)) (define result (parameterize ([current-output-port out] [current-error-port out]) (exact->inexact (grade assignment-file submission-file questions)))) (close-output-port out) result) (with-handlers ([(lambda (x) (equal? x 'exit)) void] [exn:fail? on-error]) (exact->inexact (grade assignment-file submission-file questions)))))
45443cbd842668b82388d0a7cf51d2a2c6a62a02aaea86ea7467f284b94406ed
haskell/hoopl
OptSupport.hs
# LANGUAGE CPP , GADTs , RankNTypes # # OPTIONS_GHC -Wall -fno - warn - name - shadowing # module OptSupport (mapVE, mapEE, mapEN, mapVN, fold_EE, fold_EN, insnToG) where import Control.Monad import Data.Maybe import Prelude hiding (succ) import Control.Applicative as AP (Applicative(..)) import Compiler.Hoopl hiding ((<*>)) import IR ---------------------------------------------- -- Map/Fold functions for expressions/insns ---------------------------------------------- type Node = Insn type MaybeChange a = a -> Maybe a mapVE :: (Var -> Maybe Expr) -> MaybeChange Expr mapEE :: MaybeChange Expr -> MaybeChange Expr mapEN :: MaybeChange Expr -> MaybeChange (Node e x) mapVN :: (Var -> Maybe Expr) -> MaybeChange (Node e x) mapVN = mapEN . mapEE . mapVE mapVE f (Var v) = f v mapVE _ _ = Nothing data Mapped a = Old a | New a instance Monad Mapped where return = AP.pure Old a >>= k = k a New a >>= k = asNew (k a) where asNew (Old a) = New a asNew m@(New _) = m instance Functor Mapped where fmap = liftM instance Applicative Mapped where pure = Old (<*>) = ap makeTotal :: (a -> Maybe a) -> (a -> Mapped a) makeTotal f a = case f a of Just a' -> New a' Nothing -> Old a makeTotalDefault :: b -> (a -> Maybe b) -> (a -> Mapped b) makeTotalDefault b f a = case f a of Just b' -> New b' Nothing -> Old b ifNew :: Mapped a -> Maybe a ifNew (New a) = Just a ifNew (Old _) = Nothing type Mapping a b = a -> Mapped b (/@/) :: Mapping b c -> Mapping a b -> Mapping a c f /@/ g = \x -> g x >>= f class HasExpressions a where mapAllSubexpressions :: Mapping Expr Expr -> Mapping a a instance HasExpressions (Insn e x) where mapAllSubexpressions = error "urk!" (mapVars, (/@/), makeTotal, ifNew) mapVars :: (Var -> Maybe Expr) -> Mapping Expr Expr mapVars f e@(Var x) = makeTotalDefault e f x mapVars _ e = return e mapEE f e@(Lit _) = f e mapEE f e@(Var _) = f e mapEE f e@(Load addr) = case mapEE f addr of Just addr' -> Just $ fromMaybe e' (f e') where e' = Load addr' Nothing -> f e mapEE f e@(Binop op e1 e2) = case (mapEE f e1, mapEE f e2) of (Nothing, Nothing) -> f e (e1', e2') -> Just $ fromMaybe e' (f e') where e' = Binop op (fromMaybe e1 e1') (fromMaybe e2 e2') mapEN _ (Label _) = Nothing mapEN f (Assign v e) = liftM (Assign v) $ f e mapEN f (Store addr e) = case (f addr, f e) of (Nothing, Nothing) -> Nothing (addr', e') -> Just $ Store (fromMaybe addr addr') (fromMaybe e e') mapEN _ (Branch _) = Nothing mapEN f (Cond e tid fid) = case f e of Just e' -> Just $ Cond e' tid fid Nothing -> Nothing mapEN f (Call rs n es succ) = if all isNothing es' then Nothing else Just $ Call rs n (map (uncurry fromMaybe) (zip es es')) succ where es' = map f es mapEN f (Return es) = if all isNothing es' then Nothing else Just $ Return (map (uncurry fromMaybe) (zip es es')) where es' = map f es fold_EE :: (a -> Expr -> a) -> a -> Expr -> a fold_EN :: (a -> Expr -> a) -> a -> Insn e x -> a fold_EE f z e@(Lit _) = f z e fold_EE f z e@(Var _) = f z e fold_EE f z e@(Load addr) = f (fold_EE f z addr) e fold_EE f z e@(Binop _ e1 e2) = let afterE1 = fold_EE f z e1 afterE2 = fold_EE f afterE1 e2 in f afterE2 e fold_EN _ z (Label _) = z fold_EN f z (Assign _ e) = f z e fold_EN f z (Store addr e) = f (f z e) addr fold_EN _ z (Branch _) = z fold_EN f z (Cond e _ _) = f z e fold_EN f z (Call _ _ es _) = foldl f z es fold_EN f z (Return es) = foldl f z es ---------------------------------------------- Lift a insn to a ---------------------------------------------- insnToG :: Insn e x -> Graph Insn e x insnToG n@(Label _) = mkFirst n insnToG n@(Assign _ _) = mkMiddle n insnToG n@(Store _ _) = mkMiddle n insnToG n@(Branch _) = mkLast n insnToG n@(Cond _ _ _) = mkLast n insnToG n@(Call _ _ _ _) = mkLast n insnToG n@(Return _) = mkLast n
null
https://raw.githubusercontent.com/haskell/hoopl/89dde6af5b2fadfad726412c00a1ab01d34fd2a0/testing/OptSupport.hs
haskell
-------------------------------------------- Map/Fold functions for expressions/insns -------------------------------------------- -------------------------------------------- --------------------------------------------
# LANGUAGE CPP , GADTs , RankNTypes # # OPTIONS_GHC -Wall -fno - warn - name - shadowing # module OptSupport (mapVE, mapEE, mapEN, mapVN, fold_EE, fold_EN, insnToG) where import Control.Monad import Data.Maybe import Prelude hiding (succ) import Control.Applicative as AP (Applicative(..)) import Compiler.Hoopl hiding ((<*>)) import IR type Node = Insn type MaybeChange a = a -> Maybe a mapVE :: (Var -> Maybe Expr) -> MaybeChange Expr mapEE :: MaybeChange Expr -> MaybeChange Expr mapEN :: MaybeChange Expr -> MaybeChange (Node e x) mapVN :: (Var -> Maybe Expr) -> MaybeChange (Node e x) mapVN = mapEN . mapEE . mapVE mapVE f (Var v) = f v mapVE _ _ = Nothing data Mapped a = Old a | New a instance Monad Mapped where return = AP.pure Old a >>= k = k a New a >>= k = asNew (k a) where asNew (Old a) = New a asNew m@(New _) = m instance Functor Mapped where fmap = liftM instance Applicative Mapped where pure = Old (<*>) = ap makeTotal :: (a -> Maybe a) -> (a -> Mapped a) makeTotal f a = case f a of Just a' -> New a' Nothing -> Old a makeTotalDefault :: b -> (a -> Maybe b) -> (a -> Mapped b) makeTotalDefault b f a = case f a of Just b' -> New b' Nothing -> Old b ifNew :: Mapped a -> Maybe a ifNew (New a) = Just a ifNew (Old _) = Nothing type Mapping a b = a -> Mapped b (/@/) :: Mapping b c -> Mapping a b -> Mapping a c f /@/ g = \x -> g x >>= f class HasExpressions a where mapAllSubexpressions :: Mapping Expr Expr -> Mapping a a instance HasExpressions (Insn e x) where mapAllSubexpressions = error "urk!" (mapVars, (/@/), makeTotal, ifNew) mapVars :: (Var -> Maybe Expr) -> Mapping Expr Expr mapVars f e@(Var x) = makeTotalDefault e f x mapVars _ e = return e mapEE f e@(Lit _) = f e mapEE f e@(Var _) = f e mapEE f e@(Load addr) = case mapEE f addr of Just addr' -> Just $ fromMaybe e' (f e') where e' = Load addr' Nothing -> f e mapEE f e@(Binop op e1 e2) = case (mapEE f e1, mapEE f e2) of (Nothing, Nothing) -> f e (e1', e2') -> Just $ fromMaybe e' (f e') where e' = Binop op (fromMaybe e1 e1') (fromMaybe e2 e2') mapEN _ (Label _) = Nothing mapEN f (Assign v e) = liftM (Assign v) $ f e mapEN f (Store addr e) = case (f addr, f e) of (Nothing, Nothing) -> Nothing (addr', e') -> Just $ Store (fromMaybe addr addr') (fromMaybe e e') mapEN _ (Branch _) = Nothing mapEN f (Cond e tid fid) = case f e of Just e' -> Just $ Cond e' tid fid Nothing -> Nothing mapEN f (Call rs n es succ) = if all isNothing es' then Nothing else Just $ Call rs n (map (uncurry fromMaybe) (zip es es')) succ where es' = map f es mapEN f (Return es) = if all isNothing es' then Nothing else Just $ Return (map (uncurry fromMaybe) (zip es es')) where es' = map f es fold_EE :: (a -> Expr -> a) -> a -> Expr -> a fold_EN :: (a -> Expr -> a) -> a -> Insn e x -> a fold_EE f z e@(Lit _) = f z e fold_EE f z e@(Var _) = f z e fold_EE f z e@(Load addr) = f (fold_EE f z addr) e fold_EE f z e@(Binop _ e1 e2) = let afterE1 = fold_EE f z e1 afterE2 = fold_EE f afterE1 e2 in f afterE2 e fold_EN _ z (Label _) = z fold_EN f z (Assign _ e) = f z e fold_EN f z (Store addr e) = f (f z e) addr fold_EN _ z (Branch _) = z fold_EN f z (Cond e _ _) = f z e fold_EN f z (Call _ _ es _) = foldl f z es fold_EN f z (Return es) = foldl f z es Lift a insn to a insnToG :: Insn e x -> Graph Insn e x insnToG n@(Label _) = mkFirst n insnToG n@(Assign _ _) = mkMiddle n insnToG n@(Store _ _) = mkMiddle n insnToG n@(Branch _) = mkLast n insnToG n@(Cond _ _ _) = mkLast n insnToG n@(Call _ _ _ _) = mkLast n insnToG n@(Return _) = mkLast n
217cfd90c8cd204aa2f2c9de5598b813d1ab253b20dc3f86440159010b21e303
tweag/funflow
Util.hs
# LANGUAGE OverloadedLists # {-# LANGUAGE OverloadedStrings #-} | ' Util ' contains various utility functions used throughout . API.Client 's internals . module Docker.API.Client.Internal.Util where import Control.Monad.IO.Class (MonadIO) import Data.Binary.Get (getWord32be, getWord8, runGet) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Conduit (ConduitT, await, yield) import qualified Data.Conduit.Tar as Tar import qualified Data.Text as T import Docker.API.Client.Internal.Schemas (CreateContainer (..), HostConfig (..)) import Docker.API.Client.Internal.Types (ContainerLogType (..), ContainerSpec (..), DockerStreamType (..)) import System.Posix.Types (GroupID, UserID) | ( Internal only , do not export ) Converts a client ContainerSpec into the format expected by the docker api containerSpecToCreateContainer :: ContainerSpec -> CreateContainer containerSpecToCreateContainer spec = CreateContainer { createContainerUser = textToMaybe $ user spec, createContainerWorkingDir = textToMaybe $ workingDir spec, createContainerEnv = listToMaybe $ envVars spec, createContainerImage = image spec, createContainerCmd = listToMaybe $ cmd spec, createContainerHostConfig = convertHostVolumes $ hostVolumes spec } where textToMaybe t = if not $ T.null t then Just t else Nothing listToMaybe l = if not $ null l then Just l else Nothing convertHostVolumes hvs = if null hvs then Nothing else Just HostConfig {hostConfigBinds = Just hvs} -- | Conduit helper which checks the length of the input bytestring and reads data from upstream until the length is at least nBytes . Note that this method may return a Bytestring result which has length > = nBytes . readUpstream :: Monad m => B.ByteString -> Int -> ConduitT B.ByteString o m (Maybe B.ByteString) readUpstream acc nBytes = if B.length acc >= nBytes then do return $ Just acc else do result <- await case result of Nothing -> return Nothing Just val -> readUpstream (B.concat [acc, val]) nBytes | Parses the first byte from a stream metadata bytestring returned by the Docker Engine API -- and returns the corresponding stream type. getStreamType :: B.ByteString -> DockerStreamType getStreamType meta | indicator == 0 = DockerStreamStdIn | indicator == 1 = DockerStreamStdOut | indicator == 2 = DockerStreamStdErr | otherwise = error "Unrecognized stream type in docker engine response" where indicator = runGet getWord8 (LBS.fromStrict meta) | Converts an 8 byte section length ByteString into an integer . This value indicates the number of data bytes in the body of a Docker Engine stream record . getSectionLength :: B.ByteString -> Int getSectionLength = fromIntegral . runGet getWord32be . LBS.fromStrict | Parses a docker metadata bytestring of length > = 8 into it 's individual components -- See /#operation/ContainerAttach parseDockerStream :: B.ByteString -> (DockerStreamType, Int, B.ByteString) parseDockerStream bytes = let parts = splitToParts bytes streamType = getStreamType $ fst parts sectionLength = getSectionLength $ fst $ snd parts dataBytes = snd $ snd parts in (streamType, sectionLength, dataBytes) where splitToParts b = (B.singleton $ B.head b, B.splitAt 4 $ snd $ B.splitAt 4 b) | Conduit for parsing a multiplexed stream from the Docker Engine API ( e.g. the output of the attatch and logs endpoints ) . This will force memory usage up to the returned frame size ( for docker logs this is usually just one line of text ) . See /#operation/ContainerAttach for more details on this format . parseMultiplexedDockerStream :: MonadIO m => ConduitT B.ByteString (DockerStreamType, B.ByteString) m () parseMultiplexedDockerStream = loop B.empty where loop acc = do -- This whole thing could be recursive This ensures that we get at least 8 bytes ( could be more ) input <- readUpstream acc 8 case input of Nothing -> return () Just meta -> do let (streamType, sectionLength, dataBytes) = parseDockerStream meta -- This ensures that we have at least as much data as our section (could be more) section <- readUpstream dataBytes sectionLength case section of Nothing -> return () Just s -> do let (expectedBytes, additionalBytes) = B.splitAt sectionLength s yield (streamType, expectedBytes) loop additionalBytes | Creates a DockerStreamType filter using the input ContainerLogType createLogTypeFilter :: ContainerLogType -> ((DockerStreamType, a) -> Bool) createLogTypeFilter clt = case clt of Stdout -> \(t, _) -> case t of DockerStreamStdOut -> True _ -> False StdErr -> \(t, _) -> case t of DockerStreamStdErr -> True _ -> False Both -> \(t, _) -> case t of _ -> True -- | Replaces the user and group id for an entry in a tarball with the specified user and group chownTarballContent :: UserID -> GroupID -> Tar.FileInfo -> Tar.FileInfo chownTarballContent uid gid info = info { Tar.fileUserName = "", Tar.fileUserId = uid, Tar.fileGroupName = "", Tar.fileGroupId = gid }
null
https://raw.githubusercontent.com/tweag/funflow/e273cfa83a45eaa640305e1cfb51fc707ab4b8bf/docker-client/src/Docker/API/Client/Internal/Util.hs
haskell
# LANGUAGE OverloadedStrings # | Conduit helper which checks the length of the input bytestring and reads data from upstream and returns the corresponding stream type. See /#operation/ContainerAttach This whole thing could be recursive This ensures that we have at least as much data as our section (could be more) | Replaces the user and group id for an entry in a tarball with the specified user and group
# LANGUAGE OverloadedLists # | ' Util ' contains various utility functions used throughout . API.Client 's internals . module Docker.API.Client.Internal.Util where import Control.Monad.IO.Class (MonadIO) import Data.Binary.Get (getWord32be, getWord8, runGet) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LBS import Data.Conduit (ConduitT, await, yield) import qualified Data.Conduit.Tar as Tar import qualified Data.Text as T import Docker.API.Client.Internal.Schemas (CreateContainer (..), HostConfig (..)) import Docker.API.Client.Internal.Types (ContainerLogType (..), ContainerSpec (..), DockerStreamType (..)) import System.Posix.Types (GroupID, UserID) | ( Internal only , do not export ) Converts a client ContainerSpec into the format expected by the docker api containerSpecToCreateContainer :: ContainerSpec -> CreateContainer containerSpecToCreateContainer spec = CreateContainer { createContainerUser = textToMaybe $ user spec, createContainerWorkingDir = textToMaybe $ workingDir spec, createContainerEnv = listToMaybe $ envVars spec, createContainerImage = image spec, createContainerCmd = listToMaybe $ cmd spec, createContainerHostConfig = convertHostVolumes $ hostVolumes spec } where textToMaybe t = if not $ T.null t then Just t else Nothing listToMaybe l = if not $ null l then Just l else Nothing convertHostVolumes hvs = if null hvs then Nothing else Just HostConfig {hostConfigBinds = Just hvs} until the length is at least nBytes . Note that this method may return a Bytestring result which has length > = nBytes . readUpstream :: Monad m => B.ByteString -> Int -> ConduitT B.ByteString o m (Maybe B.ByteString) readUpstream acc nBytes = if B.length acc >= nBytes then do return $ Just acc else do result <- await case result of Nothing -> return Nothing Just val -> readUpstream (B.concat [acc, val]) nBytes | Parses the first byte from a stream metadata bytestring returned by the Docker Engine API getStreamType :: B.ByteString -> DockerStreamType getStreamType meta | indicator == 0 = DockerStreamStdIn | indicator == 1 = DockerStreamStdOut | indicator == 2 = DockerStreamStdErr | otherwise = error "Unrecognized stream type in docker engine response" where indicator = runGet getWord8 (LBS.fromStrict meta) | Converts an 8 byte section length ByteString into an integer . This value indicates the number of data bytes in the body of a Docker Engine stream record . getSectionLength :: B.ByteString -> Int getSectionLength = fromIntegral . runGet getWord32be . LBS.fromStrict | Parses a docker metadata bytestring of length > = 8 into it 's individual components parseDockerStream :: B.ByteString -> (DockerStreamType, Int, B.ByteString) parseDockerStream bytes = let parts = splitToParts bytes streamType = getStreamType $ fst parts sectionLength = getSectionLength $ fst $ snd parts dataBytes = snd $ snd parts in (streamType, sectionLength, dataBytes) where splitToParts b = (B.singleton $ B.head b, B.splitAt 4 $ snd $ B.splitAt 4 b) | Conduit for parsing a multiplexed stream from the Docker Engine API ( e.g. the output of the attatch and logs endpoints ) . This will force memory usage up to the returned frame size ( for docker logs this is usually just one line of text ) . See /#operation/ContainerAttach for more details on this format . parseMultiplexedDockerStream :: MonadIO m => ConduitT B.ByteString (DockerStreamType, B.ByteString) m () parseMultiplexedDockerStream = loop B.empty where loop acc = do This ensures that we get at least 8 bytes ( could be more ) input <- readUpstream acc 8 case input of Nothing -> return () Just meta -> do let (streamType, sectionLength, dataBytes) = parseDockerStream meta section <- readUpstream dataBytes sectionLength case section of Nothing -> return () Just s -> do let (expectedBytes, additionalBytes) = B.splitAt sectionLength s yield (streamType, expectedBytes) loop additionalBytes | Creates a DockerStreamType filter using the input ContainerLogType createLogTypeFilter :: ContainerLogType -> ((DockerStreamType, a) -> Bool) createLogTypeFilter clt = case clt of Stdout -> \(t, _) -> case t of DockerStreamStdOut -> True _ -> False StdErr -> \(t, _) -> case t of DockerStreamStdErr -> True _ -> False Both -> \(t, _) -> case t of _ -> True chownTarballContent :: UserID -> GroupID -> Tar.FileInfo -> Tar.FileInfo chownTarballContent uid gid info = info { Tar.fileUserName = "", Tar.fileUserId = uid, Tar.fileGroupName = "", Tar.fileGroupId = gid }
eb142bfa215a901839eab462ba5ca5a3c0898a78b85e1d69933cc1488d2bb2e5
hyperfiddle/electric
datasync1.cljc
(ns dustin.datasync1 (:require [hyperfiddle.api :as hf] [hyperfiddle.incremental :refer [fmapI capI bindI]] [minitest :refer [tests]] [missionary.core :as m] [datascript.core :as d] [dustin.fiddle :as f] [dustin.compiler2 :refer [dataflow log! source-map replay!]])) (declare something-else) we want to make two reactors communicate over wire ; communicate info about what happens at arbitrary points of ast (defn render [xs] [:table [:tr xs] #_(rfor [x :db/id xs] [:tr (pr-str x)])]) (tests (render []) := [:table [:tr []]]) (defn submissions [$ needle] (binding [hf/*$* $] (f/submissions needle))) (defn query-route [>$ [f & args :as route]] (case f dustin.fiddle/submissions (let [[needle] args] (fmapI #(submissions % needle) >$)) (m/watch (atom 404)))) (defn router [>$ >route] (fmapI render (bindI >route #(query-route >$ %)))) ;;;;;;;;;;;;; GENERIC ; ; ;;;;;;;;;;;;; (tests (def ast '(fmap render (bind >route qr))) (def sm (source-map ast)) (first (sm '>route)) := 2 (first (sm '(bind >route qr))) := 1 ) (tests (def !route (atom nil)) (def !$ (atom hf/*$*)) (def >route (m/watch !route)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)))) (def !trace (log! d)) (reset! !route ['dustin.fiddle/submissions "alice"]) (submissions hf/*$* "alice") := '(9) @!trace := [{[2] ['dustin.fiddle/submissions "alice"] [1] '(9) [0] [:table [:tr '(9)]]}] ) ;;;;;;;;;;;; ;; CLIENT ;; ;;;;;;;;;;;; (tests (def !route (atom nil)) (def !$ (atom hf/*$*)) (def >route (m/watch !route)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)) #{1} ;; bind )) (def !trace (log! d)) (reset! !route ['dustin.fiddle/submissions "alice"]) ;; set by client (replay! d {[1] '(9)}) @!trace := [{[2] ['dustin.fiddle/submissions "alice"]} {[1] '(9) [0] [:table [:tr '(9)]]}] ) ;;;;;;;;;;;; ;; SERVER ;; ;;;;;;;;;;;; (tests ;; (def !route (atom nil)) ;; (def >route (m/watch !route)) (def !$ (atom hf/*$*)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)) #{0 2} ;; (fmap render …) and >route passive )) (def !trace (log! d)) (reset! !route ['dustin.fiddle/submissions "alice"]) ;; set by client (replay! d {[2] ['dustin.fiddle/submissions "alice"]}) @!trace := [{[2] ['dustin.fiddle/submissions "alice"] [1] '(9)}] ) (comment (query-route >$ ['dustin.fiddle/submissions "alice"]) (capI *1) := [9] (router >$ >route) (capI *1) := [:table [:tr [9]]] (do (reset! !$ (:db-after (d/with @!$ [{:dustingetz/email "" :dustingetz/gender :dustingetz/male :dustingetz/shirt-size :dustingetz/mens-large}]))) nil) (router >$ >route) (capI *1) := [:table [:tr [9]]] )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/datasync1.cljc
clojure
communicate info about what happens at arbitrary points of ast ; CLIENT ;; bind set by client SERVER ;; (def !route (atom nil)) (def >route (m/watch !route)) (fmap render …) and >route passive set by client
(ns dustin.datasync1 (:require [hyperfiddle.api :as hf] [hyperfiddle.incremental :refer [fmapI capI bindI]] [minitest :refer [tests]] [missionary.core :as m] [datascript.core :as d] [dustin.fiddle :as f] [dustin.compiler2 :refer [dataflow log! source-map replay!]])) (declare something-else) we want to make two reactors communicate over wire (defn render [xs] [:table [:tr xs] #_(rfor [x :db/id xs] [:tr (pr-str x)])]) (tests (render []) := [:table [:tr []]]) (defn submissions [$ needle] (binding [hf/*$* $] (f/submissions needle))) (defn query-route [>$ [f & args :as route]] (case f dustin.fiddle/submissions (let [[needle] args] (fmapI #(submissions % needle) >$)) (m/watch (atom 404)))) (defn router [>$ >route] (fmapI render (bindI >route #(query-route >$ %)))) (tests (def ast '(fmap render (bind >route qr))) (def sm (source-map ast)) (first (sm '>route)) := 2 (first (sm '(bind >route qr))) := 1 ) (tests (def !route (atom nil)) (def !$ (atom hf/*$*)) (def >route (m/watch !route)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)))) (def !trace (log! d)) (reset! !route ['dustin.fiddle/submissions "alice"]) (submissions hf/*$* "alice") := '(9) @!trace := [{[2] ['dustin.fiddle/submissions "alice"] [1] '(9) [0] [:table [:tr '(9)]]}] ) (tests (def !route (atom nil)) (def !$ (atom hf/*$*)) (def >route (m/watch !route)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)) )) (def !trace (log! d)) (replay! d {[1] '(9)}) @!trace := [{[2] ['dustin.fiddle/submissions "alice"]} {[1] '(9) [0] [:table [:tr '(9)]]}] ) (tests (def !$ (atom hf/*$*)) (def >$ (m/watch !$)) (def qr (partial query-route >$)) (def d (dataflow (fmap render (bind >route qr)) )) (def !trace (log! d)) (replay! d {[2] ['dustin.fiddle/submissions "alice"]}) @!trace := [{[2] ['dustin.fiddle/submissions "alice"] [1] '(9)}] ) (comment (query-route >$ ['dustin.fiddle/submissions "alice"]) (capI *1) := [9] (router >$ >route) (capI *1) := [:table [:tr [9]]] (do (reset! !$ (:db-after (d/with @!$ [{:dustingetz/email "" :dustingetz/gender :dustingetz/male :dustingetz/shirt-size :dustingetz/mens-large}]))) nil) (router >$ >route) (capI *1) := [:table [:tr [9]]] )
58c01ae606c602b5c48687f763defa1e0605d0296bf3026a283d3a8e631080ad
kazu-yamamoto/llrbtree
Heap.hs
# LANGUAGE CPP , TemplateHaskell # module Main where import qualified Data.List as L #if METHOD == 1 import Data.Heap.Splay #elif METHOD == 2 import Data.Heap.Skew #elif METHOD == 3 import Data.Heap.Binominal #elif METHOD == 4 import Data.Heap.Leftist #else import Data.Heap.Splay #endif import Test.Framework.TH.Prime import Test.Framework.Providers.DocTest.Prime import Test.Framework.Providers.QuickCheck2 main :: IO () main = $(defaultMainGenerator) doc_test :: DocTests #if METHOD == 1 doc_test = docTest ["../Data/Heap/Splay.hs"] ["-i.."] #elif METHOD == 2 doc_test = docTest ["../Data/Heap/Skew.hs"] ["-i.."] #elif METHOD == 3 doc_test = docTest ["../Data/Heap/Binominal.hs"] ["-i.."] #elif METHOD == 4 doc_test = docTest ["../Data/Heap/Leftist.hs"] ["-i.."] #else doc_test = docTest ["../Data/Heap/Splay.hs"] ["-i.."] #endif prop_fromList :: [Int] -> Bool prop_fromList xs = valid $ fromList xs prop_toList :: [Int] -> Bool prop_toList xs = length (toList (fromList xs)) == length xs prop_deleteMin :: [Int] -> Bool prop_deleteMin [] = True prop_deleteMin xs = valid t' where t = fromList xs t' = deleteMin t prop_deleteMin2 :: [Int] -> Bool prop_deleteMin2 [] = True prop_deleteMin2 xs = ys == zs where t = fromList xs t' = deleteMin t ys = heapSort t' zs = tail . L.sort $ xs prop_merge :: [Int] -> Bool prop_merge [] = True prop_merge (x:xs) = valid $ merge (fromList ys) (fromList zs) where ys = filter (<x) xs zs = filter (>x) xs
null
https://raw.githubusercontent.com/kazu-yamamoto/llrbtree/36f259e36c2b320aa37bbbae9577e01fd8a27118/test/Heap.hs
haskell
# LANGUAGE CPP , TemplateHaskell # module Main where import qualified Data.List as L #if METHOD == 1 import Data.Heap.Splay #elif METHOD == 2 import Data.Heap.Skew #elif METHOD == 3 import Data.Heap.Binominal #elif METHOD == 4 import Data.Heap.Leftist #else import Data.Heap.Splay #endif import Test.Framework.TH.Prime import Test.Framework.Providers.DocTest.Prime import Test.Framework.Providers.QuickCheck2 main :: IO () main = $(defaultMainGenerator) doc_test :: DocTests #if METHOD == 1 doc_test = docTest ["../Data/Heap/Splay.hs"] ["-i.."] #elif METHOD == 2 doc_test = docTest ["../Data/Heap/Skew.hs"] ["-i.."] #elif METHOD == 3 doc_test = docTest ["../Data/Heap/Binominal.hs"] ["-i.."] #elif METHOD == 4 doc_test = docTest ["../Data/Heap/Leftist.hs"] ["-i.."] #else doc_test = docTest ["../Data/Heap/Splay.hs"] ["-i.."] #endif prop_fromList :: [Int] -> Bool prop_fromList xs = valid $ fromList xs prop_toList :: [Int] -> Bool prop_toList xs = length (toList (fromList xs)) == length xs prop_deleteMin :: [Int] -> Bool prop_deleteMin [] = True prop_deleteMin xs = valid t' where t = fromList xs t' = deleteMin t prop_deleteMin2 :: [Int] -> Bool prop_deleteMin2 [] = True prop_deleteMin2 xs = ys == zs where t = fromList xs t' = deleteMin t ys = heapSort t' zs = tail . L.sort $ xs prop_merge :: [Int] -> Bool prop_merge [] = True prop_merge (x:xs) = valid $ merge (fromList ys) (fromList zs) where ys = filter (<x) xs zs = filter (>x) xs
0ce4ff47aa87c8cd3b1dce14c98ab6ec14fb284fafb857d6624251d1eef69a21
barrel-db/barrel
create_delete_database_eqc.erl
@author < > ( C ) 2017 , %%% @doc %%% %%% @end Created : 19 Jul 2017 by < > -module(create_delete_database_eqc). -include_lib("eqc/include/eqc.hrl"). -compile(export_all). prop_create_delete_database() -> ?SETUP(fun common_eqc:init_db/0, ?FORALL(DBS, non_empty(list(common_eqc:ascii_string())), begin L = length( barrel:database_names()), [begin {ok, #{<<"database_id">> := Id}} = barrel:create_database(#{<<"database_id">> => Id}), barrel:post(Id, #{<<"id">> => <<"1234">>,<<"content">> => <<"A">>}, #{}), ok = barrel:delete_database(Id), {error, db_not_found} = barrel:post(Id, #{<<"id">> => <<"1234">>,<<"content">> => <<"A">>}, #{}) end|| Id <- DBS], L1 = length( barrel:database_names()), L == L1 end)).
null
https://raw.githubusercontent.com/barrel-db/barrel/1695ca4cfe821808526f9ecb2e019bc1b8eff48e/eqc/create_delete_database_eqc.erl
erlang
@doc @end
@author < > ( C ) 2017 , Created : 19 Jul 2017 by < > -module(create_delete_database_eqc). -include_lib("eqc/include/eqc.hrl"). -compile(export_all). prop_create_delete_database() -> ?SETUP(fun common_eqc:init_db/0, ?FORALL(DBS, non_empty(list(common_eqc:ascii_string())), begin L = length( barrel:database_names()), [begin {ok, #{<<"database_id">> := Id}} = barrel:create_database(#{<<"database_id">> => Id}), barrel:post(Id, #{<<"id">> => <<"1234">>,<<"content">> => <<"A">>}, #{}), ok = barrel:delete_database(Id), {error, db_not_found} = barrel:post(Id, #{<<"id">> => <<"1234">>,<<"content">> => <<"A">>}, #{}) end|| Id <- DBS], L1 = length( barrel:database_names()), L == L1 end)).
ac94b036f8bb2fa4d618afe97ee946307b1555fbc77890e02547758ae25e189c
ocaml-obuild/obuild
prog.ml
open Ext.Fugue open Ext.Filepath open Ext exception OCamlProgramError of string exception TarError of string exception PkgConfigError of string exception PkgConfigErrorNoVersion exception PkgConfigErrorUnexpectedOutput of string exception ProgramNotFound of string let get_cache prog names = let res = Gconf.get_env prog in match res with | Some p -> p | None -> try let syspath = Utils.get_system_paths () in let found = list_findmap (fun n -> let n = if Utils.isWindows then (n ^ ".exe") else n in if Filename.is_implicit n then (try let found_path = Utils.find_in_paths syspath (fn n) in Some (fp_to_string (found_path </> fn n)) with Utils.FileNotFoundInPaths _ -> None) else (if Filesystem.exists (fp n) then Some n else None) ) names in Gconf.set_env prog found; found with Not_found -> raise (ProgramNotFound prog) let getOcamlOpt () = get_cache "ocamlopt" ["ocamlopt.opt"; "ocamlopt"] let getOcamlC () = get_cache "ocamlc" ["ocamlc.opt"; "ocamlc"] let getOcamlDep () = get_cache "ocamldep" ["ocamldep.opt"; "ocamldep"] let getOcamlDoc () = get_cache "ocamldoc" ["ocamldoc.opt"; "ocamldoc"] let getOcamlYacc ()= get_cache "ocamlyacc" ["ocamlyacc"] let getOcamlLex () = get_cache "ocamllex" ["ocamllex.opt"; "ocamllex"] let getOcamlMklib () = get_cache "ocamlmklib" ["ocamlmklib"] let getCamlp4 () = get_cache "camlp4" ["camlp4"] let getCC () = get_cache "cc" ["gcc"] let getRanlib () = get_cache "ranlib" ["ranlib"] let getAR () = get_cache "ar" ["ar"] let getLD () = get_cache "ld" ["ld"] let getPkgConfig() = get_cache "pkg-config" ["pkg-config"] let getOcaml () = get_cache "ocaml" ["ocaml"] let getOcamlMktop () = get_cache "ocamlmktop" ["ocamlmktop"] let getAtdGen () = get_cache "atdgen" ["atdgen"; "atdgen.run"] let get_ocaml_version cfg = let ver = Hashtbl.find cfg "version" in match string_split ~limit:3 '.' ver with | [major;minor;other] -> (major,minor,other) | _ -> raise (OCamlProgramError ("ocaml return an unknown version " ^ ver)) let ocaml_config = ref None let getOcamlConfig () = match !ocaml_config with | None -> (match Process.run [ getOcamlC (); "-config" ] with | Process.Success (s,_,_) -> let lines = string_lines_noempty s in let h = Hashtbl.create 32 in List.iter (fun l -> let (k,v) = Utils.toKV l in Hashtbl.add h k (default "" v) ) lines; ocaml_config := Some h; h | Process.Failure err -> raise (OCamlProgramError ("ocamlc cannot get config " ^ err))) | Some h -> h let getCamlp4Config () = match Process.run [ getCamlp4 (); "-where" ] with | Process.Success (s,_,_) -> let (l:_) = string_lines_noempty s in l | Process.Failure err -> raise (OCamlProgramError ("ocamlopt cannot get config " ^ err)) let runTar output dir = match Process.run [ "tar"; "czf"; output; dir ] with | Process.Success _ -> () | Process.Failure err -> raise (TarError err) let runPkgConfig typ name = match Process.run [ getPkgConfig (); typ; name ] with | Process.Success (s,_,_) -> s | Process.Failure err -> raise (PkgConfigError err) let runPkgConfigVersion name = let output = runPkgConfig "--version" name in match string_words_noempty output with | [ver] -> ver | [] -> raise PkgConfigErrorNoVersion | _ -> raise (PkgConfigErrorUnexpectedOutput ("version: " ^ output)) let runPkgConfigIncludes name = let output = runPkgConfig "--cflags" name in (* FIXME check if every items actually got -L as expected *) List.map (string_drop 2) (string_words_noempty output) let runPkgConfigLibs name = let output = runPkgConfig "--libs" name in (* FIXME check if every items actually got -l as expected *) List.map (string_drop 2) (string_words_noempty output)
null
https://raw.githubusercontent.com/ocaml-obuild/obuild/28252e8cee836448e85bfbc9e09a44e7674dae39/obuild/prog.ml
ocaml
FIXME check if every items actually got -L as expected FIXME check if every items actually got -l as expected
open Ext.Fugue open Ext.Filepath open Ext exception OCamlProgramError of string exception TarError of string exception PkgConfigError of string exception PkgConfigErrorNoVersion exception PkgConfigErrorUnexpectedOutput of string exception ProgramNotFound of string let get_cache prog names = let res = Gconf.get_env prog in match res with | Some p -> p | None -> try let syspath = Utils.get_system_paths () in let found = list_findmap (fun n -> let n = if Utils.isWindows then (n ^ ".exe") else n in if Filename.is_implicit n then (try let found_path = Utils.find_in_paths syspath (fn n) in Some (fp_to_string (found_path </> fn n)) with Utils.FileNotFoundInPaths _ -> None) else (if Filesystem.exists (fp n) then Some n else None) ) names in Gconf.set_env prog found; found with Not_found -> raise (ProgramNotFound prog) let getOcamlOpt () = get_cache "ocamlopt" ["ocamlopt.opt"; "ocamlopt"] let getOcamlC () = get_cache "ocamlc" ["ocamlc.opt"; "ocamlc"] let getOcamlDep () = get_cache "ocamldep" ["ocamldep.opt"; "ocamldep"] let getOcamlDoc () = get_cache "ocamldoc" ["ocamldoc.opt"; "ocamldoc"] let getOcamlYacc ()= get_cache "ocamlyacc" ["ocamlyacc"] let getOcamlLex () = get_cache "ocamllex" ["ocamllex.opt"; "ocamllex"] let getOcamlMklib () = get_cache "ocamlmklib" ["ocamlmklib"] let getCamlp4 () = get_cache "camlp4" ["camlp4"] let getCC () = get_cache "cc" ["gcc"] let getRanlib () = get_cache "ranlib" ["ranlib"] let getAR () = get_cache "ar" ["ar"] let getLD () = get_cache "ld" ["ld"] let getPkgConfig() = get_cache "pkg-config" ["pkg-config"] let getOcaml () = get_cache "ocaml" ["ocaml"] let getOcamlMktop () = get_cache "ocamlmktop" ["ocamlmktop"] let getAtdGen () = get_cache "atdgen" ["atdgen"; "atdgen.run"] let get_ocaml_version cfg = let ver = Hashtbl.find cfg "version" in match string_split ~limit:3 '.' ver with | [major;minor;other] -> (major,minor,other) | _ -> raise (OCamlProgramError ("ocaml return an unknown version " ^ ver)) let ocaml_config = ref None let getOcamlConfig () = match !ocaml_config with | None -> (match Process.run [ getOcamlC (); "-config" ] with | Process.Success (s,_,_) -> let lines = string_lines_noempty s in let h = Hashtbl.create 32 in List.iter (fun l -> let (k,v) = Utils.toKV l in Hashtbl.add h k (default "" v) ) lines; ocaml_config := Some h; h | Process.Failure err -> raise (OCamlProgramError ("ocamlc cannot get config " ^ err))) | Some h -> h let getCamlp4Config () = match Process.run [ getCamlp4 (); "-where" ] with | Process.Success (s,_,_) -> let (l:_) = string_lines_noempty s in l | Process.Failure err -> raise (OCamlProgramError ("ocamlopt cannot get config " ^ err)) let runTar output dir = match Process.run [ "tar"; "czf"; output; dir ] with | Process.Success _ -> () | Process.Failure err -> raise (TarError err) let runPkgConfig typ name = match Process.run [ getPkgConfig (); typ; name ] with | Process.Success (s,_,_) -> s | Process.Failure err -> raise (PkgConfigError err) let runPkgConfigVersion name = let output = runPkgConfig "--version" name in match string_words_noempty output with | [ver] -> ver | [] -> raise PkgConfigErrorNoVersion | _ -> raise (PkgConfigErrorUnexpectedOutput ("version: " ^ output)) let runPkgConfigIncludes name = let output = runPkgConfig "--cflags" name in List.map (string_drop 2) (string_words_noempty output) let runPkgConfigLibs name = let output = runPkgConfig "--libs" name in List.map (string_drop 2) (string_words_noempty output)
66bbcc75b0b959e4682b742125f261b7fc0ac885b9ab932a6157a433f8caa551
GaloisInc/daedalus
MemoSearch.hs
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # # LANGUAGE DataKinds # module Talos.Strategy.MemoSearch ( memoSearch , randRestartPolicy , randDFSPolicy , randAccelDFSPolicy , BacktrackPolicy(..) ) where import Control.Lens import Control.Monad.Reader (runReaderT) import Control.Monad.State import Control.Monad.Trans.Free import Control.Monad.Trans.Writer.CPS import Data.Foldable (foldl', foldlM, toList, fold) import Data.Functor (($>)) import Data.Generics.Product (field) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Merge.Lazy as Map import Data.Maybe (maybeToList, fromMaybe) import Data.Monoid (Any (Any), First (First), getAny, getFirst) import Data.Set (Set) import qualified Data.Set as Set import GHC.Generics (Generic) import SimpleSMT (SExpr, ppSExpr) import qualified SimpleSMT as SMT import Daedalus.Core (Name, Typed (..), casePats, caseVar, nameId) import Daedalus.Core.Free (freeVars) import Daedalus.PP (Doc, block, bullets, hang, parens, pp, ppPrec, showPP, text) import Daedalus.Panic (panic) import Daedalus.Rec (Rec (..), forgetRecs) import Talos.Analysis.Exported (ExpSlice, SliceId, ecnSliceId) import Talos.Analysis.Slice (Slice' (..)) import Talos.Strategy.Monad (LiftStrategyM, StrategyM, isRecVar, randR) import Talos.Strategy.SearchTree (Location) import qualified Talos.Strategy.SearchTree as ST import Talos.Strategy.SymbolicM hiding (inSolver) import Talos.SymExec.SemiExpr (SemiSExpr) import Talos.SymExec.SemiValue (SemiValue (..)) import Talos.SymExec.SolverT (SMTVar, SolverContext, SolverFrame, SolverT, collapseContext, extendContext, freshContext, freshSymbol, getContext, instantiateSolverFrame, restoreContext, substSExpr) import Talos.SymExec.Type (symExecTy) -------------------------------------------------------------------------------- Memoization -- -- The idea here is to share solutions across the search space. -- Consider code like -- -- x = P a -- y = block -- let w = G -- Guard (p w) -- ^ w -- z = Q b -- Guard (g x z) -- -- If the guard g x z fails, then we may have to backtrack to x, and -- then proceed forward again. Without memoisation, this would require the solver to re - discover solutions for y s.t . p y , which -- may be expensive. -- -- We associate solutions with the variables which binds them, so when -- we have 'x = R a b c' we consult the memo table for x. This is -- more fine-grained than memoing at the function level, although that -- may be simpler. -- -- To memoize, we note that the solution for a grammar 'R a b c' is -- dependent on the values of a, b, and c, along with any context -- constraining these variables. We want to share the solution to 'R a b c ' , so the first thing we do is find solutions in the empty -- context: this over-approximates the set of solutions, but allows us -- to avoid over-constraining the solution through outside assertions -- (which may come through other parts of the grammar via transitive SMT constraints ) . -- -- We wish to take advantage of information we have about the free -- variables, at least the information we have in the value -- environment (i.e., not the solver environment). In particular, -- knowing which sum type variant a variable is makes e.g. case much -- simpler. Thus, we don't want to abstract over the variables entirely . Conversely , having the SMT variables ( in the value -- environment) be fresh means when we are figuring out whether we can -- re-use a solution we don't need to worry about overlap of variables -- between the orignal environment (the one used to find the solution) -- and the new environment. Overlap may happen, for example, if we are re - using a solution where only some ( or no ) have changed . -- Fresh variables also means we do n't need to unify SExprs . -- One wrinkle is that we can not memo recursive functions as the -- recursive call would occur in the solution for itself. Notes : -- -- - Proving outside the context means we have to do a lot of -- pushing/popping, which may be expensive (and negate the gain of -- memoing). -- -- - Proving outside the context means we also have to check the -- solution after we find it, as instantiating it may further -- constrain bound variables which leads to unsat constraints. -- - In a related note , abstracting the structure of the SMT portion -- of the environment may also lead to unsat constraints. -- Ideas: -- - We could ignore 'unimportant' variables, although slicing -- should do most of that already(?) -------------------------------------------------------------------------------- -- Unification of SemiSExprs -- -- The idea here is that solutions are shared between different - environments , where the environments are unifiable at the SMTVar -- level. This is more general than using the index of the solution -- for each free variable, as multiple solutions may have the same -- value (but, e.g., different constraints). By using unification we -- can share solutions between solutions of free variables which have -- the same shape. Note that this means we also don't need a solution -- ID for each free variable, which may not exist in e.g. recursive -- calls where we unfold terms rather than memoize. -- -- In addition, if we have sequential uses of a grammar like -- -- ys = Many { let y = P x; Q y } -- -- different iterations can share the same instance for y, although we will need to make sure that any ( new ) SMT variables are renamed . -- FIXME: we should name every computation, even terminal ones -- (e.g. P -> x = P; ^ x). type Unifier = Map SMTVar SExpr emptyUnifier :: Unifier emptyUnifier = Map.empty -- Makes sure that we don't bind the same variable twice. We only -- need to worry about this if we repeat variables in the environment, which currently we do n't do ( we replace every ' ' by a fresh -- variable) --- probably we can just the Monoid inst. for maps, but -- this is clearer. mergeUnifiers :: Unifier -> Unifier -> Maybe Unifier mergeUnifiers = Map.mergeA Map.preserveMissing Map.preserveMissing (Map.zipWithAMatched (\_k x y -> guard (x == y) $> x)) mergeUnifierss :: [Unifier] -> Maybe Unifier mergeUnifierss = foldlM mergeUnifiers emptyUnifier -- This is allowed to be incomplete, e.g. for maps. We can also assume type safety. unifySemiSExprs :: SemiValue SMTVar -> SemiSExpr -> Maybe Unifier unifySemiSExprs orig new = case (orig, new) of (VValue v1, VValue v2) -> guard (v1 == v2) $> emptyUnifier (VOther v, VOther s2) -> Just (Map.singleton v (typedThing s2)) (VUnionElem l1 se1, VUnionElem l2 se2) | l1 == l2 -> unifySemiSExprs se1 se2 | otherwise -> Nothing -- FIXME: we assume labels are in the same order (VStruct fs1, VStruct fs2) -> unifys (map snd fs1) (map snd fs2) (VSequence _b1 vs1, VSequence _b2 vs2) -> unifys vs1 vs2 (VMaybe m_v1, VMaybe m_v2) -> join (unifySemiSExprs <$> m_v1 <*> m_v2) -- We require the keys to be in the same order, which is not -- strictly necessary. (VMap kvs1, VMap kvs2) -> unifys2 kvs1 kvs2 (VIterator kvs1, VIterator kvs2) -> unifys2 kvs1 kvs2 _ -> Nothing where unifys xs ys = do guard (length xs == length ys) mergeUnifierss =<< zipWithM unifySemiSExprs xs ys unifys2 kvs1 kvs2 = let (ks1, vs1) = unzip kvs1 (ks2, vs2) = unzip kvs2 in join (mergeUnifiers <$> unifys ks1 ks2 <*> unifys vs1 vs2) unifyEnvs :: SolutionEnv -> SymVarEnv -> Maybe Unifier unifyEnvs s1 s2 = doMerge s1 s2 >>= mergeUnifierss . Map.elems where doMerge = Map.mergeA panicOnMissing Map.dropMissing (Map.zipWithAMatched (const unifySemiSExprs)) panicOnMissing = Map.mapMissing (\k _ -> panic "Missing key" [showPP k]) -------------------------------------------------------------------------------- -- Instance management SMT Context management -- ====================== -- -- The SMT API in SolverT has the freshContext / getContext / restoreContext ops . These are used during -- regular backtracking to decouple the solver state from where we are -- in the grammar. With the addition of memoisation, we need to be -- able to generate new solutions in the solution's context, and then -- continue in the requestors context, plus extras from the solution. -- When we generate a solution , we also export the SMT context that we -- have when the solution is found (i.e., all the bits that we need). As we start with the empty context for memo'd variables , this -- context contains only the bits from the corresponding grammar, and -- needs to be appended to the context of the caller, and checked for -- satisfiability (as we may make inconsistent assumptions in the -- solution). -- -- We do all context management here so it isn't spread through the -- code (and so we could inspect it instead of it being implicit in the monadic code ) . Note that the first time we enter a memo node -- the code _will_ set up the context. data Solution = Solution { sValue :: SemiSExpr , sPathBuilder :: PathBuilder , sCtxFrame :: SolverFrame } type SolutionEnv = Map Name (SemiValue SMTVar) -- Proposition: Given a solution S for monad M under env E, we can get -- a solution S' for M under E' where S' = subst t S and E and E' are unified by t , where t contains SMT variables . data MemoInstance = MemoInstance { miVarShape :: SolutionEnv -- We could also leave the solutions (and failures) in the search tree and store a parallel search tree in the ( instead of the nseen Int ) . That way we avoid just using the found solutions -- (although finding existing solutions might be tricky, hence this -- approach). , miSolutions :: [Solution] , miUnexplored :: Maybe Location' } -- This will allocate the symbols, but not add them to the solver context. nameSExprs :: SemiSExpr -> WriterT (Map SMTVar (Typed SExpr)) MemoM (SemiValue (Typed SMTVar)) nameSExprs = traverse nameOne where nameOne se = do sym <- lift . inSolver $ freshSymbol "memo" tell (Map.singleton sym se) pure (se {typedThing = sym}) _ppUnifier :: Unifier -> Doc _ppUnifier m = bullets [ text k <> " -> " <> text (ppSExpr v "") | (k, v) <- Map.toList m ] addMemoInstance :: Name -> SymVarEnv -> SymbolicM Result -> MemoM (MemoIdx, Unifier) addMemoInstance n e m = do fvs <- gets ((Map.! n) . frees) Replace all SExprs in e with fresh ( SMT ) variables (sole, vmap) <- runWriterT (traverse nameSExprs (Map.restrictKeys e fvs)) sc <- inSolver $ freshContext (Map.toList (symExecTy . typedType <$> vmap)) turn a SolutionEnv into a SymbolicEnv ( i.e. , turn vars into sexprs ) e' = fmap (fmap (fmap SMT.const)) sole We run with the empty path , env . env' = emptySymbolicEnv { sVarEnv = e' All free vars have empty . , sVarDeps = Set.empty <$ e' } -- We reset the context and declare the new variables m' = runReaderT (getSymbolicM m) env' mi = MemoInstance { miVarShape = fmap (fmap typedThing) sole , miSolutions = [] , miUnexplored = Just (ST.empty (sc, m')) } u = typedThing <$> vmap liftIO $ print ( hang ( " Add memo instance for " < > pp n ) 4 ( pp sc ) ) liftIO $ print ( hang " Unifier " 4 ( ppUnifier u ) ) m_old <- field @"memos" %%= Map.insertLookupWithKey (\_ -> flip (<>)) n [mi] We return the index of the new MemoInstance , which is at the end -- of any existing instances. pure (maybe 0 length m_old, u) findMemoInstance :: Name -> SymVarEnv -> MemoM (Maybe (MemoIdx, Unifier)) findMemoInstance n e = uses (field @"memos" . at n) (go =<<) where go = getFirst . ifoldMap (\i m -> First $ (,) i <$> unifyEnvs (miVarShape m) e) memoIdx :: Name -> SymVarEnv -> SymbolicM Result -> MemoM (MemoIdx, Unifier) memoIdx n e m = do m_res <- findMemoInstance n e case m_res of Just r -> pure r Nothing -> addMemoInstance n e m -- This is the main worker: we want to generate another solution. memoGen :: MemoInstance -> MemoM (Maybe Solution, MemoInstance) memoGen mi | Just loc <- miUnexplored mi = do (m_r, m_loc) <- memoLocation loc -- FIXME: for now we discard the cids, we don't keep a pointer -- in Solution to where the solution came from if we want to use -- the cids to generate more. let mk_soln (r, _cids, p) = do fr <- inSolver (collapseContext =<< getContext) pure Solution { sValue = r , sPathBuilder = p , sCtxFrame = fr } m_soln <- traverse mk_soln m_r let mi' = mi { miUnexplored = m_loc , miSolutions = miSolutions mi <> maybeToList m_soln } pure (m_soln, mi') | otherwise = pure (Nothing, mi) -- Gets another solution, may do a whole bunch of work to find it. -- FIXME: parameterise by no. attempts? -- FIXME: who is responsible for doing the check? nextSolution :: ChoiceId -> MemoTagInfo -> Int -> MemoM (Maybe (SolverContext, SearchT' Result)) nextSolution cid mti nseen = do m_mi <- preuse (field @"memos" . ix (mtiName mti) . ix (mtiIdx mti)) let mi = case m_mi of Nothing -> panic "Missing MemoInstance" [] Just r -> r m_soln <- case miSolutions mi ^? ix nseen of Just soln -> pure (Just soln) Nothing -> do (r, mi') <- memoGen mi field @"memos" . ix (mtiName mti) . ix (mtiIdx mti) .= mi' pure r case m_soln of Nothing -> pure Nothing Just soln -> do -- Make all vars in the context fresh so we don't clash -- with other instances. We also instantiate the unifier -- we got from matching the memoinst. env. (fr', u') <- inSolver $ instantiateSolverFrame (mtiUnifier mti) (sCtxFrame soln) liftIO $ print ( hang ( " Found memo instance for " < > pp n ) 4 ( bullets [ pp sc , pp ( sCtxFrame ) , pp fr ' ] ) ) -- We need to instantiate all the vars in the path as well. -- fmaps because: PathBuilderF ( SemiValue ( Typed < here > ) ) let path' = fmap (fmap (fmap (substSExpr u'))) <$> sPathBuilder soln v' = fmap (substSExpr u') <$> sValue soln sc' = extendContext (mtiSolverContext mti) fr' -- Note that to get another choice for n we need to look -- at this node. cids = Set.singleton cid pure (Just (sc', mtiRHS mti (v', cids, path'))) NestTag _ n Nothing _ m - > pure ( tag , Nothing ) -- NestTag n (Just loc) m -> do sc < - inSolver getContext ( m_r , m_loc ' ) < - memoLocation loc let tag ' = NestTag n m_loc ' m -- mk r = (sc, m r) -- pure (tag', mk <$> m_r) -------------------------------------------------------------------------------- -- Backtracking policy data BacktrackPolicy = BacktrackPolicy { btsChoose :: Location' -> MemoM (Maybe Location') -- ^ Called When we see a choose node , btsReenter :: Location' -> MemoM (Maybe Location') ^ Called when we need to get more solutions from a memo'd var , in -- the parent of the last successful node. , btsBacktrack :: BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') -- ^ Called when we need another solutino, in the parent of the last -- successful node. If we just exhausted all the options, we pass -- Nothing as the reason. } memoChoose :: Location' -> MemoM (Maybe Location') memoChoose loc = do bts <- gets policy btsChoose bts loc memoBacktrack :: BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') memoBacktrack reason pathToHere loc = do bts <- gets policy btsBacktrack bts reason pathToHere loc memoReenter :: Location' -> MemoM (Maybe Location') memoReenter loc = do bts <- gets policy btsReenter bts loc -------------------------------------------------------------------------------- Monad and State -- This is the state that is shared across the entire search space -- (i.e., it isn't local to a path). type MemoIdx = Int data MemoTagInfo = MemoTagInfo { mtiName :: Name , mtiIdx :: MemoIdx , mtiUnifier :: Unifier , mtiDeps :: (BacktrackReason, Set ChoiceId) , mtiSolverContext :: SolverContext , mtiRHS :: Result -> SearchT' Result } data SearchTag = FixedTag (Set ChoiceId) -- ^ The only choices are the ones we have seen | MemoTag MemoTagInfo Int -- ^ The tag info and no. solutions seen. -- | NestTag Name (Maybe Location') (Result -> SearchT' Result) -- -- ^ An inlined bind node, where the name is used for backtracking. -- -- Doing it this way means we can't backtrack outside of the nested -- -- node when exploring it (or at least, not easily). The -- SolverContext is the one that is inside the Location ' type SearchTree ' = SearchTree ( SolverContext , ' Result ) SearchTag type Location' = Location (SolverContext, SearchT' Result) (ChoiceId, SearchTag) data MemoState = MemoState We could associate the SymbolidM here with the name , but we -- always have it when we need to extend memos (i.e., when we see a ) . memos :: Map Name [MemoInstance] -- Read only , frees :: Map Name (Set Name) , shouldMemoVars :: Set Name -- ^ These variables are complex enough that memoisation make sense. , policy :: BacktrackPolicy } deriving (Generic) newtype MemoM a = MemoM { _getMemoM :: StateT MemoState (SolverT StrategyM) a } deriving (Functor, Applicative, Monad, MonadState MemoState, LiftStrategyM, MonadIO) inSolver :: SolverT StrategyM a -> MemoM a inSolver = MemoM . lift runMemoM :: Map Name (Set Name) -> Set Name -> BacktrackPolicy -> MemoM a -> SolverT StrategyM a runMemoM fs sm bts (MemoM m) = evalStateT m st0 where st0 = MemoState { memos = mempty , frees = fs , shouldMemoVars = sm , policy = bts } -------------------------------------------------------------------------------- -- Top-level entry point for the memo search strat. ppSetName :: Set Name -> Doc ppSetName e = block "{" ", " "}" (map ppN (Set.toList e)) where ppN n = ppPrec 1 n <> parens (pp (nameId n)) memoSearch :: BacktrackPolicy -> SearchStrat memoSearch bts = SearchStrat $ \sls@(rootSlice, deps) m -> do let fs = buildFreeMap (rootSlice : map snd (forgetRecs deps)) sm = buildShouldMemo sls liftIO $ print ( hang " Should memo : " 4 ( ppSetName sm ) ) sc <- getContext fst <$> runMemoM fs sm bts (memoLocation (ST.empty (sc, m))) buildFreeMap :: [ExpSlice] -> Map Name (Set Name) buildFreeMap = execWriter . mapM_ go where go sl = do let dflt = pure (freeVars sl) case sl of SHole -> dflt SPure {} -> dflt SDo x lsl rsl -> do lfs <- go lsl rfs <- go rsl let fs = lfs `Set.union` Set.delete x rfs tell (Map.singleton x fs) pure fs SMatch {} -> dflt SChoice sls -> mconcat <$> mapM go sls SCall {} -> dflt SCase _ c -> Set.insert (caseVar c) . mconcat <$> traverse go (toList c) -- We don't care about the inverse function when dealing with -- slice deps. (it should only be used when turning a val into -- bytes later on). SInverse n _ifn p -> pure (Set.delete n (freeVars p)) -- FIXME: we don't really care that we have a Location', we could -- generalise and let the policy figure it out. memoLocation :: Location' -> MemoM (Maybe Result, Maybe Location') memoLocation loc = m_go =<< memoReenter loc where m_go = maybe (pure (Nothing, Nothing)) go -- Just check that we arrived at an unexplored loc. go loc' | ST.Unexplored (sc, m) <- ST.locTree loc' = do MemoM . lift $ restoreContext sc next loc' m | otherwise = panic "Expecting to be at an unexplored node" [] next :: Location' -> SearchT' Result -> MemoM (Maybe Result, Maybe Location') next loc' m = do r <- MemoM . lift $ runFreeT (getSearchT m) case r of Free (Choose cid pathToHere ms) -> do sc' <- inSolver getContext let ms' = map ((,) sc' . SearchT) ms m_go =<< memoChoose (ST.replaceUnexplored (cid, FixedTag pathToHere) ms' loc') Free (Backtrack reason pathToFailure) -> m_go =<< maybe (pure Nothing) (memoBacktrack reason pathToFailure) (ST.forgetGoUp loc') Free (Bind n e lhs rhs) -> memoNodeMaybe loc' n e lhs (SearchT <$> rhs) =<< shouldMemo n Pure r' -> pure (Just r', ST.forgetGoUp loc') memoNodeMaybe loc' n e lhs rhs' True = do (i, u) <- memoIdx n (sVarEnv e) lhs sc' <- inSolver getContext deps <- mkDeps n e let mti = MemoTagInfo { mtiName = n , mtiIdx = i , mtiUnifier = u , mtiDeps = deps , mtiSolverContext = sc' , mtiRHS = rhs' } tag = MemoTag mti 0 cid <- freshChoiceId m_go =<< memoChoose (ST.replaceUnexplored (cid, tag) [] loc') memoNodeMaybe loc' _n e lhs rhs' False = next loc' (runReaderT (getSymbolicM lhs) e >>= rhs') If we fail to find a solution in the memo'd slice , then there -- is no solution there irrespective of the solver context, so we -- can pick a different dep to get (maybe) a solution. mkDeps :: Name -> SymbolicEnv -> MemoM (BacktrackReason, Set ChoiceId) mkDeps n e = do fvs <- gets ((Map.! n) . frees) pure (ConcreteFailure $ fold (Map.restrictKeys (sVarDeps e) fvs) , mconcat (sPath e)) -------------------------------------------------------------------------------- -- Memoisation policy -- -- Memoisation can be expensive, as we do a whole bunch of context manipulation . If the lhs of a bind does n't branch , then there is -- no real reason to memoize the bound variable, and so we try to -- determine if a slice never branches so we only memo 'interesting' -- slices. -- FIXME: we could deal with e.g. case by having each variable state -- under which circumstances the grammar doesn't branch, e.g. if we have -- -- case x of -- A -> ... -- B -> ... -- -- then if we know that the head of x is concrete, we can inline -- without missing memo opportunities. shouldMemo :: Name -> MemoM Bool shouldMemo n = do isRec <- isRecVar n memo <- gets (Set.member n . shouldMemoVars) pure (memo && not isRec) buildShouldMemo :: (ExpSlice, [ Rec (SliceId, ExpSlice) ]) -> Set Name buildShouldMemo (rootSlice, deps) = snd (shouldMemoSlice trivialSlices rootSlice) <> depNames where (trivialSlices, depNames) = foldl' go mempty deps go (ts, dns) (NonRec (sid, sl)) = let (Any memo, dns') = shouldMemoSlice ts sl in (if memo then ts else Set.insert sid ts, dns <> dns') -- FIXME: we just assume recursive functions are non-trivial and so calls should be memo'd . go (ts, dns) (MutRec recs) = let (_, dns') = foldMap (shouldMemoSlice ts . snd) recs in (ts, dns <> dns') -- c.f. Exported.sliceToRecVars shouldMemoSlice :: Set SliceId -> ExpSlice -> (Any, Set Name) shouldMemoSlice trivialSlices = go where go :: ExpSlice -> (Any, Set Name) go sl = case sl of SHole -> mempty SPure {} -> mempty SDo x l r -> let (l_br, ls) = go l (r_br, rs) = go r in ( l_br <> r_br , ls <> rs <> (if getAny l_br then Set.singleton x else mempty) ) SMatch {} -> mempty SChoice cs -> (Any True, snd (foldMap go cs)) SCall cn -> (Any $ not (ecnSliceId cn `Set.member` trivialSlices), mempty) -- We have some leeway with case: mostly it will be concrete, so -- we could assume that it is deterministic; we could also -- produce essentially a strictness analysis which says what we -- need on the input for the slice to be deterministic; finally -- we can treat it like choice, which is what we do here. SCase _ cs | length (casePats cs) <= 1 -> foldMap go cs | otherwise -> (Any True, snd (foldMap go cs)) SInverse {} -> mempty -------------------------------------------------------------------------------- -- Policies -- FIXME: move btFindUnexplored :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btFindUnexplored pol = go where go loc | ST.Unexplored {} <- ST.locTree loc = pure (Just loc) go loc = do m_loc' <- btsChoose pol loc maybe (pure Nothing) go m_loc' Random restart randRestartPolicy :: BacktrackPolicy randRestartPolicy = BacktrackPolicy { btsChoose = btChooseRand randRestartPolicy , btsReenter = btReenterRestart randRestartPolicy , btsBacktrack = \_ _ -> btReenterRestart randRestartPolicy } btReenterRestart :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btReenterRestart pol = go . moveToRoot where -- Go to the top of the tree after forgetting the current node. moveToRoot = ST.maximally ST.upward -- Find something to do, starting at the root. go :: Location' -> MemoM (Maybe Location') go = btFindUnexplored pol -- | 1-step choice, backtracking if the current node is empty. btChooseRand :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btChooseRand pol loc = case ST.locTree loc of ST.Unexplored {} -> pure (Just loc) ST.Node (_cid, FixedTag pathToHere) [] -> maybe (pure Nothing) (btsBacktrack pol OtherFailure pathToHere) (ST.forgetGoUp loc) ST.Node (cid, MemoTag mti nseen) [] -> do m_r <- nextSolution cid mti nseen case m_r of Just r -> do -- FIXME: this seems to be the wrong place to be messing with -- nseen etc. let tag' = MemoTag mti (nseen + 1) -- FIXME: this is gross let loc' = loc { ST.locTree = ST.Node (cid, tag') [ST.Unexplored r] } pure (ST.downward 0 loc') -- No more solutions, we need to backtrack. -- FIXME: we could look at e.g. the free variables here to get the cids Nothing -> let bt = uncurry (btsBacktrack pol) (mtiDeps mti) in maybe (pure Nothing) bt (ST.forgetGoUp loc) -- Prefer existing solutions. ST.Node _ sts -> do i <- randR (0, length sts - 1) pure (ST.downward i loc) Random DFS randDFSPolicy :: BacktrackPolicy randDFSPolicy = BacktrackPolicy { btsChoose = btChooseRand randDFSPolicy , btsReenter = btLocalBacktrack randDFSPolicy , btsBacktrack = \_ _ -> btLocalBacktrack randDFSPolicy } Random DFS Accelerated randAccelDFSPolicy :: BacktrackPolicy randAccelDFSPolicy = BacktrackPolicy { btsChoose = btChooseRand randDFSPolicy , btsReenter = btLocalBacktrack randDFSPolicy , btsBacktrack = btAcceleratedBacktrack randDFSPolicy } btLocalBacktrack :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btLocalBacktrack = btFindUnexplored -- This takes into account the choices. btAcceleratedBacktrack :: BacktrackPolicy -> BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') -- FIXME: could we do better here? btAcceleratedBacktrack pol OtherFailure _pathToFailure loc = btLocalBacktrack pol loc -- There are a whole bunch of btAcceleratedBacktrack pol (ConcreteFailure dataCids) pathToFailure loc = go loc where cids = dataCids <> pathToFailure We search backwards for the first CID that will change the -- outcome. Everything between there and the start can be -- pruned as it is unsatisfiable. go loc' = case ST.locTree loc' of ST.Unexplored {} -> pure (Just loc') ST.Node (_cid, FixedTag {}) [] -> maybe (pure Nothing) go (ST.forgetGoUp loc') ST.Node (cid, _tag) _ms | cid `Set.member` cids -> btFindUnexplored pol loc' | otherwise -> maybe (pure Nothing) go (ST.forgetGoUp loc')
null
https://raw.githubusercontent.com/GaloisInc/daedalus/f9e3fb93656a087c9e1f45b18f012db704890499/talos/src/Talos/Strategy/MemoSearch.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ The idea here is to share solutions across the search space. Consider code like x = P a y = block let w = G Guard (p w) ^ w z = Q b Guard (g x z) If the guard g x z fails, then we may have to backtrack to x, and then proceed forward again. Without memoisation, this would may be expensive. We associate solutions with the variables which binds them, so when we have 'x = R a b c' we consult the memo table for x. This is more fine-grained than memoing at the function level, although that may be simpler. To memoize, we note that the solution for a grammar 'R a b c' is dependent on the values of a, b, and c, along with any context constraining these variables. We want to share the solution to 'R context: this over-approximates the set of solutions, but allows us to avoid over-constraining the solution through outside assertions (which may come through other parts of the grammar via transitive We wish to take advantage of information we have about the free variables, at least the information we have in the value environment (i.e., not the solver environment). In particular, knowing which sum type variant a variable is makes e.g. case much simpler. Thus, we don't want to abstract over the variables environment) be fresh means when we are figuring out whether we can re-use a solution we don't need to worry about overlap of variables between the orignal environment (the one used to find the solution) and the new environment. Overlap may happen, for example, if we recursive call would occur in the solution for itself. - Proving outside the context means we have to do a lot of pushing/popping, which may be expensive (and negate the gain of memoing). - Proving outside the context means we also have to check the solution after we find it, as instantiating it may further constrain bound variables which leads to unsat constraints. of the environment may also lead to unsat constraints. Ideas: - We could ignore 'unimportant' variables, although slicing should do most of that already(?) ------------------------------------------------------------------------------ Unification of SemiSExprs The idea here is that solutions are shared between different level. This is more general than using the index of the solution for each free variable, as multiple solutions may have the same value (but, e.g., different constraints). By using unification we can share solutions between solutions of free variables which have the same shape. Note that this means we also don't need a solution ID for each free variable, which may not exist in e.g. recursive calls where we unfold terms rather than memoize. In addition, if we have sequential uses of a grammar like ys = Many { let y = P x; Q y } different iterations can share the same instance for y, although we FIXME: we should name every computation, even terminal ones (e.g. P -> x = P; ^ x). Makes sure that we don't bind the same variable twice. We only need to worry about this if we repeat variables in the environment, variable) --- probably we can just the Monoid inst. for maps, but this is clearer. This is allowed to be incomplete, e.g. for maps. We can also assume type safety. FIXME: we assume labels are in the same order We require the keys to be in the same order, which is not strictly necessary. ------------------------------------------------------------------------------ Instance management ====================== The SMT API in SolverT has the regular backtracking to decouple the solver state from where we are in the grammar. With the addition of memoisation, we need to be able to generate new solutions in the solution's context, and then continue in the requestors context, plus extras from the solution. have when the solution is found (i.e., all the bits that we need). context contains only the bits from the corresponding grammar, and needs to be appended to the context of the caller, and checked for satisfiability (as we may make inconsistent assumptions in the solution). We do all context management here so it isn't spread through the code (and so we could inspect it instead of it being implicit in the code _will_ set up the context. Proposition: Given a solution S for monad M under env E, we can get a solution S' for M under E' where S' = subst t S and E and E' are We could also leave the solutions (and failures) in the search (although finding existing solutions might be tricky, hence this approach). This will allocate the symbols, but not add them to the solver context. We reset the context and declare the new variables of any existing instances. This is the main worker: we want to generate another solution. FIXME: for now we discard the cids, we don't keep a pointer in Solution to where the solution came from if we want to use the cids to generate more. Gets another solution, may do a whole bunch of work to find it. FIXME: parameterise by no. attempts? FIXME: who is responsible for doing the check? Make all vars in the context fresh so we don't clash with other instances. We also instantiate the unifier we got from matching the memoinst. env. We need to instantiate all the vars in the path as well. fmaps because: Note that to get another choice for n we need to look at this node. NestTag n (Just loc) m -> do mk r = (sc, m r) pure (tag', mk <$> m_r) ------------------------------------------------------------------------------ Backtracking policy ^ Called When we see a choose node the parent of the last successful node. ^ Called when we need another solutino, in the parent of the last successful node. If we just exhausted all the options, we pass Nothing as the reason. ------------------------------------------------------------------------------ This is the state that is shared across the entire search space (i.e., it isn't local to a path). ^ The only choices are the ones we have seen ^ The tag info and no. solutions seen. | NestTag Name (Maybe Location') (Result -> SearchT' Result) -- ^ An inlined bind node, where the name is used for backtracking. -- Doing it this way means we can't backtrack outside of the nested -- node when exploring it (or at least, not easily). The SolverContext is the one that is inside the Location ' always have it when we need to extend memos (i.e., when we see Read only ^ These variables are complex enough that memoisation make sense. ------------------------------------------------------------------------------ Top-level entry point for the memo search strat. We don't care about the inverse function when dealing with slice deps. (it should only be used when turning a val into bytes later on). FIXME: we don't really care that we have a Location', we could generalise and let the policy figure it out. Just check that we arrived at an unexplored loc. is no solution there irrespective of the solver context, so we can pick a different dep to get (maybe) a solution. ------------------------------------------------------------------------------ Memoisation policy Memoisation can be expensive, as we do a whole bunch of context no real reason to memoize the bound variable, and so we try to determine if a slice never branches so we only memo 'interesting' slices. FIXME: we could deal with e.g. case by having each variable state under which circumstances the grammar doesn't branch, e.g. if we have case x of A -> ... B -> ... then if we know that the head of x is concrete, we can inline without missing memo opportunities. FIXME: we just assume recursive functions are non-trivial and c.f. Exported.sliceToRecVars We have some leeway with case: mostly it will be concrete, so we could assume that it is deterministic; we could also produce essentially a strictness analysis which says what we need on the input for the slice to be deterministic; finally we can treat it like choice, which is what we do here. ------------------------------------------------------------------------------ Policies FIXME: move Go to the top of the tree after forgetting the current node. Find something to do, starting at the root. | 1-step choice, backtracking if the current node is empty. FIXME: this seems to be the wrong place to be messing with nseen etc. FIXME: this is gross No more solutions, we need to backtrack. FIXME: we could look at e.g. the free variables here to get the cids Prefer existing solutions. This takes into account the choices. FIXME: could we do better here? There are a whole bunch of outcome. Everything between there and the start can be pruned as it is unsatisfiable.
# LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # # LANGUAGE DataKinds # module Talos.Strategy.MemoSearch ( memoSearch , randRestartPolicy , randDFSPolicy , randAccelDFSPolicy , BacktrackPolicy(..) ) where import Control.Lens import Control.Monad.Reader (runReaderT) import Control.Monad.State import Control.Monad.Trans.Free import Control.Monad.Trans.Writer.CPS import Data.Foldable (foldl', foldlM, toList, fold) import Data.Functor (($>)) import Data.Generics.Product (field) import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Map.Merge.Lazy as Map import Data.Maybe (maybeToList, fromMaybe) import Data.Monoid (Any (Any), First (First), getAny, getFirst) import Data.Set (Set) import qualified Data.Set as Set import GHC.Generics (Generic) import SimpleSMT (SExpr, ppSExpr) import qualified SimpleSMT as SMT import Daedalus.Core (Name, Typed (..), casePats, caseVar, nameId) import Daedalus.Core.Free (freeVars) import Daedalus.PP (Doc, block, bullets, hang, parens, pp, ppPrec, showPP, text) import Daedalus.Panic (panic) import Daedalus.Rec (Rec (..), forgetRecs) import Talos.Analysis.Exported (ExpSlice, SliceId, ecnSliceId) import Talos.Analysis.Slice (Slice' (..)) import Talos.Strategy.Monad (LiftStrategyM, StrategyM, isRecVar, randR) import Talos.Strategy.SearchTree (Location) import qualified Talos.Strategy.SearchTree as ST import Talos.Strategy.SymbolicM hiding (inSolver) import Talos.SymExec.SemiExpr (SemiSExpr) import Talos.SymExec.SemiValue (SemiValue (..)) import Talos.SymExec.SolverT (SMTVar, SolverContext, SolverFrame, SolverT, collapseContext, extendContext, freshContext, freshSymbol, getContext, instantiateSolverFrame, restoreContext, substSExpr) import Talos.SymExec.Type (symExecTy) Memoization require the solver to re - discover solutions for y s.t . p y , which a b c ' , so the first thing we do is find solutions in the empty SMT constraints ) . entirely . Conversely , having the SMT variables ( in the value are re - using a solution where only some ( or no ) have changed . Fresh variables also means we do n't need to unify SExprs . One wrinkle is that we can not memo recursive functions as the Notes : - In a related note , abstracting the structure of the SMT portion - environments , where the environments are unifiable at the SMTVar will need to make sure that any ( new ) SMT variables are renamed . type Unifier = Map SMTVar SExpr emptyUnifier :: Unifier emptyUnifier = Map.empty which currently we do n't do ( we replace every ' ' by a fresh mergeUnifiers :: Unifier -> Unifier -> Maybe Unifier mergeUnifiers = Map.mergeA Map.preserveMissing Map.preserveMissing (Map.zipWithAMatched (\_k x y -> guard (x == y) $> x)) mergeUnifierss :: [Unifier] -> Maybe Unifier mergeUnifierss = foldlM mergeUnifiers emptyUnifier unifySemiSExprs :: SemiValue SMTVar -> SemiSExpr -> Maybe Unifier unifySemiSExprs orig new = case (orig, new) of (VValue v1, VValue v2) -> guard (v1 == v2) $> emptyUnifier (VOther v, VOther s2) -> Just (Map.singleton v (typedThing s2)) (VUnionElem l1 se1, VUnionElem l2 se2) | l1 == l2 -> unifySemiSExprs se1 se2 | otherwise -> Nothing (VStruct fs1, VStruct fs2) -> unifys (map snd fs1) (map snd fs2) (VSequence _b1 vs1, VSequence _b2 vs2) -> unifys vs1 vs2 (VMaybe m_v1, VMaybe m_v2) -> join (unifySemiSExprs <$> m_v1 <*> m_v2) (VMap kvs1, VMap kvs2) -> unifys2 kvs1 kvs2 (VIterator kvs1, VIterator kvs2) -> unifys2 kvs1 kvs2 _ -> Nothing where unifys xs ys = do guard (length xs == length ys) mergeUnifierss =<< zipWithM unifySemiSExprs xs ys unifys2 kvs1 kvs2 = let (ks1, vs1) = unzip kvs1 (ks2, vs2) = unzip kvs2 in join (mergeUnifiers <$> unifys ks1 ks2 <*> unifys vs1 vs2) unifyEnvs :: SolutionEnv -> SymVarEnv -> Maybe Unifier unifyEnvs s1 s2 = doMerge s1 s2 >>= mergeUnifierss . Map.elems where doMerge = Map.mergeA panicOnMissing Map.dropMissing (Map.zipWithAMatched (const unifySemiSExprs)) panicOnMissing = Map.mapMissing (\k _ -> panic "Missing key" [showPP k]) SMT Context management freshContext / getContext / restoreContext ops . These are used during When we generate a solution , we also export the SMT context that we As we start with the empty context for memo'd variables , this the monadic code ) . Note that the first time we enter a memo node data Solution = Solution { sValue :: SemiSExpr , sPathBuilder :: PathBuilder , sCtxFrame :: SolverFrame } type SolutionEnv = Map Name (SemiValue SMTVar) unified by t , where t contains SMT variables . data MemoInstance = MemoInstance { miVarShape :: SolutionEnv tree and store a parallel search tree in the ( instead of the nseen Int ) . That way we avoid just using the found solutions , miSolutions :: [Solution] , miUnexplored :: Maybe Location' } nameSExprs :: SemiSExpr -> WriterT (Map SMTVar (Typed SExpr)) MemoM (SemiValue (Typed SMTVar)) nameSExprs = traverse nameOne where nameOne se = do sym <- lift . inSolver $ freshSymbol "memo" tell (Map.singleton sym se) pure (se {typedThing = sym}) _ppUnifier :: Unifier -> Doc _ppUnifier m = bullets [ text k <> " -> " <> text (ppSExpr v "") | (k, v) <- Map.toList m ] addMemoInstance :: Name -> SymVarEnv -> SymbolicM Result -> MemoM (MemoIdx, Unifier) addMemoInstance n e m = do fvs <- gets ((Map.! n) . frees) Replace all SExprs in e with fresh ( SMT ) variables (sole, vmap) <- runWriterT (traverse nameSExprs (Map.restrictKeys e fvs)) sc <- inSolver $ freshContext (Map.toList (symExecTy . typedType <$> vmap)) turn a SolutionEnv into a SymbolicEnv ( i.e. , turn vars into sexprs ) e' = fmap (fmap (fmap SMT.const)) sole We run with the empty path , env . env' = emptySymbolicEnv { sVarEnv = e' All free vars have empty . , sVarDeps = Set.empty <$ e' } m' = runReaderT (getSymbolicM m) env' mi = MemoInstance { miVarShape = fmap (fmap typedThing) sole , miSolutions = [] , miUnexplored = Just (ST.empty (sc, m')) } u = typedThing <$> vmap liftIO $ print ( hang ( " Add memo instance for " < > pp n ) 4 ( pp sc ) ) liftIO $ print ( hang " Unifier " 4 ( ppUnifier u ) ) m_old <- field @"memos" %%= Map.insertLookupWithKey (\_ -> flip (<>)) n [mi] We return the index of the new MemoInstance , which is at the end pure (maybe 0 length m_old, u) findMemoInstance :: Name -> SymVarEnv -> MemoM (Maybe (MemoIdx, Unifier)) findMemoInstance n e = uses (field @"memos" . at n) (go =<<) where go = getFirst . ifoldMap (\i m -> First $ (,) i <$> unifyEnvs (miVarShape m) e) memoIdx :: Name -> SymVarEnv -> SymbolicM Result -> MemoM (MemoIdx, Unifier) memoIdx n e m = do m_res <- findMemoInstance n e case m_res of Just r -> pure r Nothing -> addMemoInstance n e m memoGen :: MemoInstance -> MemoM (Maybe Solution, MemoInstance) memoGen mi | Just loc <- miUnexplored mi = do (m_r, m_loc) <- memoLocation loc let mk_soln (r, _cids, p) = do fr <- inSolver (collapseContext =<< getContext) pure Solution { sValue = r , sPathBuilder = p , sCtxFrame = fr } m_soln <- traverse mk_soln m_r let mi' = mi { miUnexplored = m_loc , miSolutions = miSolutions mi <> maybeToList m_soln } pure (m_soln, mi') | otherwise = pure (Nothing, mi) nextSolution :: ChoiceId -> MemoTagInfo -> Int -> MemoM (Maybe (SolverContext, SearchT' Result)) nextSolution cid mti nseen = do m_mi <- preuse (field @"memos" . ix (mtiName mti) . ix (mtiIdx mti)) let mi = case m_mi of Nothing -> panic "Missing MemoInstance" [] Just r -> r m_soln <- case miSolutions mi ^? ix nseen of Just soln -> pure (Just soln) Nothing -> do (r, mi') <- memoGen mi field @"memos" . ix (mtiName mti) . ix (mtiIdx mti) .= mi' pure r case m_soln of Nothing -> pure Nothing Just soln -> do (fr', u') <- inSolver $ instantiateSolverFrame (mtiUnifier mti) (sCtxFrame soln) liftIO $ print ( hang ( " Found memo instance for " < > pp n ) 4 ( bullets [ pp sc , pp ( sCtxFrame ) , pp fr ' ] ) ) PathBuilderF ( SemiValue ( Typed < here > ) ) let path' = fmap (fmap (fmap (substSExpr u'))) <$> sPathBuilder soln v' = fmap (substSExpr u') <$> sValue soln sc' = extendContext (mtiSolverContext mti) fr' cids = Set.singleton cid pure (Just (sc', mtiRHS mti (v', cids, path'))) NestTag _ n Nothing _ m - > pure ( tag , Nothing ) sc < - inSolver getContext ( m_r , m_loc ' ) < - memoLocation loc let tag ' = NestTag n m_loc ' m data BacktrackPolicy = BacktrackPolicy { btsChoose :: Location' -> MemoM (Maybe Location') , btsReenter :: Location' -> MemoM (Maybe Location') ^ Called when we need to get more solutions from a memo'd var , in , btsBacktrack :: BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') } memoChoose :: Location' -> MemoM (Maybe Location') memoChoose loc = do bts <- gets policy btsChoose bts loc memoBacktrack :: BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') memoBacktrack reason pathToHere loc = do bts <- gets policy btsBacktrack bts reason pathToHere loc memoReenter :: Location' -> MemoM (Maybe Location') memoReenter loc = do bts <- gets policy btsReenter bts loc Monad and State type MemoIdx = Int data MemoTagInfo = MemoTagInfo { mtiName :: Name , mtiIdx :: MemoIdx , mtiUnifier :: Unifier , mtiDeps :: (BacktrackReason, Set ChoiceId) , mtiSolverContext :: SolverContext , mtiRHS :: Result -> SearchT' Result } data SearchTag = FixedTag (Set ChoiceId) | MemoTag MemoTagInfo Int type SearchTree ' = SearchTree ( SolverContext , ' Result ) SearchTag type Location' = Location (SolverContext, SearchT' Result) (ChoiceId, SearchTag) data MemoState = MemoState We could associate the SymbolidM here with the name , but we a ) . memos :: Map Name [MemoInstance] , frees :: Map Name (Set Name) , shouldMemoVars :: Set Name , policy :: BacktrackPolicy } deriving (Generic) newtype MemoM a = MemoM { _getMemoM :: StateT MemoState (SolverT StrategyM) a } deriving (Functor, Applicative, Monad, MonadState MemoState, LiftStrategyM, MonadIO) inSolver :: SolverT StrategyM a -> MemoM a inSolver = MemoM . lift runMemoM :: Map Name (Set Name) -> Set Name -> BacktrackPolicy -> MemoM a -> SolverT StrategyM a runMemoM fs sm bts (MemoM m) = evalStateT m st0 where st0 = MemoState { memos = mempty , frees = fs , shouldMemoVars = sm , policy = bts } ppSetName :: Set Name -> Doc ppSetName e = block "{" ", " "}" (map ppN (Set.toList e)) where ppN n = ppPrec 1 n <> parens (pp (nameId n)) memoSearch :: BacktrackPolicy -> SearchStrat memoSearch bts = SearchStrat $ \sls@(rootSlice, deps) m -> do let fs = buildFreeMap (rootSlice : map snd (forgetRecs deps)) sm = buildShouldMemo sls liftIO $ print ( hang " Should memo : " 4 ( ppSetName sm ) ) sc <- getContext fst <$> runMemoM fs sm bts (memoLocation (ST.empty (sc, m))) buildFreeMap :: [ExpSlice] -> Map Name (Set Name) buildFreeMap = execWriter . mapM_ go where go sl = do let dflt = pure (freeVars sl) case sl of SHole -> dflt SPure {} -> dflt SDo x lsl rsl -> do lfs <- go lsl rfs <- go rsl let fs = lfs `Set.union` Set.delete x rfs tell (Map.singleton x fs) pure fs SMatch {} -> dflt SChoice sls -> mconcat <$> mapM go sls SCall {} -> dflt SCase _ c -> Set.insert (caseVar c) . mconcat <$> traverse go (toList c) SInverse n _ifn p -> pure (Set.delete n (freeVars p)) memoLocation :: Location' -> MemoM (Maybe Result, Maybe Location') memoLocation loc = m_go =<< memoReenter loc where m_go = maybe (pure (Nothing, Nothing)) go go loc' | ST.Unexplored (sc, m) <- ST.locTree loc' = do MemoM . lift $ restoreContext sc next loc' m | otherwise = panic "Expecting to be at an unexplored node" [] next :: Location' -> SearchT' Result -> MemoM (Maybe Result, Maybe Location') next loc' m = do r <- MemoM . lift $ runFreeT (getSearchT m) case r of Free (Choose cid pathToHere ms) -> do sc' <- inSolver getContext let ms' = map ((,) sc' . SearchT) ms m_go =<< memoChoose (ST.replaceUnexplored (cid, FixedTag pathToHere) ms' loc') Free (Backtrack reason pathToFailure) -> m_go =<< maybe (pure Nothing) (memoBacktrack reason pathToFailure) (ST.forgetGoUp loc') Free (Bind n e lhs rhs) -> memoNodeMaybe loc' n e lhs (SearchT <$> rhs) =<< shouldMemo n Pure r' -> pure (Just r', ST.forgetGoUp loc') memoNodeMaybe loc' n e lhs rhs' True = do (i, u) <- memoIdx n (sVarEnv e) lhs sc' <- inSolver getContext deps <- mkDeps n e let mti = MemoTagInfo { mtiName = n , mtiIdx = i , mtiUnifier = u , mtiDeps = deps , mtiSolverContext = sc' , mtiRHS = rhs' } tag = MemoTag mti 0 cid <- freshChoiceId m_go =<< memoChoose (ST.replaceUnexplored (cid, tag) [] loc') memoNodeMaybe loc' _n e lhs rhs' False = next loc' (runReaderT (getSymbolicM lhs) e >>= rhs') If we fail to find a solution in the memo'd slice , then there mkDeps :: Name -> SymbolicEnv -> MemoM (BacktrackReason, Set ChoiceId) mkDeps n e = do fvs <- gets ((Map.! n) . frees) pure (ConcreteFailure $ fold (Map.restrictKeys (sVarDeps e) fvs) , mconcat (sPath e)) manipulation . If the lhs of a bind does n't branch , then there is shouldMemo :: Name -> MemoM Bool shouldMemo n = do isRec <- isRecVar n memo <- gets (Set.member n . shouldMemoVars) pure (memo && not isRec) buildShouldMemo :: (ExpSlice, [ Rec (SliceId, ExpSlice) ]) -> Set Name buildShouldMemo (rootSlice, deps) = snd (shouldMemoSlice trivialSlices rootSlice) <> depNames where (trivialSlices, depNames) = foldl' go mempty deps go (ts, dns) (NonRec (sid, sl)) = let (Any memo, dns') = shouldMemoSlice ts sl in (if memo then ts else Set.insert sid ts, dns <> dns') so calls should be memo'd . go (ts, dns) (MutRec recs) = let (_, dns') = foldMap (shouldMemoSlice ts . snd) recs in (ts, dns <> dns') shouldMemoSlice :: Set SliceId -> ExpSlice -> (Any, Set Name) shouldMemoSlice trivialSlices = go where go :: ExpSlice -> (Any, Set Name) go sl = case sl of SHole -> mempty SPure {} -> mempty SDo x l r -> let (l_br, ls) = go l (r_br, rs) = go r in ( l_br <> r_br , ls <> rs <> (if getAny l_br then Set.singleton x else mempty) ) SMatch {} -> mempty SChoice cs -> (Any True, snd (foldMap go cs)) SCall cn -> (Any $ not (ecnSliceId cn `Set.member` trivialSlices), mempty) SCase _ cs | length (casePats cs) <= 1 -> foldMap go cs | otherwise -> (Any True, snd (foldMap go cs)) SInverse {} -> mempty btFindUnexplored :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btFindUnexplored pol = go where go loc | ST.Unexplored {} <- ST.locTree loc = pure (Just loc) go loc = do m_loc' <- btsChoose pol loc maybe (pure Nothing) go m_loc' Random restart randRestartPolicy :: BacktrackPolicy randRestartPolicy = BacktrackPolicy { btsChoose = btChooseRand randRestartPolicy , btsReenter = btReenterRestart randRestartPolicy , btsBacktrack = \_ _ -> btReenterRestart randRestartPolicy } btReenterRestart :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btReenterRestart pol = go . moveToRoot where moveToRoot = ST.maximally ST.upward go :: Location' -> MemoM (Maybe Location') go = btFindUnexplored pol btChooseRand :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btChooseRand pol loc = case ST.locTree loc of ST.Unexplored {} -> pure (Just loc) ST.Node (_cid, FixedTag pathToHere) [] -> maybe (pure Nothing) (btsBacktrack pol OtherFailure pathToHere) (ST.forgetGoUp loc) ST.Node (cid, MemoTag mti nseen) [] -> do m_r <- nextSolution cid mti nseen case m_r of Just r -> do let tag' = MemoTag mti (nseen + 1) let loc' = loc { ST.locTree = ST.Node (cid, tag') [ST.Unexplored r] } pure (ST.downward 0 loc') Nothing -> let bt = uncurry (btsBacktrack pol) (mtiDeps mti) in maybe (pure Nothing) bt (ST.forgetGoUp loc) ST.Node _ sts -> do i <- randR (0, length sts - 1) pure (ST.downward i loc) Random DFS randDFSPolicy :: BacktrackPolicy randDFSPolicy = BacktrackPolicy { btsChoose = btChooseRand randDFSPolicy , btsReenter = btLocalBacktrack randDFSPolicy , btsBacktrack = \_ _ -> btLocalBacktrack randDFSPolicy } Random DFS Accelerated randAccelDFSPolicy :: BacktrackPolicy randAccelDFSPolicy = BacktrackPolicy { btsChoose = btChooseRand randDFSPolicy , btsReenter = btLocalBacktrack randDFSPolicy , btsBacktrack = btAcceleratedBacktrack randDFSPolicy } btLocalBacktrack :: BacktrackPolicy -> Location' -> MemoM (Maybe Location') btLocalBacktrack = btFindUnexplored btAcceleratedBacktrack :: BacktrackPolicy -> BacktrackReason -> Set ChoiceId -> Location' -> MemoM (Maybe Location') btAcceleratedBacktrack pol OtherFailure _pathToFailure loc = btLocalBacktrack pol loc btAcceleratedBacktrack pol (ConcreteFailure dataCids) pathToFailure loc = go loc where cids = dataCids <> pathToFailure We search backwards for the first CID that will change the go loc' = case ST.locTree loc' of ST.Unexplored {} -> pure (Just loc') ST.Node (_cid, FixedTag {}) [] -> maybe (pure Nothing) go (ST.forgetGoUp loc') ST.Node (cid, _tag) _ms | cid `Set.member` cids -> btFindUnexplored pol loc' | otherwise -> maybe (pure Nothing) go (ST.forgetGoUp loc')
bbc90274172bda4825a4cbc5f751b33bc7a696d93b1432ad3f3134983664863a
emina/rosette
safe.rkt
#lang racket (require "bool.rkt" "exn.rkt") (provide argument-error arguments-error type-error contract-error index-too-large-error assert assert-some assert-|| assert-bound assert-arity-includes) (define-syntax (assert stx) (syntax-case stx () [(_ expr) (syntax/loc stx ($assert expr #f))] [(_ expr msg) (syntax/loc stx ($assert expr msg))])) (define-syntax assert-some (syntax-rules () [(_ expr #:unless size msg) (let* ([val expr]) (unless (= size (length val)) (assert (apply || (map car val)) msg)) val)] [(_ expr #:unless size) (assert-some expr #:unless size #f)] [(_ expr msg) (let* ([val expr]) (assert (apply || (map car val)) msg) val)] [(_ expr) (assert-some expr #f)])) (define-syntax assert-|| (syntax-rules () [(_ expr #:unless size msg) (let ([val expr]) (unless (= size (length val)) (assert (apply || val) msg)))] [(_ expr #:unless size) (assert-|| expr #:unless size #f)])) (define-syntax assert-bound (syntax-rules () [(_ [limit cmp expr] name) (let ([low limit] [high expr]) (assert (cmp low high) (argument-error name (format "~.a ~.a ~.a" low cmp (syntax-e #'expr)) low)))] [(_ [lowLimit cmpLow expr cmpHigh highLimit] name) (let ([low lowLimit] [val expr] [high highLimit]) (assert (cmpLow low val) (argument-error name (format "~.a ~.a ~.a" low cmpLow (syntax-e #'expr)) val)) (assert (cmpHigh val high) (argument-error name (format "~.a ~.a ~.a" (syntax-e #'expr) cmpHigh high) val)))])) (define-syntax (assert-arity-includes stx) (syntax-case stx () [(_ f val name) (syntax/loc stx (assert (and (procedure? f) (procedure-arity-includes? f val)) (argument-error name (format "procedure arity includes ~a" val) f)))]))
null
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/rosette/base/core/safe.rkt
racket
#lang racket (require "bool.rkt" "exn.rkt") (provide argument-error arguments-error type-error contract-error index-too-large-error assert assert-some assert-|| assert-bound assert-arity-includes) (define-syntax (assert stx) (syntax-case stx () [(_ expr) (syntax/loc stx ($assert expr #f))] [(_ expr msg) (syntax/loc stx ($assert expr msg))])) (define-syntax assert-some (syntax-rules () [(_ expr #:unless size msg) (let* ([val expr]) (unless (= size (length val)) (assert (apply || (map car val)) msg)) val)] [(_ expr #:unless size) (assert-some expr #:unless size #f)] [(_ expr msg) (let* ([val expr]) (assert (apply || (map car val)) msg) val)] [(_ expr) (assert-some expr #f)])) (define-syntax assert-|| (syntax-rules () [(_ expr #:unless size msg) (let ([val expr]) (unless (= size (length val)) (assert (apply || val) msg)))] [(_ expr #:unless size) (assert-|| expr #:unless size #f)])) (define-syntax assert-bound (syntax-rules () [(_ [limit cmp expr] name) (let ([low limit] [high expr]) (assert (cmp low high) (argument-error name (format "~.a ~.a ~.a" low cmp (syntax-e #'expr)) low)))] [(_ [lowLimit cmpLow expr cmpHigh highLimit] name) (let ([low lowLimit] [val expr] [high highLimit]) (assert (cmpLow low val) (argument-error name (format "~.a ~.a ~.a" low cmpLow (syntax-e #'expr)) val)) (assert (cmpHigh val high) (argument-error name (format "~.a ~.a ~.a" (syntax-e #'expr) cmpHigh high) val)))])) (define-syntax (assert-arity-includes stx) (syntax-case stx () [(_ f val name) (syntax/loc stx (assert (and (procedure? f) (procedure-arity-includes? f val)) (argument-error name (format "procedure arity includes ~a" val) f)))]))
9f19744b79dbc349cca4f1dacd8ee8531961491037e72010e7070c24811453fd
pirapira/coq2rust
spawn.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) let proto_version = 0 let prefer_sock = Sys.os_type = "Win32" let accept_timeout = 2.0 let pr_err s = Printf.eprintf "(Spawn ,%d) %s\n%!" (Unix.getpid ()) s let prerr_endline s = if !Flags.debug then begin pr_err s end else () type req = ReqDie | ReqStats | Hello of int * int type resp = RespStats of Gc.stat module type Control = sig type handle val kill : handle -> unit val stats : handle -> Gc.stat val wait : handle -> Unix.process_status val unixpid : handle -> int val uid : handle -> string val kill_if : handle -> sec:int -> (unit -> bool) -> unit end module type Timer = sig val add_timeout : sec:int -> (unit -> bool) -> unit end module type MainLoopModel = sig type async_chan type condition type watch_id val add_watch : callback:(condition list -> bool) -> async_chan -> watch_id val remove_watch : watch_id -> unit val read_all : async_chan -> string val async_chan_of_file : Unix.file_descr -> async_chan val async_chan_of_socket : Unix.file_descr -> async_chan include Timer end (* Common code *) let assert_ b s = if not b then Errors.anomaly (Pp.str s) let mk_socket_channel () = let open Unix in let s = socket PF_INET SOCK_STREAM 0 in bind s (ADDR_INET (inet_addr_loopback,0)); listen s 1; match getsockname s with | ADDR_INET(host, port) -> s, string_of_inet_addr host ^":"^ string_of_int port | _ -> assert false let accept s = let r, _, _ = Unix.select [s] [] [] accept_timeout in if r = [] then raise (Failure (Printf.sprintf "The spawned process did not connect back in %2.1fs" accept_timeout)); let cs, _ = Unix.accept s in Unix.close s; let cin, cout = Unix.in_channel_of_descr cs, Unix.out_channel_of_descr cs in set_binary_mode_in cin true; set_binary_mode_out cout true; cs, cin, cout let handshake cin cout = try output_value cout (Hello (proto_version,Unix.getpid ())); flush cout; match input_value cin with | Hello(v, pid) when v = proto_version -> prerr_endline (Printf.sprintf "Handshake with %d OK" pid); pid | _ -> raise (Failure "handshake protocol") with | Failure s | Invalid_argument s | Sys_error s -> pr_err ("Handshake failed: " ^ s); raise (Failure "handshake") | End_of_file -> pr_err "Handshake failed: End_of_file"; raise (Failure "handshake") let spawn_sock env prog args = let main_sock, main_sock_name = mk_socket_channel () in let extra = [| prog; "-main-channel"; main_sock_name |] in let args = Array.append extra args in prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args)); let pid = Unix.create_process_env prog args env Unix.stdin Unix.stdout Unix.stderr in if pid = 0 then begin Unix.sleep 1; (* to avoid respawning like crazy *) raise (Failure "create_process failed") end; let cs, cin, cout = accept main_sock in pid, cin, cout, cs let spawn_pipe env prog args = let master2worker_r,master2worker_w = Unix.pipe () in let worker2master_r,worker2master_w = Unix.pipe () in let extra = [| prog; "-main-channel"; "stdfds" |] in let args = Array.append extra args in Unix.set_close_on_exec master2worker_w; Unix.set_close_on_exec worker2master_r; prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args)); let pid = Unix.create_process_env prog args env master2worker_r worker2master_w Unix.stderr in if pid = 0 then begin Unix.sleep 1; (* to avoid respawning like crazy *) raise (Failure "create_process failed") end; prerr_endline ("PID " ^ string_of_int pid); Unix.close master2worker_r; Unix.close worker2master_w; let cin = Unix.in_channel_of_descr worker2master_r in let cout = Unix.out_channel_of_descr master2worker_w in set_binary_mode_in cin true; set_binary_mode_out cout true; pid, cin, cout, worker2master_r let filter_args args = let rec aux = function | "-control-channel" :: _ :: rest -> aux rest | "-main-channel" :: _ :: rest -> aux rest | x :: rest -> x :: aux rest | [] -> [] in Array.of_list (aux (Array.to_list args)) let spawn_with_control prefer_sock env prog args = let control_sock, control_sock_name = mk_socket_channel () in let extra = [| "-control-channel"; control_sock_name |] in let args = Array.append extra (filter_args args) in let (pid, cin, cout, s), is_sock = if Sys.os_type <> "Unix" || prefer_sock then spawn_sock env prog args, true else spawn_pipe env prog args, false in let _, oob_resp, oob_req = accept control_sock in pid, oob_resp, oob_req, cin, cout, s, is_sock let output_death_sentence pid oob_req = prerr_endline ("death sentence for " ^ pid); try output_value oob_req ReqDie; flush oob_req with e -> prerr_endline ("death sentence: " ^ Printexc.to_string e) (* spawn a process and read its output asynchronously *) module Async(ML : MainLoopModel) = struct type process = { cin : in_channel; cout : out_channel; oob_resp : in_channel; oob_req : out_channel; gchan : ML.async_chan; pid : int; mutable watch : ML.watch_id option; mutable alive : bool; } type callback = ML.condition list -> read_all:(unit -> string) -> bool type handle = process let uid { pid; } = string_of_int pid let unixpid { pid; } = pid let kill ({ pid = unixpid; oob_req; cin; cout; alive; watch } as p) = p.alive <- false; if not alive then prerr_endline "This process is already dead" else begin try Option.iter ML.remove_watch watch; output_death_sentence (uid p) oob_req; close_in_noerr cin; close_out_noerr cout; if Sys.os_type = "Unix" then Unix.kill unixpid 9; p.watch <- None with e -> prerr_endline ("kill: "^Printexc.to_string e) end let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ()) prog args callback = let pid, oob_resp, oob_req, cin, cout, main, is_sock = spawn_with_control prefer_sock env prog args in Unix.set_nonblock main; let gchan = if is_sock then ML.async_chan_of_socket main else ML.async_chan_of_file main in let alive, watch = true, None in let p = { cin; cout; gchan; pid; oob_resp; oob_req; alive; watch } in p.watch <- Some ( ML.add_watch ~callback:(fun cl -> try let live = callback cl ~read_all:(fun () -> ML.read_all gchan) in if not live then kill p; live with e when Errors.noncritical e -> pr_err ("Async reader raised: " ^ (Printexc.to_string e)); kill p; false) gchan ); p, cout let stats { oob_req; oob_resp; alive } = assert_ alive "This process is dead"; output_value oob_req ReqStats; flush oob_req; input_value oob_resp let kill_if p ~sec test = ML.add_timeout ~sec (fun () -> if not p.alive then false else if test () then begin prerr_endline ("death condition for " ^ uid p ^ " is true"); kill p; false end else true) let rec wait p = try snd (Unix.waitpid [] p.pid) with | Unix.Unix_error (Unix.EINTR, _, _) -> wait p | Unix.Unix_error _ -> Unix.WEXITED 0o400 end module Sync(T : Timer) = struct type process = { cin : in_channel; cout : out_channel; oob_resp : in_channel; oob_req : out_channel; pid : int; mutable alive : bool; } type handle = process let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ()) prog args = let pid, oob_resp, oob_req, cin, cout, _, _ = spawn_with_control prefer_sock env prog args in { cin; cout; pid; oob_resp; oob_req; alive = true }, cin, cout let uid { pid; } = string_of_int pid let unixpid { pid = pid; } = pid let kill ({ pid = unixpid; oob_req; cin; cout; alive } as p) = p.alive <- false; if not alive then prerr_endline "This process is already dead" else begin try output_death_sentence (uid p) oob_req; close_in_noerr cin; close_out_noerr cout; if Sys.os_type = "Unix" then Unix.kill unixpid 9; with e -> prerr_endline ("kill: "^Printexc.to_string e) end let stats { oob_req; oob_resp; alive } = assert_ alive "This process is dead"; output_value oob_req ReqStats; flush oob_req; let RespStats g = input_value oob_resp in g let kill_if p ~sec test = T.add_timeout ~sec (fun () -> if not p.alive then false else if test () then begin prerr_endline ("death condition for " ^ uid p ^ " is true"); kill p; false end else true) let wait { pid = unixpid } = try snd (Unix.waitpid [] unixpid) with Unix.Unix_error _ -> Unix.WEXITED 0o400 end
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/lib/spawn.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Common code to avoid respawning like crazy to avoid respawning like crazy spawn a process and read its output asynchronously
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * let proto_version = 0 let prefer_sock = Sys.os_type = "Win32" let accept_timeout = 2.0 let pr_err s = Printf.eprintf "(Spawn ,%d) %s\n%!" (Unix.getpid ()) s let prerr_endline s = if !Flags.debug then begin pr_err s end else () type req = ReqDie | ReqStats | Hello of int * int type resp = RespStats of Gc.stat module type Control = sig type handle val kill : handle -> unit val stats : handle -> Gc.stat val wait : handle -> Unix.process_status val unixpid : handle -> int val uid : handle -> string val kill_if : handle -> sec:int -> (unit -> bool) -> unit end module type Timer = sig val add_timeout : sec:int -> (unit -> bool) -> unit end module type MainLoopModel = sig type async_chan type condition type watch_id val add_watch : callback:(condition list -> bool) -> async_chan -> watch_id val remove_watch : watch_id -> unit val read_all : async_chan -> string val async_chan_of_file : Unix.file_descr -> async_chan val async_chan_of_socket : Unix.file_descr -> async_chan include Timer end let assert_ b s = if not b then Errors.anomaly (Pp.str s) let mk_socket_channel () = let open Unix in let s = socket PF_INET SOCK_STREAM 0 in bind s (ADDR_INET (inet_addr_loopback,0)); listen s 1; match getsockname s with | ADDR_INET(host, port) -> s, string_of_inet_addr host ^":"^ string_of_int port | _ -> assert false let accept s = let r, _, _ = Unix.select [s] [] [] accept_timeout in if r = [] then raise (Failure (Printf.sprintf "The spawned process did not connect back in %2.1fs" accept_timeout)); let cs, _ = Unix.accept s in Unix.close s; let cin, cout = Unix.in_channel_of_descr cs, Unix.out_channel_of_descr cs in set_binary_mode_in cin true; set_binary_mode_out cout true; cs, cin, cout let handshake cin cout = try output_value cout (Hello (proto_version,Unix.getpid ())); flush cout; match input_value cin with | Hello(v, pid) when v = proto_version -> prerr_endline (Printf.sprintf "Handshake with %d OK" pid); pid | _ -> raise (Failure "handshake protocol") with | Failure s | Invalid_argument s | Sys_error s -> pr_err ("Handshake failed: " ^ s); raise (Failure "handshake") | End_of_file -> pr_err "Handshake failed: End_of_file"; raise (Failure "handshake") let spawn_sock env prog args = let main_sock, main_sock_name = mk_socket_channel () in let extra = [| prog; "-main-channel"; main_sock_name |] in let args = Array.append extra args in prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args)); let pid = Unix.create_process_env prog args env Unix.stdin Unix.stdout Unix.stderr in if pid = 0 then begin raise (Failure "create_process failed") end; let cs, cin, cout = accept main_sock in pid, cin, cout, cs let spawn_pipe env prog args = let master2worker_r,master2worker_w = Unix.pipe () in let worker2master_r,worker2master_w = Unix.pipe () in let extra = [| prog; "-main-channel"; "stdfds" |] in let args = Array.append extra args in Unix.set_close_on_exec master2worker_w; Unix.set_close_on_exec worker2master_r; prerr_endline ("EXEC: " ^ String.concat " " (Array.to_list args)); let pid = Unix.create_process_env prog args env master2worker_r worker2master_w Unix.stderr in if pid = 0 then begin raise (Failure "create_process failed") end; prerr_endline ("PID " ^ string_of_int pid); Unix.close master2worker_r; Unix.close worker2master_w; let cin = Unix.in_channel_of_descr worker2master_r in let cout = Unix.out_channel_of_descr master2worker_w in set_binary_mode_in cin true; set_binary_mode_out cout true; pid, cin, cout, worker2master_r let filter_args args = let rec aux = function | "-control-channel" :: _ :: rest -> aux rest | "-main-channel" :: _ :: rest -> aux rest | x :: rest -> x :: aux rest | [] -> [] in Array.of_list (aux (Array.to_list args)) let spawn_with_control prefer_sock env prog args = let control_sock, control_sock_name = mk_socket_channel () in let extra = [| "-control-channel"; control_sock_name |] in let args = Array.append extra (filter_args args) in let (pid, cin, cout, s), is_sock = if Sys.os_type <> "Unix" || prefer_sock then spawn_sock env prog args, true else spawn_pipe env prog args, false in let _, oob_resp, oob_req = accept control_sock in pid, oob_resp, oob_req, cin, cout, s, is_sock let output_death_sentence pid oob_req = prerr_endline ("death sentence for " ^ pid); try output_value oob_req ReqDie; flush oob_req with e -> prerr_endline ("death sentence: " ^ Printexc.to_string e) module Async(ML : MainLoopModel) = struct type process = { cin : in_channel; cout : out_channel; oob_resp : in_channel; oob_req : out_channel; gchan : ML.async_chan; pid : int; mutable watch : ML.watch_id option; mutable alive : bool; } type callback = ML.condition list -> read_all:(unit -> string) -> bool type handle = process let uid { pid; } = string_of_int pid let unixpid { pid; } = pid let kill ({ pid = unixpid; oob_req; cin; cout; alive; watch } as p) = p.alive <- false; if not alive then prerr_endline "This process is already dead" else begin try Option.iter ML.remove_watch watch; output_death_sentence (uid p) oob_req; close_in_noerr cin; close_out_noerr cout; if Sys.os_type = "Unix" then Unix.kill unixpid 9; p.watch <- None with e -> prerr_endline ("kill: "^Printexc.to_string e) end let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ()) prog args callback = let pid, oob_resp, oob_req, cin, cout, main, is_sock = spawn_with_control prefer_sock env prog args in Unix.set_nonblock main; let gchan = if is_sock then ML.async_chan_of_socket main else ML.async_chan_of_file main in let alive, watch = true, None in let p = { cin; cout; gchan; pid; oob_resp; oob_req; alive; watch } in p.watch <- Some ( ML.add_watch ~callback:(fun cl -> try let live = callback cl ~read_all:(fun () -> ML.read_all gchan) in if not live then kill p; live with e when Errors.noncritical e -> pr_err ("Async reader raised: " ^ (Printexc.to_string e)); kill p; false) gchan ); p, cout let stats { oob_req; oob_resp; alive } = assert_ alive "This process is dead"; output_value oob_req ReqStats; flush oob_req; input_value oob_resp let kill_if p ~sec test = ML.add_timeout ~sec (fun () -> if not p.alive then false else if test () then begin prerr_endline ("death condition for " ^ uid p ^ " is true"); kill p; false end else true) let rec wait p = try snd (Unix.waitpid [] p.pid) with | Unix.Unix_error (Unix.EINTR, _, _) -> wait p | Unix.Unix_error _ -> Unix.WEXITED 0o400 end module Sync(T : Timer) = struct type process = { cin : in_channel; cout : out_channel; oob_resp : in_channel; oob_req : out_channel; pid : int; mutable alive : bool; } type handle = process let spawn ?(prefer_sock=prefer_sock) ?(env=Unix.environment ()) prog args = let pid, oob_resp, oob_req, cin, cout, _, _ = spawn_with_control prefer_sock env prog args in { cin; cout; pid; oob_resp; oob_req; alive = true }, cin, cout let uid { pid; } = string_of_int pid let unixpid { pid = pid; } = pid let kill ({ pid = unixpid; oob_req; cin; cout; alive } as p) = p.alive <- false; if not alive then prerr_endline "This process is already dead" else begin try output_death_sentence (uid p) oob_req; close_in_noerr cin; close_out_noerr cout; if Sys.os_type = "Unix" then Unix.kill unixpid 9; with e -> prerr_endline ("kill: "^Printexc.to_string e) end let stats { oob_req; oob_resp; alive } = assert_ alive "This process is dead"; output_value oob_req ReqStats; flush oob_req; let RespStats g = input_value oob_resp in g let kill_if p ~sec test = T.add_timeout ~sec (fun () -> if not p.alive then false else if test () then begin prerr_endline ("death condition for " ^ uid p ^ " is true"); kill p; false end else true) let wait { pid = unixpid } = try snd (Unix.waitpid [] unixpid) with Unix.Unix_error _ -> Unix.WEXITED 0o400 end
1b8a1fb16996c6542ab1d504b8ef0a02bf18d4db45fabf9e2a9b6aabe1cef603
tisnik/clojure-examples
core.clj
; ( C ) Copyright 2018 , 2020 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (ns cucumber+expect4.core (:gen-class)) funkce faktorial obsahuje i test na (defn factorial [n] (if (neg? n) (throw (IllegalArgumentException. "negative numbers are not supported!")) (apply * (range 1M (inc n))))) otestujeme funkci faktorial (defn -main [& args] (doseq [i (range 0 10)] (println i "! = " (factorial i))))
null
https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/cucumber%2Bexpect4/src/cucumber%2Bexpect4/core.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors:
( C ) Copyright 2018 , 2020 -v10.html (ns cucumber+expect4.core (:gen-class)) funkce faktorial obsahuje i test na (defn factorial [n] (if (neg? n) (throw (IllegalArgumentException. "negative numbers are not supported!")) (apply * (range 1M (inc n))))) otestujeme funkci faktorial (defn -main [& args] (doseq [i (range 0 10)] (println i "! = " (factorial i))))
303ef7742327e68081b6fa56838f595fac6340729dcc91d9b2013ed49861b61d
metabase/metabase
dashboards.clj
(ns metabase-enterprise.audit-app.pages.common.dashboards (:require [honey.sql.helpers :as sql.helpers] [metabase-enterprise.audit-app.pages.common :as common] [metabase.util.honey-sql-2 :as h2x] [metabase.util.urls :as urls])) (defn table "Dashboard table!" [query-string & [where-clause]] {:metadata [[:dashboard_id {:display_name "Dashboard ID", :base_type :type/Integer, :remapped_to :title}] [:title {:display_name "Title", :base_type :type/Title, :remapped_from :dashboard_id}] [:saved_by_id {:display_name "Saved by User ID", :base_type :type/Text, :remapped_to :saved_by}] [:saved_by {:display_name "Saved by", :base_type :type/Text, :remapped_from :saved_by_id}] [:saved_on {:display_name "Saved on", :base_type :type/DateTime}] [:cache_ttl {:display_name "Cache Duration", :base_type :type/Integer}] [:last_edited_on {:display_name "Last edited on", :base_type :type/DateTime}] [:cards {:display_name "Cards", :base_type :type/Integer}] [:public_link {:display_name "Public Link", :base_type :type/URL}] [:average_execution_time_ms {:display_name "Avg. exec. time (ms)", :base_type :type/Decimal}] [:total_views {:display_name "Total views", :base_type :type/Integer}]] :results (common/reducible-query (-> {:with [[:card_count {:select [:dashboard_id [:%count.* :card_count]] :from [:report_dashboardcard] :group-by [:dashboard_id]}] [:card_avg_execution_time {:select [:card_id [:%avg.running_time :avg_running_time]] :from [:query_execution] :where [:not= :card_id nil] :group-by [:card_id]}] [:avg_execution_time {:select [:dc.dashboard_id [[:avg :cxt.avg_running_time] :avg_running_time]] :from [[:report_dashboardcard :dc]] :left-join [[:card_avg_execution_time :cxt] [:= :dc.card_id :cxt.card_id]] :group-by [:dc.dashboard_id]}] [:views {:select [[:model_id :dashboard_id] [:%count.* :view_count]] :from [:view_log] :where [:= :model (h2x/literal "dashboard")] :group-by [:model_id]}]] :select [[:d.id :dashboard_id] [:d.name :title] [:u.id :saved_by_id] [(common/user-full-name :u) :saved_by] [:d.created_at :saved_on] [:d.cache_ttl :saved_on] [:d.updated_at :last_edited_on] [:cc.card_count :cards] [[:case [:not= :d.public_uuid nil] (h2x/concat (urls/public-dashboard-prefix) :d.public_uuid)] :public_link] [:axt.avg_running_time :average_execution_time_ms] [:v.view_count :total_views]] :from [[:report_dashboard :d]] :left-join [[:core_user :u] [:= :d.creator_id :u.id] [:card_count :cc] [:= :d.id :cc.dashboard_id] [:avg_execution_time :axt] [:= :d.id :axt.dashboard_id] [:views :v] [:= :d.id :v.dashboard_id]] :order-by [[[:lower :d.name] :asc] [:dashboard_id :asc]]} (common/add-search-clause query-string :d.name) (sql.helpers/where where-clause)))})
null
https://raw.githubusercontent.com/metabase/metabase/fab6832052f8312ec37b1f24e1faf4b9df265ed1/enterprise/backend/src/metabase_enterprise/audit_app/pages/common/dashboards.clj
clojure
(ns metabase-enterprise.audit-app.pages.common.dashboards (:require [honey.sql.helpers :as sql.helpers] [metabase-enterprise.audit-app.pages.common :as common] [metabase.util.honey-sql-2 :as h2x] [metabase.util.urls :as urls])) (defn table "Dashboard table!" [query-string & [where-clause]] {:metadata [[:dashboard_id {:display_name "Dashboard ID", :base_type :type/Integer, :remapped_to :title}] [:title {:display_name "Title", :base_type :type/Title, :remapped_from :dashboard_id}] [:saved_by_id {:display_name "Saved by User ID", :base_type :type/Text, :remapped_to :saved_by}] [:saved_by {:display_name "Saved by", :base_type :type/Text, :remapped_from :saved_by_id}] [:saved_on {:display_name "Saved on", :base_type :type/DateTime}] [:cache_ttl {:display_name "Cache Duration", :base_type :type/Integer}] [:last_edited_on {:display_name "Last edited on", :base_type :type/DateTime}] [:cards {:display_name "Cards", :base_type :type/Integer}] [:public_link {:display_name "Public Link", :base_type :type/URL}] [:average_execution_time_ms {:display_name "Avg. exec. time (ms)", :base_type :type/Decimal}] [:total_views {:display_name "Total views", :base_type :type/Integer}]] :results (common/reducible-query (-> {:with [[:card_count {:select [:dashboard_id [:%count.* :card_count]] :from [:report_dashboardcard] :group-by [:dashboard_id]}] [:card_avg_execution_time {:select [:card_id [:%avg.running_time :avg_running_time]] :from [:query_execution] :where [:not= :card_id nil] :group-by [:card_id]}] [:avg_execution_time {:select [:dc.dashboard_id [[:avg :cxt.avg_running_time] :avg_running_time]] :from [[:report_dashboardcard :dc]] :left-join [[:card_avg_execution_time :cxt] [:= :dc.card_id :cxt.card_id]] :group-by [:dc.dashboard_id]}] [:views {:select [[:model_id :dashboard_id] [:%count.* :view_count]] :from [:view_log] :where [:= :model (h2x/literal "dashboard")] :group-by [:model_id]}]] :select [[:d.id :dashboard_id] [:d.name :title] [:u.id :saved_by_id] [(common/user-full-name :u) :saved_by] [:d.created_at :saved_on] [:d.cache_ttl :saved_on] [:d.updated_at :last_edited_on] [:cc.card_count :cards] [[:case [:not= :d.public_uuid nil] (h2x/concat (urls/public-dashboard-prefix) :d.public_uuid)] :public_link] [:axt.avg_running_time :average_execution_time_ms] [:v.view_count :total_views]] :from [[:report_dashboard :d]] :left-join [[:core_user :u] [:= :d.creator_id :u.id] [:card_count :cc] [:= :d.id :cc.dashboard_id] [:avg_execution_time :axt] [:= :d.id :axt.dashboard_id] [:views :v] [:= :d.id :v.dashboard_id]] :order-by [[[:lower :d.name] :asc] [:dashboard_id :asc]]} (common/add-search-clause query-string :d.name) (sql.helpers/where where-clause)))})
958b9625279364a758aaade8557bed99b189372436afdf5ba268706eaf1d912b
AlexKnauth/quote-bad
quote-bad.rkt
#lang racket/base (provide quote #%datum) (require (only-in racket/base [quote rkt:quote] [#%datum rkt:#%datum]) (for-syntax racket/base syntax/parse "translate-quoted.rkt" "quote-bad-error.rkt" )) (module+ test (require racket/match rackunit (only-in unstable/macro-testing convert-compile-time-error) )) (define-syntax quote (lambda (stx) (syntax-parse stx [(quote id:id) (syntax/loc stx (rkt:quote id))] [(quote kw:keyword) (syntax/loc stx (rkt:quote kw))] [(quote simple) #:when (atomic-literal-data? (syntax-e #'simple)) (syntax/loc stx (rkt:quote simple))] [(quote stuff) (raise-quote-bad-error stx #'stuff)]))) (define-syntax #%datum (lambda (stx) (syntax-parse stx for some reason ( # % datum . i d ) expands ( quote i d ) (syntax/loc stx (rkt:#%datum . id))] [(#%datum . simple) #:when (atomic-literal-data? (syntax-e #'simple)) (syntax/loc stx (rkt:#%datum . simple))] [(#%datum . stuff) (raise-self-quote-bad-error stx #'stuff)]))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (module+ test (define-syntax check-error (lambda (stx) (syntax-parse stx [(check-stxerr exn-predicate expr) (syntax/loc stx (check-exn exn-predicate (λ () (convert-compile-time-error expr))))]))) (define-match-expander *q* (lambda (stx) (syntax-parse stx [(*q* s-expr) #'(== (rkt:quote s-expr))]))) (define (expected-msg* msg s-expr-matches?) (define n (string-length msg)) (define (pred e) (and (exn:fail? e) (< n (string-length (exn-message e))) (match (exn-message e) [(regexp (regexp (string-append (regexp-quote msg) "(.*)$")) (list _ s-expr-string)) (s-expr-matches? (read (open-input-string s-expr-string)))] [_ #false]))) pred) (define-syntax-rule (expected-msg msg s-expr-pat) (expected-msg* msg (λ (v) (match v [s-expr-pat #true] [_ #false])))) (test-case "okay uses of quote, with symbols and simple atomic literal data" (check-equal? 'abc (string->symbol "abc")) (check-equal? 'def (string->symbol "def")) (check-equal? '#true #true) (check-equal? '#false #false) (check-equal? '2 2) (check-equal? '4.5 4.5) (check-equal? '"abc" "abc") (check-equal? '"def" "def") (check-equal? '#"abc" #"abc") (check-equal? '#"def" #"def") (check-equal? '#:abc (string->keyword "abc")) (check-equal? '#:def (string->keyword "def")) ) (test-case "bad uses of quote, with lists, vectors, and other compound literal data" (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list))) '()) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list 'a 'b 'c (list 'd) (list 'e (list 'f)) (list (list 'g))))) '(a b c (d) (e (f)) ((g)))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list '#:abc))) '(#:abc)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (cons 'a 'b))) '(a . b)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list (cons 'a 'b) (cons 'c 'd) (cons 'e 'f)))) '([a . b] [c . d] [e . f])) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list* 'a 'b 'c))) '(a b . c)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list 'a 'b 'c))) '(a b . (c))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (vector-immutable 'a 'b 'c (list 'd) (vector-immutable 'e (list 'f)) (list (list 'g))))) '#(a b c (d) #(e (f)) ((g)))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (or (*q* (hash 'a 'b 'c 'd 'e 'f)) (*q* (hash 'a 'b 'e 'f 'c 'd)) (*q* (hash 'c 'd 'a 'b 'e 'f)) (*q* (hash 'c 'd 'e 'f 'a 'b)) (*q* (hash 'e 'f 'a 'b 'c 'd)) (*q* (hash 'e 'f 'c 'd 'a 'b)))) '#hash([a . b] [c . d] [e . f])) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (box-immutable 'a))) '#&a) ) )
null
https://raw.githubusercontent.com/AlexKnauth/quote-bad/251c2ed6f6cfd24b733ea7e0d41ff44c63cb3b2d/quote-bad/quote-bad.rkt
racket
#lang racket/base (provide quote #%datum) (require (only-in racket/base [quote rkt:quote] [#%datum rkt:#%datum]) (for-syntax racket/base syntax/parse "translate-quoted.rkt" "quote-bad-error.rkt" )) (module+ test (require racket/match rackunit (only-in unstable/macro-testing convert-compile-time-error) )) (define-syntax quote (lambda (stx) (syntax-parse stx [(quote id:id) (syntax/loc stx (rkt:quote id))] [(quote kw:keyword) (syntax/loc stx (rkt:quote kw))] [(quote simple) #:when (atomic-literal-data? (syntax-e #'simple)) (syntax/loc stx (rkt:quote simple))] [(quote stuff) (raise-quote-bad-error stx #'stuff)]))) (define-syntax #%datum (lambda (stx) (syntax-parse stx for some reason ( # % datum . i d ) expands ( quote i d ) (syntax/loc stx (rkt:#%datum . id))] [(#%datum . simple) #:when (atomic-literal-data? (syntax-e #'simple)) (syntax/loc stx (rkt:#%datum . simple))] [(#%datum . stuff) (raise-self-quote-bad-error stx #'stuff)]))) (module+ test (define-syntax check-error (lambda (stx) (syntax-parse stx [(check-stxerr exn-predicate expr) (syntax/loc stx (check-exn exn-predicate (λ () (convert-compile-time-error expr))))]))) (define-match-expander *q* (lambda (stx) (syntax-parse stx [(*q* s-expr) #'(== (rkt:quote s-expr))]))) (define (expected-msg* msg s-expr-matches?) (define n (string-length msg)) (define (pred e) (and (exn:fail? e) (< n (string-length (exn-message e))) (match (exn-message e) [(regexp (regexp (string-append (regexp-quote msg) "(.*)$")) (list _ s-expr-string)) (s-expr-matches? (read (open-input-string s-expr-string)))] [_ #false]))) pred) (define-syntax-rule (expected-msg msg s-expr-pat) (expected-msg* msg (λ (v) (match v [s-expr-pat #true] [_ #false])))) (test-case "okay uses of quote, with symbols and simple atomic literal data" (check-equal? 'abc (string->symbol "abc")) (check-equal? 'def (string->symbol "def")) (check-equal? '#true #true) (check-equal? '#false #false) (check-equal? '2 2) (check-equal? '4.5 4.5) (check-equal? '"abc" "abc") (check-equal? '"def" "def") (check-equal? '#"abc" #"abc") (check-equal? '#"def" #"def") (check-equal? '#:abc (string->keyword "abc")) (check-equal? '#:def (string->keyword "def")) ) (test-case "bad uses of quote, with lists, vectors, and other compound literal data" (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list))) '()) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list 'a 'b 'c (list 'd) (list 'e (list 'f)) (list (list 'g))))) '(a b c (d) (e (f)) ((g)))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list '#:abc))) '(#:abc)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (cons 'a 'b))) '(a . b)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list (cons 'a 'b) (cons 'c 'd) (cons 'e 'f)))) '([a . b] [c . d] [e . f])) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list* 'a 'b 'c))) '(a b . c)) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (list 'a 'b 'c))) '(a b . (c))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (vector-immutable 'a 'b 'c (list 'd) (vector-immutable 'e (list 'f)) (list (list 'g))))) '#(a b c (d) #(e (f)) ((g)))) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (or (*q* (hash 'a 'b 'c 'd 'e 'f)) (*q* (hash 'a 'b 'e 'f 'c 'd)) (*q* (hash 'c 'd 'a 'b 'e 'f)) (*q* (hash 'c 'd 'e 'f 'a 'b)) (*q* (hash 'e 'f 'a 'b 'c 'd)) (*q* (hash 'e 'f 'c 'd 'a 'b)))) '#hash([a . b] [c . d] [e . f])) (check-error (expected-msg "quote: Don't use quote for this. Instead you can use" (*q* (box-immutable 'a))) '#&a) ) )
cddca9ecb7ec646cc0058ee3d6a88ba3e5fdcbcc7fdb00b5107a8bd1dfde7360
mdedwards/slippery-chicken
cmu.lisp
;;; ********************************************************************** Copyright ( C ) 2002 ( ) ;;; This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . ;;; This program is distributed in the hope that it will be useful, ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; ********************************************************************** ;;; $Name: rel-2_6_0 $ $ Revision : 1.9 $ $ Date : 2005/01/08 15:10:33 $ (in-package :cm) (import '(ext::load-foreign pcl:slot-definition-initargs pcl:slot-definition-initform pcl:slot-definition-name pcl:class-direct-slots pcl:class-slots ;pcl::class-direct-subclasses pcl::class-direct-superclasses pcl:generic-function-name ) :cm) (defun quit () (ext::quit)) (defun exit () (quit)) #+cmu19 (defun class-subclasses (c) (let ((subs (pcl::class-direct-subclasses c))) (if (null subs) '() (loop for s in subs append (cons s (class-subclasses s)))))) #+cmu18 (defun class-subclasses (class) (let ((tbl (kernel:class-subclasses class)) (sub '())) (maphash (lambda (k v) v (push k sub)) tbl) (nreverse sub))) #-(or cmu19 cmu18) (error "Fix class-subclasses for this version of cmu.") ;(defun make-load-form (obj) ; (pcl::make-load-form obj)) (defun finalize-class (class) ;(pcl::finalize-inheritance class) ) (defmethod validate-class ((class t) (superclass t)) this is a no - op except in OpenMCL 014 t) (defun slot-defintion-reader (slot) slot nil) ;;; ;;; misc. stuff ;;; (defun object-address (thing) (kernel:get-lisp-obj-address thing)) (defconstant directory-delimiter #\/) ( defun cd ( & optional dir ) ; (if dir ( progn ( setf ( ext : default - directory ) dir ) ; (namestring (ext:default-directory))) ; (namestring (ext:default-directory)))) (defun cd (&optional (dir (user-homedir-pathname ))) (setf (ext:default-directory) dir) (namestring (ext:default-directory))) (defun pwd () (namestring (ext:default-directory))) ;;(defun shell (format &rest strings) ;; (let ((str (apply #'format nil format strings))) ;; (extensions:run-program "/bin/csh" (list "-fc" str) :output t))) (defun shell (cmd &key (wait t) (output t)) (extensions:run-program "/bin/csh" (list "-fc" cmd) :output output :wait wait)) (defun env-var (var) (let ((x (assoc var ext:*environment-list* :test #'string=))) (and x (cdr x) ))) (defun cm-image-dir () (let ((img (member "-core" ext:*command-line-strings*))) (if img (namestring (make-pathname :directory (pathname-directory (cadr img)))) nil))) (defun save-cm (path &rest args) (declare (ignore args)) (extensions:save-lisp path :print-herald NIL :init-function #'(lambda () (declare (special *cm-readtable*)) (setf *readtable* *cm-readtable*) (setf *package* (find-package :cm)) (load-cminit) (cm-logo) (lisp::%top-level))))
null
https://raw.githubusercontent.com/mdedwards/slippery-chicken/c1c11fadcdb40cd869d5b29091ba5e53c5270e04/src/cm-2.6.0/src/cmu.lisp
lisp
********************************************************************** This program is free software; you can redistribute it and/or either version 2 This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ********************************************************************** $Name: rel-2_6_0 $ pcl::class-direct-subclasses (defun make-load-form (obj) (pcl::make-load-form obj)) (pcl::finalize-inheritance class) misc. stuff (if dir (namestring (ext:default-directory))) (namestring (ext:default-directory)))) (defun shell (format &rest strings) (let ((str (apply #'format nil format strings))) (extensions:run-program "/bin/csh" (list "-fc" str) :output t)))
Copyright ( C ) 2002 ( ) modify it under the terms of the GNU General Public License of the License , or ( at your option ) any later version . $ Revision : 1.9 $ $ Date : 2005/01/08 15:10:33 $ (in-package :cm) (import '(ext::load-foreign pcl:slot-definition-initargs pcl:slot-definition-initform pcl:slot-definition-name pcl:class-direct-slots pcl:class-slots pcl::class-direct-superclasses pcl:generic-function-name ) :cm) (defun quit () (ext::quit)) (defun exit () (quit)) #+cmu19 (defun class-subclasses (c) (let ((subs (pcl::class-direct-subclasses c))) (if (null subs) '() (loop for s in subs append (cons s (class-subclasses s)))))) #+cmu18 (defun class-subclasses (class) (let ((tbl (kernel:class-subclasses class)) (sub '())) (maphash (lambda (k v) v (push k sub)) tbl) (nreverse sub))) #-(or cmu19 cmu18) (error "Fix class-subclasses for this version of cmu.") (defun finalize-class (class) ) (defmethod validate-class ((class t) (superclass t)) this is a no - op except in OpenMCL 014 t) (defun slot-defintion-reader (slot) slot nil) (defun object-address (thing) (kernel:get-lisp-obj-address thing)) (defconstant directory-delimiter #\/) ( defun cd ( & optional dir ) ( progn ( setf ( ext : default - directory ) dir ) (defun cd (&optional (dir (user-homedir-pathname ))) (setf (ext:default-directory) dir) (namestring (ext:default-directory))) (defun pwd () (namestring (ext:default-directory))) (defun shell (cmd &key (wait t) (output t)) (extensions:run-program "/bin/csh" (list "-fc" cmd) :output output :wait wait)) (defun env-var (var) (let ((x (assoc var ext:*environment-list* :test #'string=))) (and x (cdr x) ))) (defun cm-image-dir () (let ((img (member "-core" ext:*command-line-strings*))) (if img (namestring (make-pathname :directory (pathname-directory (cadr img)))) nil))) (defun save-cm (path &rest args) (declare (ignore args)) (extensions:save-lisp path :print-herald NIL :init-function #'(lambda () (declare (special *cm-readtable*)) (setf *readtable* *cm-readtable*) (setf *package* (find-package :cm)) (load-cminit) (cm-logo) (lisp::%top-level))))
4636821cef17fc61f401ae70ddaf481201df2c21728bad14baf5d52844b6b441
gchrupala/morfette
Token.hs
{-# LANGUAGE OverloadedStrings #-} module GramLab.Morfette.Token ( Token , Sentence , Emb , tokenForm , tokenEmb , tokenLemma , tokenPOS , parseToken , nullToken , isNullToken , lowercaseToken ) where import qualified Data.Vector.Unboxed as U import GramLab.Utils import Data.Char import Debug.Trace import qualified Data.Text.Lazy as Text import qualified Data.Text.Lazy.Read as Text type Emb = U.Vector Double data Token = Token { tokenForm :: String , tokenEmb :: Maybe Emb , tokenLemma :: Maybe String , tokenPOS :: Maybe String } deriving (Show, Eq) type Sentence = [Token] token :: String -> Maybe Emb -> Maybe String -> Maybe String -> Token token f e l p = Token { tokenForm = f, tokenEmb = e, tokenLemma = l, tokenPOS = p } parseToken :: Text.Text -> Token parseToken line = let str = Text.unpack t = case Text.words line of [form, embedding, lemma, pos] -> token (str form) (Just (parseEmb embedding)) (Just $ str lemma) (Just $ str pos) [form, lemma, pos] -> token (str form) Nothing (Just $ str lemma) (Just $ str pos) [form, embedding] -> token (str form) (Just (parseEmb embedding)) Nothing Nothing [form] -> token (str form) Nothing Nothing Nothing [] -> nullToken in U.length (maybe U.empty id (tokenEmb t)) `seq` t nullToken = token "" Nothing Nothing Nothing isNullToken t = t == nullToken parseEmb :: Text.Text -> Emb parseEmb = U.fromList . map readDouble . filter (not . Text.null) . Text.splitOn "," readDouble :: Text.Text -> Double readDouble s = case Text.double s of Right (d, "") -> d Left e -> error $ "GramLab.Morfette.Token.readDouble: " ++ show e _ -> error $ "GramLab.Morfette.Token.readDouble: parse error" lowercaseToken :: Token -> Token lowercaseToken t = token (lowercase (tokenForm t)) (tokenEmb t) (fmap lowercase (tokenLemma t)) (fmap lowercase (tokenPOS t)) where lowercase = map toLower
null
https://raw.githubusercontent.com/gchrupala/morfette/be40676c975d660bbb893953d354168506069862/src/GramLab/Morfette/Token.hs
haskell
# LANGUAGE OverloadedStrings #
module GramLab.Morfette.Token ( Token , Sentence , Emb , tokenForm , tokenEmb , tokenLemma , tokenPOS , parseToken , nullToken , isNullToken , lowercaseToken ) where import qualified Data.Vector.Unboxed as U import GramLab.Utils import Data.Char import Debug.Trace import qualified Data.Text.Lazy as Text import qualified Data.Text.Lazy.Read as Text type Emb = U.Vector Double data Token = Token { tokenForm :: String , tokenEmb :: Maybe Emb , tokenLemma :: Maybe String , tokenPOS :: Maybe String } deriving (Show, Eq) type Sentence = [Token] token :: String -> Maybe Emb -> Maybe String -> Maybe String -> Token token f e l p = Token { tokenForm = f, tokenEmb = e, tokenLemma = l, tokenPOS = p } parseToken :: Text.Text -> Token parseToken line = let str = Text.unpack t = case Text.words line of [form, embedding, lemma, pos] -> token (str form) (Just (parseEmb embedding)) (Just $ str lemma) (Just $ str pos) [form, lemma, pos] -> token (str form) Nothing (Just $ str lemma) (Just $ str pos) [form, embedding] -> token (str form) (Just (parseEmb embedding)) Nothing Nothing [form] -> token (str form) Nothing Nothing Nothing [] -> nullToken in U.length (maybe U.empty id (tokenEmb t)) `seq` t nullToken = token "" Nothing Nothing Nothing isNullToken t = t == nullToken parseEmb :: Text.Text -> Emb parseEmb = U.fromList . map readDouble . filter (not . Text.null) . Text.splitOn "," readDouble :: Text.Text -> Double readDouble s = case Text.double s of Right (d, "") -> d Left e -> error $ "GramLab.Morfette.Token.readDouble: " ++ show e _ -> error $ "GramLab.Morfette.Token.readDouble: parse error" lowercaseToken :: Token -> Token lowercaseToken t = token (lowercase (tokenForm t)) (tokenEmb t) (fmap lowercase (tokenLemma t)) (fmap lowercase (tokenPOS t)) where lowercase = map toLower
d7ef6c79fe42cf8a88566df44b14d9086c8239487b1df915e5f4eb2c211043f8
scrintal/heroicons-reagent
pause_circle.cljs
(ns com.scrintal.heroicons.solid.pause-circle) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zM9 8.25a.75.75 0 00-.75.75v6c0 .414.336.75.75.75h.75a.75.75 0 00.75-.75V9a.75.75 0 00-.75-.75H9zm5.25 0a.75.75 0 00-.75.75v6c0 .414.336.75.75.75H15a.75.75 0 00.75-.75V9a.75.75 0 00-.75-.75h-.75z" :clipRule "evenodd"}]])
null
https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/pause_circle.cljs
clojure
(ns com.scrintal.heroicons.solid.pause-circle) (defn render [] [:svg {:xmlns "" :viewBox "0 0 24 24" :fill "currentColor" :aria-hidden "true"} [:path {:fillRule "evenodd" :d "M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zM9 8.25a.75.75 0 00-.75.75v6c0 .414.336.75.75.75h.75a.75.75 0 00.75-.75V9a.75.75 0 00-.75-.75H9zm5.25 0a.75.75 0 00-.75.75v6c0 .414.336.75.75.75H15a.75.75 0 00.75-.75V9a.75.75 0 00-.75-.75h-.75z" :clipRule "evenodd"}]])
d0aa79f3c70721ee899d74bc64c65b1da8de77cca5777ab05c6b103b2912020c
MondayMorningHaskell/AdventOfCode
Day14.hs
{-# LANGUAGE OverloadedStrings #-} module Day14 where import Text.Megaparsec (ParsecT, some, sepEndBy1) import Text.Megaparsec.Char (letterChar, eol, string) import Data.Void (Void) import Data.Text (Text, pack) import Utils (parseFile, incKey, emptyOcc, OccMapBig, addKey) import Control.Monad.Logger (MonadLogger, runStdoutLoggingT, logDebugN, logErrorN) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Control.Monad (foldM) import qualified Data.Map as M import Data.Maybe (fromMaybe) d14ES :: IO (Maybe Integer) d14ES = solveDay14Easy "inputs/day_14_small.txt" d14EB :: IO (Maybe Integer) d14EB = solveDay14Easy "inputs/day_14_big.txt" d14HS :: IO (Maybe Integer) d14HS = solveDay14Hard "inputs/day_14_small.txt" d14HB :: IO (Maybe Integer) d14HB = solveDay14Hard "inputs/day_14_big.txt" solveDay14Easy :: String -> IO (Maybe Integer) solveDay14Easy fp = runStdoutLoggingT $ do (starterCode, pairCodes) <- parseFile parseInput fp expandPolymerLong 10 starterCode pairCodes solveDay14Hard :: String -> IO (Maybe Integer) solveDay14Hard fp = runStdoutLoggingT $ do (starterCode, pairCodes) <- parseFile parseInput fp expandPolymerLong 40 starterCode pairCodes type PairMap = HashMap (Char, Char) Char Does n't work well beyond size 10 or so expandPolymerNaive :: (MonadLogger m) => Int -> String -> PairMap -> m (Maybe Integer) expandPolymerNaive numSteps starterCode pairMap = do finalString <- foldM runStep starterCode [1..numSteps] let charMap = M.elems $ foldl incKey emptyOcc finalString if null charMap then logErrorN "Final Occurrence Map is empty!" >> return Nothing else return $ Just $ fromIntegral (maximum charMap - minimum charMap) where runStep :: (MonadLogger m) => String -> Int -> m String runStep input _ = runExpand "" input runExpand :: (MonadLogger m) => String -> String -> m String runExpand accum "" = logErrorN "Reached empty remainder!" >> return (reverse accum) -- < This case shouldn't happen runExpand accum [lastChar] = return $ reverse (lastChar : accum) runExpand accum (nextChar : secondChar : rest) = case HM.lookup (nextChar, secondChar) pairMap of Nothing -> logErrorN ("Missing Case: " <> pack [nextChar, secondChar]) >> runExpand (nextChar : accum) (secondChar : rest) Just insertChar -> runExpand (insertChar : nextChar : accum) (secondChar : rest) expandPolymerLong :: (MonadLogger m) => Int -> String -> PairMap -> m (Maybe Integer) expandPolymerLong numSteps starterCode pairMap = do let starterMap = buildMapF M.empty starterCode finalOccMap <- foldM runStep starterMap [1..numSteps] let finalCharCountMap = foldl countChars M.empty (M.toList finalOccMap) let finalCounts = map quotRoundUp (M.toList finalCharCountMap) if null finalCounts then logErrorN "Final Occurence Map is empty" >> return Nothing else return $ Just $ fromIntegral (maximum finalCounts - minimum finalCounts) where buildMapF :: OccMapBig (Char, Char) -> String -> OccMapBig (Char, Char) buildMapF prevMap "" = prevMap buildMapF prevMap [_] = prevMap buildMapF prevMap (firstChar : secondChar : rest) = buildMapF (incKey prevMap (firstChar, secondChar)) (secondChar : rest) runStep :: (MonadLogger m) => OccMapBig (Char, Char) -> Int -> m (OccMapBig (Char, Char)) runStep prevMap _ = foldM runExpand M.empty (M.toList prevMap) runExpand :: (MonadLogger m) => OccMapBig (Char, Char) -> ((Char, Char), Integer) -> m (OccMapBig (Char, Char)) runExpand prevMap (code@(c1,c2), count) = case HM.lookup code pairMap of Nothing -> logErrorN ("Missing Code: " <> pack [c1, c2]) >> return prevMap Just newChar -> do let first = (c1, newChar) second = (newChar, c2) return $ addKey (addKey prevMap first count) second count countChars :: OccMapBig Char -> ((Char, Char), Integer) -> OccMapBig Char countChars prevMap ((c1, c2), count) = addKey (addKey prevMap c1 count) c2 count quotRoundUp :: (Char, Integer) -> Integer quotRoundUp (c, i) = if even i then quot i 2 + if head starterCode == c && last starterCode == c then 1 else 0 else quot i 2 + 1 buildPairMap :: [(Char, Char, Char)] -> HashMap (Char, Char) Char buildPairMap = foldl (\prevMap (c1, c2, c3) -> HM.insert (c1, c2) c3 prevMap) HM.empty parseInput :: (MonadLogger m) => ParsecT Void Text m (String, PairMap) parseInput = do starterCode <- some letterChar eol >> eol pairCodes <- sepEndBy1 parsePairCode eol return (starterCode, buildPairMap pairCodes) parsePairCode :: (MonadLogger m) => ParsecT Void Text m (Char, Char, Char) parsePairCode = do input1 <- letterChar input2 <- letterChar string " -> " output <- letterChar return (input1, input2, output)
null
https://raw.githubusercontent.com/MondayMorningHaskell/AdventOfCode/ec3160a219900f3945bb10b099ebfd588cbd19b8/src/Day14.hs
haskell
# LANGUAGE OverloadedStrings # < This case shouldn't happen
module Day14 where import Text.Megaparsec (ParsecT, some, sepEndBy1) import Text.Megaparsec.Char (letterChar, eol, string) import Data.Void (Void) import Data.Text (Text, pack) import Utils (parseFile, incKey, emptyOcc, OccMapBig, addKey) import Control.Monad.Logger (MonadLogger, runStdoutLoggingT, logDebugN, logErrorN) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Control.Monad (foldM) import qualified Data.Map as M import Data.Maybe (fromMaybe) d14ES :: IO (Maybe Integer) d14ES = solveDay14Easy "inputs/day_14_small.txt" d14EB :: IO (Maybe Integer) d14EB = solveDay14Easy "inputs/day_14_big.txt" d14HS :: IO (Maybe Integer) d14HS = solveDay14Hard "inputs/day_14_small.txt" d14HB :: IO (Maybe Integer) d14HB = solveDay14Hard "inputs/day_14_big.txt" solveDay14Easy :: String -> IO (Maybe Integer) solveDay14Easy fp = runStdoutLoggingT $ do (starterCode, pairCodes) <- parseFile parseInput fp expandPolymerLong 10 starterCode pairCodes solveDay14Hard :: String -> IO (Maybe Integer) solveDay14Hard fp = runStdoutLoggingT $ do (starterCode, pairCodes) <- parseFile parseInput fp expandPolymerLong 40 starterCode pairCodes type PairMap = HashMap (Char, Char) Char Does n't work well beyond size 10 or so expandPolymerNaive :: (MonadLogger m) => Int -> String -> PairMap -> m (Maybe Integer) expandPolymerNaive numSteps starterCode pairMap = do finalString <- foldM runStep starterCode [1..numSteps] let charMap = M.elems $ foldl incKey emptyOcc finalString if null charMap then logErrorN "Final Occurrence Map is empty!" >> return Nothing else return $ Just $ fromIntegral (maximum charMap - minimum charMap) where runStep :: (MonadLogger m) => String -> Int -> m String runStep input _ = runExpand "" input runExpand :: (MonadLogger m) => String -> String -> m String runExpand accum [lastChar] = return $ reverse (lastChar : accum) runExpand accum (nextChar : secondChar : rest) = case HM.lookup (nextChar, secondChar) pairMap of Nothing -> logErrorN ("Missing Case: " <> pack [nextChar, secondChar]) >> runExpand (nextChar : accum) (secondChar : rest) Just insertChar -> runExpand (insertChar : nextChar : accum) (secondChar : rest) expandPolymerLong :: (MonadLogger m) => Int -> String -> PairMap -> m (Maybe Integer) expandPolymerLong numSteps starterCode pairMap = do let starterMap = buildMapF M.empty starterCode finalOccMap <- foldM runStep starterMap [1..numSteps] let finalCharCountMap = foldl countChars M.empty (M.toList finalOccMap) let finalCounts = map quotRoundUp (M.toList finalCharCountMap) if null finalCounts then logErrorN "Final Occurence Map is empty" >> return Nothing else return $ Just $ fromIntegral (maximum finalCounts - minimum finalCounts) where buildMapF :: OccMapBig (Char, Char) -> String -> OccMapBig (Char, Char) buildMapF prevMap "" = prevMap buildMapF prevMap [_] = prevMap buildMapF prevMap (firstChar : secondChar : rest) = buildMapF (incKey prevMap (firstChar, secondChar)) (secondChar : rest) runStep :: (MonadLogger m) => OccMapBig (Char, Char) -> Int -> m (OccMapBig (Char, Char)) runStep prevMap _ = foldM runExpand M.empty (M.toList prevMap) runExpand :: (MonadLogger m) => OccMapBig (Char, Char) -> ((Char, Char), Integer) -> m (OccMapBig (Char, Char)) runExpand prevMap (code@(c1,c2), count) = case HM.lookup code pairMap of Nothing -> logErrorN ("Missing Code: " <> pack [c1, c2]) >> return prevMap Just newChar -> do let first = (c1, newChar) second = (newChar, c2) return $ addKey (addKey prevMap first count) second count countChars :: OccMapBig Char -> ((Char, Char), Integer) -> OccMapBig Char countChars prevMap ((c1, c2), count) = addKey (addKey prevMap c1 count) c2 count quotRoundUp :: (Char, Integer) -> Integer quotRoundUp (c, i) = if even i then quot i 2 + if head starterCode == c && last starterCode == c then 1 else 0 else quot i 2 + 1 buildPairMap :: [(Char, Char, Char)] -> HashMap (Char, Char) Char buildPairMap = foldl (\prevMap (c1, c2, c3) -> HM.insert (c1, c2) c3 prevMap) HM.empty parseInput :: (MonadLogger m) => ParsecT Void Text m (String, PairMap) parseInput = do starterCode <- some letterChar eol >> eol pairCodes <- sepEndBy1 parsePairCode eol return (starterCode, buildPairMap pairCodes) parsePairCode :: (MonadLogger m) => ParsecT Void Text m (Char, Char, Char) parsePairCode = do input1 <- letterChar input2 <- letterChar string " -> " output <- letterChar return (input1, input2, output)
4d38d904199d873bf17f259c793df12cb4b62c57b823be482c5106ce4aa670e0
LexiFi/landmarks
test.ml
let[@landmark] call f = f () let rec fp n () = if n > 0 then call (fp (n - 1)) let () = begin let open Landmark in let open Landmark.Graph in start_profiling ~profiling_options:{default_options with recursive = true} (); fp 10 (); stop_profiling (); let nb_recursive_nodes = List.length (nodes (export_and_reset ())) in Printf.printf "recursive: %d nodes\n%!" nb_recursive_nodes; start_profiling ~profiling_options:{default_options with recursive = false} (); fp 10 (); stop_profiling (); let nb_nodes = List.length (nodes (export_and_reset ())) in Printf.printf "non-recursive: %d nodes\n%!" nb_nodes; assert (nb_nodes <> nb_recursive_nodes); end
null
https://raw.githubusercontent.com/LexiFi/landmarks/ea90c657f39d03d14d892732ad58123711eb9457/tests/recursive/test.ml
ocaml
let[@landmark] call f = f () let rec fp n () = if n > 0 then call (fp (n - 1)) let () = begin let open Landmark in let open Landmark.Graph in start_profiling ~profiling_options:{default_options with recursive = true} (); fp 10 (); stop_profiling (); let nb_recursive_nodes = List.length (nodes (export_and_reset ())) in Printf.printf "recursive: %d nodes\n%!" nb_recursive_nodes; start_profiling ~profiling_options:{default_options with recursive = false} (); fp 10 (); stop_profiling (); let nb_nodes = List.length (nodes (export_and_reset ())) in Printf.printf "non-recursive: %d nodes\n%!" nb_nodes; assert (nb_nodes <> nb_recursive_nodes); end
746c90fd21e231252ac8fecb9e6ac4d7e91149a1246edaa41f5f8dd1bca1285d
hoelzl/Clicc
bindings.lisp
;;;----------------------------------------------------------------------------- Projekt : APPLY - A Practicable And Portable Lisp Implementation ;;; ------------------------------------------------------ Inhalt : Tests , in let / let*-Ausdruecken ;;; $ Revision : 1.4 $ ;;; $Log: bindings.lisp,v $ Revision 1.4 1993/02/16 17:14:34 hk Revision Keyword eingefuegt . ;;; ;;; Revision 1.3 1992/09/30 18:49:51 hk bindings6a eingefuegt . ;;; ;;; Revision 1.2 1992/09/09 13:11:34 kl Die let*-Tests eingefuegt . ;;; Revision 1.1 1992/09/08 15:16:16 kl ;;; Initial revision ;;;----------------------------------------------------------------------------- (in-package "USER") ;;------------------------------------------------------------------------------ ;; Funktionsdefinitionen zu den Bindungstests: ;;------------------------------------------------------------------------------ ;;------------------------------------------------------------------------------ : ;;------------------------------------------------------------------------------ (defun bindings1a (a b) (let ((a b) (b a)) (list a b))) ;;------------------------------------------------------------------------------ ;; special-Deklaration vor einem let-Ausdruck: ;;------------------------------------------------------------------------------ (defun bindings2a (a b) (declare (special a b)) (let ((a b) (b a)) (list a b))) ;;------------------------------------------------------------------------------ ;; special-Deklaration in einem let-Ausdruck: [Ste84] ;;------------------------------------------------------------------------------ (defun bindings3a (a b) (let ((c a) (d b)) (declare (special c d)) (let ((c d) (d c)) (list c d)))) ;;------------------------------------------------------------------------------ ;; special-Deklaration vor und in einem let-Ausdruck: ;;------------------------------------------------------------------------------ (defun bindings4a (a b) (declare (special a b)) (let ((a b) (b a)) (declare (special a b)) (list a b))) ;;------------------------------------------------------------------------------ Beispiel aus dem draft ANSI Common Lisp : ;;------------------------------------------------------------------------------ (defun bindings5a () (let ((x 1)) (declare (special x)) (let ((x 2)) (let ((old-x x) (x 3)) (declare (special x)) (list old-x x))))) ;;------------------------------------------------------------------------------ globale special - Deklaration und lokale special Deklaration ;;------------------------------------------------------------------------------ (defvar *c* 77) (defun bindings6a (a b *c* d) (declare (special a)) (let ((a b) (b a) (*c* d) (d *c*)) (declare (special a)) (list a b *c* d))) ;;------------------------------------------------------------------------------ : ;;------------------------------------------------------------------------------ (defun bindings1b (a b) (let* ((a b) (b a)) (list a b))) ;;------------------------------------------------------------------------------ ;; special-Deklaration vor einem let-Ausdruck: ;;------------------------------------------------------------------------------ (defun bindings2b (a b) (declare (special a b)) (let* ((a b) (b a)) (list a b))) ;;------------------------------------------------------------------------------ ;; special-Deklaration in einem let-Ausdruck: [Ste84] ;;------------------------------------------------------------------------------ (defun bindings3b (a b) (let* ((c b) (d a)) (declare (special c d)) (let* ((c d) (d c)) (list c d)))) ;;------------------------------------------------------------------------------ ;; special-Deklaration vor und in einem let-Ausdruck: ;;------------------------------------------------------------------------------ (defun bindings4b (a b) (declare (special a b)) (let* ((a b) (b a)) (declare (special a b)) (list a b))) ;;------------------------------------------------------------------------------ Beispiel aus dem draft ANSI Common Lisp : ;;------------------------------------------------------------------------------ (defun bindings5b () (let* ((x 1)) (declare (special x)) (let* ((x 2)) (let* ((old-x x) (x 3)) (declare (special x)) (list old-x x))))) ;;------------------------------------------------------------------------------ ;; Aufruf der Bindungstests: ;;------------------------------------------------------------------------------ (clicc-test "Binding" ";;; Tests variable bindings introduced by let and let*." (((bindings1a 1 2) (2 1)) ((bindings2a 3 4) (4 3)) ((bindings3a 5 6) (6 5)) ((bindings4a 7 8) (8 7)) ((bindings5a) (1 3) "uses [Ste84]'s declaration scope") ((bindings5a) (2 3) "uses ANSI CL's declaration scope") ((bindings6a 1 2 3 4) (2 1 4 3)) ((bindings1b 1 2) (2 2)) ((bindings2b 3 4) (4 4)) ((bindings3b 5 6) (5 5)) ((bindings4b 7 8) (8 8)) ((bindings5b) (1 3) "uses [Ste84]'s declaration scope") ((bindings5b) (2 3) "uses ANSI CL's declaration scope") )) ;;------------------------------------------------------------------------------ (provide "bindings")
null
https://raw.githubusercontent.com/hoelzl/Clicc/cea01db35301144967dc74fd2f96dd58aa52d6ea/src/test/bindings.lisp
lisp
----------------------------------------------------------------------------- ------------------------------------------------------ $Log: bindings.lisp,v $ Revision 1.3 1992/09/30 18:49:51 hk Revision 1.2 1992/09/09 13:11:34 kl Initial revision ----------------------------------------------------------------------------- ------------------------------------------------------------------------------ Funktionsdefinitionen zu den Bindungstests: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration vor einem let-Ausdruck: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration in einem let-Ausdruck: [Ste84] ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration vor und in einem let-Ausdruck: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration vor einem let-Ausdruck: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration in einem let-Ausdruck: [Ste84] ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ special-Deklaration vor und in einem let-Ausdruck: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ Aufruf der Bindungstests: ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
Projekt : APPLY - A Practicable And Portable Lisp Implementation Inhalt : Tests , in let / let*-Ausdruecken $ Revision : 1.4 $ Revision 1.4 1993/02/16 17:14:34 hk Revision Keyword eingefuegt . bindings6a eingefuegt . Die let*-Tests eingefuegt . Revision 1.1 1992/09/08 15:16:16 kl (in-package "USER") : (defun bindings1a (a b) (let ((a b) (b a)) (list a b))) (defun bindings2a (a b) (declare (special a b)) (let ((a b) (b a)) (list a b))) (defun bindings3a (a b) (let ((c a) (d b)) (declare (special c d)) (let ((c d) (d c)) (list c d)))) (defun bindings4a (a b) (declare (special a b)) (let ((a b) (b a)) (declare (special a b)) (list a b))) Beispiel aus dem draft ANSI Common Lisp : (defun bindings5a () (let ((x 1)) (declare (special x)) (let ((x 2)) (let ((old-x x) (x 3)) (declare (special x)) (list old-x x))))) globale special - Deklaration und lokale special Deklaration (defvar *c* 77) (defun bindings6a (a b *c* d) (declare (special a)) (let ((a b) (b a) (*c* d) (d *c*)) (declare (special a)) (list a b *c* d))) : (defun bindings1b (a b) (let* ((a b) (b a)) (list a b))) (defun bindings2b (a b) (declare (special a b)) (let* ((a b) (b a)) (list a b))) (defun bindings3b (a b) (let* ((c b) (d a)) (declare (special c d)) (let* ((c d) (d c)) (list c d)))) (defun bindings4b (a b) (declare (special a b)) (let* ((a b) (b a)) (declare (special a b)) (list a b))) Beispiel aus dem draft ANSI Common Lisp : (defun bindings5b () (let* ((x 1)) (declare (special x)) (let* ((x 2)) (let* ((old-x x) (x 3)) (declare (special x)) (list old-x x))))) (clicc-test "Binding" ";;; Tests variable bindings introduced by let and let*." (((bindings1a 1 2) (2 1)) ((bindings2a 3 4) (4 3)) ((bindings3a 5 6) (6 5)) ((bindings4a 7 8) (8 7)) ((bindings5a) (1 3) "uses [Ste84]'s declaration scope") ((bindings5a) (2 3) "uses ANSI CL's declaration scope") ((bindings6a 1 2 3 4) (2 1 4 3)) ((bindings1b 1 2) (2 2)) ((bindings2b 3 4) (4 4)) ((bindings3b 5 6) (5 5)) ((bindings4b 7 8) (8 8)) ((bindings5b) (1 3) "uses [Ste84]'s declaration scope") ((bindings5b) (2 3) "uses ANSI CL's declaration scope") )) (provide "bindings")
159f9bb47218aaf920df139ef919e04d14b0cd452ddd4a1cf464bdfa0bf0283d
reborg/reclojure
persistent_map.clj
(ns reclojure.lang.protocols.persistent-map (:require [reclojure.lang.protocols.persistent-vector :as pv] [clojure.tools.logging :as log]) (:refer-clojure :exclude [cons empty seq get remove assoc count]) (:import [clojure.lang RT])) (defprotocol PersistentMap (assoc [this key val]) ;; common-provided (assocEx [this key val]) (without [this key]) (iterator [this]) (entryAt [this key]) (count [this]) (cons [this o]) ;; specific (empty [this]) (equiv [this o]) (seq [this]) (valAt [this key] [this key notFound]) (size [this]) (isEmpty [this]) (containsKey [this key]) (containsValue [this value]) (get [this key]) (put [this key value]) (remove [this key]) (putAll [this map]) (clear [this]) (keySet [this]) (values [this]) (entrySet [this]) (equals [this o]) (hashCode [this]) (hasheq [this])) (defn ^String ->toString [this] (RT/printString this)) (defn ->cons [pm o] (log/debug (format "->cons object %s" o)) (cond (instance? java.util.Map$Entry o) (assoc pm (.getKey o) (.getValue o)) (satisfies? pv/PersistentVector o) (if (= 2 (pv/count o)) (pv/assoc pm (pv/nth o 0) (pv/nth o 1)) (throw (IllegalArgumentException. "Vector arg to map conj must be a pair"))) :else (throw (RuntimeException. "pm/->cons missing implementation")))) (defn ->get [pm k] (valAt pm k)) (def PersistentMapImpl {:cons #'->cons :get #'->get})
null
https://raw.githubusercontent.com/reborg/reclojure/c8aae4cc384d59262569cbc9c332e08619f292ef/src/reclojure/lang/protocols/persistent_map.clj
clojure
common-provided specific
(ns reclojure.lang.protocols.persistent-map (:require [reclojure.lang.protocols.persistent-vector :as pv] [clojure.tools.logging :as log]) (:refer-clojure :exclude [cons empty seq get remove assoc count]) (:import [clojure.lang RT])) (defprotocol PersistentMap (assocEx [this key val]) (without [this key]) (iterator [this]) (entryAt [this key]) (count [this]) (empty [this]) (equiv [this o]) (seq [this]) (valAt [this key] [this key notFound]) (size [this]) (isEmpty [this]) (containsKey [this key]) (containsValue [this value]) (get [this key]) (put [this key value]) (remove [this key]) (putAll [this map]) (clear [this]) (keySet [this]) (values [this]) (entrySet [this]) (equals [this o]) (hashCode [this]) (hasheq [this])) (defn ^String ->toString [this] (RT/printString this)) (defn ->cons [pm o] (log/debug (format "->cons object %s" o)) (cond (instance? java.util.Map$Entry o) (assoc pm (.getKey o) (.getValue o)) (satisfies? pv/PersistentVector o) (if (= 2 (pv/count o)) (pv/assoc pm (pv/nth o 0) (pv/nth o 1)) (throw (IllegalArgumentException. "Vector arg to map conj must be a pair"))) :else (throw (RuntimeException. "pm/->cons missing implementation")))) (defn ->get [pm k] (valAt pm k)) (def PersistentMapImpl {:cons #'->cons :get #'->get})
54b53fc373203d418ecde08898b42399e324186e3eee01b0cfd785468751f306
jbracker/supermonad
TypeChecker.hs
# LANGUAGE RebindableSyntax # {-# OPTIONS_GHC -fplugin Control.Supermonad.Plugin #-} * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * H M T C * * * * Module : TypeChcker * * Purpose : MiniTriangle Type Checker * * Authors : * * * * Copyright ( c ) , 2006 - 2015 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ****************************************************************************** * H M T C * * * * Module: TypeChcker * * Purpose: MiniTriangle Type Checker * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2006 - 2015 * * * ****************************************************************************** -} | MiniTriangle Type Checker . Substantially re - written autumn 2013 module TypeChecker ( typeCheck, -- :: A.AST -> D MTIR testTypeChecker -- :: String -> [(Name,Type)] -> IO () ) where import Control.Supermonad.Prelude -- Standard library imports import Data.List ((\\), nub, sort, intersperse) import Data.Maybe (fromJust) import Control.Monad (mapAndUnzipM, unless) import Control.Monad.Fix (mfix) import Debug.Trace (trace, traceShow) HMTC module imports import SrcPos import Diagnostics import Name import ScopeLevel import Type import Symbol import Env import MTStdEnv import qualified AST as A import MTIR import PPMTIR import Parser (parse) | Type checks a complete MiniTriangle program in the standard environment -- and reports any errors. Hence a computation in the diagnostics monad 'D'. -- Additionally, translates the program into the type-annotated, intermediate representation MTIR , including eliminating implicit dereferencing at the -- source level by inserting explicit dereferencing operations. See the Coursework Description Part II for an explanation of the concepts -- and principles behind this type checker, along with the typing rules that define the MiniTriangle type system which this type checker implements . In particular , comments like " T - IF " , " env(x ) = s " and " env |- e : t " -- refers to those typing rules, with the following naming conventions: -- -- Type set typing rule ASCII Comments -- -------------------- -------------- -- Capital gamma "env" -- turnstile "|-" -- vector notation (e.g. "e" overlined) plural "s" suffix, e.g. "es" typeCheck :: A.AST -> D MTIR typeCheck (A.AST {A.astCmd = c}) = do c' <- chkCmd mtStdEnv c return (MTIR {mtirCmd = c'}) ------------------------------------------------------------------------------ -- Implementation of main typing rules ------------------------------------------------------------------------------ -- Check that command is well-formed in the given environment: -- -- env |- c chkCmd :: Env -> A.Command -> D Command -- T-ASSIGN chkCmd env (A.CmdAssign {A.caVar = x, A.caVal = e, A.cmdSrcPos = sp}) = do (s, x') <- infTpExp env x -- env |- x : s (t, x'')<- sinks_nonreftype s x' -- sinks(s,t), not reftype(t) e' <- chkTpExp env e t -- env |- e : t return (CmdAssign {caVar = x'', caVal = e', cmdSrcPos = sp}) -- T-CALL chkCmd env (A.CmdCall {A.ccProc = p, A.ccArgs = es, A.cmdSrcPos = sp}) = do (ss, es') <- mapAndUnzipM (infTpExp env) es (ts, t, p') <- infArrTpExp env p ss -- env |- p : ts->Void require (t == Void) sp (notProcMsg t) es'' <- zipWith3M sources ss ts es' -- env |- es : ts return (CmdCall {ccProc = p', ccArgs = es'', cmdSrcPos = sp}) where notProcMsg t = "Not a procedure; return type is " ++ show t -- T-SEQ (generalized to sequence of any length) chkCmd env (A.CmdSeq {A.csCmds = cs, A.cmdSrcPos = sp}) = do cs' <- mapM (chkCmd env) cs return (CmdSeq {csCmds = cs', cmdSrcPos = sp}) -- T-IF chkCmd env (A.CmdIf {A.ciCondThens = ecs, A.ciMbElse = mbce, A.cmdSrcPos=sp}) = do ecs' <- mapM (tcCondThen env) ecs -- env |- cs mbce' <- case mbce of Nothing -> return Nothing Just ce -> do ce' <- chkCmd env ce -- env |- ce return (Just ce') return (CmdIf {ciCondThens = ecs', ciMbElse = mbce', cmdSrcPos = sp}) where tcCondThen :: Env -> (A.Expression, A.Command) -> D (Expression, Command) tcCondThen env (e, c) = do e' <- chkTpExp env e Boolean c' <- chkCmd env c return (e', c') -- T-WHILE chkCmd env (A.CmdWhile {A.cwCond = e, A.cwBody = c, A.cmdSrcPos = sp}) = do e' <- chkTpExp env e Boolean -- env |- e : Boolean c' <- chkCmd env c -- env |- c return (CmdWhile {cwCond = e', cwBody = c', cmdSrcPos = sp}) -- T-REPEAT chkCmd env (A.CmdRepeat {A.crBody = c, A.crCond = e, A.cmdSrcPos = sp}) = do c' <- chkCmd env c -- env |- c e' <- chkTpExp env e Boolean -- env |- e : Boolean return (CmdRepeat {crBody = c', crCond = e', cmdSrcPos = sp}) -- T-LET chkCmd env (A.CmdLet {A.clDecls = ds, A.clBody = c, A.cmdSrcPos = sp}) = do (ds', env') <- mfix $ \ ~(_, env') -> -- env;env'|- ds | env' chkDeclarations (openMinScope env) env' ds c' <- chkCmd env' c -- env' |- c return (CmdLet {clDecls = ds', clBody = c', cmdSrcPos = sp}) -- Check that declarations/definitions are well-typed in given environment -- and environmant for function/procedure bodies and compute extended -- environment: -- -- env; envB |- ds | env' -- -- [For future reference: If user defined types were allowed, envB should -- perhaps be used in place of env for elaboarting types and computing -- function/procedure types if it is desired to allow (mutually) recursive -- type definitions.] chkDeclarations :: Env -> Env -> [A.Declaration] -> D ([Declaration], Env) -- T-DECLEMPTY chkDeclarations env envB [] = return ([], env) -- T-DECLCONST chkDeclarations env envB (A.DeclConst {A.dcConst = x, A.dcVal = e, A.dcType = t, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t e' <- chkTpExp env e t' -- env |- e : t case enterIntTermSym x (Src t') sp env of -- env' = env, x : Src t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do wellinit (itmsLvl x') e' (ds', env'') <- chkDeclarations env' -- env'; envB |- ds | env'' envB ds return (DeclConst {dcConst = x', dcVal = e'} : ds', env'') -- T-DECLVAR chkDeclarations env envB (A.DeclVar {A.dvVar = x, A.dvType = t, A.dvMbVal = Nothing, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t case enterIntTermSym x (Ref t') sp env of -- env' = env, x : Ref t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do (ds', env'') <- chkDeclarations env' -- env'; envB |- ds | env'' envB ds return (DeclVar {dvVar = x', dvMbVal = Nothing} : ds', env'') -- T-DECLINITVAR chkDeclarations env envB (A.DeclVar {A.dvVar = x, A.dvType = t, A.dvMbVal = Just e, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t e' <- chkTpExp env e t' -- env |- e : t case enterIntTermSym x (Ref t') sp env of -- env' = env, x : Ref t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do wellinit (itmsLvl x') e' (ds', env'') <- chkDeclarations env' -- env'; envB |- ds | env'' envB ds return (DeclVar {dvVar = x', dvMbVal = Just e'} : ds', env'') -- T-DECLFUN chkDeclarations env envB (A.DeclFun {A.dfFun = f, A.dfOvrld = o, A.dfArgDecls = as, A.dfType = t, A.dfBody = e, A.declSrcPos = sp} : ds) = do ~(as', envB') <- chkArgDecls (openMajScope envB) as -- envB |- as | envB' tf <- funType env as t e' <- chkTpExp envB' e (retType tf) -- envB' |- e : t case enterSym f tf sp env of -- env' = env, f: tf Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', f') -> do (ds', env'') <- chkDeclarations env' -- env'; envB |- ds | env'' envB ds return (DeclFun {dfFun = f', dfArgs = as', dfBody = e'} : ds', env'') where enterSym = if o then enterOvrldIntTermSym else enterIntTermSym -- T-DECLPROC chkDeclarations env envB (A.DeclProc {A.dpProc = p, A.dpOvrld = o, A.dpArgDecls = as, A.dpBody = c, A.declSrcPos = sp} : ds) = do ~(as', envB') <- chkArgDecls (openMajScope envB) as -- envB |- as | envB' c' <- chkCmd envB' c -- envB' |- c tp <- procType env as case enterSym p tp sp env of -- env' = env, f: tf Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', p') -> do (ds', env'') <- chkDeclarations env' -- env'; envB |- ds | env'' envB ds return (DeclProc {dpProc = p', dpArgs = as', dpBody = c'} : ds', env'') where enterSym = if o then enterOvrldIntTermSym else enterIntTermSym -- Check that function/procedure argument declarations are well-typed in -- given environment and compute extended environment: -- -- env |- as | env' chkArgDecls :: Env -> [A.ArgDecl] -> D ([IntTermSym], Env) -- T-DECLARGEMPTY chkArgDecls env [] = return ([], env) -- T-DECLARG, T-DECLINARG, T-DECLOUTARG, T-DECLVARARG chkArgDecls env (A.ArgDecl {A.adArg = x, A.adArgMode = am, A.adType = td, A.adSrcPos=sp} : as) = do t <- chkDclType env td case enterIntTermSym x (Src (amType am t)) sp env of -- env' = env, x: ... Left old -> do emitErrD sp (redeclaredMsg old) chkArgDecls env as Right (env', x') -> do (as', env'') <- chkArgDecls env' as -- env' |- as | env'' return (x' : as', env'') redeclaredMsg :: IntTermSym -> String redeclaredMsg itms = "Identifier \"" ++ itmsName itms ++ "\" redeclared; already declared at " ++ show (itmsSrcPos itms) procType :: Env -> [A.ArgDecl] -> D Type procType env as = do ts <- chkArgTypes env as return (Arr ts Void) funType :: Env -> [A.ArgDecl] -> A.TypeDenoter -> D Type funType env as td = do ts <- chkArgTypes env as t <- chkDclType env td return (Arr ts t) chkArgTypes :: Env -> [A.ArgDecl] -> D [Type] chkArgTypes env [] = return [] chkArgTypes env (A.ArgDecl {A.adArgMode = am, A.adType = td} : as) = do t <- chkDclType env td ts <- chkArgTypes env as return (amType am t : ts) -- Checks that a given type is defined and translate into internal type -- representation. chkDclType :: Env -> A.TypeDenoter -> D Type chkDclType env (A.TDBaseType {A.tdbtName = t, A.tdSrcPos = sp}) = case lookupTypeSym t env of Nothing -> do emitErrD sp ("Undefined type \"" ++ t ++ "\"") return SomeType Just tps -> return (tpsType tps) chkDclType env (A.TDArray {A.tdaEltType = t, A.tdaSize = s, A.tdSrcPos = sp}) = do t' <- chkDclType env t s' <- toMTInt s sp return (Ary t' s') chkDclType env (A.TDRecord {A.tdrFldTypes = fts}) = do -- Note: Ensures record fields are sorted (invariant of Rcd) let (xs,ts) = unzip fts ts' <- mapM (chkDclType env) ts return (Rcd (sortRcdFlds (zip xs ts'))) -- Type representation corresponding to given argument mode amType :: A.ArgMode -> (Type -> Type) amType A.ByValue = id -- Call-by-value amType A.ByRefIn = Src -- Call-by-ref input amType A.ByRefOut = Snk -- Call-by-ref output amType A.ByRefVar = Ref -- Call-by-ref variable -- Check that expression has type t in given environment: -- -- env |- e : t -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is known. Knowing the target type -- makes it easy to use the rule T-SOURCES. chkTpExp :: Env -> A.Expression -> Type -> D Expression -- T-SOURCES chkTpExp env e t = do (s, e') <- infTpExp env e -- env |- e : s, sources(s,t) sources s t e' -- Check that expression is well-typed in the given environment and -- infer its type assuming no (top-level) implicit dereferencing: -- -- env |- e : t -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is not known and leaving the option -- for further dereferencing open. infTpExp :: Env -> A.Expression -> D (Type, Expression) -- T-LITCHR infTpExp env e@(A.ExpLitChr {A.elcVal = c, A.expSrcPos = sp}) = do c' <- toMTChr c sp return (Character, -- env |- c : Character ExpLitChr {elcVal = c', expType = Character, expSrcPos = sp}) -- T-LITINT infTpExp env e@(A.ExpLitInt {A.eliVal = n, A.expSrcPos = sp}) = do n' <- toMTInt n sp return (Integer, -- env |- n : Integer ExpLitInt {eliVal = n', expType = Integer, expSrcPos = sp}) -- T-VAR infTpExp env (A.ExpVar {A.evVar = x, A.expSrcPos = sp}) = do env(x ) = t , sources(t , t ) Nothing -> do emitErrD sp ("Variable \"" ++ x ++ "\" undefined") return (dummyTmS x) Just tms -> return tms return (tmsType tms, tmsToExp tms sp) -- T-APP infTpExp env (A.ExpApp {A.eaFun = f, A.eaArgs = es, A.expSrcPos = sp}) = do (ss, es') <- mapAndUnzipM (infTpExp env) es (ts, t, f') <- infArrTpExp env f ss -- env |- f : ts -> t es'' <- zipWith3M sources ss ts es' -- env |- es : ts return (t, ExpApp {eaFun = f', eaArgs = es'', expType = t, expSrcPos = sp}) infTpExp env (A.ExpCond {A.ecCond = e1, A.ecTrue = e2, A.ecFalse = e3, A.expSrcPos = sp}) = do e1' <- chkTpExp env e1 Boolean -- Env |- e1 : Boolean (t, e2') <- infNonRefTpExp env e2 -- Env |- e2 : t (t', e3') <- infNonRefTpExp env e3 -- Env |- e3 : t' require (t == t') sp ("Conditional branches have to have the same \ \types; " ++ "got " ++ show t ++ " and " ++ show t') return (t, ExpCond {ecCond = e1', ecTrue = e2', ecFalse = e3', expType = t, expSrcPos = sp}) -- T-ARY, empty case handled specially infTpExp env (A.ExpAry {A.eaElts = [], A.expSrcPos = sp}) = do let t = Ary SomeType 0 return (t, ExpAry {eaElts = [], expType = t, expSrcPos = sp}) infTpExp env (A.ExpAry {A.eaElts = ees@(e:es), A.expSrcPos = sp}) = do (t, e') <- infNonRefTpExp env e -- env |- e : t, not reftype(t) es' <- mapM (\e -> chkTpExp env e t) es let ta = Ary t (fromIntegral (length ees)) return (ta, ExpAry {eaElts = e':es', expType = ta, expSrcPos = sp}) -- T-IX infTpExp env (A.ExpIx {A.eiAry = a, A.eiIx = i, A.expSrcPos = sp}) = do (rat, a') <- infRefAryTpExp env a -- env |- a : R(T[n]) i' <- chkTpExp env i Integer -- end |- i : Integer let rt = mapRfcdType eltType rat return (rt, ExpIx {eiAry = a', eiIx = i', expType = rt, expSrcPos = sp}) -- T-RCD infTpExp env (A.ExpRcd {A.erFldDefs = fds, A.expSrcPos = sp}) = do Note : Ensures record fields are sorted ( invariant of ExpRcd and Rcd ) let (xs, es) = unzip (sortRcdFlds fds) tes' <- mapM (infNonRefTpExp env) es require (allDistinct xs) sp (repeatedMsg xs) let (ts, es') = unzip tes' let fds' = zip xs es' let tr = Rcd (zip xs ts) return (tr, ExpRcd {erFldDefs = fds', expType = tr, expSrcPos = sp}) where allDistinct xs = xs == nub xs repeatedMsg xs = "Repeated record field name(s): \"" ++ concat (intersperse "\", \"" (nub (xs \\ nub xs))) ++ "\"" -- T-PRJ infTpExp env (A.ExpPrj {A.epRcd = e, A.epFld = f, A.expSrcPos = sp}) = do (rrt, e') <- infRefRcdTpExp env e -- env |- e : R({xs:ts}) require (fldExists f (rfcdType rrt)) sp (notAFieldMsg f (rfcdType rrt)) let rt = mapRfcdType (fldType f) rrt return (rt, ExpPrj {epRcd = e', epFld = f, expType = rt, expSrcPos = sp}) where notAFieldMsg f rt = "The type \"" ++ show rt ++ "\" does not contain any field \"" ++ f ++ "\"" -- Check that expression is well-typed in the given environment and -- infer its type assuming it should be an non-reference type: -- -- env |- e : t, not reftype(t) -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is known to be a non-reference type. infNonRefTpExp :: Env -> A.Expression -> D (Type, Expression) infNonRefTpExp env e = do (t, e') <- infTpExp env e sources_pred (not . refType) "non-reference type" t e' -- Check that expression is well-typed in the given environment and -- infer its type assuming it should be an arrow type and given the -- inferred but not dereferenced types of the actual arguments: -- -- env |- e : ts -> t -- -- The caller is responsible for checking that the type of each actual -- argument can source the type of the corresponding formal argument and -- dereference the argument expression as necessary (use "sources"). -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is known to be an arrow type. -- -- The number of actual arguments is used to check the arity of expression -- type, reporting any mismatch and guaranteeing that the arity of the -- returned type agrees. -- -- The number and types of the actual arguments are used for resolving -- overloading in the case of *manifest* calls (the name of the procedure -- or function given directly as opposed to a procedure or function being -- computed). infArrTpExp :: Env -> A.Expression -> [Type] -> D ([Type], Type, Expression) infArrTpExp env e@(A.ExpVar {A.evVar = x}) ss | null tmss = do emitErrD sp ("No procedure or function called \"" ++ x ++ "\"") return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) | arrType (tmsType (head tmss)) = -- Manifest procedure or function call. Overloading resolution only carried -- out for manifest calls. A call is considered manifest if at least the -- first of any overloadings of the applied symbol is a manifest procedure -- or function (arrow type). case tmssCA of [] -> do emitErrD sp ("No instance of \"" ++ x ++ "\" has expected arity " ++ show a) return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) [tms] -> case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" _ -> case tmssCS of [] -> do emitErrD sp ("No instance of \"" ++ x ++ "\" has a signature that agrees with \ \the types of the actual arguments: " ++ concat(intersperse ", " (map show ss))) return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) [tms] -> case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" (tms : _) -> do emitWngD sp ("Ambiguous overloading of \"" ++ x ++ "\": more than one instance have \ \a signature that agrees with the \ \types of the actual arguments") case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" where sp = srcPos e a = length ss -- Expected arity tmss = lookupOvrldTermSym x env tmssCA = [ tms -- Tm syms with Correct Arity | tms <- tmss, let t = tmsType tms, arrType t && arity t == a ] Tm syms with Compatible Sig . | tms <- tmssCA, and (zipWith sourcesp ss (argTypes (tmsType tms))) ] infArrTpExp env e ss = do -- This is the case of a computation yielding (a reference to) a -- procedure or function. No overloading resolution in this case. (s, e') <- infNonRefTpExp env e case s of Arr ts t -> do require (length ts == a) sp ("Bad arity: expected " ++ show (length ts) ++ " arguments, got " ++ show a) return (ensureArity a ts, t, e') SomeType -> do return (ensureArity a [], SomeType, e') _ -> do emitErrD sp "Not a function or procedure" return (ensureArity a [], SomeType, e') where sp = srcPos e a = length ss -- Expected arity ensureArity :: Int -> [Type] -> [Type] ensureArity a ts = take a (ts ++ repeat SomeType) -- Check that expression is well-typed in the given environment and -- infer its type assuming it should be a reference to an array: -- env |- e : R ( t[n ] ) , R in { Src , Snk , Ref } -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is known to be a reference to an array. infRefAryTpExp :: Env -> A.Expression -> D (Type, Expression) infRefAryTpExp env e = do (t, e') <- infTpExp env e sources_pred refAry "reference to array" t e' where refAry (Src (Ary _ _)) = True refAry (Snk (Ary _ _)) = True refAry (Ref (Ary _ _)) = True refAry _ = False -- Check that expression is well-typed in the given environment and -- infer its type assuming it should be a reference to a record: -- env |- e : R ( { a : t , ... } ) , R in { Src , Snk , Ref } -- -- This is an algorithmic version of the typing relation for expressions -- to be used when the desired type is known to be a reference to a record. infRefRcdTpExp :: Env -> A.Expression -> D (Type, Expression) infRefRcdTpExp env e = do (t, e') <- infTpExp env e sources_pred refRcd "reference to record" t e' where refRcd (Src (Rcd _)) = True refRcd (Snk (Rcd _)) = True refRcd (Ref (Rcd _)) = True refRcd _ = False Convert Integer to MTInt ( MiniTriangle integer ) , ensuring it is -- representable as such. toMTInt :: Integer -> SrcPos -> D MTInt toMTInt n sp = if isMTInt n then return (fromInteger n) else do emitErrD sp ("Integer literal " ++ show n ++ " outside the range of " ++ "representable MiniTriangle integers") return 0 ( MiniTriangle character ) , ensuring it is -- representable as such. toMTChr :: Char -> SrcPos -> D MTChr toMTChr c sp = if isMTChr c then MTChr is currently just a type synonym else do emitErrD sp ("Character literal " ++ show c ++ " outside the range of " ++ "representable MiniTriangle characters") return '?' -- Converts an (internal or external) term symbol into an MTIR expression: -- a variable for internal symbols, or constant/external reference for -- an external symbol. tmsToExp :: TermSym -> SrcPos -> Expression tmsToExp (Left (ExtTermSym {etmsVal = v, etmsType = t})) sp = case v of ESVBool b -> ExpLitBool {elbVal = b, expType = t, expSrcPos = sp} ESVInt n -> ExpLitInt {eliVal = n, expType = t, expSrcPos = sp} ESVChar c -> ExpLitChr {elcVal = c, expType = t, expSrcPos = sp} ESVLbl l -> ExpExtRef {eerVal = l, expType = t, expSrcPos = sp} tmsToExp (Right itms@(IntTermSym {itmsType = t})) sp = ExpVar { evVar = itms, expType = t, expSrcPos = sp } ------------------------------------------------------------------------------ -- Implementation of auxiliary predicates ------------------------------------------------------------------------------ -- Check if the value of an expression of the given type can source a value -- of the other given type. This is a version of the predicate "sources" -- from the type system specification turned into a function assuming both -- types are known. -- Additionally "coerces" the type of the expression by embedding it in -- the appropriate number of dereferencing operations. sources :: Type -> Type -> Expression -> D Expression sources s t e | s <: t = return e sources (Ref s) t e = sources s t (deref e) sources (Src s) t e = sources s t (deref e) sources s t e = do emitErrD (srcPos e) ("Expected type \"" ++ show t ++ "\", got \"" ++ show s ++ "\"") return e -- Predicate version of the above. sourcesp :: Type -> Type -> Bool sourcesp s t | s <: t = True sourcesp (Ref s) t = sourcesp s t sourcesp (Src s) t = sourcesp s t sourcesp _ _ = False -- Alternative definition without explicit use of subtyping for reference . -- Somewhat less flexible and a bit more verbose , but adequate for -- MiniTriangle as it stands , and avoiding subtyping is a simplification . sources : : Type - > Type - > Expression - > D Expression sources s t e | s = = t = return e sources ( Ref s ) ( Snk t ) e | s = = t = return e sources ( Ref s ) ( Src t ) e | s = = t = return e sources ( Ref s ) t e = sources s t ( deref e ) sources ( Src s ) t e = sources s t ( deref e ) sources s t e = do emitErrD ( srcPos e ) ( " Expected type \ " " + + show t + + " \ " , got \ " " + + show s + + " \ " " ) return e -- Alternative definition without explicit use of subtyping for reference. -- Somewhat less flexible and a bit more verbose, but adequate for -- MiniTriangle as it stands, and avoiding subtyping is a simplification. sources :: Type -> Type -> Expression -> D Expression sources s t e | s == t = return e sources (Ref s) (Snk t) e | s == t = return e sources (Ref s) (Src t) e | s == t = return e sources (Ref s) t e = sources s t (deref e) sources (Src s) t e = sources s t (deref e) sources s t e = do emitErrD (srcPos e) ("Expected type \"" ++ show t ++ "\", got \"" ++ show s ++ "\"") return e -} -- Check if the value of an expression of the given type can source a type -- satisfying an additinal predicate p. That is, an implementation of the -- combination: -- -- sources(s,t), p(t) -- -- assuming type "s" is given and "t" is to be computed. -- Additionally "coerces" the type of the expression by embedding it in -- the appropriate number of dereferencing operations. sources_pred :: (Type -> Bool) -> String -> Type -> Expression -> D (Type, Expression) sources_pred p et t e | p t = return (t, e) sources_pred p et (Ref t) e = sources_pred p et t (deref e) sources_pred p et (Src t) e = sources_pred p et t (deref e) sources_pred p et t e = do emitErrD (srcPos e) ("Expected " ++ et ++ ", got \"" ++ show t ++ "\"") return (SomeType, e) -- Check if the value of an expression of the given type can sink a non- -- reference type. That is, an implementation of the combination: -- -- sinks(s,t), not reftype(t) -- -- assuming type "s" is given and "t" is to be computed. -- Additionally "coerces" the type of the expression by embedding it in -- the appropriate number of dereferencing operations. sinks_nonreftype :: Type -> Expression -> D (Type, Expression) sinks_nonreftype (Snk t) e | not (refType t) = return (t, e) | otherwise = do emitErrD (srcPos e) "Cannot assign value of non-reference type to this variable" return (SomeType, e) sinks_nonreftype (Src t) e = sinks_nonreftype t (deref e) sinks_nonreftype (Ref t) e | not (refType t) = return (t, e) | otherwise = sinks_nonreftype t (deref e) sinks_nonreftype SomeType e = return (SomeType, e) sinks_nonreftype _ e = do emitErrD (srcPos e) "Does not denote an assignable variable" return (SomeType, e) an expression in a dereferencing operation . deref :: Expression -> Expression deref e = ExpDeref { edArg = e, expType = rfcdType (expType e), expSrcPos = srcPos e } -- Check that an initialiser (expression defining a constant or initialising -- a variable) is well-initialised; i.e. does not call a function defined -- at the present scope level as this means it could refer to constants -- or variables that have not yet been initialised or even allocated. This is defined on MTIR rather than AST , simplifying the definition -- as the scope level of a variable is directly available, meaning that -- there is no need to look up variables in the environment. -- -- [For future reference: -- Note that this restriction could be relaxed. For example, one could -- for each function compute the set of constants/variables from the -- same block to which it refers directly or indirectly, and then -- flag a problem only if a function referring to constants/variables -- currently not in scope are called. But, as functions may be mutually -- recursive, this requires computing strongly connected components or -- an iterative fixed-point computation. -- -- Or one could implement initialization in dependency order, combined -- with a static check that there are no cycles. Or one could reorder -- declaration lists, moving procedures and functions to the end, -- either after type checking and then possibly combined with adapted -- code generation strategies, or before type checking, combined with -- changed scope rules (bringing all functions and procedures into scope -- at the start of a block) and possibly with adapted code generation -- strategies.] wellinit :: ScopeLvl -> Expression -> D () wellinit _ (ExpLitBool {}) = return () wellinit _ (ExpLitInt {}) = return () wellinit _ (ExpLitChr {}) = return () wellinit _ (ExpExtRef {}) = return () wellinit _ (ExpVar {}) = return () wellinit l (ExpDeref {edArg = e}) = wellinit l e wellinit l (ExpApp {eaFun = f, eaArgs = es}) = do case f of ExpLitBool {} -> return () -- Type error, will have been caught ExpLitInt {} -> return () -- Type error, will have been caught ExpLitChr {} -> return () -- Type error, will have been caught ExpExtRef {} -> return () -- Defined outside present scope ExpVar {evVar = IntTermSym {itmsLvl = l', itmsName = n}, expSrcPos = sp} | l' == l -> emitErrD sp ("Function \"" ++ n ++ "\" may not be called from initializers in the \ \same block as in which it is defined.") | otherwise -> return () e -> emitErrD (srcPos e) "Only known functions may be called in initializers." mapM_ (wellinit l) es wellinit l (ExpCond {ecCond = e1, ecTrue = e2, ecFalse = e3}) = wellinit l e1 >> wellinit l e2 >> wellinit l e3 wellinit l (ExpAry {eaElts = es}) = mapM_ (wellinit l) es wellinit l (ExpIx {eiAry = a, eiIx = i}) = wellinit l a >> wellinit l i wellinit l (ExpRcd {erFldDefs = fds}) = mapM_ (wellinit l . snd) fds wellinit l (ExpPrj {epRcd = e}) = wellinit l e ------------------------------------------------------------------------------ -- Error reporting utilities ------------------------------------------------------------------------------ -- Report an error unless the condition is true. require :: Bool -> SrcPos -> String -> D () require p sp m = unless p (emitErrD sp m) ------------------------------------------------------------------------------ Monadic utilities ------------------------------------------------------------------------------ -- Generalisation of zipWithM zipWith3M :: (BindCts m m m, Bind m m m, Return m, ReturnCts m) => (a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d] zipWith3M f (a:as) (b:bs) (c:cs) = do d <- f a b c ds <- zipWith3M f as bs cs return (d:ds) zipWith3M _ _ _ _ = return [] ------------------------------------------------------------------------------ -- Test utilities ------------------------------------------------------------------------------ -- | Test utility. Attempts to parse and then type check the given string input in the standard MT environment extended with any given bindings . If successful , pretty - prints the resulting MTIR representation . testTypeChecker :: String -> [(Name,Type)] -> IO () testTypeChecker s bs = do putStrLn "Diagnostics:" mapM_ (putStrLn . ppDMsg) (snd result) putStrLn "" case fst result of Just mtir -> do putStrLn "MTIR:" putStrLn (ppMTIR mtir) Nothing -> putStrLn "Parsing and typechecking produced no result." putStrLn "" where result :: (Maybe MTIR, [DMsg]) result = runDF (parseCheck s (extend mtStdEnv bs)) extend env [] = env extend env ((n,t):bs) = case enterIntTermSym n t NoSrcPos env of Left _ -> error "Extending MT Standard Environment failed!" Right (env', _) -> extend env' bs parseCheck s env = do ast <- parse s failIfErrorsD c <- dToDF (chkCmd env (A.astCmd ast)) return (MTIR {mtirCmd = c}) ------------------------------------------------------------------------------ -- Internal error reporting ------------------------------------------------------------------------------ tcErr :: String -> String -> a tcErr = internalError "TypeChecker"
null
https://raw.githubusercontent.com/jbracker/supermonad/2595396a225a65b1dce6ed9a1ce59960f392a55b/examples/monad/hmtc/supermonad/TypeChecker.hs
haskell
# OPTIONS_GHC -fplugin Control.Supermonad.Plugin # :: A.AST -> D MTIR :: String -> [(Name,Type)] -> IO () Standard library imports and reports any errors. Hence a computation in the diagnostics monad 'D'. Additionally, translates the program into the type-annotated, intermediate source level by inserting explicit dereferencing operations. and principles behind this type checker, along with the typing rules that refers to those typing rules, with the following naming conventions: Type set typing rule ASCII Comments -------------------- -------------- Capital gamma "env" turnstile "|-" vector notation (e.g. "e" overlined) plural "s" suffix, e.g. "es" ---------------------------------------------------------------------------- Implementation of main typing rules ---------------------------------------------------------------------------- Check that command is well-formed in the given environment: env |- c T-ASSIGN env |- x : s sinks(s,t), not reftype(t) env |- e : t T-CALL env |- p : ts->Void env |- es : ts T-SEQ (generalized to sequence of any length) T-IF env |- cs env |- ce T-WHILE env |- e : Boolean env |- c T-REPEAT env |- c env |- e : Boolean T-LET env;env'|- ds | env' env' |- c Check that declarations/definitions are well-typed in given environment and environmant for function/procedure bodies and compute extended environment: env; envB |- ds | env' [For future reference: If user defined types were allowed, envB should perhaps be used in place of env for elaboarting types and computing function/procedure types if it is desired to allow (mutually) recursive type definitions.] T-DECLEMPTY T-DECLCONST env |- e : t env' = env, x : Src t env'; envB |- ds | env'' T-DECLVAR env' = env, x : Ref t env'; envB |- ds | env'' T-DECLINITVAR env |- e : t env' = env, x : Ref t env'; envB |- ds | env'' T-DECLFUN envB |- as | envB' envB' |- e : t env' = env, f: tf env'; envB |- ds | env'' T-DECLPROC envB |- as | envB' envB' |- c env' = env, f: tf env'; envB |- ds | env'' Check that function/procedure argument declarations are well-typed in given environment and compute extended environment: env |- as | env' T-DECLARGEMPTY T-DECLARG, T-DECLINARG, T-DECLOUTARG, T-DECLVARARG env' = env, x: ... env' |- as | env'' Checks that a given type is defined and translate into internal type representation. Note: Ensures record fields are sorted (invariant of Rcd) Type representation corresponding to given argument mode Call-by-value Call-by-ref input Call-by-ref output Call-by-ref variable Check that expression has type t in given environment: env |- e : t This is an algorithmic version of the typing relation for expressions to be used when the desired type is known. Knowing the target type makes it easy to use the rule T-SOURCES. T-SOURCES env |- e : s, sources(s,t) Check that expression is well-typed in the given environment and infer its type assuming no (top-level) implicit dereferencing: env |- e : t This is an algorithmic version of the typing relation for expressions to be used when the desired type is not known and leaving the option for further dereferencing open. T-LITCHR env |- c : Character T-LITINT env |- n : Integer T-VAR T-APP env |- f : ts -> t env |- es : ts Env |- e1 : Boolean Env |- e2 : t Env |- e3 : t' T-ARY, empty case handled specially env |- e : t, not reftype(t) T-IX env |- a : R(T[n]) end |- i : Integer T-RCD T-PRJ env |- e : R({xs:ts}) Check that expression is well-typed in the given environment and infer its type assuming it should be an non-reference type: env |- e : t, not reftype(t) This is an algorithmic version of the typing relation for expressions to be used when the desired type is known to be a non-reference type. Check that expression is well-typed in the given environment and infer its type assuming it should be an arrow type and given the inferred but not dereferenced types of the actual arguments: env |- e : ts -> t The caller is responsible for checking that the type of each actual argument can source the type of the corresponding formal argument and dereference the argument expression as necessary (use "sources"). This is an algorithmic version of the typing relation for expressions to be used when the desired type is known to be an arrow type. The number of actual arguments is used to check the arity of expression type, reporting any mismatch and guaranteeing that the arity of the returned type agrees. The number and types of the actual arguments are used for resolving overloading in the case of *manifest* calls (the name of the procedure or function given directly as opposed to a procedure or function being computed). Manifest procedure or function call. Overloading resolution only carried out for manifest calls. A call is considered manifest if at least the first of any overloadings of the applied symbol is a manifest procedure or function (arrow type). Expected arity Tm syms with Correct Arity This is the case of a computation yielding (a reference to) a procedure or function. No overloading resolution in this case. Expected arity Check that expression is well-typed in the given environment and infer its type assuming it should be a reference to an array: This is an algorithmic version of the typing relation for expressions to be used when the desired type is known to be a reference to an array. Check that expression is well-typed in the given environment and infer its type assuming it should be a reference to a record: This is an algorithmic version of the typing relation for expressions to be used when the desired type is known to be a reference to a record. representable as such. representable as such. Converts an (internal or external) term symbol into an MTIR expression: a variable for internal symbols, or constant/external reference for an external symbol. ---------------------------------------------------------------------------- Implementation of auxiliary predicates ---------------------------------------------------------------------------- Check if the value of an expression of the given type can source a value of the other given type. This is a version of the predicate "sources" from the type system specification turned into a function assuming both types are known. Additionally "coerces" the type of the expression by embedding it in the appropriate number of dereferencing operations. Predicate version of the above. Alternative definition without explicit use of subtyping for reference . Somewhat less flexible and a bit more verbose , but adequate for MiniTriangle as it stands , and avoiding subtyping is a simplification . Alternative definition without explicit use of subtyping for reference. Somewhat less flexible and a bit more verbose, but adequate for MiniTriangle as it stands, and avoiding subtyping is a simplification. Check if the value of an expression of the given type can source a type satisfying an additinal predicate p. That is, an implementation of the combination: sources(s,t), p(t) assuming type "s" is given and "t" is to be computed. Additionally "coerces" the type of the expression by embedding it in the appropriate number of dereferencing operations. Check if the value of an expression of the given type can sink a non- reference type. That is, an implementation of the combination: sinks(s,t), not reftype(t) assuming type "s" is given and "t" is to be computed. Additionally "coerces" the type of the expression by embedding it in the appropriate number of dereferencing operations. Check that an initialiser (expression defining a constant or initialising a variable) is well-initialised; i.e. does not call a function defined at the present scope level as this means it could refer to constants or variables that have not yet been initialised or even allocated. as the scope level of a variable is directly available, meaning that there is no need to look up variables in the environment. [For future reference: Note that this restriction could be relaxed. For example, one could for each function compute the set of constants/variables from the same block to which it refers directly or indirectly, and then flag a problem only if a function referring to constants/variables currently not in scope are called. But, as functions may be mutually recursive, this requires computing strongly connected components or an iterative fixed-point computation. Or one could implement initialization in dependency order, combined with a static check that there are no cycles. Or one could reorder declaration lists, moving procedures and functions to the end, either after type checking and then possibly combined with adapted code generation strategies, or before type checking, combined with changed scope rules (bringing all functions and procedures into scope at the start of a block) and possibly with adapted code generation strategies.] Type error, will have been caught Type error, will have been caught Type error, will have been caught Defined outside present scope ---------------------------------------------------------------------------- Error reporting utilities ---------------------------------------------------------------------------- Report an error unless the condition is true. ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- Generalisation of zipWithM ---------------------------------------------------------------------------- Test utilities ---------------------------------------------------------------------------- | Test utility. Attempts to parse and then type check the given string ---------------------------------------------------------------------------- Internal error reporting ----------------------------------------------------------------------------
# LANGUAGE RebindableSyntax # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * H M T C * * * * Module : TypeChcker * * Purpose : MiniTriangle Type Checker * * Authors : * * * * Copyright ( c ) , 2006 - 2015 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ****************************************************************************** * H M T C * * * * Module: TypeChcker * * Purpose: MiniTriangle Type Checker * * Authors: Henrik Nilsson * * * * Copyright (c) Henrik Nilsson, 2006 - 2015 * * * ****************************************************************************** -} | MiniTriangle Type Checker . Substantially re - written autumn 2013 module TypeChecker ( ) where import Control.Supermonad.Prelude import Data.List ((\\), nub, sort, intersperse) import Data.Maybe (fromJust) import Control.Monad (mapAndUnzipM, unless) import Control.Monad.Fix (mfix) import Debug.Trace (trace, traceShow) HMTC module imports import SrcPos import Diagnostics import Name import ScopeLevel import Type import Symbol import Env import MTStdEnv import qualified AST as A import MTIR import PPMTIR import Parser (parse) | Type checks a complete MiniTriangle program in the standard environment representation MTIR , including eliminating implicit dereferencing at the See the Coursework Description Part II for an explanation of the concepts define the MiniTriangle type system which this type checker implements . In particular , comments like " T - IF " , " env(x ) = s " and " env |- e : t " typeCheck :: A.AST -> D MTIR typeCheck (A.AST {A.astCmd = c}) = do c' <- chkCmd mtStdEnv c return (MTIR {mtirCmd = c'}) chkCmd :: Env -> A.Command -> D Command chkCmd env (A.CmdAssign {A.caVar = x, A.caVal = e, A.cmdSrcPos = sp}) = do return (CmdAssign {caVar = x'', caVal = e', cmdSrcPos = sp}) chkCmd env (A.CmdCall {A.ccProc = p, A.ccArgs = es, A.cmdSrcPos = sp}) = do (ss, es') <- mapAndUnzipM (infTpExp env) es require (t == Void) sp (notProcMsg t) return (CmdCall {ccProc = p', ccArgs = es'', cmdSrcPos = sp}) where notProcMsg t = "Not a procedure; return type is " ++ show t chkCmd env (A.CmdSeq {A.csCmds = cs, A.cmdSrcPos = sp}) = do cs' <- mapM (chkCmd env) cs return (CmdSeq {csCmds = cs', cmdSrcPos = sp}) chkCmd env (A.CmdIf {A.ciCondThens = ecs, A.ciMbElse = mbce, A.cmdSrcPos=sp}) = do ecs' <- mapM (tcCondThen env) ecs mbce' <- case mbce of Nothing -> return Nothing Just ce -> do return (Just ce') return (CmdIf {ciCondThens = ecs', ciMbElse = mbce', cmdSrcPos = sp}) where tcCondThen :: Env -> (A.Expression, A.Command) -> D (Expression, Command) tcCondThen env (e, c) = do e' <- chkTpExp env e Boolean c' <- chkCmd env c return (e', c') chkCmd env (A.CmdWhile {A.cwCond = e, A.cwBody = c, A.cmdSrcPos = sp}) = do return (CmdWhile {cwCond = e', cwBody = c', cmdSrcPos = sp}) chkCmd env (A.CmdRepeat {A.crBody = c, A.crCond = e, A.cmdSrcPos = sp}) = do return (CmdRepeat {crBody = c', crCond = e', cmdSrcPos = sp}) chkCmd env (A.CmdLet {A.clDecls = ds, A.clBody = c, A.cmdSrcPos = sp}) = do chkDeclarations (openMinScope env) env' ds return (CmdLet {clDecls = ds', clBody = c', cmdSrcPos = sp}) chkDeclarations :: Env -> Env -> [A.Declaration] -> D ([Declaration], Env) chkDeclarations env envB [] = return ([], env) chkDeclarations env envB (A.DeclConst {A.dcConst = x, A.dcVal = e, A.dcType = t, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do wellinit (itmsLvl x') e' envB ds return (DeclConst {dcConst = x', dcVal = e'} : ds', env'') chkDeclarations env envB (A.DeclVar {A.dvVar = x, A.dvType = t, A.dvMbVal = Nothing, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do envB ds return (DeclVar {dvVar = x', dvMbVal = Nothing} : ds', env'') chkDeclarations env envB (A.DeclVar {A.dvVar = x, A.dvType = t, A.dvMbVal = Just e, A.declSrcPos=sp} : ds) = do t' <- chkDclType env t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', x') -> do wellinit (itmsLvl x') e' envB ds return (DeclVar {dvVar = x', dvMbVal = Just e'} : ds', env'') chkDeclarations env envB (A.DeclFun {A.dfFun = f, A.dfOvrld = o, A.dfArgDecls = as, A.dfType = t, A.dfBody = e, A.declSrcPos = sp} : ds) = do tf <- funType env as t Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', f') -> do envB ds return (DeclFun {dfFun = f', dfArgs = as', dfBody = e'} : ds', env'') where enterSym = if o then enterOvrldIntTermSym else enterIntTermSym chkDeclarations env envB (A.DeclProc {A.dpProc = p, A.dpOvrld = o, A.dpArgDecls = as, A.dpBody = c, A.declSrcPos = sp} : ds) = do tp <- procType env as Left old -> do emitErrD sp (redeclaredMsg old) chkDeclarations env envB ds Right (env', p') -> do envB ds return (DeclProc {dpProc = p', dpArgs = as', dpBody = c'} : ds', env'') where enterSym = if o then enterOvrldIntTermSym else enterIntTermSym chkArgDecls :: Env -> [A.ArgDecl] -> D ([IntTermSym], Env) chkArgDecls env [] = return ([], env) chkArgDecls env (A.ArgDecl {A.adArg = x, A.adArgMode = am, A.adType = td, A.adSrcPos=sp} : as) = do t <- chkDclType env td Left old -> do emitErrD sp (redeclaredMsg old) chkArgDecls env as Right (env', x') -> do return (x' : as', env'') redeclaredMsg :: IntTermSym -> String redeclaredMsg itms = "Identifier \"" ++ itmsName itms ++ "\" redeclared; already declared at " ++ show (itmsSrcPos itms) procType :: Env -> [A.ArgDecl] -> D Type procType env as = do ts <- chkArgTypes env as return (Arr ts Void) funType :: Env -> [A.ArgDecl] -> A.TypeDenoter -> D Type funType env as td = do ts <- chkArgTypes env as t <- chkDclType env td return (Arr ts t) chkArgTypes :: Env -> [A.ArgDecl] -> D [Type] chkArgTypes env [] = return [] chkArgTypes env (A.ArgDecl {A.adArgMode = am, A.adType = td} : as) = do t <- chkDclType env td ts <- chkArgTypes env as return (amType am t : ts) chkDclType :: Env -> A.TypeDenoter -> D Type chkDclType env (A.TDBaseType {A.tdbtName = t, A.tdSrcPos = sp}) = case lookupTypeSym t env of Nothing -> do emitErrD sp ("Undefined type \"" ++ t ++ "\"") return SomeType Just tps -> return (tpsType tps) chkDclType env (A.TDArray {A.tdaEltType = t, A.tdaSize = s, A.tdSrcPos = sp}) = do t' <- chkDclType env t s' <- toMTInt s sp return (Ary t' s') chkDclType env (A.TDRecord {A.tdrFldTypes = fts}) = do let (xs,ts) = unzip fts ts' <- mapM (chkDclType env) ts return (Rcd (sortRcdFlds (zip xs ts'))) amType :: A.ArgMode -> (Type -> Type) chkTpExp :: Env -> A.Expression -> Type -> D Expression chkTpExp env e t = do sources s t e' infTpExp :: Env -> A.Expression -> D (Type, Expression) infTpExp env e@(A.ExpLitChr {A.elcVal = c, A.expSrcPos = sp}) = do c' <- toMTChr c sp ExpLitChr {elcVal = c', expType = Character, expSrcPos = sp}) infTpExp env e@(A.ExpLitInt {A.eliVal = n, A.expSrcPos = sp}) = do n' <- toMTInt n sp ExpLitInt {eliVal = n', expType = Integer, expSrcPos = sp}) infTpExp env (A.ExpVar {A.evVar = x, A.expSrcPos = sp}) = do env(x ) = t , sources(t , t ) Nothing -> do emitErrD sp ("Variable \"" ++ x ++ "\" undefined") return (dummyTmS x) Just tms -> return tms return (tmsType tms, tmsToExp tms sp) infTpExp env (A.ExpApp {A.eaFun = f, A.eaArgs = es, A.expSrcPos = sp}) = do (ss, es') <- mapAndUnzipM (infTpExp env) es return (t, ExpApp {eaFun = f', eaArgs = es'', expType = t, expSrcPos = sp}) infTpExp env (A.ExpCond {A.ecCond = e1, A.ecTrue = e2, A.ecFalse = e3, A.expSrcPos = sp}) = do require (t == t') sp ("Conditional branches have to have the same \ \types; " ++ "got " ++ show t ++ " and " ++ show t') return (t, ExpCond {ecCond = e1', ecTrue = e2', ecFalse = e3', expType = t, expSrcPos = sp}) infTpExp env (A.ExpAry {A.eaElts = [], A.expSrcPos = sp}) = do let t = Ary SomeType 0 return (t, ExpAry {eaElts = [], expType = t, expSrcPos = sp}) infTpExp env (A.ExpAry {A.eaElts = ees@(e:es), A.expSrcPos = sp}) = do es' <- mapM (\e -> chkTpExp env e t) es let ta = Ary t (fromIntegral (length ees)) return (ta, ExpAry {eaElts = e':es', expType = ta, expSrcPos = sp}) infTpExp env (A.ExpIx {A.eiAry = a, A.eiIx = i, A.expSrcPos = sp}) = do let rt = mapRfcdType eltType rat return (rt, ExpIx {eiAry = a', eiIx = i', expType = rt, expSrcPos = sp}) infTpExp env (A.ExpRcd {A.erFldDefs = fds, A.expSrcPos = sp}) = do Note : Ensures record fields are sorted ( invariant of ExpRcd and Rcd ) let (xs, es) = unzip (sortRcdFlds fds) tes' <- mapM (infNonRefTpExp env) es require (allDistinct xs) sp (repeatedMsg xs) let (ts, es') = unzip tes' let fds' = zip xs es' let tr = Rcd (zip xs ts) return (tr, ExpRcd {erFldDefs = fds', expType = tr, expSrcPos = sp}) where allDistinct xs = xs == nub xs repeatedMsg xs = "Repeated record field name(s): \"" ++ concat (intersperse "\", \"" (nub (xs \\ nub xs))) ++ "\"" infTpExp env (A.ExpPrj {A.epRcd = e, A.epFld = f, A.expSrcPos = sp}) = do require (fldExists f (rfcdType rrt)) sp (notAFieldMsg f (rfcdType rrt)) let rt = mapRfcdType (fldType f) rrt return (rt, ExpPrj {epRcd = e', epFld = f, expType = rt, expSrcPos = sp}) where notAFieldMsg f rt = "The type \"" ++ show rt ++ "\" does not contain any field \"" ++ f ++ "\"" infNonRefTpExp :: Env -> A.Expression -> D (Type, Expression) infNonRefTpExp env e = do (t, e') <- infTpExp env e sources_pred (not . refType) "non-reference type" t e' infArrTpExp :: Env -> A.Expression -> [Type] -> D ([Type], Type, Expression) infArrTpExp env e@(A.ExpVar {A.evVar = x}) ss | null tmss = do emitErrD sp ("No procedure or function called \"" ++ x ++ "\"") return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) | arrType (tmsType (head tmss)) = case tmssCA of [] -> do emitErrD sp ("No instance of \"" ++ x ++ "\" has expected arity " ++ show a) return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) [tms] -> case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" _ -> case tmssCS of [] -> do emitErrD sp ("No instance of \"" ++ x ++ "\" has a signature that agrees with \ \the types of the actual arguments: " ++ concat(intersperse ", " (map show ss))) return (ensureArity a [], SomeType, tmsToExp (dummyTmS x) sp) [tms] -> case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" (tms : _) -> do emitWngD sp ("Ambiguous overloading of \"" ++ x ++ "\": more than one instance have \ \a signature that agrees with the \ \types of the actual arguments") case tmsType tms of Arr ts t -> return (ts, t, tmsToExp tms sp) _ -> tcErr "infArrTpExp" "Expected arrow type" where sp = srcPos e tmss = lookupOvrldTermSym x env | tms <- tmss, let t = tmsType tms, arrType t && arity t == a ] Tm syms with Compatible Sig . | tms <- tmssCA, and (zipWith sourcesp ss (argTypes (tmsType tms))) ] infArrTpExp env e ss = do (s, e') <- infNonRefTpExp env e case s of Arr ts t -> do require (length ts == a) sp ("Bad arity: expected " ++ show (length ts) ++ " arguments, got " ++ show a) return (ensureArity a ts, t, e') SomeType -> do return (ensureArity a [], SomeType, e') _ -> do emitErrD sp "Not a function or procedure" return (ensureArity a [], SomeType, e') where sp = srcPos e ensureArity :: Int -> [Type] -> [Type] ensureArity a ts = take a (ts ++ repeat SomeType) env |- e : R ( t[n ] ) , R in { Src , Snk , Ref } infRefAryTpExp :: Env -> A.Expression -> D (Type, Expression) infRefAryTpExp env e = do (t, e') <- infTpExp env e sources_pred refAry "reference to array" t e' where refAry (Src (Ary _ _)) = True refAry (Snk (Ary _ _)) = True refAry (Ref (Ary _ _)) = True refAry _ = False env |- e : R ( { a : t , ... } ) , R in { Src , Snk , Ref } infRefRcdTpExp :: Env -> A.Expression -> D (Type, Expression) infRefRcdTpExp env e = do (t, e') <- infTpExp env e sources_pred refRcd "reference to record" t e' where refRcd (Src (Rcd _)) = True refRcd (Snk (Rcd _)) = True refRcd (Ref (Rcd _)) = True refRcd _ = False Convert Integer to MTInt ( MiniTriangle integer ) , ensuring it is toMTInt :: Integer -> SrcPos -> D MTInt toMTInt n sp = if isMTInt n then return (fromInteger n) else do emitErrD sp ("Integer literal " ++ show n ++ " outside the range of " ++ "representable MiniTriangle integers") return 0 ( MiniTriangle character ) , ensuring it is toMTChr :: Char -> SrcPos -> D MTChr toMTChr c sp = if isMTChr c then MTChr is currently just a type synonym else do emitErrD sp ("Character literal " ++ show c ++ " outside the range of " ++ "representable MiniTriangle characters") return '?' tmsToExp :: TermSym -> SrcPos -> Expression tmsToExp (Left (ExtTermSym {etmsVal = v, etmsType = t})) sp = case v of ESVBool b -> ExpLitBool {elbVal = b, expType = t, expSrcPos = sp} ESVInt n -> ExpLitInt {eliVal = n, expType = t, expSrcPos = sp} ESVChar c -> ExpLitChr {elcVal = c, expType = t, expSrcPos = sp} ESVLbl l -> ExpExtRef {eerVal = l, expType = t, expSrcPos = sp} tmsToExp (Right itms@(IntTermSym {itmsType = t})) sp = ExpVar { evVar = itms, expType = t, expSrcPos = sp } sources :: Type -> Type -> Expression -> D Expression sources s t e | s <: t = return e sources (Ref s) t e = sources s t (deref e) sources (Src s) t e = sources s t (deref e) sources s t e = do emitErrD (srcPos e) ("Expected type \"" ++ show t ++ "\", got \"" ++ show s ++ "\"") return e sourcesp :: Type -> Type -> Bool sourcesp s t | s <: t = True sourcesp (Ref s) t = sourcesp s t sourcesp (Src s) t = sourcesp s t sourcesp _ _ = False sources : : Type - > Type - > Expression - > D Expression sources s t e | s = = t = return e sources ( Ref s ) ( Snk t ) e | s = = t = return e sources ( Ref s ) ( Src t ) e | s = = t = return e sources ( Ref s ) t e = sources s t ( deref e ) sources ( Src s ) t e = sources s t ( deref e ) sources s t e = do emitErrD ( srcPos e ) ( " Expected type \ " " + + show t + + " \ " , got \ " " + + show s + + " \ " " ) return e sources :: Type -> Type -> Expression -> D Expression sources s t e | s == t = return e sources (Ref s) (Snk t) e | s == t = return e sources (Ref s) (Src t) e | s == t = return e sources (Ref s) t e = sources s t (deref e) sources (Src s) t e = sources s t (deref e) sources s t e = do emitErrD (srcPos e) ("Expected type \"" ++ show t ++ "\", got \"" ++ show s ++ "\"") return e -} sources_pred :: (Type -> Bool) -> String -> Type -> Expression -> D (Type, Expression) sources_pred p et t e | p t = return (t, e) sources_pred p et (Ref t) e = sources_pred p et t (deref e) sources_pred p et (Src t) e = sources_pred p et t (deref e) sources_pred p et t e = do emitErrD (srcPos e) ("Expected " ++ et ++ ", got \"" ++ show t ++ "\"") return (SomeType, e) sinks_nonreftype :: Type -> Expression -> D (Type, Expression) sinks_nonreftype (Snk t) e | not (refType t) = return (t, e) | otherwise = do emitErrD (srcPos e) "Cannot assign value of non-reference type to this variable" return (SomeType, e) sinks_nonreftype (Src t) e = sinks_nonreftype t (deref e) sinks_nonreftype (Ref t) e | not (refType t) = return (t, e) | otherwise = sinks_nonreftype t (deref e) sinks_nonreftype SomeType e = return (SomeType, e) sinks_nonreftype _ e = do emitErrD (srcPos e) "Does not denote an assignable variable" return (SomeType, e) an expression in a dereferencing operation . deref :: Expression -> Expression deref e = ExpDeref { edArg = e, expType = rfcdType (expType e), expSrcPos = srcPos e } This is defined on MTIR rather than AST , simplifying the definition wellinit :: ScopeLvl -> Expression -> D () wellinit _ (ExpLitBool {}) = return () wellinit _ (ExpLitInt {}) = return () wellinit _ (ExpLitChr {}) = return () wellinit _ (ExpExtRef {}) = return () wellinit _ (ExpVar {}) = return () wellinit l (ExpDeref {edArg = e}) = wellinit l e wellinit l (ExpApp {eaFun = f, eaArgs = es}) = do case f of ExpVar {evVar = IntTermSym {itmsLvl = l', itmsName = n}, expSrcPos = sp} | l' == l -> emitErrD sp ("Function \"" ++ n ++ "\" may not be called from initializers in the \ \same block as in which it is defined.") | otherwise -> return () e -> emitErrD (srcPos e) "Only known functions may be called in initializers." mapM_ (wellinit l) es wellinit l (ExpCond {ecCond = e1, ecTrue = e2, ecFalse = e3}) = wellinit l e1 >> wellinit l e2 >> wellinit l e3 wellinit l (ExpAry {eaElts = es}) = mapM_ (wellinit l) es wellinit l (ExpIx {eiAry = a, eiIx = i}) = wellinit l a >> wellinit l i wellinit l (ExpRcd {erFldDefs = fds}) = mapM_ (wellinit l . snd) fds wellinit l (ExpPrj {epRcd = e}) = wellinit l e require :: Bool -> SrcPos -> String -> D () require p sp m = unless p (emitErrD sp m) Monadic utilities zipWith3M :: (BindCts m m m, Bind m m m, Return m, ReturnCts m) => (a -> b -> c -> m d) -> [a] -> [b] -> [c] -> m [d] zipWith3M f (a:as) (b:bs) (c:cs) = do d <- f a b c ds <- zipWith3M f as bs cs return (d:ds) zipWith3M _ _ _ _ = return [] input in the standard MT environment extended with any given bindings . If successful , pretty - prints the resulting MTIR representation . testTypeChecker :: String -> [(Name,Type)] -> IO () testTypeChecker s bs = do putStrLn "Diagnostics:" mapM_ (putStrLn . ppDMsg) (snd result) putStrLn "" case fst result of Just mtir -> do putStrLn "MTIR:" putStrLn (ppMTIR mtir) Nothing -> putStrLn "Parsing and typechecking produced no result." putStrLn "" where result :: (Maybe MTIR, [DMsg]) result = runDF (parseCheck s (extend mtStdEnv bs)) extend env [] = env extend env ((n,t):bs) = case enterIntTermSym n t NoSrcPos env of Left _ -> error "Extending MT Standard Environment failed!" Right (env', _) -> extend env' bs parseCheck s env = do ast <- parse s failIfErrorsD c <- dToDF (chkCmd env (A.astCmd ast)) return (MTIR {mtirCmd = c}) tcErr :: String -> String -> a tcErr = internalError "TypeChecker"
7d1915df4483b17f9822f8592905f33ebbfe4267edd3b5db64cda4fcd87956a6
zenspider/schemers
exercise.4.74.scm
#!/usr/bin/env csi -s (require rackunit) Exercise 4.74 proposes to use a simpler ;; version of `stream-flatmap' in `negate', `lisp-value', and ;; `find-assertions'. She observes that the procedure that is mapped ;; over the frame stream in these cases always produces either the ;; empty stream or a singleton stream, so no interleaving is needed ;; when combining these streams. ;; a. Fill in the missing expressions in 's program . ;; ;; (define (simple-stream-flatmap proc s) ;; (simple-flatten (stream-map proc s))) ;; ;; (define (simple-flatten stream) ;; (stream-map <??> ;; (stream-filter <??> stream))) ;; ;; b. Does the query system's behavior change if we change it in ;; this way?
null
https://raw.githubusercontent.com/zenspider/schemers/2939ca553ac79013a4c3aaaec812c1bad3933b16/sicp/ch_4/exercise.4.74.scm
scheme
version of `stream-flatmap' in `negate', `lisp-value', and `find-assertions'. She observes that the procedure that is mapped over the frame stream in these cases always produces either the empty stream or a singleton stream, so no interleaving is needed when combining these streams. (define (simple-stream-flatmap proc s) (simple-flatten (stream-map proc s))) (define (simple-flatten stream) (stream-map <??> (stream-filter <??> stream))) b. Does the query system's behavior change if we change it in this way?
#!/usr/bin/env csi -s (require rackunit) Exercise 4.74 proposes to use a simpler a. Fill in the missing expressions in 's program .
0495e4d7e17e15c1ef8e81a13d56a59f7eccc5a5fdd5302de29b2b93d5b1dbdb
kloimhardt/werkbank
euclid.clj
; Copyright © 2017 . This work is based on the Scmutils system of MIT / GNU Scheme : Copyright © 2002 Massachusetts Institute of Technology ; ; This 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 software 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 code; if not, see </>. ; (ns sicmutils.euclid (:require [sicmutils.generic :as g] [sicmutils.value :as v])) (defn extended-gcd "The extended Euclidean algorithm (see ) Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs." [a b] (cond (v/nullity? a) [(g/abs b) 0 1] (v/nullity? b) [(g/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (g/abs b) r0 (g/abs a)] (if (v/nullity? r) [r0 s0 t0] (let [q (g/quotient r0 r)] (recur (g/- s0 (g/* q s)) s (g/- t0 (g/* q t)) t (g/- r0 (g/* q r)) r)))))) (defn gcd [a b] (cond (v/nullity? a) (g/abs b) (v/nullity? b) (g/abs a) (not (and (integer? a) (integer? b))) 1 :else (loop [a (g/abs a) b (g/abs b)] (if (v/nullity? b) a (recur b (g/remainder a b)))))) (defn lcm [a b] (g/abs (g/divide (g/* a b) (gcd a b))))
null
https://raw.githubusercontent.com/kloimhardt/werkbank/df66274eb978d060a043b8429b29d0f36c4a2e89/src/sicmutils/euclid.clj
clojure
This is free software; you can redistribute it and/or modify either version 3 of the License , or ( at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. along with this code; if not, see </>.
Copyright © 2017 . This work is based on the Scmutils system of MIT / GNU Scheme : Copyright © 2002 Massachusetts Institute of Technology it under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License (ns sicmutils.euclid (:require [sicmutils.generic :as g] [sicmutils.value :as v])) (defn extended-gcd "The extended Euclidean algorithm (see ) Returns a list containing the GCD and the Bézout coefficients corresponding to the inputs." [a b] (cond (v/nullity? a) [(g/abs b) 0 1] (v/nullity? b) [(g/abs a) 1 0] :else (loop [s 0 s0 1 t 1 t0 0 r (g/abs b) r0 (g/abs a)] (if (v/nullity? r) [r0 s0 t0] (let [q (g/quotient r0 r)] (recur (g/- s0 (g/* q s)) s (g/- t0 (g/* q t)) t (g/- r0 (g/* q r)) r)))))) (defn gcd [a b] (cond (v/nullity? a) (g/abs b) (v/nullity? b) (g/abs a) (not (and (integer? a) (integer? b))) 1 :else (loop [a (g/abs a) b (g/abs b)] (if (v/nullity? b) a (recur b (g/remainder a b)))))) (defn lcm [a b] (g/abs (g/divide (g/* a b) (gcd a b))))
e9aef00951a28e2aef82306b87bfac564d16ed6d5e3f97dbd5b6c53db6b92e40
jaredly/reepl
replumb.cljs
(ns reepl.replumb (:require [cljs.js :as jsc] [cljs.analyzer :as ana] [reepl.core :as reepl] [reepl.helpers :as helpers] [devtools.core :as devtools] [cljs.pprint :as pprint] [reagent.core :as r] [quil.core :as q :include-macros true] [cljs.tools.reader] [clojure.string :as str] [replumb.core :as replumb] [replumb.repl] [replumb.ast :as ast] [replumb.doc-maps :as docs] [cljs.repl :as repl] [parinfer-codemirror.editor :as parinfer] [parinfer.codemirror.mode.clojure.clojure-parinfer] [cljs.tools.reader.reader-types :refer [string-push-back-reader]] [cljs.tools.reader] [cljs.tagged-literals :as tags] [quil.middleware :as m]) (:import goog.net.XhrIo)) (defn fetch-file! "Very simple implementation of XMLHttpRequests that given a file path calls src-cb with the string fetched of nil in case of error. See doc at " [file-url src-cb] (try (.send XhrIo file-url (fn [e] (if (.isSuccess (.-target e)) (src-cb (.. e -target getResponseText)) (src-cb nil)))) (catch :default e (src-cb nil)))) (def replumb-opts (merge (replumb/browser-options ["/main.out" "/main.out"] TODO figure out file loading #_(fn [& a] nil) fetch-file!) {:warning-as-error true ;; :verbose true :no-pr-str-on-value true})) (defn find-last-expr-pos [text] ;; parse #js {} correctly (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) ;; get a unique js object as a sigil eof (js-obj) read #(cljs.tools.reader/read {:eof eof} rr) ] (loop [last-pos 0 second-pos 0 last-form nil second-form nil] (let [form (read) new-pos (.-s-pos (.-rdr rr))] (if (identical? eof form) second - form ] (recur new-pos last-pos form last-form))))))) (defn make-last-expr-set-val [text js-name] (let [last-pos (find-last-expr-pos text)] (js/console.log last-pos text) (when-not (= last-pos 0) (str (.slice text 0 last-pos) "(aset js/window \"" js-name "\" " (.slice text last-pos) ")" )))) (defn jsc-run [source cb] (jsc/eval-str replumb.repl/st source 'stuff {:eval (fn a [& b] (js/console.log "eval source" b) (apply jsc/js-eval b)) :ns (replumb.repl/current-ns) :context :statement :def-emits-var true} (fn [result] (swap! replumb.repl/app-env assoc :current-ns (:ns result)) (if (contains? result :error) (cb false (:error result)) (cb true (aget js/window "last_repl_value")))))) (defn get-first-form [text] ;; parse #js {} correctly (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) form (cljs.tools.reader/read rr) TODO this is a bit dependent on tools.reader internals ... s-pos (.-s-pos (.-rdr rr))] [form s-pos]))) (defn run-repl-multi [text opts cb] (let [text (.trim text) [form pos] (get-first-form text) source (.slice text 0 pos) remainder (.trim (.slice text pos)) has-more? (not (empty? remainder))] (js/console.log [text form pos source remainder has-more?]) (replumb/read-eval-call opts #(let [success? (replumb/success? %) result (replumb/unwrap-result %)] (js/console.log "evaled" [success? result has-more?]) (if-not success? (cb success? result) ;; TODO should I log the result if it's not the end? (if has-more? (run-repl-multi remainder opts cb) (cb success? result)) )) source))) ;; Trying to get expressions + statements to play well together TODO is this a better way ? The ` do ' stuff seems to work alright ... although ;; it won't work if there are other `ns' statements inside there... (defn run-repl-experimental* [text opts cb] (let [fixed (make-last-expr-set-val text "last_repl_value")] (if fixed (jsc-run fixed cb) (replumb/read-eval-call opts #(cb (replumb/success? %) (replumb/unwrap-result %)) text)))) (defn fix-ns-do [text] ;; parse #js {} correctly (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) form (cljs.tools.reader/read rr) is-ns (and (sequential? form) (= 'ns (first form))) TODO this is a bit dependent on tools.reader internals ... s-pos (.-s-pos (.-rdr rr))] (js/console.log is-ns form s-pos) (if-not is-ns (str "(do " text ")") (str (.slice text 0 s-pos) "(do " (.slice text s-pos) ")" ))))) (defn run-repl* [text opts cb] (replumb/read-eval-call opts #(cb (replumb/success? %) (replumb/unwrap-result %)) (fix-ns-do text))) (defn run-repl ([text cb] (run-repl-multi text replumb-opts cb)) ([text opts cb] (run-repl-multi text (merge replumb-opts opts) cb))) (defn compare-completion "The comparison algo for completions 1. if one is exactly the text, then it goes first 2. if one *starts* with the text, then it goes first 3. otherwise leave in current order" [text a b] (cond (and (= text a) (= text b)) 0 (= text a) -1 (= text b) 1 :else (let [a-starts (= 0 (.indexOf a text)) b-starts (= 0 (.indexOf b text))] (cond (and a-starts b-starts) 0 a-starts -1 b-starts 1 :default 0)))) (defn compare-ns "Sorting algo for namespaces The current ns comes first, then cljs.core, then anything else alphabetically" [current ns1 ns2] (cond (= ns1 current) -1 (= ns2 current) 1 (= ns1 'cljs.core) -1 (= ns2 'cljs.core) 1 :default (compare ns1 ns2))) (defn get-from-js-ns "Use js introspection to get a list of interns in a namespaces This is pretty dependent on cljs runtime internals, so it may break in the future (although I think it's fairly unlikely). It takes advantage of the fact that the ns `something.other.thing' is available as an object on `window.something.other.thing', and Object.keys gets all the variables in that namespace." [ns] (let [parts (map munge (.split (str ns) ".")) ns (reduce aget js/window parts)] (if-not ns [] (map demunge (js/Object.keys ns))))) (defn dedup-requires "Takes a map of {require-name ns-name} and dedups multiple keys that have the same ns-name value." [requires] (first (reduce (fn [[result seen] [k v]] (if (seen v) [result seen] [(assoc result k v) (conj seen v)])) [{} #{}] requires))) (defn get-matching-ns-interns [[name ns] matches? only-ns] (let [ns-name (str ns) publics (keys (ast/ns-publics @replumb.repl/st ns)) publics (if (empty? publics) (get-from-js-ns ns) publics)] (if-not (or (nil? only-ns) (= only-ns ns-name)) [] (sort (map #(symbol name (str %)) (filter matches? publics)))))) (defn js-attrs [obj] (if-not obj [] (let [constructor (.-constructor obj) proto (js/Object.getPrototypeOf obj)] (concat (js/Object.keys obj) (when-not (= proto obj) (js-attrs proto)))))) (defn js-completion [text] (let [parts (vec (.split text ".")) completing (or (last parts) "") prefix #(str "js/" (str/join "." (conj (vec (butlast parts)) %))) possibles (js-attrs (reduce aget js/window (butlast parts)))] (->> possibles (filter #(not (= -1 (.indexOf % completing)))) (sort (partial compare-completion text)) (map #(-> [nil (prefix %) (prefix %)]))))) ;; TODO fuzzy-match if there are no normal matches (defn cljs-completion "Tab completion. Copied w/ extensive modifications from replumb.repl/process-apropos." [text] (let [[only-ns text] (if-not (= -1 (.indexOf text "/")) (.split text "/") [nil text]) matches? #(and TODO find out what these t_cljs$core things are ... seem to be nil (= -1 (.indexOf (str %) "t_cljs$core")) (< -1 (.indexOf (str %) text))) current-ns (replumb.repl/current-ns) replace-name (fn [sym] (if (or (= (namespace sym) "cljs.core") (= (namespace sym) (str current-ns))) (name sym) (str sym))) requires (:requires (ast/namespace @replumb.repl/st current-ns)) only-ns (when only-ns (or (str (get requires (symbol only-ns))) only-ns)) requires (concat [[nil current-ns] [nil 'cljs.core]] (dedup-requires (vec requires))) names (set (apply concat requires)) defs (->> requires (sort-by second (partial compare-ns current-ns)) (mapcat #(get-matching-ns-interns % matches? only-ns)) ;; [qualified symbol, show text, replace text] (map #(-> [% (str %) (replace-name %) (name %)])) (sort-by #(get % 3) (partial compare-completion text)))] (vec (concat TODO make this configurable (take 75 defs) (map #(-> [% (str %) (str %)]) (filter matches? names)))))) (defn process-apropos [text] (if (= 0 (.indexOf text "js/")) (js-completion (.slice text 3)) (cljs-completion text) )) (defn get-forms [m] (cond (:forms m) (:forms m) (:arglists m) (let [arglists (:arglists m)] (if (or (:macro m) (:repl-special-function m)) arglists (if (= 'quote (first arglists)) (second arglists) arglists))))) Copied & modified from cljs.repl/print-doc (defn get-doc [m] (merge {:name (str (when-let [ns (:ns m)] (str ns "/")) (:name m)) :type (cond (:protocol m) :protocol (:special-form m) :special-form (:macro m) :macro (:repl-special-function m) :repl-special-function :else :normal) :forms (get-forms m) :doc (:doc m)} (if (:special-form m) {:please-see (if (contains? m :url) (when (:url m) (str "/" (:url m))) (str "#" (:name m)))} (when (:protocol m) {:protocol-methods (:methods m)})))) (defn doc-from-sym [sym] (cond (docs/special-doc-map sym) (get-doc (docs/special-doc sym)) (docs/repl-special-doc-map sym) (get-doc (docs/repl-special-doc sym)) (ast/namespace @replumb.repl/st sym) (get-doc (select-keys (ast/namespace @replumb.repl/st sym) [:name :doc])) :else (get-doc (replumb.repl/get-var nil (replumb.repl/empty-analyzer-env) sym)))) (def type-name {:protocol "Protocol" :special-form "Special Form" :macro "Macro" :repl-special-function "REPL Special Function"}) Copied & modified from cljs.repl/print-doc (defn print-doc [doc] (println (:name doc)) (if-not (= :normal (:type doc)) (println (type-name (:type doc)))) (when (:forms doc) (prn (:forms doc))) (when (:please-see doc) (println (str "\n Please see " (:please-see doc)))) (when (:doc doc) (println (:doc doc))) (when (:methods doc) (doseq [[name {:keys [doc arglists]}] (:methods doc)] (println) (println " " name) (println " " arglists) (when doc (println " " doc))))) (defn process-doc "Get the documentation for a symbol. Copied & modified from replumb." [sym] (when sym (with-out-str (print-doc (doc-from-sym sym)))))
null
https://raw.githubusercontent.com/jaredly/reepl/96a8979c574b3979a7aeeed27e57a2ec4d357350/src/reepl/replumb.cljs
clojure
:verbose true parse #js {} correctly get a unique js object as a sigil parse #js {} correctly TODO should I log the result if it's not the end? Trying to get expressions + statements to play well together it won't work if there are other `ns' statements inside there... parse #js {} correctly TODO fuzzy-match if there are no normal matches [qualified symbol, show text, replace text]
(ns reepl.replumb (:require [cljs.js :as jsc] [cljs.analyzer :as ana] [reepl.core :as reepl] [reepl.helpers :as helpers] [devtools.core :as devtools] [cljs.pprint :as pprint] [reagent.core :as r] [quil.core :as q :include-macros true] [cljs.tools.reader] [clojure.string :as str] [replumb.core :as replumb] [replumb.repl] [replumb.ast :as ast] [replumb.doc-maps :as docs] [cljs.repl :as repl] [parinfer-codemirror.editor :as parinfer] [parinfer.codemirror.mode.clojure.clojure-parinfer] [cljs.tools.reader.reader-types :refer [string-push-back-reader]] [cljs.tools.reader] [cljs.tagged-literals :as tags] [quil.middleware :as m]) (:import goog.net.XhrIo)) (defn fetch-file! "Very simple implementation of XMLHttpRequests that given a file path calls src-cb with the string fetched of nil in case of error. See doc at " [file-url src-cb] (try (.send XhrIo file-url (fn [e] (if (.isSuccess (.-target e)) (src-cb (.. e -target getResponseText)) (src-cb nil)))) (catch :default e (src-cb nil)))) (def replumb-opts (merge (replumb/browser-options ["/main.out" "/main.out"] TODO figure out file loading #_(fn [& a] nil) fetch-file!) {:warning-as-error true :no-pr-str-on-value true})) (defn find-last-expr-pos [text] (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) eof (js-obj) read #(cljs.tools.reader/read {:eof eof} rr) ] (loop [last-pos 0 second-pos 0 last-form nil second-form nil] (let [form (read) new-pos (.-s-pos (.-rdr rr))] (if (identical? eof form) second - form ] (recur new-pos last-pos form last-form))))))) (defn make-last-expr-set-val [text js-name] (let [last-pos (find-last-expr-pos text)] (js/console.log last-pos text) (when-not (= last-pos 0) (str (.slice text 0 last-pos) "(aset js/window \"" js-name "\" " (.slice text last-pos) ")" )))) (defn jsc-run [source cb] (jsc/eval-str replumb.repl/st source 'stuff {:eval (fn a [& b] (js/console.log "eval source" b) (apply jsc/js-eval b)) :ns (replumb.repl/current-ns) :context :statement :def-emits-var true} (fn [result] (swap! replumb.repl/app-env assoc :current-ns (:ns result)) (if (contains? result :error) (cb false (:error result)) (cb true (aget js/window "last_repl_value")))))) (defn get-first-form [text] (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) form (cljs.tools.reader/read rr) TODO this is a bit dependent on tools.reader internals ... s-pos (.-s-pos (.-rdr rr))] [form s-pos]))) (defn run-repl-multi [text opts cb] (let [text (.trim text) [form pos] (get-first-form text) source (.slice text 0 pos) remainder (.trim (.slice text pos)) has-more? (not (empty? remainder))] (js/console.log [text form pos source remainder has-more?]) (replumb/read-eval-call opts #(let [success? (replumb/success? %) result (replumb/unwrap-result %)] (js/console.log "evaled" [success? result has-more?]) (if-not success? (cb success? result) (if has-more? (run-repl-multi remainder opts cb) (cb success? result)) )) source))) TODO is this a better way ? The ` do ' stuff seems to work alright ... although (defn run-repl-experimental* [text opts cb] (let [fixed (make-last-expr-set-val text "last_repl_value")] (if fixed (jsc-run fixed cb) (replumb/read-eval-call opts #(cb (replumb/success? %) (replumb/unwrap-result %)) text)))) (defn fix-ns-do [text] (binding [cljs.tools.reader/*data-readers* tags/*cljs-data-readers*] (let [rr (string-push-back-reader text) form (cljs.tools.reader/read rr) is-ns (and (sequential? form) (= 'ns (first form))) TODO this is a bit dependent on tools.reader internals ... s-pos (.-s-pos (.-rdr rr))] (js/console.log is-ns form s-pos) (if-not is-ns (str "(do " text ")") (str (.slice text 0 s-pos) "(do " (.slice text s-pos) ")" ))))) (defn run-repl* [text opts cb] (replumb/read-eval-call opts #(cb (replumb/success? %) (replumb/unwrap-result %)) (fix-ns-do text))) (defn run-repl ([text cb] (run-repl-multi text replumb-opts cb)) ([text opts cb] (run-repl-multi text (merge replumb-opts opts) cb))) (defn compare-completion "The comparison algo for completions 1. if one is exactly the text, then it goes first 2. if one *starts* with the text, then it goes first 3. otherwise leave in current order" [text a b] (cond (and (= text a) (= text b)) 0 (= text a) -1 (= text b) 1 :else (let [a-starts (= 0 (.indexOf a text)) b-starts (= 0 (.indexOf b text))] (cond (and a-starts b-starts) 0 a-starts -1 b-starts 1 :default 0)))) (defn compare-ns "Sorting algo for namespaces The current ns comes first, then cljs.core, then anything else alphabetically" [current ns1 ns2] (cond (= ns1 current) -1 (= ns2 current) 1 (= ns1 'cljs.core) -1 (= ns2 'cljs.core) 1 :default (compare ns1 ns2))) (defn get-from-js-ns "Use js introspection to get a list of interns in a namespaces This is pretty dependent on cljs runtime internals, so it may break in the future (although I think it's fairly unlikely). It takes advantage of the fact that the ns `something.other.thing' is available as an object on `window.something.other.thing', and Object.keys gets all the variables in that namespace." [ns] (let [parts (map munge (.split (str ns) ".")) ns (reduce aget js/window parts)] (if-not ns [] (map demunge (js/Object.keys ns))))) (defn dedup-requires "Takes a map of {require-name ns-name} and dedups multiple keys that have the same ns-name value." [requires] (first (reduce (fn [[result seen] [k v]] (if (seen v) [result seen] [(assoc result k v) (conj seen v)])) [{} #{}] requires))) (defn get-matching-ns-interns [[name ns] matches? only-ns] (let [ns-name (str ns) publics (keys (ast/ns-publics @replumb.repl/st ns)) publics (if (empty? publics) (get-from-js-ns ns) publics)] (if-not (or (nil? only-ns) (= only-ns ns-name)) [] (sort (map #(symbol name (str %)) (filter matches? publics)))))) (defn js-attrs [obj] (if-not obj [] (let [constructor (.-constructor obj) proto (js/Object.getPrototypeOf obj)] (concat (js/Object.keys obj) (when-not (= proto obj) (js-attrs proto)))))) (defn js-completion [text] (let [parts (vec (.split text ".")) completing (or (last parts) "") prefix #(str "js/" (str/join "." (conj (vec (butlast parts)) %))) possibles (js-attrs (reduce aget js/window (butlast parts)))] (->> possibles (filter #(not (= -1 (.indexOf % completing)))) (sort (partial compare-completion text)) (map #(-> [nil (prefix %) (prefix %)]))))) (defn cljs-completion "Tab completion. Copied w/ extensive modifications from replumb.repl/process-apropos." [text] (let [[only-ns text] (if-not (= -1 (.indexOf text "/")) (.split text "/") [nil text]) matches? #(and TODO find out what these t_cljs$core things are ... seem to be nil (= -1 (.indexOf (str %) "t_cljs$core")) (< -1 (.indexOf (str %) text))) current-ns (replumb.repl/current-ns) replace-name (fn [sym] (if (or (= (namespace sym) "cljs.core") (= (namespace sym) (str current-ns))) (name sym) (str sym))) requires (:requires (ast/namespace @replumb.repl/st current-ns)) only-ns (when only-ns (or (str (get requires (symbol only-ns))) only-ns)) requires (concat [[nil current-ns] [nil 'cljs.core]] (dedup-requires (vec requires))) names (set (apply concat requires)) defs (->> requires (sort-by second (partial compare-ns current-ns)) (mapcat #(get-matching-ns-interns % matches? only-ns)) (map #(-> [% (str %) (replace-name %) (name %)])) (sort-by #(get % 3) (partial compare-completion text)))] (vec (concat TODO make this configurable (take 75 defs) (map #(-> [% (str %) (str %)]) (filter matches? names)))))) (defn process-apropos [text] (if (= 0 (.indexOf text "js/")) (js-completion (.slice text 3)) (cljs-completion text) )) (defn get-forms [m] (cond (:forms m) (:forms m) (:arglists m) (let [arglists (:arglists m)] (if (or (:macro m) (:repl-special-function m)) arglists (if (= 'quote (first arglists)) (second arglists) arglists))))) Copied & modified from cljs.repl/print-doc (defn get-doc [m] (merge {:name (str (when-let [ns (:ns m)] (str ns "/")) (:name m)) :type (cond (:protocol m) :protocol (:special-form m) :special-form (:macro m) :macro (:repl-special-function m) :repl-special-function :else :normal) :forms (get-forms m) :doc (:doc m)} (if (:special-form m) {:please-see (if (contains? m :url) (when (:url m) (str "/" (:url m))) (str "#" (:name m)))} (when (:protocol m) {:protocol-methods (:methods m)})))) (defn doc-from-sym [sym] (cond (docs/special-doc-map sym) (get-doc (docs/special-doc sym)) (docs/repl-special-doc-map sym) (get-doc (docs/repl-special-doc sym)) (ast/namespace @replumb.repl/st sym) (get-doc (select-keys (ast/namespace @replumb.repl/st sym) [:name :doc])) :else (get-doc (replumb.repl/get-var nil (replumb.repl/empty-analyzer-env) sym)))) (def type-name {:protocol "Protocol" :special-form "Special Form" :macro "Macro" :repl-special-function "REPL Special Function"}) Copied & modified from cljs.repl/print-doc (defn print-doc [doc] (println (:name doc)) (if-not (= :normal (:type doc)) (println (type-name (:type doc)))) (when (:forms doc) (prn (:forms doc))) (when (:please-see doc) (println (str "\n Please see " (:please-see doc)))) (when (:doc doc) (println (:doc doc))) (when (:methods doc) (doseq [[name {:keys [doc arglists]}] (:methods doc)] (println) (println " " name) (println " " arglists) (when doc (println " " doc))))) (defn process-doc "Get the documentation for a symbol. Copied & modified from replumb." [sym] (when sym (with-out-str (print-doc (doc-from-sym sym)))))
07422c4bdf2b147ae5d0980fec823570a821f3e89d63b79376cda05c9c4d0d83
sibylfs/sibylfs_src
property_testgen.ml
(****************************************************************************) Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) (* *) (* Permission to use, copy, modify, and/or distribute this software for *) (* any purpose with or without fee is hereby granted, provided that the *) (* above copyright notice and this permission notice appear in all *) (* copies. *) (* *) THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL (* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED *) (* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE *) (* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL *) (* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR *) PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR (* PERFORMANCE OF THIS SOFTWARE. *) (* *) Meta : (* - Headers maintained using headache. *) (* - License source: *) (****************************************************************************) (* a version of exhaustive testing based on properties *) todo : - X add hard links - X replace sample fs with fs generated from spec via posix arch - X check semantics of single paths with posix name resolution - X test current code - generate all paths - find first path that satisfies each property - determine which properties are mutually exclusive - X semantics for all properties - X semantics for properties of pairs of paths - X create spec fs from s0 - X resolve a path using spec resolve functions - X add paths that do n't resolve to anything - X check that all combs of single path properties have some path that satisfies them - X check that all combinations of properties have some path that satisfies them - check that testgen actually tests all paths , with the same state ( or start using this to generate tests ) - need to isolate each test in a subdir , whilst still ensuring that all the properties are satsified ; this might be difficult since to isolate tests we typically make a new subdirectory " test_id " and the test commands execute within this directory ; however , now we require that we test paths such as " / " , and this references something outside the " test_id " directory , and is therefore likely to interfere with the results of other tests ; the alternative is to run each test in a clean filesystem - FIXMEs in this file todo: - X add hard links - X replace sample fs with fs generated from spec via posix arch - X check semantics of single paths with posix name resolution - X test current code - generate all paths - find first path that satisfies each property - determine which properties are mutually exclusive - X semantics for all properties - X semantics for properties of pairs of paths - X create spec fs from s0 - X resolve a path using spec resolve functions - X add paths that don't resolve to anything - X check that all combs of single path properties have some path that satisfies them - X check that all combinations of properties have some path that satisfies them - check that testgen actually tests all paths, with the same state (or start using this to generate tests) - need to isolate each test in a subdir, whilst still ensuring that all the properties are satsified; this might be difficult since to isolate tests we typically make a new subdirectory "test_id" and the test commands execute within this directory; however, now we require that we test paths such as "/", and this references something outside the "test_id" directory, and is therefore likely to interfere with the results of other tests; the alternative is to run each test in a clean filesystem - FIXMEs in this file *) let rec find_first_rest p xs = (match xs with | [] -> failwith "find_first_rest: []" | x::xs -> if p x then (x,xs) else find_first_rest p xs) let find_first_n p xs = let rec f1 (xs,n) = (match xs with | [] -> failwith "find_first_n: []" | x::xs -> if p x then (x,n) else f1 (xs,n+1)) in f1 (xs,0) let rec drop n h = (match (n,h) with | (0,_) -> h | (_,[]) -> [] | (_,x::xs) -> drop (n-1) xs) let list_subset ps qs = ( List.for_all (fun p -> List.mem p qs) ps) (**********************************************************************) (* file system initialization; link to spec *) module DH = Fs_interface.Dir_heap_intf pth = [ .. ] then the corresponding string is String.concat " / " pth ; the pth can not be empty ( the empty string " " corresponds to the path [ " " ] ) ; components can not contain ' / ' let string_of_path (p:path) = String.concat "/" p let arch0 = Fs_interface.Fs_spec_intf.Fs_types.ARCH_POSIX let script0 = "@type script # initial state mkdir \"empty_dir1\" 0o777 mkdir \"empty_dir2\" 0o777 mkdir \"nonempty_dir1\" 0o777 # nonempty_dir1 mkdir \"nonempty_dir1/d2\" 0o777 open \"nonempty_dir1/d2/f3.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor inc\" 83 close (FD 3) mkdir \"nonempty_dir1/d2/d3\" 0o777 symlink \"../f1.txt\" \"nonempty_dir1/d2/sl_dotdot_f1.txt\" symlink \"no_such_target\" \"nonempty_dir1/d2/sl_no_such_target\" symlink \"../no_such_target\" \"nonempty_dir1/d2/sl_dotdot_no_such_target\" symlink \"../d2\" \"nonempty_dir1/d2/sl_dotdot_d2\" open_close \"nonempty_dir1/f1.txt\" [O_CREAT;O_WRONLY] 0o666 symlink \"f1.txt\" \"nonempty_dir1/sl_f1.txt\" symlink \"../empty_dir1\" \"nonempty_dir1/sl_dotdot_empty_dir1\" symlink \"../empty_dir2\" \"nonempty_dir1/sl_dotdot_empty_dir2\" symlink \"../nonempty_dir1\" \"nonempty_dir1/sl_dotdot_nonempty_dir1\" symlink \"../nonempty_dir2\" \"nonempty_dir1/sl_dotdot_nonempty_dir2\" symlink \"/nonempty_dir1\" \"/sl_nonempty_dir1\" link \"nonempty_dir1/f1.txt\" \"nonempty_dir1/link_f1.txt\" symlink \"link_f1.txt\" \"nonempty_dir1/sl_link_f1.txt\" link \"nonempty_dir1/sl_link_f1.txt\" \"nonempty_dir1/link_to_symlink\" # nonempty_dir2 mkdir \"nonempty_dir2\" 0o777 open_close \"nonempty_dir2/f1.txt\" [O_CREAT;O_WRONLY] 0o666 open \"nonempty_dir2/f2.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exer\" 167 close (FD 3) mkdir \"nonempty_dir2/d2\" 0o777 mkdir \"nonempty_dir2/d2/d3\" 0o777 symlink \"../../nonempty_dir1/d2/f3.txt\" \"nonempty_dir2/d2/sl_f3.txt\" open \"/f4.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor inc\" 83 close (FD 3) " let t0 = Trace.of_string arch0 script0 (* let outfun = CheckLib.default_check_output_fun (* FIXME may want this silent *) *) let d0 = CheckLib.spec_initial_state arch0 true (* no_root *) let r0 = CheckLib.Check_spec.process_script d0 (snd t0) let s0 = match r0 with | CheckLib.Interp (s0,_) -> s0 | _ -> failwith "impossible" let s0 = match Fs_prelude.distinct_list_from_finset_by (fun x y -> false) s0 with | [(s0:CheckLib.Check_spec.m_os_state)] -> s0 | _ -> failwith "impossible" (* potentially dangerous *) let s0 : Dir_heap.Dir_heap_types.dh_os_state = Obj.magic (s0) let dhops = Dir_heap.Dir_heap_ops.dir_heap_ops let dh0 : Dir_heap.Dir_heap_types.dir_heap_state = s0.Fs_spec.Fs_types.oss_fs_state let env0 = Dir_heap.Dir_heap_ops.dir_heap_env open Fs_spec.Fs_types take a state and return the set of paths , as a list of lists - maintain a path to current directory /tmp / a / b - in directory b - return current path - for dirs , recurse on all directory entries ( with updated cwd ) - for files , just add /tmp / a / b / f to the list of paths to be returned - maintain a path to current directory /tmp/a/b - in directory b - return current path - for dirs, recurse on all directory entries (with updated cwd) - for files, just add /tmp/a/b/f to the list of paths to be returned *) let get_paths : ('a, 'b, 'c) Fs_spec.Fs_types.fs_ops -> 'c -> Fs_spec.Fs_types.name list list = (fun fops s0 -> let root = match fops.fops_get_root s0 with | Some root -> root | _ -> failwith "impossible" in (* sofar is a list of strings indicating the directories travelled so far; d0 is the current directory *) let rec f1 sofar d0 = ( let (s1_ignore,es) = fops.fops_readdir s0 d0 in let f2 name = ( match fops.fops_resolve s0 d0 name with | None -> (failwith "get_paths: impossible") | Some x -> ( match x with | Dir_ref_entry d1 -> (f1 (sofar@[name]) d1) | File_ref_entry f1 -> [sofar@[name]])) in sofar::(List.concat (List.map f2 es))) in f1 [""] root) (* "" ensures we get a slash at front of path; this also means we get an "empty" path "" to check; do we want this? yes, it seems reasonable and is allowed by the model *) let paths0 = ( let ps = get_paths dhops dh0 in (* get relative paths - we add leading / later *) let ps = let f1 = fun x -> match x with (""::x) -> x | _ -> failwith "impossible" in ps |> List.map f1 |> List.filter (fun x -> x <> []) in let ps = [[""];["";""]]@ps in (* don't forget root and empty string *) let other_paths = [ (* must have nonexist paths, and some must end in / *) ["nonexist_1"]; ["";"nonexist_1";"nonexist_11"]; ["";"nonexist_2"]; ["";"nonexist_2";"nonexist_22"]; (* we also need nonexistent path in an empty dir *) ["empty_dir1";"nonexist_3"]; (* and error through an empty dir *) ["empty_dir1";"nonexist_3";"nonexist_4"]; ux7 (* also want paths via a symlink *) ["nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"";"";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; (* and relative paths to nonexist, not via a symlink *) ["nonempty_dir1";"nonexist_1"]; ["nonempty_dir1";"nonexist_1";""]; (* and .. paths *) ["nonempty_dir1";".."]; (* nonexist via symlink *) ["nonempty_dir1";"sl_dotdot_empty_dir1";"nonexist_1"]; ["nonempty_dir1";"sl_dotdot_nonempty_dir2";"nonexist_1"] ] in add trailing slash to all paths ; use in List.concat ( List.map ) let add_trailing_slash p = [p;p@[""]] in (* add initial slashes *) let add_initial_slashes p = [ p; ""::p; ""::""::p; ""::""::""::p ] in let add_via_symlink p = [ p; ["nonempty_dir1";"sl_dotdot_nonempty_dir1";".."]@p; ["";"nonempty_dir1";"sl_dotdot_nonempty_dir1";".."]@p; ["nonempty_dir1";"sl_dotdot_nonempty_dir2";".."]@p; ["";"nonempty_dir1";"sl_dotdot_nonempty_dir2";".."]@p ] in (ps@other_paths) |> List.map add_via_symlink |> List.concat |> List.map add_trailing_slash |> List.concat |> List.map add_initial_slashes |> List.concat ) type dh_res_name = (Dir_heap.Dir_heap_types.dh_dir_ref, Dir_heap.Dir_heap_types.dh_file_ref) Fs_spec.Fs_types.res_name (* resolve a path; we don't want to follow symlinks ever *) let resolve : string -> dh_res_name = fun path -> let path = CS_Some path in let dummy_cmd = OS_READLINK path in Fs_spec.Resolve.process_path_from_root env0 dh0 dummy_cmd path let memo f = ( let tbl = Hashtbl.create 100 in let key_of_input i = Some i in fun i -> let k = key_of_input i in match k with | None -> (f i) | Some k -> ( if (Hashtbl.mem tbl k) then (Hashtbl.find tbl k) else let v = f i in let _ = Hashtbl.add tbl k v in v)) let resolve = memo resolve (**********************************************************************) (* properties *) type single_path_props = | Ends_in_slash | Starts_with_no_slash | Starts_with_one_slash | Starts_with_slash_x2 | Starts_with_slash_x3 | Is_empty_string | Is_slash | Is_file | Is_dir | Is_symlink | Is_nonexist | Is_error | If_dir_then_is_empty | If_dir_then_is_nonempty FIXME satisifed if not dir - but this is not really what we want ; except that we also have combination with Is_dir except that we also have combination with Is_dir *) | Has_symlink_component | Not of single_path_props (* a list of (representatives of) equivalence classes; an equivalence class is represented as a list of properties which are mutually disjoint and cover the space *) let single_path_props = [ [Ends_in_slash;Not Ends_in_slash]; [Starts_with_no_slash; Starts_with_one_slash; Starts_with_slash_x2; Starts_with_slash_x3]; [Is_empty_string; Not Is_empty_string]; [Is_slash;Not Is_slash]; [Is_file;Is_dir;Is_symlink;Is_nonexist;Is_error]; [Not Is_dir; If_dir_then_is_empty;If_dir_then_is_nonempty]; [Has_symlink_component;Not Has_symlink_component] ] let drop_last xs = xs |> List.rev |> List.tl |> List.rev (* all prefixes, including empty and full *) let prefixes_of_path : path -> path list = (fun p -> let rec f1 acc xs = ( match xs with | [] -> acc (* we don't add [] since it isn't a valid path *) | _ -> (f1 (xs::acc) (drop_last xs))) in f1 [] p) (* let _ = prefixes_of_path ["";"a";"b"] *) let rec allpairs f l1 l2 = match l1 with h1::t1 -> List.fold_right (fun x a -> f h1 x :: a) l2 (allpairs f t1 l2) | [] -> [] let list_product l1 l2 = allpairs (fun x -> fun y -> (x,y)) l1 l2 let list_product_as_list : 'a list -> 'a list -> 'a list list = (fun l1 l2 -> allpairs (fun x -> fun y -> [x;y]) l1 l2) let _ = list_product_as_list [1;2;3] [4;5;6] let list_product_as_list : 'a list list -> 'a list -> 'a list list = (fun l1 l2 -> allpairs (fun x -> fun y -> x@[y]) l1 l2) let _ = list_product_as_list [[1;2;3];[7]] [4;5;6] let property_combs0 = let f1 acc x = list_product_as_list acc x in List.fold_left f1 (List.map (fun x -> [x]) (List.hd single_path_props)) (List.tl single_path_props) let _ = List.length property_combs0 (* semantics of properties *) let is_symlink i0_ref = ( (dhops.fops_stat_file dh0 i0_ref).st_kind = S_IFLNK) let rec sem1 prop p0 = ( match p0 with | None -> false (* check for null path *) | Some p -> ( match prop with | Ends_in_slash -> (p |> List.rev |> (fun x -> match x with [""] -> false | ""::_ -> true | _ -> false)) | Starts_with_no_slash -> ( match p with | [""] -> true | c::_ -> c <> "" | _ -> failwith "impossible") | Starts_with_one_slash -> ( match p with | ["";""] -> true exactly one slash | _ -> false) | Starts_with_slash_x2 -> ( match p with | ""::""::x::_ -> (x <> "") | _ -> false) | Starts_with_slash_x3 -> ( match p with | ""::""::""::x::_ -> (x <> "") | _ -> false) | Is_empty_string -> (p = [""]) (* path was "" *) | Is_slash -> (p = ["";""]) | Is_file -> (p |> string_of_path |> resolve |> is_RN_file) | Is_dir -> (p |> string_of_path |> resolve |> is_RN_dir) | Is_symlink -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_file (_,_,i0_ref,_) -> (is_symlink i0_ref) | _ -> false)) | Is_nonexist -> (p |> string_of_path |> resolve |> is_RN_none) | Is_error -> (p |> string_of_path |> resolve |> is_RN_error) | If_dir_then_is_empty -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_dir(d0_ref,_) -> ( dhops.fops_readdir dh0 d0_ref |> (fun (_,ns) -> ns=[])) | _ -> true)) | If_dir_then_is_nonempty -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_dir(d0_ref,_) -> ( dhops.fops_readdir dh0 d0_ref |> (fun (_,ns) -> ns<>[])) | _ -> true)) | Has_symlink_component -> ( (* take a path and form prefixes *) let is_symlink p = ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_file (_,_,i0_ref,_) -> (is_symlink i0_ref) | _ -> false)) in p |> prefixes_of_path |> List.exists is_symlink) | Not x -> not(sem1 x p0))) let sem1_list props p = List.for_all (fun prop -> sem1 prop p) props let implies p q = (not p) || q (* properties that logically can occur together; we remove impossible properties from the combinations of all properties, justifying the impossibility of each *) let logically_possible : single_path_props list -> bool = fun props -> let sub_props ps = List.for_all (fun p -> List.mem p props) ps in (not (List.mem Ends_in_slash props && List.mem Is_empty_string props)) && (not (List.mem Is_slash props && List.mem Starts_with_no_slash props)) && (not (sub_props [Ends_in_slash;Is_file])) && (not (sub_props [Ends_in_slash;Is_symlink])) && (not (sub_props [Is_slash;Has_symlink_component])) FIXME interesting case - we need to check a path which is / where there are no entries in the root directory && (not (sub_props [Is_empty_string;Is_file])) && (not (sub_props [Is_empty_string;Is_dir])) && (not (sub_props [Is_empty_string;Is_symlink])) && (not (List.mem Is_slash props && List.exists (fun x -> List.mem x [Is_file;Is_symlink;Is_nonexist;Is_error]) props)) && (not (List.mem Is_slash props && not (List.mem Starts_with_one_slash props))) && (implies (List.mem Is_empty_string props) (List.mem Is_error props)) && (implies (List.mem Is_empty_string props) (not (List.mem Has_symlink_component props))) && (implies (List.mem Is_symlink props) (not (List.mem (Not Has_symlink_component) props))) && (not (sub_props [Is_empty_string; Starts_with_one_slash])) && (not (sub_props [Is_slash;Not Ends_in_slash])) && (implies (List.mem Is_empty_string props) (List.mem Starts_with_no_slash props)) FIXME possible ? let property_combs1 = property_combs0 |> List.filter logically_possible let _ = List.length property_combs1 let list_find_opt p xs = try Some(List.find p xs) with _ -> None let path_with_property : single_path_props -> path option = (fun prop -> paths0 |> (List.map (fun p -> Some p)) |> list_find_opt (sem1 prop) |> (fun x -> match x with | None -> None | Some(Some p) -> Some p | _ -> failwith "impossible")) let _ = path_with_property (Starts_with_one_slash) FIXME should n't this be path opt list ? - a path is either none or some let paths_with_properties : single_path_props list -> path list = (fun props -> paths0 |> List.filter (fun p -> List.for_all (fun prop -> sem1 prop (Some p)) props)) (**********************************************************************) (* checking single path properties on selection of paths *) let _ = paths_with_properties [ Starts_with_one_slash;Is_file;Not Is_symlink ] ( * first interesting missing case - no symlink to emptydir let _ = paths_with_properties [Starts_with_one_slash;Is_file;Not Is_symlink] (* first interesting missing case - no symlink to emptydir *) let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] (* another interesting case - we need nonexistent paths that are not just via symlink *) let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; If_dir_then_is_empty; Not Has_symlink_component] another interesting case - we need to check single paths / where the root directory is empty ; FIXME marking this as impossible for now so we can continue to explore let _ = paths_with_properties [Is_slash; Is_dir; If_dir_then_is_empty] (* *) let _ = paths_with_properties [Is_empty_string; Is_file] let _ = paths_with_properties [Is_slash; Is_nonexist] let _ = paths_with_properties [Is_empty_string;Is_nonexist] let _ = paths_with_properties [Is_empty_string] let _ = paths_with_properties [Not Ends_in_slash; Is_empty_string] let _ = paths_with_properties [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; ] (* interesting case we are missing - need a path that resolves to a dir via a symlink *) let _ = paths_with_properties [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] let _ = paths_with_properties [Is_dir; If_dir_then_is_empty; Has_symlink_component ] let _ = paths_with_properties [Is_symlink; Not Has_symlink_component ] (* really interesting - we were missing an error that is not due to a slash on end of file (so we should include eg an attempt to resolve a file through a directory that doesn't exist) *) let _ = paths_with_properties [Not Ends_in_slash; Not Is_empty_string; Is_error] let _ = List.find (list_subset [Not Ends_in_slash; Not Is_empty_string; Is_error]) property_combs1 we were not testing paths starting with two slashes , with a symlink component let _ = paths_with_properties [Not Ends_in_slash; Starts_with_slash_x2; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; Not Is_dir; Has_symlink_component] *) (* properties with no satisfying paths *) let _ = assert([] = ( property_combs1 |> List.map (fun x -> (x,paths_with_properties x)) |> List.filter (fun (x,y) -> y=[]) )) (**********************************************************************) (* checking path-pair properties on selection of path-pairs *) (* properties of pairs of paths *) type path_pair_props = | Paths_equal (* FIXME do we want this on the realpath, or on the syntactic representation of the path? really, the real path is what matters *) two paths to same file ; paths not minor variations e.g. differ by trailing slash ; currently uses realpath | First_path_proper_prefix_of_second (* prefix component-wise; currently uses realpath *) | Not2 of path_pair_props | Swap of path_pair_props (* apply a property "the other way round" *) let rp_of_res_name rn = ( match rn with | RN_dir (_,rp) -> (Some rp) | RN_file (_,_,_,rp) -> (Some rp) | RN_none (_,_,rp) -> (Some rp) | RN_error _ -> None) (* FIXME what about null paths? *) let rec sem2 prop (p0,p1) = ( match prop with | Paths_equal -> (p1=p0) | Essentially_different_paths_same_inode -> ( let r0 = p0 |> string_of_path |> resolve in let r1 = p1 |> string_of_path |> resolve in match (r0,r1) with | (RN_file(_,_,i0_ref,rp0),RN_file(_,_,i1_ref,rp1)) -> ((i0_ref = i1_ref) && rp0.rp_ns <> rp1.rp_ns) | _ -> false) note that this is on realpaths - i.e. it is checking whether first contains second let rec f1 p q = (match p,q with | [],[] -> false | [],_ -> true | _,[] -> false | x::xs,y::ys -> (x=y) && f1 xs ys) in let r0 = p0 |> string_of_path |> resolve in let r1 = p1 |> string_of_path |> resolve in let rp0 = (rp_of_res_name r0) in let rp1 = (rp_of_res_name r1) in match (rp0,rp1) with | Some(rp0),Some(rp1) -> ( match (rp0.rp_ns, rp1.rp_ns) with (* / - root is special cased *) | (["";""],[""]) -> false | (["";""],["";""]) -> false | (["";""],_) -> true | _ -> f1 rp0.rp_ns rp1.rp_ns) | _ -> ( (* fall back to textual comparison FIXME semantically not clear this is the right thing to do *) match (p0,p1) with (* / - root is special cased *) | (["";""],[""]) -> false | (["";""],["";""]) -> false | (["";""],_) -> true | _ -> f1 p0 p1) ) | Not2 prop -> (not (sem2 prop (p0,p1))) | Swap prop -> (sem2 prop (p1,p0))) let sem2_list: path_pair_props list -> path * path -> bool = ( fun props p -> List.for_all (fun prop -> sem2 prop p) props) let path_pair_props = [ [Paths_equal; Not2 Paths_equal]; [Essentially_different_paths_same_inode; Not2 Essentially_different_paths_same_inode]; (* following should also have swap variants *) [First_path_proper_prefix_of_second; Not2 First_path_proper_prefix_of_second]; [Swap First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]; ] let ppairs1 = allpairs (fun x y -> (x,y)) paths0 paths0 let _ = List.length ppairs1 (* get a prefix of pairs, to make checking more feasible *) let ppairs0 = let f1 (acc,n) x = if n=0 then (acc,n) else (x::acc,n-1) in (List.fold_left f1 ([],3000000) ppairs1) |> (fun (acc,n) -> acc) let props_hold_for_path_pair: path_pair_props list -> (path * path) -> bool = (fun props (p1,p2) -> List.for_all (fun prop -> sem2 prop (p1,p2)) props) let path_pairs_with_properties : path_pair_props list -> (path * path) list = (fun props -> ppairs0 |> List.filter (props_hold_for_path_pair props)) let pair_prop_combs0 = let f1 acc x = list_product_as_list acc x in List.fold_left f1 (List.map (fun x -> [x]) (List.hd path_pair_props)) (List.tl path_pair_props) let pair_props_logically_possible : path_pair_props list -> bool = (fun props -> let sub_props ps = List.for_all (fun p -> List.mem p props) ps in (* if the paths are equal, then we can't expect essentially different paths etc *) (implies (List.mem Paths_equal props) (not (List.exists (fun x -> List.mem x props) [ Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second; ]))) & & ( not ( List.mem ( ) props ) ) (* can't expect a proper_prefix b, and b proper_prefix of a *) && (not (sub_props [First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second])) first_path_proper_prefix_of_second implies first_path is_dir , so ca n't expect first path dir to reference a file && (not (sub_props [Essentially_different_paths_same_inode; First_path_proper_prefix_of_second])) (* link to file, so can't be a prefix *) && (not (sub_props [Essentially_different_paths_same_inode; Swap First_path_proper_prefix_of_second])) ) let pair_prop_combs0 = pair_prop_combs0 |> List.filter pair_props_logically_possible (**********************************************************************) (* checking pair properties *) (* let _ = path_pairs_with_properties [Paths_equal] let _ = path_pairs_with_properties [Not2 Paths_equal] (* interesting error in comparison of realpaths - we were comparing the realpath component whereas we should compare rp.rp_ns *) let _ = resolve (string_of_path [""; ""; ""; "nonempty_dir1"; "d2"; "sl_dotdot_d2"; ".."; ".."; ""; "nonempty_dir1"; "sl_f1.txt"]) (* should not be empty *) let _ = path_pairs_with_properties [Not2 Paths_equal; Essentially_different_paths_same_inode] (* first path must be a dir, so can't reference a file (and thus have same inode) *) let _ = path_pairs_with_properties [Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; ] let _ = path_pairs_with_properties [Essentially_different_paths_same_inode; Swap First_path_proper_prefix_of_second] (* expect not nil *) let _ = path_pairs_with_properties [Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; ] let _ = path_pairs_with_properties [First_path_proper_prefix_of_second] *) (* which combinations are not possible ? can skip this if working interactively - the assertion should hold *) FIXME uncomment let _ = assert ( None = try let = ( [ ] = path_pairs_with_properties x ) in Some ( List.find f1 pair_prop_combs0 ) with _ - > None ) let _ = assert( None = try let f1 x = ([] = path_pairs_with_properties x) in Some (List.find f1 pair_prop_combs0) with _ -> None) *) (**********************************************************************) (* checking all combinations, of both single path properties, and path pair properties *) let classes_for_single_path : single_path_props list list = property_combs1 let classes_for_path_pairs : path_pair_props list list = pair_prop_combs0 S is the set of path pairs . We have E1 which is a set of equiv classes for the first path . We also have E2 , which is a set of equiv classes for the second path . Finally , we have E3 , which is a set of equiv classes on the set of pairs . We combine these equivalences to get a very fine equivalence . To combine two equivalence classes E1 and E2 : Suppose E1 = { e11,e12 } ; E2 = { e21,e22 } The combined set of classes is : E = { e11 /\ e21 , e11 /\ e22 , e12 /\ e21 , e12 /\ e22 } There is a slight wrinkle : if e1i /\ e2j = { } then E is not a proper set of equivalence classes : one of the partitions is empty . In our setting , this means that there is a combination such that we can not find a satisfying path pair . Obviously such empty entries should be discarded . ( See picture in tr notes 2014 - 11 - 10 ) Now , E1 is a property on the first path , and E2 is a property on the second path . So as properties on pairs of paths , they are such that any e1i /\ e2j is nonempty . However , when combining with E3 , which is an equivalence of pairs of paths , it may be that we have a e_ijk that is empty . So we must check for this when forming the combination . We hope it does n't take too long to eliminate the problematic cases . Previously we manually removed those combinations that were empty . Ca n't we just automatically remove these ? Manually removing them forced us to uncover bugs , and also identifies the smallest " unsatisfiable core " of the empty partitions . This also provides a " human - readable " explanation of why some combination e_ijk is not satisfiable . However , if we believe the code is correct , we might be tempted just to remove all those combinations that are empty . NO ! the problem is that we were uncovering the fact that the partition was empty , which meant ( in some cases ) that the underlying set of paths was not big enough , rather than that the combination was unsatisfiable . So this is a technique that properly helps to increase coverage and completeness . So we do have to manually check the unsatisfiable combinations . classes for the first path. We also have E2, which is a set of equiv classes for the second path. Finally, we have E3, which is a set of equiv classes on the set of pairs. We combine these equivalences to get a very fine equivalence. To combine two equivalence classes E1 and E2: Suppose E1 = {e11,e12}; E2 = {e21,e22} The combined set of classes is: E = { e11 /\ e21, e11 /\ e22, e12 /\ e21, e12 /\ e22 } There is a slight wrinkle: if e1i /\ e2j = {} then E is not a proper set of equivalence classes: one of the partitions is empty. In our setting, this means that there is a combination such that we cannot find a satisfying path pair. Obviously such empty entries should be discarded. (See picture in tr notes 2014-11-10) Now, E1 is a property on the first path, and E2 is a property on the second path. So as properties on pairs of paths, they are such that any e1i /\ e2j is nonempty. However, when combining with E3, which is an equivalence of pairs of paths, it may be that we have a e_ijk that is empty. So we must check for this when forming the combination. We hope it doesn't take too long to eliminate the problematic cases. Previously we manually removed those combinations that were empty. Can't we just automatically remove these? Manually removing them forced us to uncover bugs, and also identifies the smallest "unsatisfiable core" of the empty partitions. This also provides a "human-readable" explanation of why some combination e_ijk is not satisfiable. However, if we believe the code is correct, we might be tempted just to remove all those combinations that are empty. NO! the problem is that we were uncovering the fact that the partition was empty, which meant (in some cases) that the underlying set of paths was not big enough, rather than that the combination was unsatisfiable. So this is a technique that properly helps to increase coverage and completeness. So we do have to manually check the unsatisfiable combinations. *) type combined_pair_props = P1 of single_path_props list | P2 of single_path_props list | P12 of path_pair_props list type combined_pair_props = P1 of single_path_props list | P2 of single_path_props list | P12 of path_pair_props list *) let (_E1,_E2,_E3) = (classes_for_single_path) ,(classes_for_single_path) ,(classes_for_path_pairs) let es = allpairs (fun x y -> (x,y)) _E1 _E2 let es2 = allpairs (fun (x1,x2) y -> (x1,x2,y)) es _E3 let _ = List.length es2 let cp0 = es2 type combined_property = single_path_props list * single_path_props list * path_pair_props list let logically_possible_cp qi = let sub_props (q1,q2,q12) (xs,ys,zs) = List.for_all (fun p -> List.mem p q1) xs && List.for_all (fun p -> List.mem p q2) ys && List.for_all (fun p -> List.mem p q12) zs in let symmetric_prop p (q1,q2,q12) = p (q2,q1,q12) in let b1 = let (q1,q2,q12) = qi in let sub_props = sub_props qi in not (sub_props ([Is_dir],[],[Essentially_different_paths_same_inode])) && not (sub_props ([],[Is_dir],[Essentially_different_paths_same_inode])) && not (sub_props ([Is_dir;If_dir_then_is_empty],[],[First_path_proper_prefix_of_second]) && List.exists (fun x -> List.mem x q2) [Is_file;Is_dir;Is_symlink]) (* FIXME note how this could easily have an error; must be revisited if single path equivs change *) && not (sub_props ([],[Is_dir;If_dir_then_is_empty],[Swap First_path_proper_prefix_of_second]) && List.exists (fun x -> List.mem x q1) [Is_file;Is_dir;Is_symlink]) assuming paths_equal means syntactic equality , it suffices to check p = p for each possible single path equiv class && not (sub_props ([Is_dir],[Not Is_dir],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Not Is_dir],[Is_dir],[First_path_proper_prefix_of_second])) && implies (List.mem First_path_proper_prefix_of_second q12) (not (List.exists (fun x -> List.mem x q1) [Is_file; Is_nonexist; Is_error; Is_symlink])) && implies (List.mem (Swap First_path_proper_prefix_of_second) q12) (not (List.exists (fun x -> List.mem x q2) [Is_file; Is_nonexist; Is_error; Is_symlink])) && not (sub_props ([],[Is_error],[First_path_proper_prefix_of_second])) (* if we have error, realpath doesn't exist *) && not (sub_props ([Is_error],[],[Swap First_path_proper_prefix_of_second])) (* if we have error, realpath doesn't exist *) && not (sub_props ([Is_dir;If_dir_then_is_empty],[Is_slash],[Not2 (Swap First_path_proper_prefix_of_second)])) (* we don't test an empty root directory cf cg6 *) && not (sub_props ([],[Is_slash],[Not2 (Swap First_path_proper_prefix_of_second)])) (* we don't test an empty root directory cf cg6 *) version of resolve does n't allow / to refer to file 36k && not (sub_props ([Ends_in_slash],[],[Essentially_different_paths_same_inode])) " " is only prefix of / , but then " " is a proper prefix of / hdh && not (sub_props ([If_dir_then_is_empty],[Is_slash],[Not2 First_path_proper_prefix_of_second; Not2(Swap First_path_proper_prefix_of_second)])) && not (sub_props ([Is_slash],[Ends_in_slash],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Ends_in_slash],[Is_slash],[First_path_proper_prefix_of_second])) && not (sub_props ([Is_slash],[Not Is_empty_string],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Not Is_empty_string],[Is_slash],[First_path_proper_prefix_of_second])) && implies (sub_props ([Is_empty_string], [], [Not2 (First_path_proper_prefix_of_second)])) (not (List.exists (fun x -> List.mem x q2) [Starts_with_one_slash;Starts_with_slash_x2;Starts_with_slash_x3])) && implies (sub_props ([], [Is_empty_string], [Not2 (Swap (First_path_proper_prefix_of_second))])) (not (List.exists (fun x -> List.mem x q1) [Starts_with_one_slash;Starts_with_slash_x2;Starts_with_slash_x3])) && not (sub_props ([Is_empty_string],[Is_empty_string],[Not2 Paths_equal])) && not (sub_props ([Is_slash],[Is_slash],[Not2 Paths_equal])) && not (sub_props ([Not Has_symlink_component],[Is_symlink],[Essentially_different_paths_same_inode])) && not (sub_props ([Is_symlink],[Not Has_symlink_component],[Essentially_different_paths_same_inode])) in (* for symmetric, programmatically defined classes; q12 must be symmetric *) let b2 = ( let p (q1,q2,q12) = implies (sub_props (q1,q2,q12) ([Is_slash],[],[Not2 First_path_proper_prefix_of_second;Not2 (Swap First_path_proper_prefix_of_second)])) (not (List.exists (fun x -> List.mem x [Is_file;Is_nonexist;Is_symlink;Is_error]) q2)) in p qi && symmetric_prop p qi) && ( let p (q1,q2,q12) = implies (sub_props (q1,q2,q12) ([],[],[Essentially_different_paths_same_inode])) (List.exists (fun x -> List.mem x [Is_file;Is_symlink]) q1) in p qi && symmetric_prop p qi) in b1 && b2 want the " simplest " first let compare_cp ( p1,p2,p12 ) ( q1,q2,q12 ) = let x = ( p1 , p2 , p12 ) in let x'= ( List.length q1 , q2 , ) in Pervasives.compare x x ' ( * not antireflexive let compare_cp (p1,p2,p12) (q1,q2,q12) = let x = (List.length p1, List.length p2, List.length p12) in let x'= (List.length q1, List.length q2, List.length q12) in Pervasives.compare x x' (* not antireflexive *) *) let cp0 = cp0 |> List.filter logically_possible_cp 138927->97887->59265->54675->54659->52115->51945->41289->41228->41163- > ... - > 34101 - > 33813 (* pairs of paths *) let ppairs0 = ppairs0 let combined_properties_hold_of_path_path: combined_property -> (path * path) -> bool = (fun (q1,q2,q12) (p1,p2) -> sem1_list q1 (Some p1) && sem1_list q2 (Some p2) && sem2_list q12 (p1,p2)) let paths_with_combined_properties : combined_property -> (path * path) list = (fun (q1,q2,q12) -> let ppairs = allpairs (fun x y -> (x,y)) (paths_with_properties q1) (paths_with_properties q2) in List.filter (combined_properties_hold_of_path_path (q1,q2,q12)) ppairs) (* we want a minimizer that attempts to determine the minimal properties that are unsatisfiable; if a list of props is of length n, we try to find a subset of length (n-1) such that there are still no paths which satisfy *) /~jrh13/atp/OCaml/lib.ml let rec allsets m l = if m = 0 then [[]] else match l with [] -> [] | h::t -> List.map (fun g -> h::g) (allsets (m - 1) t) @ allsets m t;; (* find a minimal subset of an initial set, satisfying property P *) let rec minimize_set xs p = ( if xs=[] then xs else let l = List.length xs in let ss = allsets (l - 1) xs in let xs' = try Some(List.find p ss) with _ -> None in match xs' with | None -> xs | Some xs' -> minimize_set xs' p) let rec minimize_cp' stage cp = ( match stage with | 1 -> ( let (p1,p2,p12) = cp in let p p1' = ([] = paths_with_combined_properties (p1',p2,p12)) in let p1' = minimize_set p1 p in let _ = print_endline "1" in minimize_cp' 2 (p1',p2,p12)) | 2 -> ( let (p1,p2,p12) = cp in let p p2' = ([] = paths_with_combined_properties (p1,p2',p12)) in let p2' = minimize_set p2 p in let _ = print_endline "2" in minimize_cp' 3 (p1,p2',p12)) | 3 -> ( let (p1,p2,p12) = cp in let p p12' = ([] = paths_with_combined_properties (p1,p2,p12')) in let p12' = minimize_set p12 p in (p1,p2,p12')) | _ -> (failwith "impossible") ) let minimize_cp cp = minimize_cp' 1 cp let compare_paths ((p1:path),(p2:path)) (p3,p4) = Pervasives.compare (List.length p1,List.length p2) (List.length p3, List.length p4) let sort_paths_list = List.sort compare_paths module type IGNORE = sig end (* (* we can't require that directories have different paths but the same inode *) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode] ) (* we can't expect to have an empty dir which contains another dir *) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [First_path_proper_prefix_of_second; ]) (* same problem as previous, different way round *) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [ Swap First_path_proper_prefix_of_second ]) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Not Has_symlink_component], [Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) (* if we demand paths are equal, then we shouldn't expect fundamentally different properties of each of the paths *) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Not Has_symlink_component], [Paths_equal ]) if either of the paths is a dir , we ca n't expect let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Essentially_different_paths_same_inode; ]) (* interesting case: we need to check nonexist entries in an empty dir *) let _ = paths_with_combined_properties ([Is_dir; If_dir_then_is_empty], [ Is_nonexist; ], [ First_path_proper_prefix_of_second; ]) ca n't have first is_dir , second not is_dir , and second prefix of first let _ = paths_with_combined_properties ([ Is_dir], [Not Is_dir], [ Swap First_path_proper_prefix_of_second]) again , ca n't have the second a prefix of first , if second is not a directory let _ = paths_with_combined_properties ([ Is_dir], [ Is_nonexist], [ Swap First_path_proper_prefix_of_second]) we do n't check for errors through empty directories ; also , if we are using rp , then we ca n't check errors and prefix FIXME ? should be /empty_dir1 , /empty_dir1 / nonexist_3 / nonexist_4 let p1 = [ " " ; " empty_dir1 " ] let p2 = [ " " ; " empty_dir1";"nonexist_3";"nonexist_4 " ] let _ = assert ( false = combined_properties_hold_of_path_path prop ( p1,p2 ) ) ( * expect to be true ! should be /empty_dir1 , /empty_dir1/nonexist_3/nonexist_4 let p1 = ["";"empty_dir1"] let p2 = ["";"empty_dir1";"nonexist_3";"nonexist_4"] let _ = assert( false = combined_properties_hold_of_path_path prop (p1,p2)) (* expect to be true! *) let _ = sem1_list [Is_dir; If_dir_then_is_empty] (Some p1) let _ = sem1_list [Is_error] (Some p2) let _ = sem2_list [First_path_proper_prefix_of_second] (p1,p2) (* apparently false; ah, we are using realpath, and this doesn't exist for an error case; fixed by changing semantics of First_path_proper_prefix_of_second to fallback on textual comparison when no realpath *) *) let prop = ([ Is_dir; If_dir_then_is_empty], [ Is_error], [ First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop (* now we have tests for this *) this should not have any satisfying paths ; rp for relative path seems wrong NO ! this is fine - first resolves to / , second is / , and . is not a proper prefix of slash ; so there are many paths with this property , providing first path is / this should not have any satisfying paths; rp for relative path seems wrong NO! this is fine - first resolves to /, second is /, and . is not a proper prefix of slash; so there are many paths with this property, providing first path is / *) let _ = paths_with_combined_properties ([ Is_dir], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = ["nonempty_dir1"; "d2"; "sl_dotdot_d2"; ".."; ".."; ""] |> string_of_path |> resolve cg6 cf above , we do n't test on empty root directory , hence this condition is not satisfiable ( the first path is forced to be root ) so this is unsatisfiable but FIXME probably should be checked ( if we get round to checking with an empty root ) cg6 cf above, we don't test on empty root directory, hence this condition is not satisfiable (the first path is forced to be root) so this is unsatisfiable but FIXME probably should be checked (if we get round to checking with an empty root) *) let _ = paths_with_combined_properties ([ Is_dir ; If_dir_then_is_empty], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = ( module struct let _ = paths_with_combined_properties ([(*Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash;*) Is_dir; (* If_dir_then_is_empty; Has_symlink_component *)], [(*Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; *) Is_symlink; (* If_dir_then_is_empty; Has_symlink_component *)], Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties ([(*Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash;*) Is_symlink; (* If_dir_then_is_empty; Has_symlink_component *)], [(*Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; *) Is_dir; (* If_dir_then_is_empty; Has_symlink_component *)], Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) First_path_proper_prefix_of_second]) (* need a symlink to a directory which contains a subdirectory? *) let prop = ([(*Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash;*) Is_symlink; (* If_dir_then_is_empty; Has_symlink_component *)], [(*Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; *) Is_dir; (* If_dir_then_is_empty; Has_symlink_component *)], Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) First_path_proper_prefix_of_second]) (* in fact this isn't satisfiable - symlink can't be prefix of anything *) let p1 = ["";"sl_nonempty_dir1"] let p2 = ["";"nonempty_dir1";"d2"] let _ = assert( false = combined_properties_hold_of_path_path prop (p1,p2)) (* expect to be true! *) let _ = sem1_list [Is_symlink] (Some p1) let _ = sem1_list [Is_dir] (Some p2) let _ = sem2_list [First_path_proper_prefix_of_second] (p1,p2) this gives rp_ns = [ " " ; " " ; " sl_nonempty_dir1 " ] which is wrong let _ = p2 |> string_of_path |> resolve let _ = ["";"nonempty_dir1"] |> string_of_path |> resolve (* OK *) let _ = ["";"nonempty_dir1";"f1.txt"] |> string_of_path |> resolve (* OK *) not OK ; rp_ns is incorrect for files in the root directory end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = minimize_cp prop (* if p2 is /, and p1 is a proper prefix (ie "") then we can't require that p2 is not a proper prefix of p1 (because root is a proper prefix of ""?) *) let prop = ([], [Is_slash], [First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop (* is / a proper prefix of "" ? apparently yes! fixed definition of proper prefix to take empty string into account *) let prop = ([],[],[Swap (First_path_proper_prefix_of_second)]) let p1 = [""] let p2 = ["";""] let _ = combined_properties_hold_of_path_path prop (p1,p2) ( * this shows that p1= " " and p2=/ satisfy that first path is a proper prefix of / (* this shows that p1="" and p2=/ satisfy that first path is a proper prefix of / *) let prop = ([], [Is_slash], [First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop (* this combination is easy: eg / is not a proper prefix of any relative path *) let prop = ([], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop expect nonexmpty_dir1 , nonexmpty_dir1 / nonexist_1 should satisfy let prop = ([Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Starts_with_no_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let p1 = ["nonempty_dir1"] let p2 = ["nonempty_dir1";"nonexist_1"] let _ = combined_properties_hold_of_path_path prop (p1,p2) (* fixed by adding nonempty_dir1,nonempty_dir1/nonexist_1 *) (* satisfiable? *) let prop = ([Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], (* eg nonempty_dir1 *) eg [ " nonempty_dir1 " ; " d2 " ; " sl_dotdot_no_such_target " ; " " ] [First_path_proper_prefix_of_second]) (* so we need to have something that doesn't contain a symlink, and resolves to nonexist eg nonempty_dir1/nonexist*) let compare_paths (p1,p2) (p3,p4) = Pervasives.compare (List.length p1,List.length p2) (List.length p3, List.length p4) let sort_paths_list = List.sort compare_paths let _ = paths_with_combined_properties prop |> sort_paths_list end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop expect nonexmpty_dir1 , nonexmpty_dir1 / nonexist_1 should satisfy let prop = ([Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop (* as with previous case, but in addition need to have a path ending in / *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([Ends_in_slash; Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Starts_with_one_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop (* FIXED - made sure paths that should have been there, are there *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([Starts_with_no_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Starts_with_no_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal]) let _ = paths_with_combined_properties prop FIXED by adding further sl to empty dirs end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([If_dir_then_is_empty], [Is_nonexist; Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop we do n't check a nonexist in an empty dir , with the nonexist via a symlink component eg / / nonexist_1 FIXED eg nonempty_dir1/sl_dotdot_empty_dir1/nonexist_1 FIXED *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let prop = minimize_cp prop let prop = ([], [Is_slash], []) let _ = paths_with_combined_properties prop let _ = paths_with_properties [Is_slash] (* should be satisfied by _,/ ; mistake after updating defn of paths; fixed *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Not Ends_in_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], []) let _ = paths_with_combined_properties prop need a path to an empty dir via symlink ; missing paths after refactoring ; fixed end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Ends_in_slash], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop ca n't expect p2 to end in slash , and resolve to something that is a file ? or need a symlink to something that is a link nonempty_dir1 / sl_f1.txt/ should resolve to ... /f1.txt which has a hard link in nonempty_dir1 / link_f1.txt nonempty_dir1/sl_f1.txt/ should resolve to .../f1.txt which has a hard link in nonempty_dir1/link_f1.txt *) let p1 = ["nonempty_dir1";"f1.txt"] let p2 = ["nonempty_dir1";"sl_link_f1.txt";""] let _ = combined_properties_hold_of_path_path prop (p1,p2) let _ = sem1_list [Ends_in_slash] (Some p2) let _ = p1 |> string_of_path |> resolve let _ = p2 |> string_of_path |> resolve let _ = sem2 Essentially_different_paths_same_inode (p1,p2) the version of resolve we use means that a ( symlink that ) ends in a slash can not refer to a file 36k end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [If_dir_then_is_empty], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop this forces the second path to be " " ; then we ca n't stop " " being a proper prefix of " " ; " " hdh let prop = ([Is_slash], [If_dir_then_is_empty], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Ends_in_slash], [Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop (* can't have something that is not "" being a prefix of / *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_nonexist], [Not2 First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop (* slash is always a prefix of non-exist *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop if first path is / , and it is not a prefix , then second path must be " " to get error ; then we ca n't require that " " is not a proper prefix of / let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop (* fixed by adjusting lp *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop if first path is / , and it is not a prefix , then second path must be " " to get error ; then we ca n't require that " " is not a proper prefix of / let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop (* fixed by adjusting lp *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Not Is_empty_string], [Swap First_path_proper_prefix_of_second]) (* can't have a prefix of slash that isn't empty; fixed by adjusting lp *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Starts_with_one_slash], [Is_empty_string], [Not2 (Swap First_path_proper_prefix_of_second)]) let prop = ([Is_empty_string], [Starts_with_one_slash], [Not2 (First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop (* the empty string is a prefix of anything that starts with a slash; but empty string should resolve to error, in which case *) let _ = ""|>resolve (* ENOENT *) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Is_empty_string], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop let _ = logically_possible_cp prop Essentially_different_paths_same_inode must be for files ( or symlinks ? ) FIXME end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_empty_string], [Is_empty_string], [Not2 Paths_equal]) (* easy case: obviously impossible *) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_file; Not Is_dir; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_symlink; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Is_symlink], [Essentially_different_paths_same_inode]) (* need to have a hard link to a symlink! interesting case; but doesn't link dereference the symlink? *) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_file; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_symlink; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Not Has_symlink_component], [Is_symlink], [Essentially_different_paths_same_inode]) is 2nd is a symlink , then to have the same inode the first must point to the symlink ; but then the first must have a symlink component let prop = ([], [Is_symlink], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop |> sort_paths_list ( [ " nonempty_dir1 " ; " link_to_symlink " ] , [ " nonempty_dir1 " ; " sl_link_f1.txt " ] ) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not2 Paths_equal]) we only have one relative path to an error ? fixed by ux7 let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], []) let _ = paths_with_combined_properties prop |> sort_paths_list ( [ " empty_dir1 " ; " nonexist_3 " ; " nonexist_4 " ] , [ " empty_dir1 " ; " nonexist_3 " ; " nonexist_4 " ] ) ["empty_dir1"; "nonexist_3"; "nonexist_4"]) *) let _ = paths_with_properties [ Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component] end : IGNORE) *) let _ = let _ = assert (not (List.exists (fun x -> [] = paths_with_combined_properties x) cp0)) in () let _ = Printf.printf "property_testgen.ml: all tests pass\n" (* (* could make this quicker by rebinding cp0 *) let n0 = ref 0 let prop = let f1 x = ([] = paths_with_combined_properties x) in let (prop,n') = find_first_n f1 (drop (!n0) cp0) in let _ = n0 := !n0 + n' in let _ = Printf.printf "Index now %d \n" (!n0) in prop let _ = let f1 x = ([] = paths_with_combined_properties x) in List.find f1 cp0 let _ = let f1 x = ([] = paths_with_combined_properties x) in cp0 |> List.filter f1 |> List.length *)
null
https://raw.githubusercontent.com/sibylfs/sibylfs_src/30675bc3b91e73f7133d0c30f18857bb1f4df8fa/fs_test/test_generation/property_testgen.ml
ocaml
************************************************************************** Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PERFORMANCE OF THIS SOFTWARE. - Headers maintained using headache. - License source: ************************************************************************** a version of exhaustive testing based on properties ******************************************************************** file system initialization; link to spec let outfun = CheckLib.default_check_output_fun (* FIXME may want this silent no_root potentially dangerous sofar is a list of strings indicating the directories travelled so far; d0 is the current directory "" ensures we get a slash at front of path; this also means we get an "empty" path "" to check; do we want this? yes, it seems reasonable and is allowed by the model get relative paths - we add leading / later don't forget root and empty string must have nonexist paths, and some must end in / we also need nonexistent path in an empty dir and error through an empty dir also want paths via a symlink and relative paths to nonexist, not via a symlink and .. paths nonexist via symlink add initial slashes resolve a path; we don't want to follow symlinks ever ******************************************************************** properties a list of (representatives of) equivalence classes; an equivalence class is represented as a list of properties which are mutually disjoint and cover the space all prefixes, including empty and full we don't add [] since it isn't a valid path let _ = prefixes_of_path ["";"a";"b"] semantics of properties check for null path path was "" take a path and form prefixes properties that logically can occur together; we remove impossible properties from the combinations of all properties, justifying the impossibility of each ******************************************************************** checking single path properties on selection of paths first interesting missing case - no symlink to emptydir another interesting case - we need nonexistent paths that are not just via symlink interesting case we are missing - need a path that resolves to a dir via a symlink really interesting - we were missing an error that is not due to a slash on end of file (so we should include eg an attempt to resolve a file through a directory that doesn't exist) properties with no satisfying paths ******************************************************************** checking path-pair properties on selection of path-pairs properties of pairs of paths FIXME do we want this on the realpath, or on the syntactic representation of the path? really, the real path is what matters prefix component-wise; currently uses realpath apply a property "the other way round" FIXME what about null paths? / - root is special cased fall back to textual comparison FIXME semantically not clear this is the right thing to do / - root is special cased following should also have swap variants get a prefix of pairs, to make checking more feasible if the paths are equal, then we can't expect essentially different paths etc can't expect a proper_prefix b, and b proper_prefix of a link to file, so can't be a prefix ******************************************************************** checking pair properties let _ = path_pairs_with_properties [Paths_equal] let _ = path_pairs_with_properties [Not2 Paths_equal] (* interesting error in comparison of realpaths - we were comparing the realpath component whereas we should compare rp.rp_ns should not be empty first path must be a dir, so can't reference a file (and thus have same inode) expect not nil which combinations are not possible ? can skip this if working interactively - the assertion should hold ******************************************************************** checking all combinations, of both single path properties, and path pair properties FIXME note how this could easily have an error; must be revisited if single path equivs change if we have error, realpath doesn't exist if we have error, realpath doesn't exist we don't test an empty root directory cf cg6 we don't test an empty root directory cf cg6 for symmetric, programmatically defined classes; q12 must be symmetric not antireflexive pairs of paths we want a minimizer that attempts to determine the minimal properties that are unsatisfiable; if a list of props is of length n, we try to find a subset of length (n-1) such that there are still no paths which satisfy find a minimal subset of an initial set, satisfying property P (* we can't require that directories have different paths but the same inode we can't expect to have an empty dir which contains another dir same problem as previous, different way round if we demand paths are equal, then we shouldn't expect fundamentally different properties of each of the paths interesting case: we need to check nonexist entries in an empty dir expect to be true! apparently false; ah, we are using realpath, and this doesn't exist for an error case; fixed by changing semantics of First_path_proper_prefix_of_second to fallback on textual comparison when no realpath now we have tests for this Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component need a symlink to a directory which contains a subdirectory? Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; If_dir_then_is_empty; Has_symlink_component in fact this isn't satisfiable - symlink can't be prefix of anything expect to be true! OK OK if p2 is /, and p1 is a proper prefix (ie "") then we can't require that p2 is not a proper prefix of p1 (because root is a proper prefix of ""?) is / a proper prefix of "" ? apparently yes! fixed definition of proper prefix to take empty string into account this shows that p1="" and p2=/ satisfy that first path is a proper prefix of / this combination is easy: eg / is not a proper prefix of any relative path fixed by adding nonempty_dir1,nonempty_dir1/nonexist_1 satisfiable? eg nonempty_dir1 so we need to have something that doesn't contain a symlink, and resolves to nonexist eg nonempty_dir1/nonexist as with previous case, but in addition need to have a path ending in / FIXED - made sure paths that should have been there, are there should be satisfied by _,/ ; mistake after updating defn of paths; fixed can't have something that is not "" being a prefix of / slash is always a prefix of non-exist fixed by adjusting lp fixed by adjusting lp can't have a prefix of slash that isn't empty; fixed by adjusting lp the empty string is a prefix of anything that starts with a slash; but empty string should resolve to error, in which case ENOENT easy case: obviously impossible need to have a hard link to a symlink! interesting case; but doesn't link dereference the symlink? (* could make this quicker by rebinding cp0
Copyright ( c ) 2013 , 2014 , 2015 , , , , ( as part of the SibylFS project ) THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR Meta : todo : - X add hard links - X replace sample fs with fs generated from spec via posix arch - X check semantics of single paths with posix name resolution - X test current code - generate all paths - find first path that satisfies each property - determine which properties are mutually exclusive - X semantics for all properties - X semantics for properties of pairs of paths - X create spec fs from s0 - X resolve a path using spec resolve functions - X add paths that do n't resolve to anything - X check that all combs of single path properties have some path that satisfies them - X check that all combinations of properties have some path that satisfies them - check that testgen actually tests all paths , with the same state ( or start using this to generate tests ) - need to isolate each test in a subdir , whilst still ensuring that all the properties are satsified ; this might be difficult since to isolate tests we typically make a new subdirectory " test_id " and the test commands execute within this directory ; however , now we require that we test paths such as " / " , and this references something outside the " test_id " directory , and is therefore likely to interfere with the results of other tests ; the alternative is to run each test in a clean filesystem - FIXMEs in this file todo: - X add hard links - X replace sample fs with fs generated from spec via posix arch - X check semantics of single paths with posix name resolution - X test current code - generate all paths - find first path that satisfies each property - determine which properties are mutually exclusive - X semantics for all properties - X semantics for properties of pairs of paths - X create spec fs from s0 - X resolve a path using spec resolve functions - X add paths that don't resolve to anything - X check that all combs of single path properties have some path that satisfies them - X check that all combinations of properties have some path that satisfies them - check that testgen actually tests all paths, with the same state (or start using this to generate tests) - need to isolate each test in a subdir, whilst still ensuring that all the properties are satsified; this might be difficult since to isolate tests we typically make a new subdirectory "test_id" and the test commands execute within this directory; however, now we require that we test paths such as "/", and this references something outside the "test_id" directory, and is therefore likely to interfere with the results of other tests; the alternative is to run each test in a clean filesystem - FIXMEs in this file *) let rec find_first_rest p xs = (match xs with | [] -> failwith "find_first_rest: []" | x::xs -> if p x then (x,xs) else find_first_rest p xs) let find_first_n p xs = let rec f1 (xs,n) = (match xs with | [] -> failwith "find_first_n: []" | x::xs -> if p x then (x,n) else f1 (xs,n+1)) in f1 (xs,0) let rec drop n h = (match (n,h) with | (0,_) -> h | (_,[]) -> [] | (_,x::xs) -> drop (n-1) xs) let list_subset ps qs = ( List.for_all (fun p -> List.mem p qs) ps) module DH = Fs_interface.Dir_heap_intf pth = [ .. ] then the corresponding string is String.concat " / " pth ; the pth can not be empty ( the empty string " " corresponds to the path [ " " ] ) ; components can not contain ' / ' let string_of_path (p:path) = String.concat "/" p let arch0 = Fs_interface.Fs_spec_intf.Fs_types.ARCH_POSIX let script0 = "@type script # initial state mkdir \"empty_dir1\" 0o777 mkdir \"empty_dir2\" 0o777 mkdir \"nonempty_dir1\" 0o777 # nonempty_dir1 mkdir \"nonempty_dir1/d2\" 0o777 open \"nonempty_dir1/d2/f3.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor inc\" 83 close (FD 3) mkdir \"nonempty_dir1/d2/d3\" 0o777 symlink \"../f1.txt\" \"nonempty_dir1/d2/sl_dotdot_f1.txt\" symlink \"no_such_target\" \"nonempty_dir1/d2/sl_no_such_target\" symlink \"../no_such_target\" \"nonempty_dir1/d2/sl_dotdot_no_such_target\" symlink \"../d2\" \"nonempty_dir1/d2/sl_dotdot_d2\" open_close \"nonempty_dir1/f1.txt\" [O_CREAT;O_WRONLY] 0o666 symlink \"f1.txt\" \"nonempty_dir1/sl_f1.txt\" symlink \"../empty_dir1\" \"nonempty_dir1/sl_dotdot_empty_dir1\" symlink \"../empty_dir2\" \"nonempty_dir1/sl_dotdot_empty_dir2\" symlink \"../nonempty_dir1\" \"nonempty_dir1/sl_dotdot_nonempty_dir1\" symlink \"../nonempty_dir2\" \"nonempty_dir1/sl_dotdot_nonempty_dir2\" symlink \"/nonempty_dir1\" \"/sl_nonempty_dir1\" link \"nonempty_dir1/f1.txt\" \"nonempty_dir1/link_f1.txt\" symlink \"link_f1.txt\" \"nonempty_dir1/sl_link_f1.txt\" link \"nonempty_dir1/sl_link_f1.txt\" \"nonempty_dir1/link_to_symlink\" # nonempty_dir2 mkdir \"nonempty_dir2\" 0o777 open_close \"nonempty_dir2/f1.txt\" [O_CREAT;O_WRONLY] 0o666 open \"nonempty_dir2/f2.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exer\" 167 close (FD 3) mkdir \"nonempty_dir2/d2\" 0o777 mkdir \"nonempty_dir2/d2/d3\" 0o777 symlink \"../../nonempty_dir1/d2/f3.txt\" \"nonempty_dir2/d2/sl_f3.txt\" open \"/f4.txt\" [O_CREAT;O_WRONLY] 0o666 write! (FD 3) \"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor inc\" 83 close (FD 3) " let t0 = Trace.of_string arch0 script0 let r0 = CheckLib.Check_spec.process_script d0 (snd t0) let s0 = match r0 with | CheckLib.Interp (s0,_) -> s0 | _ -> failwith "impossible" let s0 = match Fs_prelude.distinct_list_from_finset_by (fun x y -> false) s0 with | [(s0:CheckLib.Check_spec.m_os_state)] -> s0 | _ -> failwith "impossible" let s0 : Dir_heap.Dir_heap_types.dh_os_state = Obj.magic (s0) let dhops = Dir_heap.Dir_heap_ops.dir_heap_ops let dh0 : Dir_heap.Dir_heap_types.dir_heap_state = s0.Fs_spec.Fs_types.oss_fs_state let env0 = Dir_heap.Dir_heap_ops.dir_heap_env open Fs_spec.Fs_types take a state and return the set of paths , as a list of lists - maintain a path to current directory /tmp / a / b - in directory b - return current path - for dirs , recurse on all directory entries ( with updated cwd ) - for files , just add /tmp / a / b / f to the list of paths to be returned - maintain a path to current directory /tmp/a/b - in directory b - return current path - for dirs, recurse on all directory entries (with updated cwd) - for files, just add /tmp/a/b/f to the list of paths to be returned *) let get_paths : ('a, 'b, 'c) Fs_spec.Fs_types.fs_ops -> 'c -> Fs_spec.Fs_types.name list list = (fun fops s0 -> let root = match fops.fops_get_root s0 with | Some root -> root | _ -> failwith "impossible" in let rec f1 sofar d0 = ( let (s1_ignore,es) = fops.fops_readdir s0 d0 in let f2 name = ( match fops.fops_resolve s0 d0 name with | None -> (failwith "get_paths: impossible") | Some x -> ( match x with | Dir_ref_entry d1 -> (f1 (sofar@[name]) d1) | File_ref_entry f1 -> [sofar@[name]])) in sofar::(List.concat (List.map f2 es))) in let paths0 = ( let ps = get_paths dhops dh0 in let ps = let f1 = fun x -> match x with (""::x) -> x | _ -> failwith "impossible" in ps |> List.map f1 |> List.filter (fun x -> x <> []) in let other_paths = [ ["nonexist_1"]; ["";"nonexist_1";"nonexist_11"]; ["";"nonexist_2"]; ["";"nonexist_2";"nonexist_22"]; ["empty_dir1";"nonexist_3"]; ["empty_dir1";"nonexist_3";"nonexist_4"]; ux7 ["nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["";"";"";"nonempty_dir1";"d2";"sl_dotdot_d2";"..";".."]; ["nonempty_dir1";"nonexist_1"]; ["nonempty_dir1";"nonexist_1";""]; ["nonempty_dir1";".."]; ["nonempty_dir1";"sl_dotdot_empty_dir1";"nonexist_1"]; ["nonempty_dir1";"sl_dotdot_nonempty_dir2";"nonexist_1"] ] in add trailing slash to all paths ; use in List.concat ( List.map ) let add_trailing_slash p = [p;p@[""]] in let add_initial_slashes p = [ p; ""::p; ""::""::p; ""::""::""::p ] in let add_via_symlink p = [ p; ["nonempty_dir1";"sl_dotdot_nonempty_dir1";".."]@p; ["";"nonempty_dir1";"sl_dotdot_nonempty_dir1";".."]@p; ["nonempty_dir1";"sl_dotdot_nonempty_dir2";".."]@p; ["";"nonempty_dir1";"sl_dotdot_nonempty_dir2";".."]@p ] in (ps@other_paths) |> List.map add_via_symlink |> List.concat |> List.map add_trailing_slash |> List.concat |> List.map add_initial_slashes |> List.concat ) type dh_res_name = (Dir_heap.Dir_heap_types.dh_dir_ref, Dir_heap.Dir_heap_types.dh_file_ref) Fs_spec.Fs_types.res_name let resolve : string -> dh_res_name = fun path -> let path = CS_Some path in let dummy_cmd = OS_READLINK path in Fs_spec.Resolve.process_path_from_root env0 dh0 dummy_cmd path let memo f = ( let tbl = Hashtbl.create 100 in let key_of_input i = Some i in fun i -> let k = key_of_input i in match k with | None -> (f i) | Some k -> ( if (Hashtbl.mem tbl k) then (Hashtbl.find tbl k) else let v = f i in let _ = Hashtbl.add tbl k v in v)) let resolve = memo resolve type single_path_props = | Ends_in_slash | Starts_with_no_slash | Starts_with_one_slash | Starts_with_slash_x2 | Starts_with_slash_x3 | Is_empty_string | Is_slash | Is_file | Is_dir | Is_symlink | Is_nonexist | Is_error | If_dir_then_is_empty | If_dir_then_is_nonempty FIXME satisifed if not dir - but this is not really what we want ; except that we also have combination with Is_dir except that we also have combination with Is_dir *) | Has_symlink_component | Not of single_path_props let single_path_props = [ [Ends_in_slash;Not Ends_in_slash]; [Starts_with_no_slash; Starts_with_one_slash; Starts_with_slash_x2; Starts_with_slash_x3]; [Is_empty_string; Not Is_empty_string]; [Is_slash;Not Is_slash]; [Is_file;Is_dir;Is_symlink;Is_nonexist;Is_error]; [Not Is_dir; If_dir_then_is_empty;If_dir_then_is_nonempty]; [Has_symlink_component;Not Has_symlink_component] ] let drop_last xs = xs |> List.rev |> List.tl |> List.rev let prefixes_of_path : path -> path list = (fun p -> let rec f1 acc xs = ( match xs with | _ -> (f1 (xs::acc) (drop_last xs))) in f1 [] p) let rec allpairs f l1 l2 = match l1 with h1::t1 -> List.fold_right (fun x a -> f h1 x :: a) l2 (allpairs f t1 l2) | [] -> [] let list_product l1 l2 = allpairs (fun x -> fun y -> (x,y)) l1 l2 let list_product_as_list : 'a list -> 'a list -> 'a list list = (fun l1 l2 -> allpairs (fun x -> fun y -> [x;y]) l1 l2) let _ = list_product_as_list [1;2;3] [4;5;6] let list_product_as_list : 'a list list -> 'a list -> 'a list list = (fun l1 l2 -> allpairs (fun x -> fun y -> x@[y]) l1 l2) let _ = list_product_as_list [[1;2;3];[7]] [4;5;6] let property_combs0 = let f1 acc x = list_product_as_list acc x in List.fold_left f1 (List.map (fun x -> [x]) (List.hd single_path_props)) (List.tl single_path_props) let _ = List.length property_combs0 let is_symlink i0_ref = ( (dhops.fops_stat_file dh0 i0_ref).st_kind = S_IFLNK) let rec sem1 prop p0 = ( match p0 with | Some p -> ( match prop with | Ends_in_slash -> (p |> List.rev |> (fun x -> match x with [""] -> false | ""::_ -> true | _ -> false)) | Starts_with_no_slash -> ( match p with | [""] -> true | c::_ -> c <> "" | _ -> failwith "impossible") | Starts_with_one_slash -> ( match p with | ["";""] -> true exactly one slash | _ -> false) | Starts_with_slash_x2 -> ( match p with | ""::""::x::_ -> (x <> "") | _ -> false) | Starts_with_slash_x3 -> ( match p with | ""::""::""::x::_ -> (x <> "") | _ -> false) | Is_slash -> (p = ["";""]) | Is_file -> (p |> string_of_path |> resolve |> is_RN_file) | Is_dir -> (p |> string_of_path |> resolve |> is_RN_dir) | Is_symlink -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_file (_,_,i0_ref,_) -> (is_symlink i0_ref) | _ -> false)) | Is_nonexist -> (p |> string_of_path |> resolve |> is_RN_none) | Is_error -> (p |> string_of_path |> resolve |> is_RN_error) | If_dir_then_is_empty -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_dir(d0_ref,_) -> ( dhops.fops_readdir dh0 d0_ref |> (fun (_,ns) -> ns=[])) | _ -> true)) | If_dir_then_is_nonempty -> ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_dir(d0_ref,_) -> ( dhops.fops_readdir dh0 d0_ref |> (fun (_,ns) -> ns<>[])) | _ -> true)) | Has_symlink_component -> ( let is_symlink p = ( p |> string_of_path |> resolve |> (fun x -> match x with | RN_file (_,_,i0_ref,_) -> (is_symlink i0_ref) | _ -> false)) in p |> prefixes_of_path |> List.exists is_symlink) | Not x -> not(sem1 x p0))) let sem1_list props p = List.for_all (fun prop -> sem1 prop p) props let implies p q = (not p) || q let logically_possible : single_path_props list -> bool = fun props -> let sub_props ps = List.for_all (fun p -> List.mem p props) ps in (not (List.mem Ends_in_slash props && List.mem Is_empty_string props)) && (not (List.mem Is_slash props && List.mem Starts_with_no_slash props)) && (not (sub_props [Ends_in_slash;Is_file])) && (not (sub_props [Ends_in_slash;Is_symlink])) && (not (sub_props [Is_slash;Has_symlink_component])) FIXME interesting case - we need to check a path which is / where there are no entries in the root directory && (not (sub_props [Is_empty_string;Is_file])) && (not (sub_props [Is_empty_string;Is_dir])) && (not (sub_props [Is_empty_string;Is_symlink])) && (not (List.mem Is_slash props && List.exists (fun x -> List.mem x [Is_file;Is_symlink;Is_nonexist;Is_error]) props)) && (not (List.mem Is_slash props && not (List.mem Starts_with_one_slash props))) && (implies (List.mem Is_empty_string props) (List.mem Is_error props)) && (implies (List.mem Is_empty_string props) (not (List.mem Has_symlink_component props))) && (implies (List.mem Is_symlink props) (not (List.mem (Not Has_symlink_component) props))) && (not (sub_props [Is_empty_string; Starts_with_one_slash])) && (not (sub_props [Is_slash;Not Ends_in_slash])) && (implies (List.mem Is_empty_string props) (List.mem Starts_with_no_slash props)) FIXME possible ? let property_combs1 = property_combs0 |> List.filter logically_possible let _ = List.length property_combs1 let list_find_opt p xs = try Some(List.find p xs) with _ -> None let path_with_property : single_path_props -> path option = (fun prop -> paths0 |> (List.map (fun p -> Some p)) |> list_find_opt (sem1 prop) |> (fun x -> match x with | None -> None | Some(Some p) -> Some p | _ -> failwith "impossible")) let _ = path_with_property (Starts_with_one_slash) FIXME should n't this be path opt list ? - a path is either none or some let paths_with_properties : single_path_props list -> path list = (fun props -> paths0 |> List.filter (fun p -> List.for_all (fun prop -> sem1 prop (Some p)) props)) let _ = paths_with_properties [ Starts_with_one_slash;Is_file;Not Is_symlink ] ( * first interesting missing case - no symlink to emptydir let _ = paths_with_properties [Starts_with_one_slash;Is_file;Not Is_symlink] let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; If_dir_then_is_empty; Not Has_symlink_component] another interesting case - we need to check single paths / where the root directory is empty ; FIXME marking this as impossible for now so we can continue to explore let _ = paths_with_properties [Is_slash; Is_dir; If_dir_then_is_empty] let _ = paths_with_properties [Is_empty_string; Is_file] let _ = paths_with_properties [Is_slash; Is_nonexist] let _ = paths_with_properties [Is_empty_string;Is_nonexist] let _ = paths_with_properties [Is_empty_string] let _ = paths_with_properties [Not Ends_in_slash; Is_empty_string] let _ = paths_with_properties [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; ] let _ = paths_with_properties [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] let _ = paths_with_properties [Is_dir; If_dir_then_is_empty; Has_symlink_component ] let _ = paths_with_properties [Is_symlink; Not Has_symlink_component ] let _ = paths_with_properties [Not Ends_in_slash; Not Is_empty_string; Is_error] let _ = List.find (list_subset [Not Ends_in_slash; Not Is_empty_string; Is_error]) property_combs1 we were not testing paths starting with two slashes , with a symlink component let _ = paths_with_properties [Not Ends_in_slash; Starts_with_slash_x2; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component] let _ = paths_with_properties [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; Not Is_dir; Has_symlink_component] *) let _ = assert([] = ( property_combs1 |> List.map (fun x -> (x,paths_with_properties x)) |> List.filter (fun (x,y) -> y=[]) )) type path_pair_props = two paths to same file ; paths not minor variations e.g. differ by trailing slash ; currently uses realpath | Not2 of path_pair_props let rp_of_res_name rn = ( match rn with | RN_dir (_,rp) -> (Some rp) | RN_file (_,_,_,rp) -> (Some rp) | RN_none (_,_,rp) -> (Some rp) | RN_error _ -> None) let rec sem2 prop (p0,p1) = ( match prop with | Paths_equal -> (p1=p0) | Essentially_different_paths_same_inode -> ( let r0 = p0 |> string_of_path |> resolve in let r1 = p1 |> string_of_path |> resolve in match (r0,r1) with | (RN_file(_,_,i0_ref,rp0),RN_file(_,_,i1_ref,rp1)) -> ((i0_ref = i1_ref) && rp0.rp_ns <> rp1.rp_ns) | _ -> false) note that this is on realpaths - i.e. it is checking whether first contains second let rec f1 p q = (match p,q with | [],[] -> false | [],_ -> true | _,[] -> false | x::xs,y::ys -> (x=y) && f1 xs ys) in let r0 = p0 |> string_of_path |> resolve in let r1 = p1 |> string_of_path |> resolve in let rp0 = (rp_of_res_name r0) in let rp1 = (rp_of_res_name r1) in match (rp0,rp1) with | Some(rp0),Some(rp1) -> ( | (["";""],[""]) -> false | (["";""],["";""]) -> false | (["";""],_) -> true | _ -> f1 rp0.rp_ns rp1.rp_ns) | (["";""],[""]) -> false | (["";""],["";""]) -> false | (["";""],_) -> true | _ -> f1 p0 p1) ) | Not2 prop -> (not (sem2 prop (p0,p1))) | Swap prop -> (sem2 prop (p1,p0))) let sem2_list: path_pair_props list -> path * path -> bool = ( fun props p -> List.for_all (fun prop -> sem2 prop p) props) let path_pair_props = [ [Paths_equal; Not2 Paths_equal]; [Essentially_different_paths_same_inode; Not2 Essentially_different_paths_same_inode]; [First_path_proper_prefix_of_second; Not2 First_path_proper_prefix_of_second]; [Swap First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]; ] let ppairs1 = allpairs (fun x y -> (x,y)) paths0 paths0 let _ = List.length ppairs1 let ppairs0 = let f1 (acc,n) x = if n=0 then (acc,n) else (x::acc,n-1) in (List.fold_left f1 ([],3000000) ppairs1) |> (fun (acc,n) -> acc) let props_hold_for_path_pair: path_pair_props list -> (path * path) -> bool = (fun props (p1,p2) -> List.for_all (fun prop -> sem2 prop (p1,p2)) props) let path_pairs_with_properties : path_pair_props list -> (path * path) list = (fun props -> ppairs0 |> List.filter (props_hold_for_path_pair props)) let pair_prop_combs0 = let f1 acc x = list_product_as_list acc x in List.fold_left f1 (List.map (fun x -> [x]) (List.hd path_pair_props)) (List.tl path_pair_props) let pair_props_logically_possible : path_pair_props list -> bool = (fun props -> let sub_props ps = List.for_all (fun p -> List.mem p props) ps in (implies (List.mem Paths_equal props) (not (List.exists (fun x -> List.mem x props) [ Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second; ]))) & & ( not ( List.mem ( ) props ) ) && (not (sub_props [First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second])) first_path_proper_prefix_of_second implies first_path is_dir , so ca n't expect first path dir to reference a file && (not (sub_props [Essentially_different_paths_same_inode; Swap First_path_proper_prefix_of_second])) ) let pair_prop_combs0 = pair_prop_combs0 |> List.filter pair_props_logically_possible let _ = resolve (string_of_path [""; ""; ""; "nonempty_dir1"; "d2"; "sl_dotdot_d2"; ".."; ".."; ""; "nonempty_dir1"; "sl_f1.txt"]) let _ = path_pairs_with_properties [Not2 Paths_equal; Essentially_different_paths_same_inode] let _ = path_pairs_with_properties [Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; ] let _ = path_pairs_with_properties [Essentially_different_paths_same_inode; Swap First_path_proper_prefix_of_second] let _ = path_pairs_with_properties [Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; ] let _ = path_pairs_with_properties [First_path_proper_prefix_of_second] *) FIXME uncomment let _ = assert ( None = try let = ( [ ] = path_pairs_with_properties x ) in Some ( List.find f1 pair_prop_combs0 ) with _ - > None ) let _ = assert( None = try let f1 x = ([] = path_pairs_with_properties x) in Some (List.find f1 pair_prop_combs0) with _ -> None) *) let classes_for_single_path : single_path_props list list = property_combs1 let classes_for_path_pairs : path_pair_props list list = pair_prop_combs0 S is the set of path pairs . We have E1 which is a set of equiv classes for the first path . We also have E2 , which is a set of equiv classes for the second path . Finally , we have E3 , which is a set of equiv classes on the set of pairs . We combine these equivalences to get a very fine equivalence . To combine two equivalence classes E1 and E2 : Suppose E1 = { e11,e12 } ; E2 = { e21,e22 } The combined set of classes is : E = { e11 /\ e21 , e11 /\ e22 , e12 /\ e21 , e12 /\ e22 } There is a slight wrinkle : if e1i /\ e2j = { } then E is not a proper set of equivalence classes : one of the partitions is empty . In our setting , this means that there is a combination such that we can not find a satisfying path pair . Obviously such empty entries should be discarded . ( See picture in tr notes 2014 - 11 - 10 ) Now , E1 is a property on the first path , and E2 is a property on the second path . So as properties on pairs of paths , they are such that any e1i /\ e2j is nonempty . However , when combining with E3 , which is an equivalence of pairs of paths , it may be that we have a e_ijk that is empty . So we must check for this when forming the combination . We hope it does n't take too long to eliminate the problematic cases . Previously we manually removed those combinations that were empty . Ca n't we just automatically remove these ? Manually removing them forced us to uncover bugs , and also identifies the smallest " unsatisfiable core " of the empty partitions . This also provides a " human - readable " explanation of why some combination e_ijk is not satisfiable . However , if we believe the code is correct , we might be tempted just to remove all those combinations that are empty . NO ! the problem is that we were uncovering the fact that the partition was empty , which meant ( in some cases ) that the underlying set of paths was not big enough , rather than that the combination was unsatisfiable . So this is a technique that properly helps to increase coverage and completeness . So we do have to manually check the unsatisfiable combinations . classes for the first path. We also have E2, which is a set of equiv classes for the second path. Finally, we have E3, which is a set of equiv classes on the set of pairs. We combine these equivalences to get a very fine equivalence. To combine two equivalence classes E1 and E2: Suppose E1 = {e11,e12}; E2 = {e21,e22} The combined set of classes is: E = { e11 /\ e21, e11 /\ e22, e12 /\ e21, e12 /\ e22 } There is a slight wrinkle: if e1i /\ e2j = {} then E is not a proper set of equivalence classes: one of the partitions is empty. In our setting, this means that there is a combination such that we cannot find a satisfying path pair. Obviously such empty entries should be discarded. (See picture in tr notes 2014-11-10) Now, E1 is a property on the first path, and E2 is a property on the second path. So as properties on pairs of paths, they are such that any e1i /\ e2j is nonempty. However, when combining with E3, which is an equivalence of pairs of paths, it may be that we have a e_ijk that is empty. So we must check for this when forming the combination. We hope it doesn't take too long to eliminate the problematic cases. Previously we manually removed those combinations that were empty. Can't we just automatically remove these? Manually removing them forced us to uncover bugs, and also identifies the smallest "unsatisfiable core" of the empty partitions. This also provides a "human-readable" explanation of why some combination e_ijk is not satisfiable. However, if we believe the code is correct, we might be tempted just to remove all those combinations that are empty. NO! the problem is that we were uncovering the fact that the partition was empty, which meant (in some cases) that the underlying set of paths was not big enough, rather than that the combination was unsatisfiable. So this is a technique that properly helps to increase coverage and completeness. So we do have to manually check the unsatisfiable combinations. *) type combined_pair_props = P1 of single_path_props list | P2 of single_path_props list | P12 of path_pair_props list type combined_pair_props = P1 of single_path_props list | P2 of single_path_props list | P12 of path_pair_props list *) let (_E1,_E2,_E3) = (classes_for_single_path) ,(classes_for_single_path) ,(classes_for_path_pairs) let es = allpairs (fun x y -> (x,y)) _E1 _E2 let es2 = allpairs (fun (x1,x2) y -> (x1,x2,y)) es _E3 let _ = List.length es2 let cp0 = es2 type combined_property = single_path_props list * single_path_props list * path_pair_props list let logically_possible_cp qi = let sub_props (q1,q2,q12) (xs,ys,zs) = List.for_all (fun p -> List.mem p q1) xs && List.for_all (fun p -> List.mem p q2) ys && List.for_all (fun p -> List.mem p q12) zs in let symmetric_prop p (q1,q2,q12) = p (q2,q1,q12) in let b1 = let (q1,q2,q12) = qi in let sub_props = sub_props qi in not (sub_props ([Is_dir],[],[Essentially_different_paths_same_inode])) && not (sub_props ([],[Is_dir],[Essentially_different_paths_same_inode])) && not (sub_props ([],[Is_dir;If_dir_then_is_empty],[Swap First_path_proper_prefix_of_second]) && List.exists (fun x -> List.mem x q1) [Is_file;Is_dir;Is_symlink]) assuming paths_equal means syntactic equality , it suffices to check p = p for each possible single path equiv class && not (sub_props ([Is_dir],[Not Is_dir],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Not Is_dir],[Is_dir],[First_path_proper_prefix_of_second])) && implies (List.mem First_path_proper_prefix_of_second q12) (not (List.exists (fun x -> List.mem x q1) [Is_file; Is_nonexist; Is_error; Is_symlink])) && implies (List.mem (Swap First_path_proper_prefix_of_second) q12) (not (List.exists (fun x -> List.mem x q2) [Is_file; Is_nonexist; Is_error; Is_symlink])) version of resolve does n't allow / to refer to file 36k && not (sub_props ([Ends_in_slash],[],[Essentially_different_paths_same_inode])) " " is only prefix of / , but then " " is a proper prefix of / hdh && not (sub_props ([If_dir_then_is_empty],[Is_slash],[Not2 First_path_proper_prefix_of_second; Not2(Swap First_path_proper_prefix_of_second)])) && not (sub_props ([Is_slash],[Ends_in_slash],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Ends_in_slash],[Is_slash],[First_path_proper_prefix_of_second])) && not (sub_props ([Is_slash],[Not Is_empty_string],[Swap First_path_proper_prefix_of_second])) && not (sub_props ([Not Is_empty_string],[Is_slash],[First_path_proper_prefix_of_second])) && implies (sub_props ([Is_empty_string], [], [Not2 (First_path_proper_prefix_of_second)])) (not (List.exists (fun x -> List.mem x q2) [Starts_with_one_slash;Starts_with_slash_x2;Starts_with_slash_x3])) && implies (sub_props ([], [Is_empty_string], [Not2 (Swap (First_path_proper_prefix_of_second))])) (not (List.exists (fun x -> List.mem x q1) [Starts_with_one_slash;Starts_with_slash_x2;Starts_with_slash_x3])) && not (sub_props ([Is_empty_string],[Is_empty_string],[Not2 Paths_equal])) && not (sub_props ([Is_slash],[Is_slash],[Not2 Paths_equal])) && not (sub_props ([Not Has_symlink_component],[Is_symlink],[Essentially_different_paths_same_inode])) && not (sub_props ([Is_symlink],[Not Has_symlink_component],[Essentially_different_paths_same_inode])) in let b2 = ( let p (q1,q2,q12) = implies (sub_props (q1,q2,q12) ([Is_slash],[],[Not2 First_path_proper_prefix_of_second;Not2 (Swap First_path_proper_prefix_of_second)])) (not (List.exists (fun x -> List.mem x [Is_file;Is_nonexist;Is_symlink;Is_error]) q2)) in p qi && symmetric_prop p qi) && ( let p (q1,q2,q12) = implies (sub_props (q1,q2,q12) ([],[],[Essentially_different_paths_same_inode])) (List.exists (fun x -> List.mem x [Is_file;Is_symlink]) q1) in p qi && symmetric_prop p qi) in b1 && b2 want the " simplest " first let compare_cp ( p1,p2,p12 ) ( q1,q2,q12 ) = let x = ( p1 , p2 , p12 ) in let x'= ( List.length q1 , q2 , ) in Pervasives.compare x x ' ( * not antireflexive let compare_cp (p1,p2,p12) (q1,q2,q12) = let x = (List.length p1, List.length p2, List.length p12) in let x'= (List.length q1, List.length q2, List.length q12) in *) let cp0 = cp0 |> List.filter logically_possible_cp 138927->97887->59265->54675->54659->52115->51945->41289->41228->41163- > ... - > 34101 - > 33813 let ppairs0 = ppairs0 let combined_properties_hold_of_path_path: combined_property -> (path * path) -> bool = (fun (q1,q2,q12) (p1,p2) -> sem1_list q1 (Some p1) && sem1_list q2 (Some p2) && sem2_list q12 (p1,p2)) let paths_with_combined_properties : combined_property -> (path * path) list = (fun (q1,q2,q12) -> let ppairs = allpairs (fun x y -> (x,y)) (paths_with_properties q1) (paths_with_properties q2) in List.filter (combined_properties_hold_of_path_path (q1,q2,q12)) ppairs) /~jrh13/atp/OCaml/lib.ml let rec allsets m l = if m = 0 then [[]] else match l with [] -> [] | h::t -> List.map (fun g -> h::g) (allsets (m - 1) t) @ allsets m t;; let rec minimize_set xs p = ( if xs=[] then xs else let l = List.length xs in let ss = allsets (l - 1) xs in let xs' = try Some(List.find p ss) with _ -> None in match xs' with | None -> xs | Some xs' -> minimize_set xs' p) let rec minimize_cp' stage cp = ( match stage with | 1 -> ( let (p1,p2,p12) = cp in let p p1' = ([] = paths_with_combined_properties (p1',p2,p12)) in let p1' = minimize_set p1 p in let _ = print_endline "1" in minimize_cp' 2 (p1',p2,p12)) | 2 -> ( let (p1,p2,p12) = cp in let p p2' = ([] = paths_with_combined_properties (p1,p2',p12)) in let p2' = minimize_set p2 p in let _ = print_endline "2" in minimize_cp' 3 (p1,p2',p12)) | 3 -> ( let (p1,p2,p12) = cp in let p p12' = ([] = paths_with_combined_properties (p1,p2,p12')) in let p12' = minimize_set p12 p in (p1,p2,p12')) | _ -> (failwith "impossible") ) let minimize_cp cp = minimize_cp' 1 cp let compare_paths ((p1:path),(p2:path)) (p3,p4) = Pervasives.compare (List.length p1,List.length p2) (List.length p3, List.length p4) let sort_paths_list = List.sort compare_paths module type IGNORE = sig end let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode] ) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [ Swap First_path_proper_prefix_of_second ]) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Not Has_symlink_component], [Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Not Has_symlink_component], [Paths_equal ]) if either of the paths is a dir , we ca n't expect let _ = paths_with_combined_properties ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Essentially_different_paths_same_inode; ]) let _ = paths_with_combined_properties ([Is_dir; If_dir_then_is_empty], [ Is_nonexist; ], [ First_path_proper_prefix_of_second; ]) ca n't have first is_dir , second not is_dir , and second prefix of first let _ = paths_with_combined_properties ([ Is_dir], [Not Is_dir], [ Swap First_path_proper_prefix_of_second]) again , ca n't have the second a prefix of first , if second is not a directory let _ = paths_with_combined_properties ([ Is_dir], [ Is_nonexist], [ Swap First_path_proper_prefix_of_second]) we do n't check for errors through empty directories ; also , if we are using rp , then we ca n't check errors and prefix FIXME ? should be /empty_dir1 , /empty_dir1 / nonexist_3 / nonexist_4 let p1 = [ " " ; " empty_dir1 " ] let p2 = [ " " ; " empty_dir1";"nonexist_3";"nonexist_4 " ] let _ = assert ( false = combined_properties_hold_of_path_path prop ( p1,p2 ) ) ( * expect to be true ! should be /empty_dir1 , /empty_dir1/nonexist_3/nonexist_4 let p1 = ["";"empty_dir1"] let p2 = ["";"empty_dir1";"nonexist_3";"nonexist_4"] let _ = sem1_list [Is_dir; If_dir_then_is_empty] (Some p1) let _ = sem1_list [Is_error] (Some p2) *) let prop = ([ Is_dir; If_dir_then_is_empty], [ Is_error], [ First_path_proper_prefix_of_second; ]) this should not have any satisfying paths ; rp for relative path seems wrong NO ! this is fine - first resolves to / , second is / , and . is not a proper prefix of slash ; so there are many paths with this property , providing first path is / this should not have any satisfying paths; rp for relative path seems wrong NO! this is fine - first resolves to /, second is /, and . is not a proper prefix of slash; so there are many paths with this property, providing first path is / *) let _ = paths_with_combined_properties ([ Is_dir], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = ["nonempty_dir1"; "d2"; "sl_dotdot_d2"; ".."; ".."; ""] |> string_of_path |> resolve cg6 cf above , we do n't test on empty root directory , hence this condition is not satisfiable ( the first path is forced to be root ) so this is unsatisfiable but FIXME probably should be checked ( if we get round to checking with an empty root ) cg6 cf above, we don't test on empty root directory, hence this condition is not satisfiable (the first path is forced to be root) so this is unsatisfiable but FIXME probably should be checked (if we get round to checking with an empty root) *) let _ = paths_with_combined_properties ([ Is_dir ; If_dir_then_is_empty], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = ( module struct let _ = paths_with_combined_properties Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) First_path_proper_prefix_of_second]) Not2 Paths_equal ; ; Not2 First_path_proper_prefix_of_second ; Not2 First_path_proper_prefix_of_second; *) First_path_proper_prefix_of_second]) let p1 = ["";"sl_nonempty_dir1"] let p2 = ["";"nonempty_dir1";"d2"] let _ = sem1_list [Is_symlink] (Some p1) let _ = sem1_list [Is_dir] (Some p2) let _ = sem2_list [First_path_proper_prefix_of_second] (p1,p2) this gives rp_ns = [ " " ; " " ; " sl_nonempty_dir1 " ] which is wrong let _ = p2 |> string_of_path |> resolve not OK ; rp_ns is incorrect for files in the root directory end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = minimize_cp prop let prop = ([], [Is_slash], [First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = ([],[],[Swap (First_path_proper_prefix_of_second)]) let p1 = [""] let p2 = ["";""] let _ = combined_properties_hold_of_path_path prop (p1,p2) ( * this shows that p1= " " and p2=/ satisfy that first path is a proper prefix of / let prop = ([], [Is_slash], [First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop let prop = ([], [Is_slash], [ Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop expect nonexmpty_dir1 , nonexmpty_dir1 / nonexist_1 should satisfy let prop = ([Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Starts_with_no_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let p1 = ["nonempty_dir1"] let p2 = ["nonempty_dir1";"nonexist_1"] let _ = combined_properties_hold_of_path_path prop (p1,p2) eg [ " nonempty_dir1 " ; " d2 " ; " sl_dotdot_no_such_target " ; " " ] [First_path_proper_prefix_of_second]) let compare_paths (p1,p2) (p3,p4) = Pervasives.compare (List.length p1,List.length p2) (List.length p3, List.length p4) let sort_paths_list = List.sort compare_paths let _ = paths_with_combined_properties prop |> sort_paths_list end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop expect nonexmpty_dir1 , nonexmpty_dir1 / nonexist_1 should satisfy let prop = ([Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([Ends_in_slash; Starts_with_no_slash; If_dir_then_is_nonempty; Not Has_symlink_component], [Starts_with_one_slash; Is_nonexist; Not Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([Starts_with_no_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Starts_with_no_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal]) let _ = paths_with_combined_properties prop FIXED by adding further sl to empty dirs end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let prop = minimize_cp prop let prop = ([If_dir_then_is_empty], [Is_nonexist; Has_symlink_component], [First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop we do n't check a nonexist in an empty dir , with the nonexist via a symlink component eg / / nonexist_1 FIXED eg nonempty_dir1/sl_dotdot_empty_dir1/nonexist_1 FIXED *) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let prop = minimize_cp prop let prop = ([], [Is_slash], []) let _ = paths_with_combined_properties prop let _ = paths_with_properties [Is_slash] end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Not Ends_in_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], []) let _ = paths_with_combined_properties prop need a path to an empty dir via symlink ; missing paths after refactoring ; fixed end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Ends_in_slash], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop ca n't expect p2 to end in slash , and resolve to something that is a file ? or need a symlink to something that is a link nonempty_dir1 / sl_f1.txt/ should resolve to ... /f1.txt which has a hard link in nonempty_dir1 / link_f1.txt nonempty_dir1/sl_f1.txt/ should resolve to .../f1.txt which has a hard link in nonempty_dir1/link_f1.txt *) let p1 = ["nonempty_dir1";"f1.txt"] let p2 = ["nonempty_dir1";"sl_link_f1.txt";""] let _ = combined_properties_hold_of_path_path prop (p1,p2) let _ = sem1_list [Ends_in_slash] (Some p2) let _ = p1 |> string_of_path |> resolve let _ = p2 |> string_of_path |> resolve let _ = sem2 Essentially_different_paths_same_inode (p1,p2) the version of resolve we use means that a ( symlink that ) ends in a slash can not refer to a file 36k end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [If_dir_then_is_empty], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop this forces the second path to be " " ; then we ca n't stop " " being a proper prefix of " " ; " " hdh let prop = ([Is_slash], [If_dir_then_is_empty], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Ends_in_slash], [Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_nonexist; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_nonexist], [Not2 First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop if first path is / , and it is not a prefix , then second path must be " " to get error ; then we ca n't require that " " is not a proper prefix of / let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop if first path is / , and it is not a prefix , then second path must be " " to get error ; then we ca n't require that " " is not a proper prefix of / let prop = ([Is_slash], [Is_error], [Not2 First_path_proper_prefix_of_second; ]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Is_slash; Is_dir; If_dir_then_is_nonempty; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_nonempty; Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Swap First_path_proper_prefix_of_second]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_slash], [Not Is_empty_string], [Swap First_path_proper_prefix_of_second]) end : IGNORE) let _ = ( module struct let prop = ([Ends_in_slash; Starts_with_one_slash; Not Is_empty_string; Not Is_slash; Is_dir; If_dir_then_is_empty; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Starts_with_one_slash], [Is_empty_string], [Not2 (Swap First_path_proper_prefix_of_second)]) let prop = ([Is_empty_string], [Starts_with_one_slash], [Not2 (First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Is_empty_string], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop let _ = logically_possible_cp prop Essentially_different_paths_same_inode must be for files ( or symlinks ? ) FIXME end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Is_empty_string], [Is_empty_string], [Not2 Paths_equal]) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_file; Not Is_dir; Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_symlink; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([], [Is_symlink], [Essentially_different_paths_same_inode]) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_file; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_symlink; Not Is_dir; Has_symlink_component], [Not2 Paths_equal; Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Not Has_symlink_component], [Is_symlink], [Essentially_different_paths_same_inode]) is 2nd is a symlink , then to have the same inode the first must point to the symlink ; but then the first must have a symlink component let prop = ([], [Is_symlink], [Essentially_different_paths_same_inode]) let _ = paths_with_combined_properties prop |> sort_paths_list ( [ " nonempty_dir1 " ; " link_to_symlink " ] , [ " nonempty_dir1 " ; " sl_link_f1.txt " ] ) end : IGNORE) let _ = ( module struct let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Not Is_slash; Is_error; Not Is_dir; Not Has_symlink_component], [Not2 Paths_equal; Not2 Essentially_different_paths_same_inode; Not2 First_path_proper_prefix_of_second; Not2 (Swap First_path_proper_prefix_of_second)]) let _ = paths_with_combined_properties prop let prop = minimize_cp prop let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not2 Paths_equal]) we only have one relative path to an error ? fixed by ux7 let prop = ([Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], [Not Ends_in_slash; Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component], []) let _ = paths_with_combined_properties prop |> sort_paths_list ( [ " empty_dir1 " ; " nonexist_3 " ; " nonexist_4 " ] , [ " empty_dir1 " ; " nonexist_3 " ; " nonexist_4 " ] ) ["empty_dir1"; "nonexist_3"; "nonexist_4"]) *) let _ = paths_with_properties [ Starts_with_no_slash; Not Is_empty_string; Is_error; Not Has_symlink_component] end : IGNORE) *) let _ = let _ = assert (not (List.exists (fun x -> [] = paths_with_combined_properties x) cp0)) in () let _ = Printf.printf "property_testgen.ml: all tests pass\n" let n0 = ref 0 let prop = let f1 x = ([] = paths_with_combined_properties x) in let (prop,n') = find_first_n f1 (drop (!n0) cp0) in let _ = n0 := !n0 + n' in let _ = Printf.printf "Index now %d \n" (!n0) in prop let _ = let f1 x = ([] = paths_with_combined_properties x) in List.find f1 cp0 let _ = let f1 x = ([] = paths_with_combined_properties x) in cp0 |> List.filter f1 |> List.length *)
6b53cded8a2c8394c05aaa1067970130e19ebc3dc60c89c194af9895d9487eb4
tisnik/clojure-examples
core.clj
; ( C ) Copyright 2015 , 2020 ; ; All rights reserved. This program and the accompanying materials ; are made available under the terms of the Eclipse Public License v1.0 ; which accompanies this distribution, and is available at -v10.html ; ; Contributors: ; (ns seesaw6.core (:gen-class)) (use 'seesaw.core) (use 'seesaw.color) (def formular (grid-panel :columns 3 :rows 3 :items ["Color test" (button :text ":background :red" :background :red) (button :text ":background :yellow" :background :yellow) (button :text ":background :orange" :background :orange) (button :text ":background #ff8080" :background "#ff8080") (button :text ":background #8080ff" :background "#8080ff") (button :text ":background #8f8" :background "#8f8") (button :text ":background #ff8" :background "#ff8") (button :text ":foreground :orange" :foreground :orange) ])) (defn -main [& args] (-> (frame :title "Color test" :on-close :exit :content formular) (pack!) (show!)))
null
https://raw.githubusercontent.com/tisnik/clojure-examples/984af4a3e20d994b4f4989678ee1330e409fdae3/seesaw6/src/seesaw6/core.clj
clojure
All rights reserved. This program and the accompanying materials are made available under the terms of the Eclipse Public License v1.0 which accompanies this distribution, and is available at Contributors:
( C ) Copyright 2015 , 2020 -v10.html (ns seesaw6.core (:gen-class)) (use 'seesaw.core) (use 'seesaw.color) (def formular (grid-panel :columns 3 :rows 3 :items ["Color test" (button :text ":background :red" :background :red) (button :text ":background :yellow" :background :yellow) (button :text ":background :orange" :background :orange) (button :text ":background #ff8080" :background "#ff8080") (button :text ":background #8080ff" :background "#8080ff") (button :text ":background #8f8" :background "#8f8") (button :text ":background #ff8" :background "#ff8") (button :text ":foreground :orange" :foreground :orange) ])) (defn -main [& args] (-> (frame :title "Color test" :on-close :exit :content formular) (pack!) (show!)))
e9ec0cb1a63df08968aa480618f6ba673da253565272f57e3dc9c24c21041fc6
LdBeth/star-lisp
dummy-functions.lisp
-*- SYNTAX : COMMON - LISP ; MODE : LISP ; BASE : 10 ; PACKAGE : * SIM - I ; MUSER : YES -*- (in-package :*sim-i) ;;;> *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ ;;;> ;;;> The Thinking Machines *Lisp Simulator is in the public domain. ;;;> You are free to do whatever you like with it, including but ;;;> not limited to distributing, modifying, and copying. ;;;> ;;;> *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ ;;; Author: JP Massar. (defun list-of-slc-function-types () nil) (defun get-function-type (function-symbol) (get function-symbol 'slc::function-type)) (defun set-function-type (function-symbol type) (setf (get function-symbol 'slc::function-type) type) ) (defun remove-function-type (function-symbol) (setf (get function-symbol 'slc::function-type) nil) ) (defun get-variable-descriptor (variable) (get variable 'slc::descriptor)) (defun set-variable-descriptor (variable value) (setf (get variable 'slc::descriptor) value) ) (defun remove-variable-descriptor (variable) (setf (get variable 'slc::descriptor) nil) ) (defun make-pvar-for-compiler (&rest args &key type reference read-only) (declare (ignore args type reference read-only)) nil ) (defun make-descriptor-for-compiler (&rest args) (declare (ignore args)) nil ) (defun find-compiler-keyword (keyword) (declare (ignore keyword)) (error "I need a function which tells me if keyword is a legal compiler option.") ) (defun deal-with-compiler-option-value (option value keyword) (declare (ignore option value keyword)) nil ) (defun compiler-warn (&rest args) (declare (ignore args)) (error "Internal error. This should never be called inside the simulator.") ) (defun expt2 (x) (expt 2 x)) (defun expt2-1- (x) (expt 2 (1- x))) (defun expt2-symbol () 'expt2) (defun expt2-1-symbol () 'expt2-1-) (defun simplify-expression (&rest args) (copy-list args) ) (defvar *pvar-length-error-message* "The ~S of a pvar has no meaning with respect to the *Lisp language itself. ~@ It only has meaning with respect to Paris, the CM Assembly language, and the ~@ *Lisp Simulator knows nothing about Paris. Pure *Lisp code cannot use ~S." ) (defun pvar-length (pvar) pvar (error *pvar-length-error-message* 'length 'pvar-length) ) (defun pvar-mantissa-length (pvar) pvar (error *pvar-length-error-message* 'mantissa-length 'pvar-mantissa-length) ) (defun pvar-exponent-length (pvar) pvar (error *pvar-length-error-message* 'exponent-length 'pvar-exponent-length) ) (defun starlisp-form-not-to-macroexpand (form) (declare (ignore form)) nil ) (defun call-starlisp-compiler (form environment) (declare (ignore environment)) form )
null
https://raw.githubusercontent.com/LdBeth/star-lisp/034fb97fe8780d6e9fbff7c1d8c4a6b8c331797b/source/dummy-functions.lisp
lisp
MODE : LISP ; BASE : 10 ; PACKAGE : * SIM - I ; MUSER : YES -*- > *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ > > The Thinking Machines *Lisp Simulator is in the public domain. > You are free to do whatever you like with it, including but > not limited to distributing, modifying, and copying. > > *+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+*+ Author: JP Massar.
(in-package :*sim-i) (defun list-of-slc-function-types () nil) (defun get-function-type (function-symbol) (get function-symbol 'slc::function-type)) (defun set-function-type (function-symbol type) (setf (get function-symbol 'slc::function-type) type) ) (defun remove-function-type (function-symbol) (setf (get function-symbol 'slc::function-type) nil) ) (defun get-variable-descriptor (variable) (get variable 'slc::descriptor)) (defun set-variable-descriptor (variable value) (setf (get variable 'slc::descriptor) value) ) (defun remove-variable-descriptor (variable) (setf (get variable 'slc::descriptor) nil) ) (defun make-pvar-for-compiler (&rest args &key type reference read-only) (declare (ignore args type reference read-only)) nil ) (defun make-descriptor-for-compiler (&rest args) (declare (ignore args)) nil ) (defun find-compiler-keyword (keyword) (declare (ignore keyword)) (error "I need a function which tells me if keyword is a legal compiler option.") ) (defun deal-with-compiler-option-value (option value keyword) (declare (ignore option value keyword)) nil ) (defun compiler-warn (&rest args) (declare (ignore args)) (error "Internal error. This should never be called inside the simulator.") ) (defun expt2 (x) (expt 2 x)) (defun expt2-1- (x) (expt 2 (1- x))) (defun expt2-symbol () 'expt2) (defun expt2-1-symbol () 'expt2-1-) (defun simplify-expression (&rest args) (copy-list args) ) (defvar *pvar-length-error-message* "The ~S of a pvar has no meaning with respect to the *Lisp language itself. ~@ It only has meaning with respect to Paris, the CM Assembly language, and the ~@ *Lisp Simulator knows nothing about Paris. Pure *Lisp code cannot use ~S." ) (defun pvar-length (pvar) pvar (error *pvar-length-error-message* 'length 'pvar-length) ) (defun pvar-mantissa-length (pvar) pvar (error *pvar-length-error-message* 'mantissa-length 'pvar-mantissa-length) ) (defun pvar-exponent-length (pvar) pvar (error *pvar-length-error-message* 'exponent-length 'pvar-exponent-length) ) (defun starlisp-form-not-to-macroexpand (form) (declare (ignore form)) nil ) (defun call-starlisp-compiler (form environment) (declare (ignore environment)) form )
e1583f3ee8cd2b16f9e0da926c6d076ddabe68cd9637816315ce701c1b5d9926
bmeurer/ocaml-arm
parse.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) $ Id$ (* Entry points in the parser *) val implementation : Lexing.lexbuf -> Parsetree.structure val interface : Lexing.lexbuf -> Parsetree.signature val toplevel_phrase : Lexing.lexbuf -> Parsetree.toplevel_phrase val use_file : Lexing.lexbuf -> Parsetree.toplevel_phrase list
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/parsing/parse.mli
ocaml
********************************************************************* OCaml ********************************************************************* Entry points in the parser
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . $ Id$ val implementation : Lexing.lexbuf -> Parsetree.structure val interface : Lexing.lexbuf -> Parsetree.signature val toplevel_phrase : Lexing.lexbuf -> Parsetree.toplevel_phrase val use_file : Lexing.lexbuf -> Parsetree.toplevel_phrase list
b18492842d5987784e1032af83b978f50ff055253c891d5a2244d93f9f6a1587
Twinside/Eq
Floating.hs
{-# LANGUAGE Rank2Types #-} -- | This module implements the rules to interpret all floating -- points operations which are by nature lossy. So this set -- of rules may or may not be used in the context of global -- evaluation to preserve the "true" meaning of the formula. module Language.Eq.Algorithm.Eval.Floating ( evalFloat, floatEvalRules ) where import Control.Applicative import Data.Maybe( fromMaybe ) import Data.Ratio import qualified Language.Eq.ErrorMessages as Err import Language.Eq.Algorithm.Eval.Types import Language.Eq.Algorithm.Eval.Utils import Language.Eq.EvaluationContext import Language.Eq.Types -- | General function favored to use the reduction rules -- as it preserve meta information about the formula form. evalFloat :: Formula anyForm -> EqContext (Formula anyForm) evalFloat (Formula f) = Formula <$> floatEvalRules f floatCastingOperator :: (Double -> Double -> Double) -> EvalOp floatCastingOperator f (CInteger i1) (CFloat f2) = left . CFloat $ f (fromIntegral i1) f2 floatCastingOperator f (UnOp _ OpNegate (CInteger i1)) (CFloat f2) = left . CFloat $ f (fromIntegral $ negate i1) f2 floatCastingOperator f (CFloat f1) (CInteger i2) = left . CFloat $ f f1 (fromIntegral i2) floatCastingOperator f (CFloat f1) (UnOp _ OpNegate (CInteger i2)) = left . CFloat $ f f1 (fromIntegral $ negate i2) floatCastingOperator f (CFloat f1) (CFloat f2) = left . CFloat $ f f1 f2 floatCastingOperator _ e e' = right (e, e') add, sub, mul, division, power :: EvalOp add = floatCastingOperator (+) sub = floatCastingOperator (-) mul = floatCastingOperator (*) division = floatCastingOperator (/) power = floatCastingOperator (**) ----------------------------------------------- ---- 'floor' ----------------------------------------------- floorEval :: EvalFun floorEval (CFloat f) = return . CInteger $ floor f floorEval f = return $ unOp OpFloor f ----------------------------------------------- ---- 'frac' ----------------------------------------------- fracEval :: EvalFun fracEval (CFloat f) = return . CFloat . snd $ (properFraction f :: (Int,Double)) fracEval f = return $ unOp OpFrac f ----------------------------------------------- ---- 'Ceil' ----------------------------------------------- ceilEval :: EvalFun ceilEval i@(CInteger _) = return i ceilEval (CFloat f) = return . CInteger $ ceiling f ceilEval f = return $ unOp OpCeil f ----------------------------------------------- ---- 'negate' ----------------------------------------------- fNegate :: EvalFun fNegate (CFloat f) = return . CFloat $ negate f fNegate f = return $ negate f ----------------------------------------------- ---- 'abs' ----------------------------------------------- fAbs :: EvalFun fAbs (CFloat f) = return . CFloat $ abs f fAbs f = return $ abs f ----------------------------------------------- ---- General evaluation ----------------------------------------------- -- | All the rules for floats floatEvalRules :: EvalFun floatEvalRules (Fraction f) = return . CFloat $ fromInteger (numerator f) / fromInteger (denominator f) floatEvalRules (NumEntity Pi) = return $ CFloat pi floatEvalRules (BinOp _ OpAdd fs) = binEval OpAdd add add fs floatEvalRules (BinOp _ OpSub fs) = binEval OpSub sub add fs floatEvalRules (BinOp _ OpMul fs) = binEval OpMul mul mul fs -- | Todo fix this, it's incorrect floatEvalRules (BinOp _ OpPow fs) = binEval OpPow power power fs floatEvalRules (BinOp _ OpDiv fs) = binEval OpDiv division mul fs floatEvalRules (UnOp _ OpFloor f) = floorEval f floatEvalRules (UnOp _ OpCeil f) = ceilEval f floatEvalRules (UnOp _ OpFrac f) = fracEval f floatEvalRules (UnOp _ OpNegate f) = fNegate f floatEvalRules (UnOp _ OpAbs f) = fAbs f floatEvalRules formula@(UnOp _ op f) = return . fromMaybe formula $ unOpReduce (funOf op) f where funOf OpSqrt = sqrt funOf OpSin = sin funOf OpSinh = sinh funOf OpASin = asin funOf OpASinh = asinh funOf OpCos = cos funOf OpCosh = cosh funOf OpACos = acos funOf OpACosh = acosh funOf OpTan = tan funOf OpTanh = tanh funOf OpATan = atan funOf OpATanh = atanh funOf OpLn = log funOf OpLog = logBase 10.0 funOf OpExp = exp funOf OpAbs = error $ Err.not_here "unop : abs - " funOf OpNegate = error $ Err.not_here "unop : negate - " funOf OpFloor = error $ Err.not_here "unop : floor - " funOf OpFrac = error $ Err.not_here "unop : frac - " funOf OpCeil = error $ Err.not_here "unop : ceil - " funOf OpFactorial = error $ Err.not_here "unop : factorial - " funOf OpMatrixWidth = error $ Err.not_here "unop : MatrixWidth - " funOf OpMatrixHeight = error $ Err.not_here "unop : MatrixHeight - " floatEvalRules end = return end -------------------------------------------------------------- ---- Scalar related function -------------------------------------------------------------- unOpReduce :: (forall a. (Floating a) => a -> a) -> FormulaPrim -> Maybe FormulaPrim unOpReduce f (Fraction r) = unOpReduce f . CFloat $ fromRational r unOpReduce f (CInteger i) = unOpReduce f . CFloat $ fromInteger i unOpReduce f (CFloat num) = Just . CFloat $ f num unOpReduce _ _ = Nothing
null
https://raw.githubusercontent.com/Twinside/Eq/60105372d55420735b722245db7021c239c812f4/Language/Eq/Algorithm/Eval/Floating.hs
haskell
# LANGUAGE Rank2Types # | This module implements the rules to interpret all floating points operations which are by nature lossy. So this set of rules may or may not be used in the context of global evaluation to preserve the "true" meaning of the formula. | General function favored to use the reduction rules as it preserve meta information about the formula form. --------------------------------------------- -- 'floor' --------------------------------------------- --------------------------------------------- -- 'frac' --------------------------------------------- --------------------------------------------- -- 'Ceil' --------------------------------------------- --------------------------------------------- -- 'negate' --------------------------------------------- --------------------------------------------- -- 'abs' --------------------------------------------- --------------------------------------------- -- General evaluation --------------------------------------------- | All the rules for floats | Todo fix this, it's incorrect ------------------------------------------------------------ -- Scalar related function ------------------------------------------------------------
module Language.Eq.Algorithm.Eval.Floating ( evalFloat, floatEvalRules ) where import Control.Applicative import Data.Maybe( fromMaybe ) import Data.Ratio import qualified Language.Eq.ErrorMessages as Err import Language.Eq.Algorithm.Eval.Types import Language.Eq.Algorithm.Eval.Utils import Language.Eq.EvaluationContext import Language.Eq.Types evalFloat :: Formula anyForm -> EqContext (Formula anyForm) evalFloat (Formula f) = Formula <$> floatEvalRules f floatCastingOperator :: (Double -> Double -> Double) -> EvalOp floatCastingOperator f (CInteger i1) (CFloat f2) = left . CFloat $ f (fromIntegral i1) f2 floatCastingOperator f (UnOp _ OpNegate (CInteger i1)) (CFloat f2) = left . CFloat $ f (fromIntegral $ negate i1) f2 floatCastingOperator f (CFloat f1) (CInteger i2) = left . CFloat $ f f1 (fromIntegral i2) floatCastingOperator f (CFloat f1) (UnOp _ OpNegate (CInteger i2)) = left . CFloat $ f f1 (fromIntegral $ negate i2) floatCastingOperator f (CFloat f1) (CFloat f2) = left . CFloat $ f f1 f2 floatCastingOperator _ e e' = right (e, e') add, sub, mul, division, power :: EvalOp add = floatCastingOperator (+) sub = floatCastingOperator (-) mul = floatCastingOperator (*) division = floatCastingOperator (/) power = floatCastingOperator (**) floorEval :: EvalFun floorEval (CFloat f) = return . CInteger $ floor f floorEval f = return $ unOp OpFloor f fracEval :: EvalFun fracEval (CFloat f) = return . CFloat . snd $ (properFraction f :: (Int,Double)) fracEval f = return $ unOp OpFrac f ceilEval :: EvalFun ceilEval i@(CInteger _) = return i ceilEval (CFloat f) = return . CInteger $ ceiling f ceilEval f = return $ unOp OpCeil f fNegate :: EvalFun fNegate (CFloat f) = return . CFloat $ negate f fNegate f = return $ negate f fAbs :: EvalFun fAbs (CFloat f) = return . CFloat $ abs f fAbs f = return $ abs f floatEvalRules :: EvalFun floatEvalRules (Fraction f) = return . CFloat $ fromInteger (numerator f) / fromInteger (denominator f) floatEvalRules (NumEntity Pi) = return $ CFloat pi floatEvalRules (BinOp _ OpAdd fs) = binEval OpAdd add add fs floatEvalRules (BinOp _ OpSub fs) = binEval OpSub sub add fs floatEvalRules (BinOp _ OpMul fs) = binEval OpMul mul mul fs floatEvalRules (BinOp _ OpPow fs) = binEval OpPow power power fs floatEvalRules (BinOp _ OpDiv fs) = binEval OpDiv division mul fs floatEvalRules (UnOp _ OpFloor f) = floorEval f floatEvalRules (UnOp _ OpCeil f) = ceilEval f floatEvalRules (UnOp _ OpFrac f) = fracEval f floatEvalRules (UnOp _ OpNegate f) = fNegate f floatEvalRules (UnOp _ OpAbs f) = fAbs f floatEvalRules formula@(UnOp _ op f) = return . fromMaybe formula $ unOpReduce (funOf op) f where funOf OpSqrt = sqrt funOf OpSin = sin funOf OpSinh = sinh funOf OpASin = asin funOf OpASinh = asinh funOf OpCos = cos funOf OpCosh = cosh funOf OpACos = acos funOf OpACosh = acosh funOf OpTan = tan funOf OpTanh = tanh funOf OpATan = atan funOf OpATanh = atanh funOf OpLn = log funOf OpLog = logBase 10.0 funOf OpExp = exp funOf OpAbs = error $ Err.not_here "unop : abs - " funOf OpNegate = error $ Err.not_here "unop : negate - " funOf OpFloor = error $ Err.not_here "unop : floor - " funOf OpFrac = error $ Err.not_here "unop : frac - " funOf OpCeil = error $ Err.not_here "unop : ceil - " funOf OpFactorial = error $ Err.not_here "unop : factorial - " funOf OpMatrixWidth = error $ Err.not_here "unop : MatrixWidth - " funOf OpMatrixHeight = error $ Err.not_here "unop : MatrixHeight - " floatEvalRules end = return end unOpReduce :: (forall a. (Floating a) => a -> a) -> FormulaPrim -> Maybe FormulaPrim unOpReduce f (Fraction r) = unOpReduce f . CFloat $ fromRational r unOpReduce f (CInteger i) = unOpReduce f . CFloat $ fromInteger i unOpReduce f (CFloat num) = Just . CFloat $ f num unOpReduce _ _ = Nothing
417de96e2408589fa62c412c282338baa6d58f5cbec08d217e27e56265d686b2
input-output-hk/ouroboros-network
Stream.hs
# LANGUAGE LambdaCase # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE RecordWildCards #-} # LANGUAGE ScopedTypeVariables # module Ouroboros.Consensus.Storage.LedgerDB.Stream ( NextBlock (..) , StreamAPI (..) , streamAll ) where import Control.Monad.Except import GHC.Stack import Ouroboros.Consensus.Block {------------------------------------------------------------------------------- Abstraction over the streaming API provided by the Chain DB -------------------------------------------------------------------------------} -- | Next block returned during streaming data NextBlock blk = NoMoreBlocks | NextBlock blk -- | Stream blocks from the immutable DB -- -- When we initialize the ledger DB, we try to find a snapshot close to the -- tip of the immutable DB, and then stream blocks from the immutable DB to its -- tip to bring the ledger up to date with the tip of the immutable DB. -- In CPS form to enable the use of ' withXYZ ' style iterator init functions . data StreamAPI m blk = StreamAPI { -- | Start streaming after the specified block streamAfter :: forall a. HasCallStack => Point blk -- Reference to the block corresponding to the snapshot we found ( or ' GenesisPoint ' if we did n't find any ) -> (Either (RealPoint blk) (m (NextBlock blk)) -> m a) -- Get the next block (by value) -- -- Should be @Left pt@ if the snapshot we found is more recent than the -- tip of the immutable DB. Since we only store snapshots to disk for -- blocks in the immutable DB, this can only happen if the immutable DB got truncated due to disk corruption . The returned @pt@ is a ' RealPoint ' , not a ' Point ' , since it must always be possible to -- stream after genesis. -> m a } -- | Stream all blocks streamAll :: forall m blk e a. (Monad m, HasCallStack) => StreamAPI m blk -> Point blk -- ^ Starting point for streaming -> (RealPoint blk -> e) -- ^ Error when tip not found -> a -- ^ Starting point when tip /is/ found -> (blk -> a -> m a) -- ^ Update function for each block -> ExceptT e m a streamAll StreamAPI{..} tip notFound e f = ExceptT $ streamAfter tip $ \case Left tip' -> return $ Left (notFound tip') Right getNext -> do let go :: a -> m a go a = do mNext <- getNext case mNext of NoMoreBlocks -> return a NextBlock b -> go =<< f b a Right <$> go e
null
https://raw.githubusercontent.com/input-output-hk/ouroboros-network/358880057f1d6d86cc385e8475813ace3b9ebef6/ouroboros-consensus/src/Ouroboros/Consensus/Storage/LedgerDB/Stream.hs
haskell
# LANGUAGE RankNTypes # # LANGUAGE RecordWildCards # ------------------------------------------------------------------------------ Abstraction over the streaming API provided by the Chain DB ------------------------------------------------------------------------------ | Next block returned during streaming | Stream blocks from the immutable DB When we initialize the ledger DB, we try to find a snapshot close to the tip of the immutable DB, and then stream blocks from the immutable DB to its tip to bring the ledger up to date with the tip of the immutable DB. | Start streaming after the specified block Reference to the block corresponding to the snapshot we found Get the next block (by value) Should be @Left pt@ if the snapshot we found is more recent than the tip of the immutable DB. Since we only store snapshots to disk for blocks in the immutable DB, this can only happen if the immutable DB stream after genesis. | Stream all blocks ^ Starting point for streaming ^ Error when tip not found ^ Starting point when tip /is/ found ^ Update function for each block
# LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # module Ouroboros.Consensus.Storage.LedgerDB.Stream ( NextBlock (..) , StreamAPI (..) , streamAll ) where import Control.Monad.Except import GHC.Stack import Ouroboros.Consensus.Block data NextBlock blk = NoMoreBlocks | NextBlock blk In CPS form to enable the use of ' withXYZ ' style iterator init functions . data StreamAPI m blk = StreamAPI { streamAfter :: forall a. HasCallStack => Point blk ( or ' GenesisPoint ' if we did n't find any ) -> (Either (RealPoint blk) (m (NextBlock blk)) -> m a) got truncated due to disk corruption . The returned @pt@ is a ' RealPoint ' , not a ' Point ' , since it must always be possible to -> m a } streamAll :: forall m blk e a. (Monad m, HasCallStack) => StreamAPI m blk -> ExceptT e m a streamAll StreamAPI{..} tip notFound e f = ExceptT $ streamAfter tip $ \case Left tip' -> return $ Left (notFound tip') Right getNext -> do let go :: a -> m a go a = do mNext <- getNext case mNext of NoMoreBlocks -> return a NextBlock b -> go =<< f b a Right <$> go e
912bb0d812c9496e2d4e2bb8321ce7f991edbc77ade209df8eebe51dfa7b290c
Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator
Spec.hs
{-# LANGUAGE OverloadedStrings #-} import Control.Exception import Data.Aeson hiding (Null) import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import Data.Either import qualified Data.Text as T import Lib import Network.HTTP.Client import Network.HTTP.Simple import OpenAPI import Test.Hspec main :: IO () main = hspec $ do describe "runGetInventory" $ it "get inventory" $ do response <- runGetInventory getResponseBody response `shouldBe` GetInventoryResponse200 ( KeyMap.fromList [ (Key.fromText "pet1", Number 23), (Key.fromText "pet2", Number 2) ] ) describe "runAddPet" $ it "add pet" $ do response <- runAddPet getResponseBody response `shouldBe` AddPetResponse200 describe "runFindPetsByStatus" $ it "find pets by status" $ do response <- runFindPetsByStatus FindPetsByStatusParametersStatusEnumPending getResponseBody response `shouldBe` FindPetsByStatusResponse200 [ (mkPet []) { petId = Just 23, petName = Just "Ted", petStatus = Just PetStatusEnumPending } ] describe "runFindPetsByStatus" $ it "find pets by status" $ do response <- runFindPetsByStatus $ FindPetsByStatusParametersStatusTyped "notExistingStatus" getResponseBody response `shouldBe` FindPetsByStatusResponse400 describe "runEchoUserAgent" $ it "returns the user agent" $ do response <- runEchoUserAgent getResponseBody response `shouldSatisfy` ( \body -> case body of EchoUserAgentResponse200 text -> "XYZ" `T.isInfixOf` text && "openapi3-code-generator" `T.isInfixOf` text _ -> False ) describe "runEchoUserAgentWithoutUserAgent" $ it "should fail as the user agent is not present" $ do response <- runEchoUserAgentWithoutUserAgent getResponseBody response `shouldBe` EchoUserAgentResponse400 describe "runSendAndReceiveNullableAndOptional" $ do it "should work with filled objects" $ do response <- runSendAndReceiveNullableAndOptional "filled" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } it "should work with null values where possible" $ do response <- runSendAndReceiveNullableAndOptional "emptyNull" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Just Null, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Just Null } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Just Null, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Just Null } it "should work with absent values where possible" $ do response <- runSendAndReceiveNullableAndOptional "emptyAbsent" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Nothing, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Nothing } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Nothing, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Nothing } describe "expected parse errors" $ do let defaultRequestBodyWhichIsIgnored = NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } it "should fail on null value for required key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNonNullableWithNull" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $.requiredNonNullable: parsing Text failed, expected String, but encountered Null" it "should fail on no value for required key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNonNullableWithAbsence" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $: key \"requiredNonNullable\" not found" it "should fail on no value for required nullable key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNullable" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $: key \"requiredNullable\" not found" it "should fail on null value for optional non-nullable key" $ do response <- runSendAndReceiveNullableAndOptional "errorOptionalNonNullable" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $.optionalNonNullable: parsing Text failed, expected String, but encountered Null"
null
https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator/af8435def9f3dff36180d1520b5c60200c532d2a/testing/level3/petstore-running-example/test/Spec.hs
haskell
# LANGUAGE OverloadedStrings #
import Control.Exception import Data.Aeson hiding (Null) import qualified Data.Aeson.Key as Key import qualified Data.Aeson.KeyMap as KeyMap import Data.Either import qualified Data.Text as T import Lib import Network.HTTP.Client import Network.HTTP.Simple import OpenAPI import Test.Hspec main :: IO () main = hspec $ do describe "runGetInventory" $ it "get inventory" $ do response <- runGetInventory getResponseBody response `shouldBe` GetInventoryResponse200 ( KeyMap.fromList [ (Key.fromText "pet1", Number 23), (Key.fromText "pet2", Number 2) ] ) describe "runAddPet" $ it "add pet" $ do response <- runAddPet getResponseBody response `shouldBe` AddPetResponse200 describe "runFindPetsByStatus" $ it "find pets by status" $ do response <- runFindPetsByStatus FindPetsByStatusParametersStatusEnumPending getResponseBody response `shouldBe` FindPetsByStatusResponse200 [ (mkPet []) { petId = Just 23, petName = Just "Ted", petStatus = Just PetStatusEnumPending } ] describe "runFindPetsByStatus" $ it "find pets by status" $ do response <- runFindPetsByStatus $ FindPetsByStatusParametersStatusTyped "notExistingStatus" getResponseBody response `shouldBe` FindPetsByStatusResponse400 describe "runEchoUserAgent" $ it "returns the user agent" $ do response <- runEchoUserAgent getResponseBody response `shouldSatisfy` ( \body -> case body of EchoUserAgentResponse200 text -> "XYZ" `T.isInfixOf` text && "openapi3-code-generator" `T.isInfixOf` text _ -> False ) describe "runEchoUserAgentWithoutUserAgent" $ it "should fail as the user agent is not present" $ do response <- runEchoUserAgentWithoutUserAgent getResponseBody response `shouldBe` EchoUserAgentResponse400 describe "runSendAndReceiveNullableAndOptional" $ do it "should work with filled objects" $ do response <- runSendAndReceiveNullableAndOptional "filled" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } it "should work with null values where possible" $ do response <- runSendAndReceiveNullableAndOptional "emptyNull" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Just Null, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Just Null } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Just Null, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Just Null } it "should work with absent values where possible" $ do response <- runSendAndReceiveNullableAndOptional "emptyAbsent" NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Nothing, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Nothing } getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponse200 NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = Null, nullableAndOptionalTestOptionalNonNullable = Nothing, nullableAndOptionalTestOptionalNullable = Nothing, nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = Null, nullableAndOptionalTestReferencedOptionalNonNullable = Nothing, nullableAndOptionalTestReferencedOptionalNullable = Nothing } describe "expected parse errors" $ do let defaultRequestBodyWhichIsIgnored = NullableAndOptionalTest { nullableAndOptionalTestRequiredNonNullable = "x", nullableAndOptionalTestRequiredNullable = NonNull "x", nullableAndOptionalTestOptionalNonNullable = Just "x", nullableAndOptionalTestOptionalNullable = Just (NonNull "x"), nullableAndOptionalTestReferencedRequiredNonNullable = "x", nullableAndOptionalTestReferencedRequiredNullable = NonNull "x", nullableAndOptionalTestReferencedOptionalNonNullable = Just "x", nullableAndOptionalTestReferencedOptionalNullable = Just (NonNull "x") } it "should fail on null value for required key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNonNullableWithNull" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $.requiredNonNullable: parsing Text failed, expected String, but encountered Null" it "should fail on no value for required key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNonNullableWithAbsence" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $: key \"requiredNonNullable\" not found" it "should fail on no value for required nullable key" $ do response <- runSendAndReceiveNullableAndOptional "errorRequiredNullable" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $: key \"requiredNullable\" not found" it "should fail on null value for optional non-nullable key" $ do response <- runSendAndReceiveNullableAndOptional "errorOptionalNonNullable" defaultRequestBodyWhichIsIgnored getResponseBody response `shouldBe` SendAndReceiveNullableAndOptionalResponseError "Error in $.optionalNonNullable: parsing Text failed, expected String, but encountered Null"
074781a4b4f69371db8c026d6ba24521917208e4f58574d746577b580d15e669
ntoronto/pict3d
info.rkt
#lang info (define collection 'multi) (define deps '(("base" #:version "6.1.1") "draw-lib" "srfi-lite-lib" "typed-racket-lib" "typed-racket-more" "math-lib" "scribble-lib" "gui-lib" "pconvert-lib" "pict-lib" ; why? "profile-lib" ; for tests "pfds" )) (define build-deps '("draw-doc" "gui-doc" "gui-lib" "racket-doc" "plot-doc" "plot-lib" "plot-gui-lib" "images-doc" "images-lib" "htdp-doc" "htdp-lib" "pict-doc" "typed-racket-doc" )) (define pkg-desc "Pict3D: Functional 3D Scenes") (define pkg-authors '(ntoronto))
null
https://raw.githubusercontent.com/ntoronto/pict3d/09283c9d930c63b6a6a3f2caa43e029222091bdb/info.rkt
racket
why? for tests
#lang info (define collection 'multi) (define deps '(("base" #:version "6.1.1") "draw-lib" "srfi-lite-lib" "typed-racket-lib" "typed-racket-more" "math-lib" "scribble-lib" "gui-lib" "pconvert-lib" "pfds" )) (define build-deps '("draw-doc" "gui-doc" "gui-lib" "racket-doc" "plot-doc" "plot-lib" "plot-gui-lib" "images-doc" "images-lib" "htdp-doc" "htdp-lib" "pict-doc" "typed-racket-doc" )) (define pkg-desc "Pict3D: Functional 3D Scenes") (define pkg-authors '(ntoronto))
14d4ef403aa8c455b17f3ae6cfc729d7b472af10b03f07cffe4f716ecf863c20
janestreet/bonsai
instrumentation.ml
open! Core open! Import module Entry_label = struct (* The label that gets attached to performance measurements. It shows up in the flamegraph produced by the chrome profiler, and also in the messages that we receive from the [PerformanceObserver]. Since this label may be viewed by humans, we include the [node_type] field and hand-craft the sexp representation. *) type t = { id : Node_path.t ; node_type : string } let to_string { id; node_type } = [%string "##%{node_type} %{id#Node_path}"] end let extract_node_path_from_entry_label label = if String.is_prefix ~prefix:"##" label then ( match String.split label ~on:' ' with | [ _; node_path ] -> Some (Node_path.of_string node_path) | _ -> None) else None ;; let instrument_computation (t : _ Computation.t) ~start_timer ~stop_timer = let computation_map (type result) (context : unit Transform.For_computation.context) () (computation : result Computation.t) : result Computation.t = let node_info = Graph_info.Node_info.of_computation computation in let entry_label node_type = let (lazy current_path) = context.current_path in { Entry_label.id = current_path; node_type } |> Entry_label.to_string in let compute_label = entry_label [%string "%{node_info.node_type}-compute"] in let apply_action_label = entry_label [%string "%{node_info.node_type}-apply_action"] in let by_label = entry_label [%string "%{node_info.node_type}-by"] in let time_apply_action ~apply_action ~inject_dynamic ~inject_static ~schedule_event input model action = start_timer apply_action_label; let model = apply_action ~inject_dynamic ~inject_static ~schedule_event input model action in stop_timer apply_action_label; model in let time_static_apply_action ~apply_action ~inject_dynamic ~inject_static ~schedule_event model action = start_timer apply_action_label; let model = apply_action ~inject_dynamic ~inject_static ~schedule_event model action in stop_timer apply_action_label; model in let recursed = context.recurse () computation in match recursed with | Fetch v_id -> Computation.Fetch v_id | Leaf1 t -> Leaf1 { t with apply_action = time_apply_action ~apply_action:t.apply_action } | Leaf0 t -> Leaf0 { t with apply_action = time_static_apply_action ~apply_action:t.apply_action } | Leaf_incr t -> let compute clock input = start_timer compute_label; let computed = t.compute clock input in stop_timer compute_label; computed in Leaf_incr { t with compute } | Assoc_simpl t -> let by path key value = start_timer by_label; let by = t.by path key value in stop_timer by_label; by in Assoc_simpl { t with by } | computation -> computation in let value_map (type a) (context : unit Transform.For_value.context) () ({ here; value; id } as wrapped_value : a Value.t) = let (lazy current_path) = context.current_path in let node_info = Graph_info.Node_info.of_value wrapped_value in let entry_label = { Entry_label.id = current_path; node_type = node_info.node_type } |> Entry_label.to_string in let value = match value with | Constant _ | Exception _ | Incr _ | Named _ | Both (_, _) | Cutoff _ -> value | Map t -> let f a = start_timer entry_label; let x = t.f a in stop_timer entry_label; x in Map { t with f } | Map2 t -> let f a b = start_timer entry_label; let x = t.f a b in stop_timer entry_label; x in Map2 { t with f } | Map3 t -> let f a b c = start_timer entry_label; let x = t.f a b c in stop_timer entry_label; x in Map3 { t with f } | Map4 t -> let f a b c d = start_timer entry_label; let x = t.f a b c d in stop_timer entry_label; x in Map4 { t with f } | Map5 t -> let f a b c d e = start_timer entry_label; let x = t.f a b c d e in stop_timer entry_label; x in Map5 { t with f } | Map6 t -> let f a b c d e f = start_timer entry_label; let x = t.f a b c d e f in stop_timer entry_label; x in Map6 { t with f } | Map7 t -> let f a b c d e f g = start_timer entry_label; let x = t.f a b c d e f g in stop_timer entry_label; x in Map7 { t with f } in context.recurse () { here; value; id } in Transform.map ~init:() ~computation_mapper:{ f = computation_map } ~value_mapper:{ f = value_map } t ;;
null
https://raw.githubusercontent.com/janestreet/bonsai/782fecd000a1f97b143a3f24b76efec96e36a398/src/instrumentation.ml
ocaml
The label that gets attached to performance measurements. It shows up in the flamegraph produced by the chrome profiler, and also in the messages that we receive from the [PerformanceObserver]. Since this label may be viewed by humans, we include the [node_type] field and hand-craft the sexp representation.
open! Core open! Import module Entry_label = struct type t = { id : Node_path.t ; node_type : string } let to_string { id; node_type } = [%string "##%{node_type} %{id#Node_path}"] end let extract_node_path_from_entry_label label = if String.is_prefix ~prefix:"##" label then ( match String.split label ~on:' ' with | [ _; node_path ] -> Some (Node_path.of_string node_path) | _ -> None) else None ;; let instrument_computation (t : _ Computation.t) ~start_timer ~stop_timer = let computation_map (type result) (context : unit Transform.For_computation.context) () (computation : result Computation.t) : result Computation.t = let node_info = Graph_info.Node_info.of_computation computation in let entry_label node_type = let (lazy current_path) = context.current_path in { Entry_label.id = current_path; node_type } |> Entry_label.to_string in let compute_label = entry_label [%string "%{node_info.node_type}-compute"] in let apply_action_label = entry_label [%string "%{node_info.node_type}-apply_action"] in let by_label = entry_label [%string "%{node_info.node_type}-by"] in let time_apply_action ~apply_action ~inject_dynamic ~inject_static ~schedule_event input model action = start_timer apply_action_label; let model = apply_action ~inject_dynamic ~inject_static ~schedule_event input model action in stop_timer apply_action_label; model in let time_static_apply_action ~apply_action ~inject_dynamic ~inject_static ~schedule_event model action = start_timer apply_action_label; let model = apply_action ~inject_dynamic ~inject_static ~schedule_event model action in stop_timer apply_action_label; model in let recursed = context.recurse () computation in match recursed with | Fetch v_id -> Computation.Fetch v_id | Leaf1 t -> Leaf1 { t with apply_action = time_apply_action ~apply_action:t.apply_action } | Leaf0 t -> Leaf0 { t with apply_action = time_static_apply_action ~apply_action:t.apply_action } | Leaf_incr t -> let compute clock input = start_timer compute_label; let computed = t.compute clock input in stop_timer compute_label; computed in Leaf_incr { t with compute } | Assoc_simpl t -> let by path key value = start_timer by_label; let by = t.by path key value in stop_timer by_label; by in Assoc_simpl { t with by } | computation -> computation in let value_map (type a) (context : unit Transform.For_value.context) () ({ here; value; id } as wrapped_value : a Value.t) = let (lazy current_path) = context.current_path in let node_info = Graph_info.Node_info.of_value wrapped_value in let entry_label = { Entry_label.id = current_path; node_type = node_info.node_type } |> Entry_label.to_string in let value = match value with | Constant _ | Exception _ | Incr _ | Named _ | Both (_, _) | Cutoff _ -> value | Map t -> let f a = start_timer entry_label; let x = t.f a in stop_timer entry_label; x in Map { t with f } | Map2 t -> let f a b = start_timer entry_label; let x = t.f a b in stop_timer entry_label; x in Map2 { t with f } | Map3 t -> let f a b c = start_timer entry_label; let x = t.f a b c in stop_timer entry_label; x in Map3 { t with f } | Map4 t -> let f a b c d = start_timer entry_label; let x = t.f a b c d in stop_timer entry_label; x in Map4 { t with f } | Map5 t -> let f a b c d e = start_timer entry_label; let x = t.f a b c d e in stop_timer entry_label; x in Map5 { t with f } | Map6 t -> let f a b c d e f = start_timer entry_label; let x = t.f a b c d e f in stop_timer entry_label; x in Map6 { t with f } | Map7 t -> let f a b c d e f g = start_timer entry_label; let x = t.f a b c d e f g in stop_timer entry_label; x in Map7 { t with f } in context.recurse () { here; value; id } in Transform.map ~init:() ~computation_mapper:{ f = computation_map } ~value_mapper:{ f = value_map } t ;;
7be23255d754bb25c22bfca951eb623fa9a69da2bc658bfcf722c8b8311e0be3
maxima-project-on-github/maxima-packages
trigrat.lisp
(in-package :maxima) (if #$member (global, features)$ (meval #$declare ([d2%, lg, lexp], global)$)) (defun $listofei (e ) (declare (special $d2% $lg $lexp)) (setq $d2% (copy-tree (car e))) (setq $lg ()) (setq $lexp ()) (do ((lvar (caddr $d2%) (cdr lvar)) (lg (cadddr $d2%) (cdr lg)) (var)) ((null lvar)(setq $lg (cons '(mlist) $lg)) (setq $lexp (cons '(mlist) $lexp)) (setq $d2% (cons $d2% (cdr e))) ) (setq var (car lvar)) (cond ((and (mexptp var) (equal (cadr var) '$%e) ( mtimesp ( ) ) ( eq ( cadr ( ) ) ' $ % i ) ;; Check that we have a factor of %i. This test includes ;; cases like %i, and %i*x/2, which we get for e.g. ;; sin(1) and sin(x/2). (eq '$%i (cdr (partition (if (atom (caddr var)) (list '(mtimes)(caddr var)) (caddr var)) '$%i 1)))) (setq $lexp (cons var $lexp)) (setq var (symbolconc "$_" (car lg))) (setq $lg (cons var $lg)) (rplaca lvar var))))) #$trigrat_equationp (e%) := not atom (e%) and member (op (e%), ["=", "#", "<", "<=", ">=", ">"])$ #$trigrat(exp):= if matrixp (exp) or listp (exp) or setp (exp) or trigrat_equationp (exp) then map (trigrat, exp) else block([e%,n%,d%,lg,f%,lexp,ls,d2%,l2%,alg,gcd1], alg:algebraic,gcd1:gcd, algebraic:true,gcd:subres, e%: rat(ratsimp(expand(exponentialize(exp)))), n%:num(e%),d%:denom(e%), listofei(d%), l2%:map(lambda([u%,v%],u%^((hipow(d2%,v%)+lopow(d2%,v%))/2)), lexp,lg), f%:if length(lexp)=0 then 1 else if length(lexp)=1 then part(l2%,1) else apply("*",l2%), n%:rectform(ratexpand(n%/f%)), d%:rectform(ratexpand(d%/f%)), e%:ratsimp(n%/d%,%i), algebraic:alg,gcd:gcd1, e%)$ written by , august 1988
null
https://raw.githubusercontent.com/maxima-project-on-github/maxima-packages/5a1bbd88a4e8b66b1ae659e2a07cdbaede1be7f7/robert-dodier/lexical_symbols/trigrat.lisp
lisp
Check that we have a factor of %i. This test includes cases like %i, and %i*x/2, which we get for e.g. sin(1) and sin(x/2).
(in-package :maxima) (if #$member (global, features)$ (meval #$declare ([d2%, lg, lexp], global)$)) (defun $listofei (e ) (declare (special $d2% $lg $lexp)) (setq $d2% (copy-tree (car e))) (setq $lg ()) (setq $lexp ()) (do ((lvar (caddr $d2%) (cdr lvar)) (lg (cadddr $d2%) (cdr lg)) (var)) ((null lvar)(setq $lg (cons '(mlist) $lg)) (setq $lexp (cons '(mlist) $lexp)) (setq $d2% (cons $d2% (cdr e))) ) (setq var (car lvar)) (cond ((and (mexptp var) (equal (cadr var) '$%e) ( mtimesp ( ) ) ( eq ( cadr ( ) ) ' $ % i ) (eq '$%i (cdr (partition (if (atom (caddr var)) (list '(mtimes)(caddr var)) (caddr var)) '$%i 1)))) (setq $lexp (cons var $lexp)) (setq var (symbolconc "$_" (car lg))) (setq $lg (cons var $lg)) (rplaca lvar var))))) #$trigrat_equationp (e%) := not atom (e%) and member (op (e%), ["=", "#", "<", "<=", ">=", ">"])$ #$trigrat(exp):= if matrixp (exp) or listp (exp) or setp (exp) or trigrat_equationp (exp) then map (trigrat, exp) else block([e%,n%,d%,lg,f%,lexp,ls,d2%,l2%,alg,gcd1], alg:algebraic,gcd1:gcd, algebraic:true,gcd:subres, e%: rat(ratsimp(expand(exponentialize(exp)))), n%:num(e%),d%:denom(e%), listofei(d%), l2%:map(lambda([u%,v%],u%^((hipow(d2%,v%)+lopow(d2%,v%))/2)), lexp,lg), f%:if length(lexp)=0 then 1 else if length(lexp)=1 then part(l2%,1) else apply("*",l2%), n%:rectform(ratexpand(n%/f%)), d%:rectform(ratexpand(d%/f%)), e%:ratsimp(n%/d%,%i), algebraic:alg,gcd:gcd1, e%)$ written by , august 1988
d3197baad99725d3a99496b42ebeb30e9ef3ab3f795538b3da7bd7de4b356bc4
iambrj/imin
cond_test_19.rkt
(let ([x (read)]) (let ([y (read)]) (if (if (< x 1) (eq? x 0) (eq? x 2)) (+ y 2) (+ y 10))))
null
https://raw.githubusercontent.com/iambrj/imin/a02104f795e11baba8b2df173c4061e69640891f/tests/cond_test_19.rkt
racket
(let ([x (read)]) (let ([y (read)]) (if (if (< x 1) (eq? x 0) (eq? x 2)) (+ y 2) (+ y 10))))
5f2b0ad014cae56a6c5fe2de9e0c7f03a5b324bfbb139e516e707d886efa7b6b
AlacrisIO/legicash-facts
side_chain_client.ml
open Scgi open Legilogic_lib open Signing open Yojsoning open Logging open Types open Action open Lwter (* TODO: use Lwt_exn *) open Alacris_lib open Side_chain open Side_chain_client_lib open Actions (* Side_chain also has a Request module *) module Request = Scgi.Request let side_chain_client_log = true let _ = Config.set_application_name "alacris" (* let _ = set_log_file "logs/alacris-client.log" *) (* TODO: before we got to production, make sure keys at rest are suitably encrypted *) let _ = let keys_file_ref = ref ("demo-keys-small.json" |> Config.get_config_filename) in let args = ref [] in Arg.parse_argv Sys.argv [("--keys", Set_string keys_file_ref, "file containing keys to the managed accounts")] (fun x -> args := x :: !args) "side_chain_client.exe"; register_file_keypairs !keys_file_ref (* let account_names = nicknames_with_registered_keypair () |> List.sort compare *) TODO : use DepositWanted , WithdrawalWanted , PaymentWanted from side_chain_user , directly ? type deposit_json = { address: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type withdrawal_json = { address: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type payment_json = { sender: Address.t ; recipient: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type address_json = { address: Address.t } [@@deriving yojson] let handle_lwt_exception exn = Logging.log "Got LWT exception: %s" (Printexc.to_string exn) port and address must match " scgi_pass " in nginx / conf / scgi.conf let port = 1025 let address = "127.0.0.1" let return_json id status json = let headers = [`Content_type "application/json"] in let body = `String (string_of_yojson json) in let response = Response.{status; headers; body} in if side_chain_client_log then log "[\"RESPONSE\", %d, %s]" id (Response.to_debug_string response); Lwt.return response let ok_json id json = return_json id `Ok json let bad_request id json = return_json id `Bad_request json let internal_error id json = return_json id `Internal_server_error json let bad_request_method id methodz = let json = error_json "Invalid HTTP method: %s" (Http_method.to_string methodz) in bad_request id json let invalid_api_call id methodz call = let json = error_json "No such %s API call: %s" methodz call in bad_request id json let invalid_get_api_call id call = invalid_api_call id "GET" call let invalid_post_api_call id call = invalid_api_call id "POST" call let bad_request_response id msg = bad_request id (error_json "%s" msg) let error_response id msg = ok_json id (error_json "%s" msg) let internal_error_response id msg = internal_error id (error_json "%s" msg) let return_result id json_or_exn = match json_or_exn with | Ok json -> ok_json id json | Error exn -> Printexc.to_string exn |> error_response id TODO replace with ` Lwt_exn.run_lwt ` let throw_if_err = function | Ok d -> Lwt.return d | Error e -> raise e let trent_address = Signing.Test.trent_address let zander_address = Signing.Test.zander_address let _ = if side_chain_client_log then Logging.log "side_chain_client, step 1"; let request_counter = let counter = ref 0 in fun () -> let n = !counter + 1 in counter := n ; n in (* just log Lwt exceptions *) let _ = Lwt.async_exception_hook := handle_lwt_exception in if side_chain_client_log then Logging.log "side_chain_client, step 2"; let handle_request request = (* Log the request *) let id = request_counter () in if side_chain_client_log then log "[\"REQUEST\", %d, %s]" id (Request.to_debug_string request); /api / somemethod let api_call = String.sub uri 5 (String.length uri - 5) in (* remove /api/ *) match Request.meth request with | `GET -> begin match api_call with | "balances" -> if side_chain_client_log then Logging.log "GET /api/balances"; get_all_balances_on_trent () >>= return_result id | "tps" -> if side_chain_client_log then Logging.log "GET /api/tps"; get_transaction_rate_on_trent () |> ok_json id | "proof" -> if side_chain_client_log then Logging.log "GET /api/proof"; (match Request.param request "tx-revision" with | Some param -> ( try get_proof (Revision.of_string param) >>= return_result id with | Failure msg when msg = "int_of_string" -> bad_request_response id ("Invalid tx-revision: " ^ param) | exn -> internal_error_response id (Printexc.to_string exn)) | None -> bad_request_response id "Expected one parameter, tx-revision") | "thread" -> if side_chain_client_log then Logging.log "GET /api/thread"; (match Request.param request "id" with Some param -> (try apply_main_chain_thread (int_of_string param) |> ok_json id with | Failure msg when msg = "int_of_string" -> bad_request_response id ("Invalid id: " ^ param) | exn -> internal_error_response id (Printexc.to_string exn)) | None -> bad_request_response id "Expected one parameter, id") | _ -> invalid_get_api_call id api_call end | `POST -> let json = yojson_of_string (Request.contents request) in let (=->) deserialized f = if side_chain_client_log then Logging.log "POST /api/%s" api_call; let err500 m = internal_error_response id m in match (deserialized json) with NB it 's good security practice to prevent implementation details * escaping in HTTP responses ( such as in deserialization failures * below ) , hence swallowing a useful ` Error e ` . Perhaps we should * TODO capture in an error log ( ? ) * escaping in HTTP responses (such as in deserialization failures * below), hence swallowing a useful `Error e`. Perhaps we should * TODO capture in an error log (?) *) | Error _ -> bad_request_response id "Invalid request payload" | Ok d -> try f d >>= ok_json id with | Lib.Internal_error msg -> err500 msg | exn -> err500 (Printexc.to_string exn) in begin match api_call with | "deposit" -> deposit_json_of_yojson =-> fun d -> Lwt.return @@ deposit_to ~operator:trent_address d.request_guid d.address d.amount | "withdrawal" -> withdrawal_json_of_yojson =-> fun d -> Lwt.return @@ withdrawal_from ~operator:trent_address d.request_guid d.address d.amount | "payment" -> payment_json_of_yojson =-> fun d -> Lwt.return @@ payment_on ~operator:trent_address d.request_guid d.sender d.recipient d.amount "memo" | "balance" -> address_json_of_yojson =-> fun d -> get_balance_on ~operator:trent_address d.address >>= throw_if_err | "status" -> address_json_of_yojson =-> fun d -> get_status_on_trent_and_main_chain d.address >>= throw_if_err | "recent_transactions" -> if side_chain_client_log then Logging.log "POST /api/recent_transactions"; let maybe_limit_string = Request.param request "limit" in let invalid_limit = Some (Revision.zero) in let maybe_limit = match maybe_limit_string with | Some s -> (try let limit = Revision.of_string s in if Revision.compare limit Revision.zero <= 0 then raise (Failure "bad limit"); Some limit with Failure _ -> limit string not parseable as a number , or nonpositive invalid_limit) | None -> None in if maybe_limit = invalid_limit then bad_request_response id ("Invalid limit value: " ^ (Lib.Option.get maybe_limit_string)) else let maybe_address = address_json_of_yojson json in (match maybe_address with | Ok address_record -> ( get_recent_user_transactions_on_trent address_record.address maybe_limit >>= return_result id) | Error msg -> error_response id msg) | "sleep" -> if side_chain_client_log then Logging.log "POST /api/sleep"; (try Lwt_unix.sleep 1.0 >>= (fun () -> ok_json id (`Int 42)) with | Lib.Internal_error msg -> internal_error_response id msg | exn -> internal_error_response id (Printexc.to_string exn)) | other_call -> invalid_post_api_call id other_call end (* neither GET nor POST *) | methodz -> bad_request_method id methodz in let _ = Server.handler_inet address port handle_request in if side_chain_client_log then Logging.log "side_chain_client, step 3"; (* run forever in Lwt monad *) Db.run ~db_name:"alacris_client_db" (fun () -> fst (Lwt.wait ()))
null
https://raw.githubusercontent.com/AlacrisIO/legicash-facts/5d3663bade68c09bed47b3f58fa12580f38fdb46/src/alacris_client/side_chain_client.ml
ocaml
TODO: use Lwt_exn Side_chain also has a Request module let _ = set_log_file "logs/alacris-client.log" TODO: before we got to production, make sure keys at rest are suitably encrypted let account_names = nicknames_with_registered_keypair () |> List.sort compare just log Lwt exceptions Log the request remove /api/ neither GET nor POST run forever in Lwt monad
open Scgi open Legilogic_lib open Signing open Yojsoning open Logging open Types open Action open Alacris_lib open Side_chain open Side_chain_client_lib open Actions module Request = Scgi.Request let side_chain_client_log = true let _ = Config.set_application_name "alacris" let _ = let keys_file_ref = ref ("demo-keys-small.json" |> Config.get_config_filename) in let args = ref [] in Arg.parse_argv Sys.argv [("--keys", Set_string keys_file_ref, "file containing keys to the managed accounts")] (fun x -> args := x :: !args) "side_chain_client.exe"; register_file_keypairs !keys_file_ref TODO : use DepositWanted , WithdrawalWanted , PaymentWanted from side_chain_user , directly ? type deposit_json = { address: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type withdrawal_json = { address: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type payment_json = { sender: Address.t ; recipient: Address.t ; amount: TokenAmount.t ; request_guid: RequestGuid.t } [@@deriving yojson] type address_json = { address: Address.t } [@@deriving yojson] let handle_lwt_exception exn = Logging.log "Got LWT exception: %s" (Printexc.to_string exn) port and address must match " scgi_pass " in nginx / conf / scgi.conf let port = 1025 let address = "127.0.0.1" let return_json id status json = let headers = [`Content_type "application/json"] in let body = `String (string_of_yojson json) in let response = Response.{status; headers; body} in if side_chain_client_log then log "[\"RESPONSE\", %d, %s]" id (Response.to_debug_string response); Lwt.return response let ok_json id json = return_json id `Ok json let bad_request id json = return_json id `Bad_request json let internal_error id json = return_json id `Internal_server_error json let bad_request_method id methodz = let json = error_json "Invalid HTTP method: %s" (Http_method.to_string methodz) in bad_request id json let invalid_api_call id methodz call = let json = error_json "No such %s API call: %s" methodz call in bad_request id json let invalid_get_api_call id call = invalid_api_call id "GET" call let invalid_post_api_call id call = invalid_api_call id "POST" call let bad_request_response id msg = bad_request id (error_json "%s" msg) let error_response id msg = ok_json id (error_json "%s" msg) let internal_error_response id msg = internal_error id (error_json "%s" msg) let return_result id json_or_exn = match json_or_exn with | Ok json -> ok_json id json | Error exn -> Printexc.to_string exn |> error_response id TODO replace with ` Lwt_exn.run_lwt ` let throw_if_err = function | Ok d -> Lwt.return d | Error e -> raise e let trent_address = Signing.Test.trent_address let zander_address = Signing.Test.zander_address let _ = if side_chain_client_log then Logging.log "side_chain_client, step 1"; let request_counter = let counter = ref 0 in fun () -> let n = !counter + 1 in counter := n ; n in let _ = Lwt.async_exception_hook := handle_lwt_exception in if side_chain_client_log then Logging.log "side_chain_client, step 2"; let handle_request request = let id = request_counter () in if side_chain_client_log then log "[\"REQUEST\", %d, %s]" id (Request.to_debug_string request); /api / somemethod match Request.meth request with | `GET -> begin match api_call with | "balances" -> if side_chain_client_log then Logging.log "GET /api/balances"; get_all_balances_on_trent () >>= return_result id | "tps" -> if side_chain_client_log then Logging.log "GET /api/tps"; get_transaction_rate_on_trent () |> ok_json id | "proof" -> if side_chain_client_log then Logging.log "GET /api/proof"; (match Request.param request "tx-revision" with | Some param -> ( try get_proof (Revision.of_string param) >>= return_result id with | Failure msg when msg = "int_of_string" -> bad_request_response id ("Invalid tx-revision: " ^ param) | exn -> internal_error_response id (Printexc.to_string exn)) | None -> bad_request_response id "Expected one parameter, tx-revision") | "thread" -> if side_chain_client_log then Logging.log "GET /api/thread"; (match Request.param request "id" with Some param -> (try apply_main_chain_thread (int_of_string param) |> ok_json id with | Failure msg when msg = "int_of_string" -> bad_request_response id ("Invalid id: " ^ param) | exn -> internal_error_response id (Printexc.to_string exn)) | None -> bad_request_response id "Expected one parameter, id") | _ -> invalid_get_api_call id api_call end | `POST -> let json = yojson_of_string (Request.contents request) in let (=->) deserialized f = if side_chain_client_log then Logging.log "POST /api/%s" api_call; let err500 m = internal_error_response id m in match (deserialized json) with NB it 's good security practice to prevent implementation details * escaping in HTTP responses ( such as in deserialization failures * below ) , hence swallowing a useful ` Error e ` . Perhaps we should * TODO capture in an error log ( ? ) * escaping in HTTP responses (such as in deserialization failures * below), hence swallowing a useful `Error e`. Perhaps we should * TODO capture in an error log (?) *) | Error _ -> bad_request_response id "Invalid request payload" | Ok d -> try f d >>= ok_json id with | Lib.Internal_error msg -> err500 msg | exn -> err500 (Printexc.to_string exn) in begin match api_call with | "deposit" -> deposit_json_of_yojson =-> fun d -> Lwt.return @@ deposit_to ~operator:trent_address d.request_guid d.address d.amount | "withdrawal" -> withdrawal_json_of_yojson =-> fun d -> Lwt.return @@ withdrawal_from ~operator:trent_address d.request_guid d.address d.amount | "payment" -> payment_json_of_yojson =-> fun d -> Lwt.return @@ payment_on ~operator:trent_address d.request_guid d.sender d.recipient d.amount "memo" | "balance" -> address_json_of_yojson =-> fun d -> get_balance_on ~operator:trent_address d.address >>= throw_if_err | "status" -> address_json_of_yojson =-> fun d -> get_status_on_trent_and_main_chain d.address >>= throw_if_err | "recent_transactions" -> if side_chain_client_log then Logging.log "POST /api/recent_transactions"; let maybe_limit_string = Request.param request "limit" in let invalid_limit = Some (Revision.zero) in let maybe_limit = match maybe_limit_string with | Some s -> (try let limit = Revision.of_string s in if Revision.compare limit Revision.zero <= 0 then raise (Failure "bad limit"); Some limit with Failure _ -> limit string not parseable as a number , or nonpositive invalid_limit) | None -> None in if maybe_limit = invalid_limit then bad_request_response id ("Invalid limit value: " ^ (Lib.Option.get maybe_limit_string)) else let maybe_address = address_json_of_yojson json in (match maybe_address with | Ok address_record -> ( get_recent_user_transactions_on_trent address_record.address maybe_limit >>= return_result id) | Error msg -> error_response id msg) | "sleep" -> if side_chain_client_log then Logging.log "POST /api/sleep"; (try Lwt_unix.sleep 1.0 >>= (fun () -> ok_json id (`Int 42)) with | Lib.Internal_error msg -> internal_error_response id msg | exn -> internal_error_response id (Printexc.to_string exn)) | other_call -> invalid_post_api_call id other_call end | methodz -> bad_request_method id methodz in let _ = Server.handler_inet address port handle_request in if side_chain_client_log then Logging.log "side_chain_client, step 3"; Db.run ~db_name:"alacris_client_db" (fun () -> fst (Lwt.wait ()))
fd3eb2cddda89c41450ad0f1a8ad69e3ee25bc0c33e36cb04737b2096957ffa1
emina/rosette
query.rkt
#lang rosette (require "automaton.rkt" "lib.rkt" rosette/lib/synthax) (provide verify-automaton solve-automaton synthesize-automaton matches?) ; Returns a symbolic word of length k, drawn from the given alphabet. (define (word k alphabet) (for/list ([i k]) (define-symbolic* idx integer?) (list-ref alphabet idx))) ; Returns a symbolic word of length up to k, drawn from the given alphabet. (define (word* k alphabet) (define-symbolic* n integer?) (take (word k alphabet) n)) (define (word->string w) (apply string-append (map symbol->string w))) (define (matches? regex w) (regexp-match? regex (word->string w))) (define (correct? m regex w) (eq? (m w) (matches? regex w))) (define (verify-automaton m regex [k 4]) (define w (word* k (alphabet m))) (evaluate w (verify (assert (correct? m regex w))))) (define (solve-automaton m [k 4]) (define w (word* k (alphabet m))) (evaluate w (solve (assert (m w))))) (define (synthesize-automaton m regex [k 4]) (define w (word* k (alphabet m))) (print-forms (synthesize #:forall w #:guarantee (assert (correct? m regex w)))))
null
https://raw.githubusercontent.com/emina/rosette/a64e2bccfe5876c5daaf4a17c5a28a49e2fbd501/sdsl/fsm/query.rkt
racket
Returns a symbolic word of length k, drawn from the given alphabet. Returns a symbolic word of length up to k, drawn from the given alphabet.
#lang rosette (require "automaton.rkt" "lib.rkt" rosette/lib/synthax) (provide verify-automaton solve-automaton synthesize-automaton matches?) (define (word k alphabet) (for/list ([i k]) (define-symbolic* idx integer?) (list-ref alphabet idx))) (define (word* k alphabet) (define-symbolic* n integer?) (take (word k alphabet) n)) (define (word->string w) (apply string-append (map symbol->string w))) (define (matches? regex w) (regexp-match? regex (word->string w))) (define (correct? m regex w) (eq? (m w) (matches? regex w))) (define (verify-automaton m regex [k 4]) (define w (word* k (alphabet m))) (evaluate w (verify (assert (correct? m regex w))))) (define (solve-automaton m [k 4]) (define w (word* k (alphabet m))) (evaluate w (solve (assert (m w))))) (define (synthesize-automaton m regex [k 4]) (define w (word* k (alphabet m))) (print-forms (synthesize #:forall w #:guarantee (assert (correct? m regex w)))))
aa0e92cdd5d819f8346972ebcf55bb64c812a8df25d6610cef4d2fe4727dd4ca
cedlemo/OCaml-GI-ctypes-bindings-generator
Radio_button.mli
open Ctypes type t val t_typ : t typ val create : SList.t structure (* Not implemented : interface *) ptr option -> Widget.t ptr val create_from_widget : t ptr option -> Widget.t ptr val create_with_label : SList.t structure (* Not implemented : interface *) ptr option -> string -> Widget.t ptr val create_with_label_from_widget : t ptr option -> string -> Widget.t ptr val create_with_mnemonic : SList.t structure (* Not implemented : interface *) ptr option -> string -> Widget.t ptr val create_with_mnemonic_from_widget : t ptr option -> string -> Widget.t ptr val get_group : t -> SList.t structure (* Not implemented : interface *) ptr val join_group : t -> t ptr option -> unit val set_group : t -> SList.t structure (* Not implemented : interface *) ptr option -> unit
null
https://raw.githubusercontent.com/cedlemo/OCaml-GI-ctypes-bindings-generator/21a4d449f9dbd6785131979b91aa76877bad2615/tools/Gtk3/Radio_button.mli
ocaml
Not implemented : interface Not implemented : interface Not implemented : interface Not implemented : interface Not implemented : interface
open Ctypes type t val t_typ : t typ val create : val create_from_widget : t ptr option -> Widget.t ptr val create_with_label : val create_with_label_from_widget : t ptr option -> string -> Widget.t ptr val create_with_mnemonic : val create_with_mnemonic_from_widget : t ptr option -> string -> Widget.t ptr val get_group : val join_group : t -> t ptr option -> unit val set_group :
fbb60ee6b7727bc627f796dd24435be99ce5847384289ea1773ce08ed265a2cb
mpickering/apply-refact
Apply.hs
module Refact.Apply ( applyRefactorings, applyRefactorings', runRefactoring, parseExtensions, ) where import Control.Monad (unless) import Data.List (intercalate) import Refact.Compat (Module) import Refact.Fixity (applyFixities) import Refact.Internal import Refact.Types (Refactoring, SrcSpan) -- | Apply a set of refactorings as supplied by HLint applyRefactorings :: | FilePath to [ GHC 's libdir]( / ghc / latest / docs / users_guide / using.html#ghc - flag --- print - libdir ) . -- It is possible to use @libdir@ from [ ghc - paths package]( / package / ghc - paths ) , but note -- this will make it difficult to provide a binary distribution of your program. FilePath -> -- | Apply hints relevant to a specific position Maybe (Int, Int) -> -- | 'Refactoring's to apply. Each inner list corresponds to an HLint -- <-Haskell-HLint.html#t:Idea Idea>. An @Idea@ may have more than one ' Refactoring ' . -- -- The @Idea@s are sorted in ascending order of starting location, and are applied in that order . If two @Idea@s start at the same location , the one with the larger source span comes first . An @Idea@ is filtered out ( ignored ) if there is an @Idea@ -- prior to it which has an overlapping source span and is not filtered out. [[Refactoring SrcSpan]] -> -- | Target file FilePath -> | GHC extensions , e.g. , @LambdaCase@ , The list is processed from left -- to right. An extension (e.g., @StarIsType@) may be overridden later (e.g., by @NoStarIsType@). -- -- These are in addition to the @LANGUAGE@ pragmas in the target file. When they conflict -- with the @LANGUAGE@ pragmas, pragmas win. [String] -> IO String applyRefactorings libdir optionsPos inp file exts = do let (enabled, disabled, invalid) = parseExtensions exts unless (null invalid) . fail $ "Unsupported extensions: " ++ intercalate ", " invalid m <- either (onError "apply") applyFixities =<< parseModuleWithArgs libdir (enabled, disabled) file apply optionsPos False ((mempty,) <$> inp) (Just file) Silent m -- | Like 'applyRefactorings', but takes a parsed module rather than a file path to parse. applyRefactorings' :: Maybe (Int, Int) -> [[Refactoring SrcSpan]] -> | ghc - exactprint AST annotations . This can be obtained from ' Language . Haskell . GHC.ExactPrint . Parsers.postParseTransform ' . -- Anns -> | module Module -> IO String applyRefactorings' optionsPos inp = apply optionsPos False ((mempty,) <$> inp) Nothing Silent
null
https://raw.githubusercontent.com/mpickering/apply-refact/98e1885d30f085ab010be85509288440537f0be4/src/Refact/Apply.hs
haskell
| Apply a set of refactorings as supplied by HLint - print - libdir ) . this will make it difficult to provide a binary distribution of your program. | Apply hints relevant to a specific position | 'Refactoring's to apply. Each inner list corresponds to an HLint <-Haskell-HLint.html#t:Idea Idea>. The @Idea@s are sorted in ascending order of starting location, and are applied prior to it which has an overlapping source span and is not filtered out. | Target file to right. An extension (e.g., @StarIsType@) may be overridden later (e.g., by @NoStarIsType@). These are in addition to the @LANGUAGE@ pragmas in the target file. When they conflict with the @LANGUAGE@ pragmas, pragmas win. | Like 'applyRefactorings', but takes a parsed module rather than a file path to parse. Anns ->
module Refact.Apply ( applyRefactorings, applyRefactorings', runRefactoring, parseExtensions, ) where import Control.Monad (unless) import Data.List (intercalate) import Refact.Compat (Module) import Refact.Fixity (applyFixities) import Refact.Internal import Refact.Types (Refactoring, SrcSpan) applyRefactorings :: It is possible to use @libdir@ from [ ghc - paths package]( / package / ghc - paths ) , but note FilePath -> Maybe (Int, Int) -> An @Idea@ may have more than one ' Refactoring ' . in that order . If two @Idea@s start at the same location , the one with the larger source span comes first . An @Idea@ is filtered out ( ignored ) if there is an @Idea@ [[Refactoring SrcSpan]] -> FilePath -> | GHC extensions , e.g. , @LambdaCase@ , The list is processed from left [String] -> IO String applyRefactorings libdir optionsPos inp file exts = do let (enabled, disabled, invalid) = parseExtensions exts unless (null invalid) . fail $ "Unsupported extensions: " ++ intercalate ", " invalid m <- either (onError "apply") applyFixities =<< parseModuleWithArgs libdir (enabled, disabled) file apply optionsPos False ((mempty,) <$> inp) (Just file) Silent m applyRefactorings' :: Maybe (Int, Int) -> [[Refactoring SrcSpan]] -> | ghc - exactprint AST annotations . This can be obtained from ' Language . Haskell . GHC.ExactPrint . Parsers.postParseTransform ' . | module Module -> IO String applyRefactorings' optionsPos inp = apply optionsPos False ((mempty,) <$> inp) Nothing Silent
d2a408af8ac11327b0c2cebdc99094f92493424d7a251e9866c3d470ad065e04
bscarlet/llvm-general
Target.hs
{-# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #-} module LLVM.General.Internal.FFI.Target where import LLVM.General.Prelude import Foreign.Ptr import Foreign.C import LLVM.General.Internal.FFI.LLVMCTypes import LLVM.General.Internal.FFI.Module import LLVM.General.Internal.FFI.RawOStream data Target foreign import ccall unsafe "LLVM_General_InitializeNativeTarget" initializeNativeTarget :: IO LLVMBool foreign import ccall unsafe "LLVM_General_LookupTarget" lookupTarget :: CString -> CString -> Ptr (OwnerTransfered CString) -> Ptr (OwnerTransfered CString) -> IO (Ptr Target) data TargetOptions foreign import ccall unsafe "LLVM_General_CreateTargetOptions" createTargetOptions :: IO (Ptr TargetOptions) foreign import ccall unsafe "LLVM_General_SetTargetOptionFlag" setTargetOptionFlag :: Ptr TargetOptions -> TargetOptionFlag -> LLVMBool -> IO () foreign import ccall unsafe "LLVM_General_GetTargetOptionFlag" getTargetOptionsFlag :: Ptr TargetOptions -> TargetOptionFlag -> IO LLVMBool foreign import ccall unsafe "LLVM_General_SetStackAlignmentOverride" setStackAlignmentOverride :: Ptr TargetOptions -> CUInt -> IO () foreign import ccall unsafe "LLVM_General_GetStackAlignmentOverride" getStackAlignmentOverride :: Ptr TargetOptions -> IO CUInt foreign import ccall unsafe "LLVM_General_SetTrapFuncName" setTrapFuncName :: Ptr TargetOptions -> CString -> IO () foreign import ccall unsafe "LLVM_General_GetTrapFuncName" getTrapFuncName :: Ptr TargetOptions -> IO CString foreign import ccall unsafe "LLVM_General_SetFloatABIType" setFloatABIType :: Ptr TargetOptions -> FloatABIType -> IO () foreign import ccall unsafe "LLVM_General_GetFloatABIType" getFloatABIType :: Ptr TargetOptions -> IO FloatABIType foreign import ccall unsafe "LLVM_General_SetAllowFPOpFusion" setAllowFPOpFusion :: Ptr TargetOptions -> FPOpFusionMode -> IO () foreign import ccall unsafe "LLVM_General_GetAllowFPOpFusion" getAllowFPOpFusion :: Ptr TargetOptions -> IO FPOpFusionMode foreign import ccall unsafe "LLVM_General_DisposeTargetOptions" disposeTargetOptions :: Ptr TargetOptions -> IO () data TargetMachine foreign import ccall unsafe "LLVM_General_CreateTargetMachine" createTargetMachine :: Ptr Target -> CString -> CString -> CString -> Ptr TargetOptions -> RelocModel -> CodeModel -> CodeGenOptLevel -> IO (Ptr TargetMachine) foreign import ccall unsafe "LLVMDisposeTargetMachine" disposeTargetMachine :: Ptr TargetMachine -> IO () foreign import ccall unsafe "LLVM_General_TargetMachineEmit" targetMachineEmit :: Ptr TargetMachine -> Ptr Module -> CodeGenFileType -> Ptr (OwnerTransfered CString) -> Ptr RawOStream -> IO LLVMBool data TargetLowering foreign import ccall unsafe "LLVM_General_GetTargetLowering" getTargetLowering :: Ptr TargetMachine -> IO (Ptr TargetLowering) foreign import ccall unsafe "LLVM_General_GetDefaultTargetTriple" getDefaultTargetTriple :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetProcessTargetTriple" getProcessTargetTriple :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetHostCPUName" getHostCPUName :: Ptr CSize -> IO CString foreign import ccall unsafe "LLVM_General_GetHostCPUFeatures" getHostCPUFeatures :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetTargetMachineDataLayout" getTargetMachineDataLayout :: Ptr TargetMachine -> IO (OwnerTransfered CString) data TargetLibraryInfo foreign import ccall unsafe "LLVM_General_CreateTargetLibraryInfo" createTargetLibraryInfo :: CString -> IO (Ptr TargetLibraryInfo) foreign import ccall unsafe "LLVM_General_GetLibFunc" getLibFunc :: Ptr TargetLibraryInfo -> CString -> Ptr LibFunc -> IO LLVMBool foreign import ccall unsafe "LLVM_General_LibFuncGetName" libFuncGetName :: Ptr TargetLibraryInfo -> LibFunc -> Ptr CSize -> IO CString foreign import ccall unsafe "LLVM_General_LibFuncSetAvailableWithName" libFuncSetAvailableWithName :: Ptr TargetLibraryInfo -> LibFunc -> CString -> IO () foreign import ccall unsafe "LLVM_General_DisposeTargetLibraryInfo" disposeTargetLibraryInfo :: Ptr TargetLibraryInfo -> IO () foreign import ccall unsafe "LLVM_General_InitializeAllTargets" initializeAllTargets :: IO ()
null
https://raw.githubusercontent.com/bscarlet/llvm-general/61fd03639063283e7dc617698265cc883baf0eec/llvm-general/src/LLVM/General/Internal/FFI/Target.hs
haskell
# LANGUAGE ForeignFunctionInterface, GeneralizedNewtypeDeriving #
module LLVM.General.Internal.FFI.Target where import LLVM.General.Prelude import Foreign.Ptr import Foreign.C import LLVM.General.Internal.FFI.LLVMCTypes import LLVM.General.Internal.FFI.Module import LLVM.General.Internal.FFI.RawOStream data Target foreign import ccall unsafe "LLVM_General_InitializeNativeTarget" initializeNativeTarget :: IO LLVMBool foreign import ccall unsafe "LLVM_General_LookupTarget" lookupTarget :: CString -> CString -> Ptr (OwnerTransfered CString) -> Ptr (OwnerTransfered CString) -> IO (Ptr Target) data TargetOptions foreign import ccall unsafe "LLVM_General_CreateTargetOptions" createTargetOptions :: IO (Ptr TargetOptions) foreign import ccall unsafe "LLVM_General_SetTargetOptionFlag" setTargetOptionFlag :: Ptr TargetOptions -> TargetOptionFlag -> LLVMBool -> IO () foreign import ccall unsafe "LLVM_General_GetTargetOptionFlag" getTargetOptionsFlag :: Ptr TargetOptions -> TargetOptionFlag -> IO LLVMBool foreign import ccall unsafe "LLVM_General_SetStackAlignmentOverride" setStackAlignmentOverride :: Ptr TargetOptions -> CUInt -> IO () foreign import ccall unsafe "LLVM_General_GetStackAlignmentOverride" getStackAlignmentOverride :: Ptr TargetOptions -> IO CUInt foreign import ccall unsafe "LLVM_General_SetTrapFuncName" setTrapFuncName :: Ptr TargetOptions -> CString -> IO () foreign import ccall unsafe "LLVM_General_GetTrapFuncName" getTrapFuncName :: Ptr TargetOptions -> IO CString foreign import ccall unsafe "LLVM_General_SetFloatABIType" setFloatABIType :: Ptr TargetOptions -> FloatABIType -> IO () foreign import ccall unsafe "LLVM_General_GetFloatABIType" getFloatABIType :: Ptr TargetOptions -> IO FloatABIType foreign import ccall unsafe "LLVM_General_SetAllowFPOpFusion" setAllowFPOpFusion :: Ptr TargetOptions -> FPOpFusionMode -> IO () foreign import ccall unsafe "LLVM_General_GetAllowFPOpFusion" getAllowFPOpFusion :: Ptr TargetOptions -> IO FPOpFusionMode foreign import ccall unsafe "LLVM_General_DisposeTargetOptions" disposeTargetOptions :: Ptr TargetOptions -> IO () data TargetMachine foreign import ccall unsafe "LLVM_General_CreateTargetMachine" createTargetMachine :: Ptr Target -> CString -> CString -> CString -> Ptr TargetOptions -> RelocModel -> CodeModel -> CodeGenOptLevel -> IO (Ptr TargetMachine) foreign import ccall unsafe "LLVMDisposeTargetMachine" disposeTargetMachine :: Ptr TargetMachine -> IO () foreign import ccall unsafe "LLVM_General_TargetMachineEmit" targetMachineEmit :: Ptr TargetMachine -> Ptr Module -> CodeGenFileType -> Ptr (OwnerTransfered CString) -> Ptr RawOStream -> IO LLVMBool data TargetLowering foreign import ccall unsafe "LLVM_General_GetTargetLowering" getTargetLowering :: Ptr TargetMachine -> IO (Ptr TargetLowering) foreign import ccall unsafe "LLVM_General_GetDefaultTargetTriple" getDefaultTargetTriple :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetProcessTargetTriple" getProcessTargetTriple :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetHostCPUName" getHostCPUName :: Ptr CSize -> IO CString foreign import ccall unsafe "LLVM_General_GetHostCPUFeatures" getHostCPUFeatures :: IO (OwnerTransfered CString) foreign import ccall unsafe "LLVM_General_GetTargetMachineDataLayout" getTargetMachineDataLayout :: Ptr TargetMachine -> IO (OwnerTransfered CString) data TargetLibraryInfo foreign import ccall unsafe "LLVM_General_CreateTargetLibraryInfo" createTargetLibraryInfo :: CString -> IO (Ptr TargetLibraryInfo) foreign import ccall unsafe "LLVM_General_GetLibFunc" getLibFunc :: Ptr TargetLibraryInfo -> CString -> Ptr LibFunc -> IO LLVMBool foreign import ccall unsafe "LLVM_General_LibFuncGetName" libFuncGetName :: Ptr TargetLibraryInfo -> LibFunc -> Ptr CSize -> IO CString foreign import ccall unsafe "LLVM_General_LibFuncSetAvailableWithName" libFuncSetAvailableWithName :: Ptr TargetLibraryInfo -> LibFunc -> CString -> IO () foreign import ccall unsafe "LLVM_General_DisposeTargetLibraryInfo" disposeTargetLibraryInfo :: Ptr TargetLibraryInfo -> IO () foreign import ccall unsafe "LLVM_General_InitializeAllTargets" initializeAllTargets :: IO ()
317f73095bb29a1e102701470754319414dc8de9b34757fea22d1c065ec0302c
janestreet/lwt-async
lwt_term.ml
Lightweight thread library for * Module Lwt_term * Copyright ( C ) 2009 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later * version . See COPYING file for details . * * 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 * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA * 02111 - 1307 , USA . * * Module Lwt_term * Copyright (C) 2009 Jérémie Dimino * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, with linking exceptions; * either version 2.1 of the License, or (at your option) any later * version. See COPYING file for details. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. *) #include "src/unix/lwt_config.ml" open Lwt open Lwt_text (* +-----------------------------------------------------------------+ | Terminal mode | +-----------------------------------------------------------------+ *) type state = | Normal | Raw of Unix.terminal_io let state = ref Normal (* Number of function currently using the raw mode: *) let raw_count = ref 0 let get_attr () = try_lwt lwt attr = Lwt_unix.tcgetattr Lwt_unix.stdin in return (Some attr) with _ -> return None let set_attr mode = try_lwt Lwt_unix.tcsetattr Lwt_unix.stdin Unix.TCSAFLUSH mode with _ -> return () let drawing_mode = ref false let enter_drawing_mode () = drawing_mode := true; write stdout "\027[?1049h\027[?1h\027=\r" let leave_drawing_mode () = drawing_mode := false; write stdout "\r\027[K\027[?1l\027>\027[r\027[?1049l" let cursor_visible = ref true let show_cursor _ = cursor_visible := true; write stdout "\x1B[?25h" let hide_cursor _ = cursor_visible := false; write stdout "\x1B[?25l" let clear_screen _ = write stdout "\027[2J\027[H" let clear_line _ = write stdout "\027[2K" Go - up by [ n ] lines then to the beginning of the line . Normally " \027[nF " does exactly this but for some terminal 1 need to be added ... By the way we can on the fact that all terminal react the same way to " \027[F " which is to go to the beginning of the previous line : "\027[nF" does exactly this but for some terminal 1 need to be added... By the way we can relly on the fact that all terminal react the same way to "\027[F" which is to go to the beginning of the previous line: *) let rec goto_beginning_of_line = function | 0 -> write_char stdout "\r" | 1 -> write stdout "\027[F" | n -> lwt () = write stdout "\027[F" in goto_beginning_of_line (n - 1) (* Restore terminal mode on exit: *) let cleanup () = lwt () = if not !cursor_visible then show_cursor () else return () in lwt () = if !drawing_mode then leave_drawing_mode () else return () in match !state with | Normal -> return () | Raw saved_attr -> set_attr saved_attr let () = Lwt_main.at_exit cleanup let raw_mode () = match !state with | Normal -> false | Raw _ -> true let leave_raw_mode () = decr raw_count; if !raw_count = 0 then match !state with | Normal -> assert false | Raw attr -> state := Normal; set_attr attr else return () let with_raw_mode f = match !state with | Raw attr -> incr raw_count; finalize f leave_raw_mode | Normal -> get_attr () >>= function | Some attr -> incr raw_count; state := Raw attr; lwt () = set_attr { attr with (* Inspired from Python-3.0/Lib/tty.py: *) Unix.c_brkint = false; Unix.c_inpck = false; Unix.c_istrip = false; Unix.c_ixon = false; Unix.c_csize = 8; Unix.c_parenb = false; Unix.c_echo = false; Unix.c_icanon = false; Unix.c_isig = false; Unix.c_vmin = 1; Unix.c_vtime = 0 } in try_lwt f () finally leave_raw_mode () | None -> raise_lwt (Failure "Lwt_term.with_raw_mode: input is not a tty") (* +-----------------------------------------------------------------+ | Terminal informations | +-----------------------------------------------------------------+ *) type size = { lines : int; columns : int; } external get_size : Unix.file_descr -> size = "lwt_text_term_size" #if windows let size = React.S.const (try get_size Unix.stdout with Unix.Unix_error _ -> { columns = 80; lines = 25 }) #else external sigwinch : unit -> int = "lwt_text_sigwinch" let sigwinch = sigwinch () let sigwinch_event = if sigwinch = 0 then React.E.never else try let event, push = React.E.create () in let _ = Lwt_unix.on_signal sigwinch push in event with Unix.Unix_error _ | Invalid_argument _ | Sys_error _ -> React.E.never let size = React.S.hold (try get_size Unix.stdin with Unix.Unix_error _ -> { columns = 80; lines = 25 }) (React.E.map (fun _ -> get_size Unix.stdin) sigwinch_event) #endif let columns = React.S.map (fun { columns = c } -> c) size let lines = React.S.map (fun { lines = l } -> l) size (* +-----------------------------------------------------------------+ | Keys input | +-----------------------------------------------------------------+ *) exception Exit_sequence let parse_escape st = let buf = Buffer.create 10 in Buffer.add_char buf '\027'; Read one character and add it to [ buf ] : let get () = match Lwt.state (Lwt_stream.get st) with | Sleep -> (* If the rest is not immediatly available, conclude that this is not an escape sequence but just the escape key: *) raise_lwt Exit_sequence | Fail exn -> raise_lwt exn | Return None -> raise_lwt Exit_sequence | Return(Some ch) -> (* Is it an ascii character ? *) if String.length ch = 1 then begin Buffer.add_string buf ch; return ch.[0] end else (* If it is not, then this is not an escape sequence: *) raise_lwt Exit_sequence in (* Sometimes sequences starts with several escape characters: *) let rec first count = get () >>= function | '\027' when count < 3 -> first (count + 1) | ch -> return ch in first 0 >>= function | '[' | 'O' -> let rec loop () = get () >>= function | '0' .. '9' | ';' -> loop () | ch -> return (Buffer.contents buf) in loop () | ch -> return (Buffer.contents buf) let parse_key_raw st = Lwt_stream.next st >>= function | "\027" -> begin try_lwt Lwt_stream.parse st parse_escape with Exit_sequence -> return "\027" end | ch -> return ch type key = | Key of string | Key_up | Key_down | Key_left | Key_right | Key_f of int | Key_next_page | Key_previous_page | Key_home | Key_end | Key_insert | Key_delete | Key_control of char let key_enter = Key_control 'j' let key_escape = Key_control '[' let key_tab = Key_control 'i' let key_backspace = Key_control '?' let string_of_key = function | Key ch -> Printf.sprintf "Key %S" ch | Key_f n -> Printf.sprintf "Key_f %d" n | Key_control c -> Printf.sprintf "Key_control %C" c | Key_up -> "Key_up" | Key_down -> "Key_down" | Key_left -> "Key_left" | Key_right -> "Key_right" | Key_next_page -> "Key_next_page" | Key_previous_page -> "Key_previous_page" | Key_home -> "Key_home" | Key_end -> "Key_end" | Key_insert -> "Key_insert" | Key_delete -> "Key_delete" let sequence_mapping = [ "\027[A", Key_up; "\027[B", Key_down; "\027[C", Key_right; "\027[D", Key_left; "\027A", Key_up; "\027B", Key_down; "\027C", Key_right; "\027D", Key_left; "\027OA", Key_up; "\027OB", Key_down; "\027OC", Key_right; "\027OD", Key_left; "\027[2~", Key_insert; "\027[3~", Key_delete; "\027[5~", Key_previous_page; "\027[6~", Key_next_page; "\027[7~", Key_home; "\027[8~", Key_end; "\027[11~", Key_f 1; "\027[12~", Key_f 2; "\027[13~", Key_f 3; "\027[14~", Key_f 4; "\027[15~", Key_f 5; "\027[17~", Key_f 6; "\027[18~", Key_f 7; "\027[19~", Key_f 8; "\027[20~", Key_f 9; "\027[21~", Key_f 10; "\027[23~", Key_f 11; "\027[24~", Key_f 12; "\027OP", Key_f 1; "\027OQ", Key_f 2; "\027OR", Key_f 3; "\027OS", Key_f 4; "\027[H", Key_home; "\027[F", Key_end; "\027OH", Key_home; "\027OF", Key_end; "\027H", Key_home; "\027F", Key_end; ] let control_mapping = [ 0x00, '@'; 0x01, 'a'; 0x02, 'b'; 0x03, 'c'; 0x04, 'd'; 0x05, 'e'; 0x06, 'f'; 0x07, 'g'; 0x08, 'h'; 0x09, 'i'; 0x0A, 'j'; 0x0B, 'k'; 0x0C, 'l'; 0x0D, 'm'; 0x0E, 'n'; 0x0F, 'o'; 0x10, 'p'; 0x11, 'q'; 0x12, 'r'; 0x13, 's'; 0x14, 't'; 0x15, 'u'; 0x16, 'v'; 0x17, 'w'; 0x18, 'x'; 0x19, 'y'; 0x1A, 'z'; 0x1B, '['; 0x1C, '\\'; 0x1D, ']'; 0x1E, '^'; 0x1F, '_'; 0x7F, '?'; ] let decode_key ch = if ch = "" then invalid_arg "Lwt_term.decode_key"; match ch with | ch when String.length ch = 1 -> begin try Key_control(List.assoc (Char.code ch.[0]) control_mapping) with Not_found -> Key ch end | ch -> begin try List.assoc ch sequence_mapping with Not_found -> Key ch end let standard_input = Lwt_text.read_chars Lwt_text.stdin let read_key () = with_raw_mode (fun _ -> parse_key_raw standard_input >|= decode_key) (* +-----------------------------------------------------------------+ | Styles | +-----------------------------------------------------------------+ *) type color = int let default = -1 let black = 0 let red = 1 let green = 2 let yellow = 3 let blue = 4 let magenta = 5 let cyan = 6 let white = 7 let lblack = black + 8 let lred = red + 8 let lgreen = green + 8 let lyellow = yellow + 8 let lblue = blue + 8 let lmagenta = magenta + 8 let lcyan = cyan + 8 let lwhite = white + 8 type style = { bold : bool; underlined : bool; blink : bool; inverse : bool; hidden : bool; foreground : color; background : color; } module Codes = struct let reset = 0 let bold = 1 let underlined = 4 let blink = 5 let inverse = 7 let hidden = 8 let foreground col = 30 + col let background col = 40 + col end let set_color num (r, g, b) = write stdout (Printf.sprintf "\027]4;%d;rgb:%02x/%02x/%02x;\027\\" num r g b) (* +-----------------------------------------------------------------+ | Rendering | +-----------------------------------------------------------------+ *) type point = { char : string; style : style; } let blank = { char = " "; style = { bold = false; underlined = false; blink = false; inverse = false; hidden = false; foreground = default; background = default; }; } let rec add_int buf = function | 0 -> () | n -> add_int buf (n / 10); Buffer.add_char buf (Char.unsafe_chr (48 + (n mod 10))) let render_char buf oc pt last_style = lwt () = if pt.style <> last_style then begin Buffer.clear buf; Buffer.add_string buf "\027[0"; let mode n = function | true -> Buffer.add_char buf ';'; add_int buf n | false -> () and color f col = if col = default then () else if col < 8 then begin Buffer.add_char buf ';'; add_int buf (f col) end else begin Buffer.add_char buf ';'; add_int buf (f 8); Buffer.add_string buf ";5;"; add_int buf col; end in mode Codes.bold pt.style.bold; mode Codes.underlined pt.style.underlined; mode Codes.blink pt.style.blink; mode Codes.inverse pt.style.inverse; mode Codes.hidden pt.style.hidden; color Codes.foreground pt.style.foreground; color Codes.background pt.style.background; Buffer.add_char buf 'm'; write oc (Buffer.contents buf) end else return () in write_char oc pt.char let render_update old m = let buf = Buffer.create 16 in Lwt_text.atomic begin fun oc -> let rec loop_y y last_style = if y < Array.length m then let rec loop_x x last_style = if x < Array.length m.(y) then let pt = m.(y).(x) in lwt () = render_char buf oc pt last_style in loop_x (x + 1) pt.style else loop_y (y + 1) last_style in if y < Array.length old && old.(y) = m.(y) then begin if y + 1 < Array.length m then lwt last_style = if Array.length m.(y) > 0 then let pt = m.(y).(0) in lwt () = render_char buf oc pt last_style in return pt.style else return last_style in lwt () = write oc "\r\n" in loop_y (y + 1) last_style else return () end else loop_x 0 last_style else return () in (* Go to the top-left corner and reset attributes: *) lwt () = write oc "\027[H\027[0m" in lwt () = loop_y 0 blank.style in write oc "\027[0m" end stdout let render m = render_update [||] m (* +-----------------------------------------------------------------+ | Styled text | +-----------------------------------------------------------------+ *) open Printf type styled_text_instruction = | Text of Text.t | Reset | Bold | Underlined | Blink | Inverse | Hidden | Foreground of color | Background of color type styled_text = styled_text_instruction list let textf fmt = Printf.ksprintf (fun txt -> Text txt) fmt let text txt = Text txt let reset = Reset let bold = Bold let underlined = Underlined let blink = Blink let inverse = Inverse let hidden = Hidden let fg col = Foreground col let bg col = Background col let strip_styles st = let buf = Buffer.create 42 in List.iter (function | Text t -> Buffer.add_string buf t | _ -> ()) st; Buffer.contents buf let write_styled oc st = let buf = Buffer.create 16 (* Pendings style codes: *) and codes = Queue.create () in Output pending codes using only one escape sequence : let output_pendings () = Buffer.clear buf; Buffer.add_string buf "\027["; add_int buf (Queue.take codes); Queue.iter (fun code -> Buffer.add_char buf ';'; add_int buf code) codes; Queue.clear codes; Buffer.add_char buf 'm'; write oc (Buffer.contents buf) in let rec loop = function | [] -> if not (Queue.is_empty codes) then output_pendings () else return () | instr :: rest -> match instr with | Text t -> if not (Queue.is_empty codes) then lwt () = output_pendings () in lwt () = write oc t in loop rest else lwt () = write oc t in loop rest | Reset -> Queue.add 0 codes; loop rest | Bold -> Queue.add Codes.bold codes; loop rest | Underlined -> Queue.add Codes.underlined codes; loop rest | Blink -> Queue.add Codes.blink codes; loop rest | Inverse -> Queue.add Codes.inverse codes; loop rest | Hidden -> Queue.add Codes.hidden codes; loop rest | Foreground col -> if col = default then Queue.add (Codes.foreground 9) codes else if col < 8 then Queue.add (Codes.foreground col) codes else begin Queue.add (Codes.foreground 8) codes; Queue.add 5 codes; Queue.add col codes end; loop rest | Background col -> if col = default then Queue.add (Codes.background 9) codes else if col < 8 then Queue.add (Codes.background col) codes else begin Queue.add (Codes.background 8) codes; Queue.add 5 codes; Queue.add col codes end; loop rest in loop st let styled_length st = let rec loop len = function | [] -> len | Text t :: l -> loop (len + Text.length t) l | _ :: l -> loop len l in loop 0 st let printc st = Lwt_unix.isatty Lwt_unix.stdout >>= function | true -> atomic (fun oc -> write_styled oc st) stdout | false -> write stdout (strip_styles st) let eprintc st = Lwt_unix.isatty Lwt_unix.stderr >>= function | true -> atomic (fun oc -> write_styled oc st) stderr | false -> write stderr (strip_styles st) let fprintlc oc fd st = Lwt_unix.isatty fd >>= function | true -> atomic (fun oc -> lwt () = write_styled oc st in lwt () = write oc "\027[m" in write_char oc "\n") oc | false -> write_line oc (strip_styles st) let printlc st = fprintlc stdout Lwt_unix.stdout st let eprintlc st = fprintlc stderr Lwt_unix.stderr st (* +-----------------------------------------------------------------+ | Drawing | +-----------------------------------------------------------------+ *) module Zone = struct type t = { points : point array array; x : int; y : int; width : int; height : int; } let points zone = zone.points let x zone = zone.x let y zone = zone.y let width zone = zone.width let height zone = zone.height let make ~width ~height = if width < 0 || height < 0 then invalid_arg "Lwt_term.Zone.make"; { points = Array.make_matrix height width blank; x = 0; y = 0; width = width; height = height; } let sub ~zone ~x ~y ~width ~height = if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > zone.width || y + height > zone.height) then invalid_arg "Lwt_term.Zone.sub"; { points = zone.points; x = zone.x + x; y = zone.y + y; width = width; height = height; } let inner zone = { points = zone.points; x = if zone.width >= 2 then zone.x + 1 else zone.x; y = if zone.height >= 2 then zone.y + 1 else zone.y; width = if zone.width >= 2 then zone.width - 2 else zone.width; height = if zone.height >= 2 then zone.height - 2 else zone.height; } end module Draw = struct open Zone let get ~zone ~x ~y = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then invalid_arg "Lwt_term.Draw.get"; zone.points.(zone.y + y).(zone.x + x) let set ~zone ~x ~y ~point = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then () else zone.points.(zone.y + y).(zone.x + x) <- point let map ~zone ~x ~y f = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then () else let x = zone.x + x and y = zone.y + y in zone.points.(y).(x) <- f zone.points.(y).(x) let text ~zone ~x ~y ~text = let rec loop x ptr = match Text.next ptr with | Some(ch, ptr) -> set zone x y { blank with char = ch }; loop (x + 1) ptr | None -> () in loop x (Text.pointer_l text) let textf zone x y fmt = Printf.ksprintf (fun txt -> text zone x y txt) fmt let textc ~zone ~x ~y ~text = let rec loop style x = function | [] -> () | instr :: rest -> match instr with | Text text -> loop_text style x (Text.pointer_l text) rest | Reset -> loop blank.style x rest | Bold -> loop { style with bold = true } x rest | Underlined -> loop { style with underlined = true } x rest | Blink -> loop { style with blink = true } x rest | Inverse -> loop { style with inverse = true } x rest | Hidden -> loop { style with hidden = true } x rest | Foreground color -> loop { style with foreground = color } x rest | Background color -> loop { style with background = color } x rest and loop_text style x ptr rest = match Text.next ptr with | Some(ch, ptr) -> set zone x y { char = ch; style = style }; loop_text style (x + 1) ptr rest | None -> loop style x rest in loop blank.style x text end
null
https://raw.githubusercontent.com/janestreet/lwt-async/c738e6202c1c7409e079e513c7bdf469f7f9984c/src/text/lwt_term.ml
ocaml
+-----------------------------------------------------------------+ | Terminal mode | +-----------------------------------------------------------------+ Number of function currently using the raw mode: Restore terminal mode on exit: Inspired from Python-3.0/Lib/tty.py: +-----------------------------------------------------------------+ | Terminal informations | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Keys input | +-----------------------------------------------------------------+ If the rest is not immediatly available, conclude that this is not an escape sequence but just the escape key: Is it an ascii character ? If it is not, then this is not an escape sequence: Sometimes sequences starts with several escape characters: +-----------------------------------------------------------------+ | Styles | +-----------------------------------------------------------------+ +-----------------------------------------------------------------+ | Rendering | +-----------------------------------------------------------------+ Go to the top-left corner and reset attributes: +-----------------------------------------------------------------+ | Styled text | +-----------------------------------------------------------------+ Pendings style codes: +-----------------------------------------------------------------+ | Drawing | +-----------------------------------------------------------------+
Lightweight thread library for * Module Lwt_term * Copyright ( C ) 2009 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation , with linking exceptions ; * either version 2.1 of the License , or ( at your option ) any later * version . See COPYING file for details . * * 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 * Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA * 02111 - 1307 , USA . * * Module Lwt_term * Copyright (C) 2009 Jérémie Dimino * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, with linking exceptions; * either version 2.1 of the License, or (at your option) any later * version. See COPYING file for details. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. *) #include "src/unix/lwt_config.ml" open Lwt open Lwt_text type state = | Normal | Raw of Unix.terminal_io let state = ref Normal let raw_count = ref 0 let get_attr () = try_lwt lwt attr = Lwt_unix.tcgetattr Lwt_unix.stdin in return (Some attr) with _ -> return None let set_attr mode = try_lwt Lwt_unix.tcsetattr Lwt_unix.stdin Unix.TCSAFLUSH mode with _ -> return () let drawing_mode = ref false let enter_drawing_mode () = drawing_mode := true; write stdout "\027[?1049h\027[?1h\027=\r" let leave_drawing_mode () = drawing_mode := false; write stdout "\r\027[K\027[?1l\027>\027[r\027[?1049l" let cursor_visible = ref true let show_cursor _ = cursor_visible := true; write stdout "\x1B[?25h" let hide_cursor _ = cursor_visible := false; write stdout "\x1B[?25l" let clear_screen _ = write stdout "\027[2J\027[H" let clear_line _ = write stdout "\027[2K" Go - up by [ n ] lines then to the beginning of the line . Normally " \027[nF " does exactly this but for some terminal 1 need to be added ... By the way we can on the fact that all terminal react the same way to " \027[F " which is to go to the beginning of the previous line : "\027[nF" does exactly this but for some terminal 1 need to be added... By the way we can relly on the fact that all terminal react the same way to "\027[F" which is to go to the beginning of the previous line: *) let rec goto_beginning_of_line = function | 0 -> write_char stdout "\r" | 1 -> write stdout "\027[F" | n -> lwt () = write stdout "\027[F" in goto_beginning_of_line (n - 1) let cleanup () = lwt () = if not !cursor_visible then show_cursor () else return () in lwt () = if !drawing_mode then leave_drawing_mode () else return () in match !state with | Normal -> return () | Raw saved_attr -> set_attr saved_attr let () = Lwt_main.at_exit cleanup let raw_mode () = match !state with | Normal -> false | Raw _ -> true let leave_raw_mode () = decr raw_count; if !raw_count = 0 then match !state with | Normal -> assert false | Raw attr -> state := Normal; set_attr attr else return () let with_raw_mode f = match !state with | Raw attr -> incr raw_count; finalize f leave_raw_mode | Normal -> get_attr () >>= function | Some attr -> incr raw_count; state := Raw attr; lwt () = set_attr { attr with Unix.c_brkint = false; Unix.c_inpck = false; Unix.c_istrip = false; Unix.c_ixon = false; Unix.c_csize = 8; Unix.c_parenb = false; Unix.c_echo = false; Unix.c_icanon = false; Unix.c_isig = false; Unix.c_vmin = 1; Unix.c_vtime = 0 } in try_lwt f () finally leave_raw_mode () | None -> raise_lwt (Failure "Lwt_term.with_raw_mode: input is not a tty") type size = { lines : int; columns : int; } external get_size : Unix.file_descr -> size = "lwt_text_term_size" #if windows let size = React.S.const (try get_size Unix.stdout with Unix.Unix_error _ -> { columns = 80; lines = 25 }) #else external sigwinch : unit -> int = "lwt_text_sigwinch" let sigwinch = sigwinch () let sigwinch_event = if sigwinch = 0 then React.E.never else try let event, push = React.E.create () in let _ = Lwt_unix.on_signal sigwinch push in event with Unix.Unix_error _ | Invalid_argument _ | Sys_error _ -> React.E.never let size = React.S.hold (try get_size Unix.stdin with Unix.Unix_error _ -> { columns = 80; lines = 25 }) (React.E.map (fun _ -> get_size Unix.stdin) sigwinch_event) #endif let columns = React.S.map (fun { columns = c } -> c) size let lines = React.S.map (fun { lines = l } -> l) size exception Exit_sequence let parse_escape st = let buf = Buffer.create 10 in Buffer.add_char buf '\027'; Read one character and add it to [ buf ] : let get () = match Lwt.state (Lwt_stream.get st) with | Sleep -> raise_lwt Exit_sequence | Fail exn -> raise_lwt exn | Return None -> raise_lwt Exit_sequence | Return(Some ch) -> if String.length ch = 1 then begin Buffer.add_string buf ch; return ch.[0] end else raise_lwt Exit_sequence in let rec first count = get () >>= function | '\027' when count < 3 -> first (count + 1) | ch -> return ch in first 0 >>= function | '[' | 'O' -> let rec loop () = get () >>= function | '0' .. '9' | ';' -> loop () | ch -> return (Buffer.contents buf) in loop () | ch -> return (Buffer.contents buf) let parse_key_raw st = Lwt_stream.next st >>= function | "\027" -> begin try_lwt Lwt_stream.parse st parse_escape with Exit_sequence -> return "\027" end | ch -> return ch type key = | Key of string | Key_up | Key_down | Key_left | Key_right | Key_f of int | Key_next_page | Key_previous_page | Key_home | Key_end | Key_insert | Key_delete | Key_control of char let key_enter = Key_control 'j' let key_escape = Key_control '[' let key_tab = Key_control 'i' let key_backspace = Key_control '?' let string_of_key = function | Key ch -> Printf.sprintf "Key %S" ch | Key_f n -> Printf.sprintf "Key_f %d" n | Key_control c -> Printf.sprintf "Key_control %C" c | Key_up -> "Key_up" | Key_down -> "Key_down" | Key_left -> "Key_left" | Key_right -> "Key_right" | Key_next_page -> "Key_next_page" | Key_previous_page -> "Key_previous_page" | Key_home -> "Key_home" | Key_end -> "Key_end" | Key_insert -> "Key_insert" | Key_delete -> "Key_delete" let sequence_mapping = [ "\027[A", Key_up; "\027[B", Key_down; "\027[C", Key_right; "\027[D", Key_left; "\027A", Key_up; "\027B", Key_down; "\027C", Key_right; "\027D", Key_left; "\027OA", Key_up; "\027OB", Key_down; "\027OC", Key_right; "\027OD", Key_left; "\027[2~", Key_insert; "\027[3~", Key_delete; "\027[5~", Key_previous_page; "\027[6~", Key_next_page; "\027[7~", Key_home; "\027[8~", Key_end; "\027[11~", Key_f 1; "\027[12~", Key_f 2; "\027[13~", Key_f 3; "\027[14~", Key_f 4; "\027[15~", Key_f 5; "\027[17~", Key_f 6; "\027[18~", Key_f 7; "\027[19~", Key_f 8; "\027[20~", Key_f 9; "\027[21~", Key_f 10; "\027[23~", Key_f 11; "\027[24~", Key_f 12; "\027OP", Key_f 1; "\027OQ", Key_f 2; "\027OR", Key_f 3; "\027OS", Key_f 4; "\027[H", Key_home; "\027[F", Key_end; "\027OH", Key_home; "\027OF", Key_end; "\027H", Key_home; "\027F", Key_end; ] let control_mapping = [ 0x00, '@'; 0x01, 'a'; 0x02, 'b'; 0x03, 'c'; 0x04, 'd'; 0x05, 'e'; 0x06, 'f'; 0x07, 'g'; 0x08, 'h'; 0x09, 'i'; 0x0A, 'j'; 0x0B, 'k'; 0x0C, 'l'; 0x0D, 'm'; 0x0E, 'n'; 0x0F, 'o'; 0x10, 'p'; 0x11, 'q'; 0x12, 'r'; 0x13, 's'; 0x14, 't'; 0x15, 'u'; 0x16, 'v'; 0x17, 'w'; 0x18, 'x'; 0x19, 'y'; 0x1A, 'z'; 0x1B, '['; 0x1C, '\\'; 0x1D, ']'; 0x1E, '^'; 0x1F, '_'; 0x7F, '?'; ] let decode_key ch = if ch = "" then invalid_arg "Lwt_term.decode_key"; match ch with | ch when String.length ch = 1 -> begin try Key_control(List.assoc (Char.code ch.[0]) control_mapping) with Not_found -> Key ch end | ch -> begin try List.assoc ch sequence_mapping with Not_found -> Key ch end let standard_input = Lwt_text.read_chars Lwt_text.stdin let read_key () = with_raw_mode (fun _ -> parse_key_raw standard_input >|= decode_key) type color = int let default = -1 let black = 0 let red = 1 let green = 2 let yellow = 3 let blue = 4 let magenta = 5 let cyan = 6 let white = 7 let lblack = black + 8 let lred = red + 8 let lgreen = green + 8 let lyellow = yellow + 8 let lblue = blue + 8 let lmagenta = magenta + 8 let lcyan = cyan + 8 let lwhite = white + 8 type style = { bold : bool; underlined : bool; blink : bool; inverse : bool; hidden : bool; foreground : color; background : color; } module Codes = struct let reset = 0 let bold = 1 let underlined = 4 let blink = 5 let inverse = 7 let hidden = 8 let foreground col = 30 + col let background col = 40 + col end let set_color num (r, g, b) = write stdout (Printf.sprintf "\027]4;%d;rgb:%02x/%02x/%02x;\027\\" num r g b) type point = { char : string; style : style; } let blank = { char = " "; style = { bold = false; underlined = false; blink = false; inverse = false; hidden = false; foreground = default; background = default; }; } let rec add_int buf = function | 0 -> () | n -> add_int buf (n / 10); Buffer.add_char buf (Char.unsafe_chr (48 + (n mod 10))) let render_char buf oc pt last_style = lwt () = if pt.style <> last_style then begin Buffer.clear buf; Buffer.add_string buf "\027[0"; let mode n = function | true -> Buffer.add_char buf ';'; add_int buf n | false -> () and color f col = if col = default then () else if col < 8 then begin Buffer.add_char buf ';'; add_int buf (f col) end else begin Buffer.add_char buf ';'; add_int buf (f 8); Buffer.add_string buf ";5;"; add_int buf col; end in mode Codes.bold pt.style.bold; mode Codes.underlined pt.style.underlined; mode Codes.blink pt.style.blink; mode Codes.inverse pt.style.inverse; mode Codes.hidden pt.style.hidden; color Codes.foreground pt.style.foreground; color Codes.background pt.style.background; Buffer.add_char buf 'm'; write oc (Buffer.contents buf) end else return () in write_char oc pt.char let render_update old m = let buf = Buffer.create 16 in Lwt_text.atomic begin fun oc -> let rec loop_y y last_style = if y < Array.length m then let rec loop_x x last_style = if x < Array.length m.(y) then let pt = m.(y).(x) in lwt () = render_char buf oc pt last_style in loop_x (x + 1) pt.style else loop_y (y + 1) last_style in if y < Array.length old && old.(y) = m.(y) then begin if y + 1 < Array.length m then lwt last_style = if Array.length m.(y) > 0 then let pt = m.(y).(0) in lwt () = render_char buf oc pt last_style in return pt.style else return last_style in lwt () = write oc "\r\n" in loop_y (y + 1) last_style else return () end else loop_x 0 last_style else return () in lwt () = write oc "\027[H\027[0m" in lwt () = loop_y 0 blank.style in write oc "\027[0m" end stdout let render m = render_update [||] m open Printf type styled_text_instruction = | Text of Text.t | Reset | Bold | Underlined | Blink | Inverse | Hidden | Foreground of color | Background of color type styled_text = styled_text_instruction list let textf fmt = Printf.ksprintf (fun txt -> Text txt) fmt let text txt = Text txt let reset = Reset let bold = Bold let underlined = Underlined let blink = Blink let inverse = Inverse let hidden = Hidden let fg col = Foreground col let bg col = Background col let strip_styles st = let buf = Buffer.create 42 in List.iter (function | Text t -> Buffer.add_string buf t | _ -> ()) st; Buffer.contents buf let write_styled oc st = let buf = Buffer.create 16 and codes = Queue.create () in Output pending codes using only one escape sequence : let output_pendings () = Buffer.clear buf; Buffer.add_string buf "\027["; add_int buf (Queue.take codes); Queue.iter (fun code -> Buffer.add_char buf ';'; add_int buf code) codes; Queue.clear codes; Buffer.add_char buf 'm'; write oc (Buffer.contents buf) in let rec loop = function | [] -> if not (Queue.is_empty codes) then output_pendings () else return () | instr :: rest -> match instr with | Text t -> if not (Queue.is_empty codes) then lwt () = output_pendings () in lwt () = write oc t in loop rest else lwt () = write oc t in loop rest | Reset -> Queue.add 0 codes; loop rest | Bold -> Queue.add Codes.bold codes; loop rest | Underlined -> Queue.add Codes.underlined codes; loop rest | Blink -> Queue.add Codes.blink codes; loop rest | Inverse -> Queue.add Codes.inverse codes; loop rest | Hidden -> Queue.add Codes.hidden codes; loop rest | Foreground col -> if col = default then Queue.add (Codes.foreground 9) codes else if col < 8 then Queue.add (Codes.foreground col) codes else begin Queue.add (Codes.foreground 8) codes; Queue.add 5 codes; Queue.add col codes end; loop rest | Background col -> if col = default then Queue.add (Codes.background 9) codes else if col < 8 then Queue.add (Codes.background col) codes else begin Queue.add (Codes.background 8) codes; Queue.add 5 codes; Queue.add col codes end; loop rest in loop st let styled_length st = let rec loop len = function | [] -> len | Text t :: l -> loop (len + Text.length t) l | _ :: l -> loop len l in loop 0 st let printc st = Lwt_unix.isatty Lwt_unix.stdout >>= function | true -> atomic (fun oc -> write_styled oc st) stdout | false -> write stdout (strip_styles st) let eprintc st = Lwt_unix.isatty Lwt_unix.stderr >>= function | true -> atomic (fun oc -> write_styled oc st) stderr | false -> write stderr (strip_styles st) let fprintlc oc fd st = Lwt_unix.isatty fd >>= function | true -> atomic (fun oc -> lwt () = write_styled oc st in lwt () = write oc "\027[m" in write_char oc "\n") oc | false -> write_line oc (strip_styles st) let printlc st = fprintlc stdout Lwt_unix.stdout st let eprintlc st = fprintlc stderr Lwt_unix.stderr st module Zone = struct type t = { points : point array array; x : int; y : int; width : int; height : int; } let points zone = zone.points let x zone = zone.x let y zone = zone.y let width zone = zone.width let height zone = zone.height let make ~width ~height = if width < 0 || height < 0 then invalid_arg "Lwt_term.Zone.make"; { points = Array.make_matrix height width blank; x = 0; y = 0; width = width; height = height; } let sub ~zone ~x ~y ~width ~height = if (x < 0 || y < 0 || width < 0 || height < 0 || x + width > zone.width || y + height > zone.height) then invalid_arg "Lwt_term.Zone.sub"; { points = zone.points; x = zone.x + x; y = zone.y + y; width = width; height = height; } let inner zone = { points = zone.points; x = if zone.width >= 2 then zone.x + 1 else zone.x; y = if zone.height >= 2 then zone.y + 1 else zone.y; width = if zone.width >= 2 then zone.width - 2 else zone.width; height = if zone.height >= 2 then zone.height - 2 else zone.height; } end module Draw = struct open Zone let get ~zone ~x ~y = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then invalid_arg "Lwt_term.Draw.get"; zone.points.(zone.y + y).(zone.x + x) let set ~zone ~x ~y ~point = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then () else zone.points.(zone.y + y).(zone.x + x) <- point let map ~zone ~x ~y f = if x < 0 || y < 0 || x >= zone.width || y >= zone.height then () else let x = zone.x + x and y = zone.y + y in zone.points.(y).(x) <- f zone.points.(y).(x) let text ~zone ~x ~y ~text = let rec loop x ptr = match Text.next ptr with | Some(ch, ptr) -> set zone x y { blank with char = ch }; loop (x + 1) ptr | None -> () in loop x (Text.pointer_l text) let textf zone x y fmt = Printf.ksprintf (fun txt -> text zone x y txt) fmt let textc ~zone ~x ~y ~text = let rec loop style x = function | [] -> () | instr :: rest -> match instr with | Text text -> loop_text style x (Text.pointer_l text) rest | Reset -> loop blank.style x rest | Bold -> loop { style with bold = true } x rest | Underlined -> loop { style with underlined = true } x rest | Blink -> loop { style with blink = true } x rest | Inverse -> loop { style with inverse = true } x rest | Hidden -> loop { style with hidden = true } x rest | Foreground color -> loop { style with foreground = color } x rest | Background color -> loop { style with background = color } x rest and loop_text style x ptr rest = match Text.next ptr with | Some(ch, ptr) -> set zone x y { char = ch; style = style }; loop_text style (x + 1) ptr rest | None -> loop style x rest in loop blank.style x text end
721c6ab5e861653b1ae905a173f6666077bd7db676d958b68af7ecda558fde21
MyDataFlow/ttalk-server
mam_message_xml.erl
%%% @doc Encoding and decoding messages using exml library -module(mam_message_xml). -export([encode/1, decode/1]). -behaviour(mam_message). encode(Packet) -> exml:to_binary(Packet). decode(Bin) -> {ok, Packet} = exml:parse(Bin), Packet.
null
https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/apps/ejabberd/src/mam_message_xml.erl
erlang
@doc Encoding and decoding messages using exml library
-module(mam_message_xml). -export([encode/1, decode/1]). -behaviour(mam_message). encode(Packet) -> exml:to_binary(Packet). decode(Bin) -> {ok, Packet} = exml:parse(Bin), Packet.
489fb659d917dfa1fd5f5b88eeb8b27d2f07bda1660a3c04f26647ec3c7f3da5
asr/apia
Terms.hs
| Translation from Agda internal terms to the target logic . {-# LANGUAGE CPP #-} # LANGUAGE UnicodeSyntax # module Apia.Translation.Terms ( agdaTermToFormula , agdaTermToTerm ) where ------------------------------------------------------------------------------ import Apia.Prelude import Agda.Syntax.Abstract.Name ( Name(nameConcrete) , QName(QName) ) import Agda.Syntax.Common ( Arg(Arg, argInfo, unArg) , ArgInfo(ArgInfo, argInfoHiding) , Dom(Dom, unDom) , Hiding(Hidden, NotHidden) , Nat ) import qualified Agda.Syntax.Concrete.Name as C ( Name(Name, NoName) , NamePart(Id, Hole) ) import Agda.Syntax.Internal as I ( Abs(Abs, NoAbs) , allApplyElims , Args , ConHead(ConHead) , Elim , Elim'(Apply, IApply, Proj) , Elims , Level(Max) , PlusLevel(ClosedLevel) , Sort(Type) , Term(Con, Def, Lam, Pi, Sort, Var) , Type'(El) ) import Agda.Syntax.Position ( noRange ) import Agda.Utils.Impossible ( Impossible(Impossible), throwImpossible ) import Agda.Utils.Monad ( ifM ) import Apia.FOL.Constants ( lTrue , lFalse , lNot , lAnd , lOr , lCond , lBicond1 , lBicond2 , lExists , lForAll , lEquals ) import Apia.FOL.Primitives ( appF, appP ) import Apia.FOL.Types as L ( LFormula( And , Bicond , Cond , Eq , Exists , FALSE , ForAll , Not , Or , Predicate , TRUE ) , LTerm(Fun, Var) ) import Apia.Monad.Base ( askTOpt , getTVars , newTVar , popTVar , pushTNewVar , T , tErr , TErr ( IncompatibleCLOptions , NoImplementedOption , UniversalQuantificationError ) ) import Apia.Monad.Reports ( reportDLn, reportSLn ) import Apia.Options ( Options ( optFnConstant , optNoInternalEquality , optNoPredicateConstants , optSchematicFunctions , optSchematicPropositionalFunctions , optSchematicPropositionalSymbols ) ) import {-# source #-} Apia.Translation.Types ( agdaDomTypeToFormula , agdaTypeToFormula ) import Apia . Utils . AgdaAPI.IgnoreSharing ( IgnoreSharing(ignoreSharing ) ) import Apia.Utils.AgdaAPI.Interface ( qNameToUniqueString ) import Apia.Utils.PrettyPrint ( (<>), Pretty(pretty) ) #include "undefined.h" ------------------------------------------------------------------------------ agdaArgTermToFormula ∷ Arg Term → T LFormula agdaArgTermToFormula Arg {argInfo = info, unArg = t} = case info of ArgInfo { argInfoHiding = NotHidden } → agdaTermToFormula t _ → __IMPOSSIBLE__ agdaArgTermToTerm ∷ Arg Term → T LTerm agdaArgTermToTerm Arg {argInfo = info, unArg = t} = case info of ArgInfo { argInfoHiding = Hidden } → agdaTermToTerm t ArgInfo { argInfoHiding = NotHidden } → agdaTermToTerm t _ → __IMPOSSIBLE__ binConst ∷ (LFormula → LFormula → LFormula) → Arg Term → Arg Term → T LFormula binConst op arg1 arg2 = liftM2 op (agdaArgTermToFormula arg1) (agdaArgTermToFormula arg2) elimToTerm ∷ Elim → T LTerm elimToTerm (Apply arg) = agdaArgTermToTerm arg elimToTerm (Proj _ _) = __IMPOSSIBLE__ elimToTerm IApply{} = __IMPOSSIBLE__ -- Translation of predicates. predicate ∷ QName → Elims → T LFormula predicate qName elims = do pName ← qNameToUniqueString qName lTerms ← mapM elimToTerm elims case length elims of 0 → __IMPOSSIBLE__ _ → ifM (askTOpt optNoPredicateConstants) -- Direct translation. (return $ Predicate pName lTerms) Translation using Koen 's suggestion . (return $ appP (Fun pName []) lTerms) propositionalFunctionScheme ∷ [String] → Nat → Elims → T LFormula propositionalFunctionScheme vars n elims = do let var ∷ String var = vars !! n case length elims of 0 → __IMPOSSIBLE__ _ → fmap (appP (L.Var var)) (mapM elimToTerm elims) | Translate an Agda internal ' Term ' to a target logic formula . agdaTermToFormula ∷ Term → T LFormula agdaTermToFormula term'@(Def qName@(QName _ name) elims) = do reportSLn "t2f" 10 $ "agdaTermToFormula Def:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ C.Name{} → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] | isCNameLogicConst lTrue → return TRUE | isCNameLogicConst lFalse → return FALSE | otherwise → -- In this guard we translate 0-ary predicates, i.e. -- propositional functions, for example, A : Set. flip Predicate [] <$> qNameToUniqueString qName Just [a] | isCNameHoleRight lNot → fmap Not (agdaArgTermToFormula a) | isCNameLogicConst lExists || isCNameLogicConst lForAll → do fm ← agdaArgTermToFormula a freshVar ← newTVar return $ if isCNameLogicConst lExists then Exists freshVar $ const fm else ForAll freshVar $ const fm | otherwise → predicate qName elims Just [a1, a2] | isCNameTwoHoles lAnd → binConst And a1 a2 | isCNameTwoHoles lOr → binConst Or a1 a2 | isCNameTwoHoles lCond → binConst Cond a1 a2 | isCNameTwoHoles lBicond1 || isCNameTwoHoles lBicond2 → binConst Bicond a1 a2 | isCNameTwoHoles lEquals → do reportSLn "t2f" 20 "Processing equals" ifM (askTOpt optNoInternalEquality) Not using the internal equality . (predicate qName elims) Using the internal equality . (liftM2 Eq (agdaArgTermToTerm a1) (agdaArgTermToTerm a2)) | otherwise → predicate qName elims _ → predicate qName elims where isCNameLogicConst ∷ String → Bool isCNameLogicConst lConst = -- The equality on the data type @C.Name@ is defined to -- ignore ranges, so we use @noRange@. cName == C.Name noRange [C.Id lConst] isCNameHoleRight ∷ String → Bool isCNameHoleRight lConst = The operators are represented by a list with @Hole@ 's . -- See the documentation for @C.Name@. cName == C.Name noRange [C.Id lConst, C.Hole] isCNameTwoHoles ∷ String → Bool isCNameTwoHoles lConst = The operators are represented by a list with @Hole@ 's . See -- the documentation for @C.Name@. cName == C.Name noRange [C.Hole, C.Id lConst, C.Hole] agdaTermToFormula term'@(Lam _ (Abs _ termLam)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Lam:\n" ++ show term' _ ← pushTNewVar f ← agdaTermToFormula termLam popTVar return f agdaTermToFormula (Pi domTy (Abs x absTy)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Pi _ (Abs _ _):\n" ++ "domTy: " ++ show domTy ++ "\n" ++ "absTy: " ++ show (Abs x absTy) freshVar ← pushTNewVar reportSLn "t2f" 20 $ "Starting processing in local environment with fresh variable " ++ show freshVar ++ " and type:\n" ++ show absTy f ← agdaTypeToFormula absTy popTVar reportSLn "t2f" 20 $ "Finalized processing in local environment with fresh variable " ++ show freshVar ++ " and type:\n" ++ show absTy reportDLn "t2f" 20 $ pretty "The formula f is: " <> pretty f case unDom domTy of -- The bounded variable is quantified on a @Set@, -- e.g. the bounded variable is @d : where : Set@ , -- -- so we can create a fresh variable and quantify on it without -- any problem. -- -- N.B. the pattern matching on @(Def _ [])@. El (Type (Max [])) (Def _ []) → do reportSLn "t2f" 20 $ "Adding universal quantification on variable " ++ show freshVar return $ ForAll freshVar $ const f -- The bounded variable is quantified on a proof. Due to we have -- drop the quantification on proofs terms, this case is -- impossible. El (Type (Max [])) (Def _ _) → __IMPOSSIBLE__ Non - FOL translation : First - order logic universal quantified -- functions term. -- -- The bounded variable is quantified on a function of a @Set@ -- to a @Set@, -- e.g. the bounded variable is @f : D → , where : Set@. -- In this case we handle the bounded variable / function as a FOL variable in @agdaTermToTerm ( Var n args)@ , which is processed -- first due to lazyness. We quantified on this variable. El (Type (Max [])) (Pi (Dom _ _ (El (Type (Max [])) (Def _ []))) (NoAbs _ (El (Type (Max [])) (Def _ [])))) → do reportSLn "t2f" 20 "Removing a quantification on a function of a Set to a Set" return $ ForAll freshVar $ const f -- N.B. The next case is just a generalization to various -- arguments of the previous case. Non - FOL translation : First - order logic universal quantified -- functions term. -- -- The bounded variable is quantified on a function of a @Set@ -- to a @Set@, -- e.g. the bounded variable is @f : D → D → , where @D   :   Set@. -- In this case we handle the bounded variable / function as a FOL variable in @agdaTermToTerm ( Var n args)@ , which is processed -- first due to lazyness. We quantified on this variable. El (Type (Max [])) (Pi (Dom _ _ (El (Type (Max [])) (Def _ []))) (NoAbs _ (El (Type (Max [])) (Pi _ (NoAbs _ _))))) → do reportSLn "t2f" 20 "Removing a quantification on a function of a Set to a Set" 31 May 2012 . We do n't have an example of this case . -- -- return $ ForAll freshVar (\_ → f) __IMPOSSIBLE__ El (Type (Max [])) someTerm → do reportSLn "t2f" 20 $ "The term someterm is: " ++ show someTerm __IMPOSSIBLE__ Non - FOL translation : First - order logic universal quantified -- propositional functions. -- The bounded variable is quantified on a , -- e.g. the bounded variable is @A : D → D → Set@. -- -- In this case we return a forall bind on the fresh variable. We -- use this case for translate logic schemata such as -- -- ∨-comm₂ : {A₂ B₂ : D → D → Set}{x y : D} → A₂ x y ∨ B₂ x y → A₂ x y ∨ B₂ x y. El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy return $ ForAll freshVar $ const f Non - FOL translation : First - order logic universal quantified -- propositional symbols. -- The bounded variable is quantified on a , -- e.g. the bounded variable is @A : Set@ , -- -- so we just return the consequent. We use this case for -- translating logical schemata such -- -- @∨-comm : {A B : Set} → A ∨ B → B ∨ A@. -- -- In this case we handle the bounded variable/function in @agdaTermToFormula ( Var n args)@ , which is processed first due to -- lazyness. El (Type (Max [ClosedLevel 1])) (Sort _) → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy let p ∷ String p = "--schematic-propositional-symbols" ifM (askTOpt optSchematicPropositionalSymbols) (return f) (tErr $ UniversalQuantificationError p) someType → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType __IMPOSSIBLE__ agdaTermToFormula (Pi domTy (NoAbs x absTy)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Pi _ (NoAbs _ _):\n" ++ "domTy: " ++ show domTy ++ "\n" ++ "absTy: " ++ show (NoAbs x absTy) f2 ← agdaTypeToFormula absTy if x /= "_" then case unDom domTy of -- The variable @x@ is an universal quantified variable not used , thefefore we generate a quantified first - order -- logic formula. El (Type (Max [])) (Def _ []) → do freshVar ← newTVar return $ ForAll freshVar $ const f2 -- The variable @x@ is a proof term, therefore we erase the -- quantification on it. El (Type (Max [])) (Def _ _) → do f1 ← agdaDomTypeToFormula domTy return $ Cond f1 f2 The variable in @domTy@ has type -- (e.g. A : D → Set) and it isn't used, so we omit it. El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) → return f2 someType → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType __IMPOSSIBLE__ else do f1 ← agdaDomTypeToFormula domTy return $ Cond f1 f2 agdaTermToFormula term'@(I.Var n elims) = do reportSLn "t2f" 10 $ "agdaTermToFormula Var: " ++ show term' when (n < 0) (__IMPOSSIBLE__) vars ← getTVars We also test for equality because the first argument of @I.Var@ does n't start in one but in zero . when (length vars == n) (__IMPOSSIBLE__) when (length vars < n) (__IMPOSSIBLE__) case elims of N.B. In this case we * do n't * use 's approach . [] → return $ Predicate (vars !! n) [] Non - FOL translation : First - order logic universal quantified -- propositional functions. -- If we have a bounded variable quantified on a function of a @Set@ to a , for example , the variable / function @A@ in -- @(A : D → Set ) → ( x : D ) → A x → A -- -- we are quantifying on this variable/function -- -- (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@), -- -- therefore we need to apply this variable/function to the -- others variables. _ → do let p ∷ String p = "--schematic-propositional-functions" ifM (askTOpt optSchematicPropositionalFunctions) (ifM (askTOpt optNoPredicateConstants) (tErr $ IncompatibleCLOptions "--schematic-propositional-functions" "--no-predicate-constants" ) (propositionalFunctionScheme vars n elims) ) (tErr $ UniversalQuantificationError p) agdaTermToFormula term' = do reportSLn "t2f" 20 $ "term: " ++ show term' __IMPOSSIBLE__ Translate the function @foo x1 ... xn@. appArgsF ∷ String → Args → T LTerm appArgsF fn args = do lTerms ← mapM agdaArgTermToTerm args ifM (askTOpt optFnConstant) -- Translation using a hard-coded binary function symbol. (return $ foldl' appF (Fun fn []) lTerms) -- Direct translation. (return $ Fun fn lTerms) | Translate an Agda internal ' Term ' to a target logic term . agdaTermToTerm ∷ Term → T LTerm agdaTermToTerm term'@(Con (ConHead (QName _ name) _ _) _ elims) = do reportSLn "t2t" 10 $ "agdaTermToTerm Con:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ -- The term @Con@ doesn't have holes. It should be translated as a first - order logic function . C.Name _ [C.Id str] → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → return $ Fun str [] Just args → appArgsF str args The term @Con@ has holes . It is translated as a first - order -- logic function. C.Name _ _ → __IMPOSSIBLE__ 2012 - 04 - 22 : We do not have an example of it . -- C.Name _ parts → -- case args of -- [] → __IMPOSSIBLE__ -- _ → appArgsFn (concatName parts) args agdaTermToTerm term'@(Def qName@(QName _ name) elims) = do reportSLn "t2t" 10 $ "agdaTermToTerm Def:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ The term does n't have holes . It is translated as a first - order logic function . C.Name _ [C.Id _] → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → flip Fun [] <$> qNameToUniqueString qName Just args → qNameToUniqueString qName >>= flip appArgsF args The term has holes . It is translated as a first - order -- logic function. C.Name _ _ → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → __IMPOSSIBLE__ Just args → qNameToUniqueString qName >>= flip appArgsF args agdaTermToTerm term'@(Lam ArgInfo{argInfoHiding = NotHidden} (Abs _ termLam)) = do reportSLn "t2f" 10 $ "agdaTermToTerm Lam:\n" ++ show term' _ ← pushTNewVar f ← agdaTermToTerm termLam popTVar return f agdaTermToTerm term'@(I.Var n args) = do reportSLn "t2t" 10 $ "agdaTermToTerm Var:\n" ++ show term' when (n < 0) (__IMPOSSIBLE__) vars ← getTVars We also test for equality because the first argument of @I.Var@ does n't start in one but in zero . when (length vars == n) (__IMPOSSIBLE__) when (length vars < n) (__IMPOSSIBLE__) case args of [] → return $ L.Var (vars !! n) Non - FOL translation : First - order logic universal quantified -- functions term. -- If we have a bounded variable quantified on a function of a Set to a Set , for example , the variable / function @f@ in -- -- @(f : D → D) → (a : D) → (lam f) ∙ a ≡ f a@ -- -- we are quantifying on this variable/function -- -- (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@), -- -- therefore we need to apply this variable/function to the -- others variables. See an example in -- Test.Succeed.AgdaInternalTerms.Var2.agda _varArgs → do let p ∷ String p = "--schematic-functions" ifM (askTOpt optSchematicFunctions) TODO ( 24 March 2013 ) . Implementation . (tErr $ NoImplementedOption "--schematic-functions") ( do lTerms ifM ( askTOpt optAppF ) ( return $ foldl ' app ( Var ( vars ! ! n ) ) lTerms ) -- (return $ Fun (vars !! n) lTerms)) (tErr $ UniversalQuantificationError p) agdaTermToTerm _ = __IMPOSSIBLE__ ------------------------------------------------------------------------------ -- Note [Non-dependent functions] 27 June 2012 . After the patch -- We d Sep 21 04:50:43 COT 2011 -- * got rid of the Fun constructor in internal syntax (using Pi _ (NoAbs _ _) instead) -- Agda is using ( Pi _ ( NoAbs _ _ ) ) for the non - dependent functions . In a later patch , changed somes ( Pi _ ( Abs _ _ ) ) -- to (Pi _ (NoAbs _ _)). The solution below works for *all* our cases.
null
https://raw.githubusercontent.com/asr/apia/a66c5ddca2ab470539fd68c42c4fbd45f720d682/src/Apia/Translation/Terms.hs
haskell
# LANGUAGE CPP # ---------------------------------------------------------------------------- # source # ---------------------------------------------------------------------------- Translation of predicates. Direct translation. In this guard we translate 0-ary predicates, i.e. propositional functions, for example, A : Set. The equality on the data type @C.Name@ is defined to ignore ranges, so we use @noRange@. See the documentation for @C.Name@. the documentation for @C.Name@. The bounded variable is quantified on a @Set@, so we can create a fresh variable and quantify on it without any problem. N.B. the pattern matching on @(Def _ [])@. The bounded variable is quantified on a proof. Due to we have drop the quantification on proofs terms, this case is impossible. functions term. The bounded variable is quantified on a function of a @Set@ to a @Set@, first due to lazyness. We quantified on this variable. N.B. The next case is just a generalization to various arguments of the previous case. functions term. The bounded variable is quantified on a function of a @Set@ to a @Set@, first due to lazyness. We quantified on this variable. return $ ForAll freshVar (\_ → f) propositional functions. In this case we return a forall bind on the fresh variable. We use this case for translate logic schemata such as ∨-comm₂ : {A₂ B₂ : D → D → Set}{x y : D} → propositional symbols. so we just return the consequent. We use this case for translating logical schemata such @∨-comm : {A B : Set} → A ∨ B → B ∨ A@. In this case we handle the bounded variable/function in lazyness. The variable @x@ is an universal quantified variable not logic formula. The variable @x@ is a proof term, therefore we erase the quantification on it. (e.g. A : D → Set) and it isn't used, so we omit it. propositional functions. If we have a bounded variable quantified on a function of a we are quantifying on this variable/function (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@), therefore we need to apply this variable/function to the others variables. Translation using a hard-coded binary function symbol. Direct translation. The term @Con@ doesn't have holes. It should be translated as logic function. C.Name _ parts → case args of [] → __IMPOSSIBLE__ _ → appArgsFn (concatName parts) args logic function. functions term. If we have a bounded variable quantified on a function of a @(f : D → D) → (a : D) → (lam f) ∙ a ≡ f a@ we are quantifying on this variable/function (see @agdaTermToFormula (Pi domTy (Abs _ absTy))@), therefore we need to apply this variable/function to the others variables. See an example in Test.Succeed.AgdaInternalTerms.Var2.agda (return $ Fun (vars !! n) lTerms)) ---------------------------------------------------------------------------- Note [Non-dependent functions] * got rid of the Fun constructor in internal syntax (using Pi _ (NoAbs _ _) instead) to (Pi _ (NoAbs _ _)). The solution below works for *all* our cases.
| Translation from Agda internal terms to the target logic . # LANGUAGE UnicodeSyntax # module Apia.Translation.Terms ( agdaTermToFormula , agdaTermToTerm ) where import Apia.Prelude import Agda.Syntax.Abstract.Name ( Name(nameConcrete) , QName(QName) ) import Agda.Syntax.Common ( Arg(Arg, argInfo, unArg) , ArgInfo(ArgInfo, argInfoHiding) , Dom(Dom, unDom) , Hiding(Hidden, NotHidden) , Nat ) import qualified Agda.Syntax.Concrete.Name as C ( Name(Name, NoName) , NamePart(Id, Hole) ) import Agda.Syntax.Internal as I ( Abs(Abs, NoAbs) , allApplyElims , Args , ConHead(ConHead) , Elim , Elim'(Apply, IApply, Proj) , Elims , Level(Max) , PlusLevel(ClosedLevel) , Sort(Type) , Term(Con, Def, Lam, Pi, Sort, Var) , Type'(El) ) import Agda.Syntax.Position ( noRange ) import Agda.Utils.Impossible ( Impossible(Impossible), throwImpossible ) import Agda.Utils.Monad ( ifM ) import Apia.FOL.Constants ( lTrue , lFalse , lNot , lAnd , lOr , lCond , lBicond1 , lBicond2 , lExists , lForAll , lEquals ) import Apia.FOL.Primitives ( appF, appP ) import Apia.FOL.Types as L ( LFormula( And , Bicond , Cond , Eq , Exists , FALSE , ForAll , Not , Or , Predicate , TRUE ) , LTerm(Fun, Var) ) import Apia.Monad.Base ( askTOpt , getTVars , newTVar , popTVar , pushTNewVar , T , tErr , TErr ( IncompatibleCLOptions , NoImplementedOption , UniversalQuantificationError ) ) import Apia.Monad.Reports ( reportDLn, reportSLn ) import Apia.Options ( Options ( optFnConstant , optNoInternalEquality , optNoPredicateConstants , optSchematicFunctions , optSchematicPropositionalFunctions , optSchematicPropositionalSymbols ) ) ( agdaDomTypeToFormula , agdaTypeToFormula ) import Apia . Utils . AgdaAPI.IgnoreSharing ( IgnoreSharing(ignoreSharing ) ) import Apia.Utils.AgdaAPI.Interface ( qNameToUniqueString ) import Apia.Utils.PrettyPrint ( (<>), Pretty(pretty) ) #include "undefined.h" agdaArgTermToFormula ∷ Arg Term → T LFormula agdaArgTermToFormula Arg {argInfo = info, unArg = t} = case info of ArgInfo { argInfoHiding = NotHidden } → agdaTermToFormula t _ → __IMPOSSIBLE__ agdaArgTermToTerm ∷ Arg Term → T LTerm agdaArgTermToTerm Arg {argInfo = info, unArg = t} = case info of ArgInfo { argInfoHiding = Hidden } → agdaTermToTerm t ArgInfo { argInfoHiding = NotHidden } → agdaTermToTerm t _ → __IMPOSSIBLE__ binConst ∷ (LFormula → LFormula → LFormula) → Arg Term → Arg Term → T LFormula binConst op arg1 arg2 = liftM2 op (agdaArgTermToFormula arg1) (agdaArgTermToFormula arg2) elimToTerm ∷ Elim → T LTerm elimToTerm (Apply arg) = agdaArgTermToTerm arg elimToTerm (Proj _ _) = __IMPOSSIBLE__ elimToTerm IApply{} = __IMPOSSIBLE__ predicate ∷ QName → Elims → T LFormula predicate qName elims = do pName ← qNameToUniqueString qName lTerms ← mapM elimToTerm elims case length elims of 0 → __IMPOSSIBLE__ _ → ifM (askTOpt optNoPredicateConstants) (return $ Predicate pName lTerms) Translation using Koen 's suggestion . (return $ appP (Fun pName []) lTerms) propositionalFunctionScheme ∷ [String] → Nat → Elims → T LFormula propositionalFunctionScheme vars n elims = do let var ∷ String var = vars !! n case length elims of 0 → __IMPOSSIBLE__ _ → fmap (appP (L.Var var)) (mapM elimToTerm elims) | Translate an Agda internal ' Term ' to a target logic formula . agdaTermToFormula ∷ Term → T LFormula agdaTermToFormula term'@(Def qName@(QName _ name) elims) = do reportSLn "t2f" 10 $ "agdaTermToFormula Def:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ C.Name{} → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] | isCNameLogicConst lTrue → return TRUE | isCNameLogicConst lFalse → return FALSE | otherwise → flip Predicate [] <$> qNameToUniqueString qName Just [a] | isCNameHoleRight lNot → fmap Not (agdaArgTermToFormula a) | isCNameLogicConst lExists || isCNameLogicConst lForAll → do fm ← agdaArgTermToFormula a freshVar ← newTVar return $ if isCNameLogicConst lExists then Exists freshVar $ const fm else ForAll freshVar $ const fm | otherwise → predicate qName elims Just [a1, a2] | isCNameTwoHoles lAnd → binConst And a1 a2 | isCNameTwoHoles lOr → binConst Or a1 a2 | isCNameTwoHoles lCond → binConst Cond a1 a2 | isCNameTwoHoles lBicond1 || isCNameTwoHoles lBicond2 → binConst Bicond a1 a2 | isCNameTwoHoles lEquals → do reportSLn "t2f" 20 "Processing equals" ifM (askTOpt optNoInternalEquality) Not using the internal equality . (predicate qName elims) Using the internal equality . (liftM2 Eq (agdaArgTermToTerm a1) (agdaArgTermToTerm a2)) | otherwise → predicate qName elims _ → predicate qName elims where isCNameLogicConst ∷ String → Bool isCNameLogicConst lConst = cName == C.Name noRange [C.Id lConst] isCNameHoleRight ∷ String → Bool isCNameHoleRight lConst = The operators are represented by a list with @Hole@ 's . cName == C.Name noRange [C.Id lConst, C.Hole] isCNameTwoHoles ∷ String → Bool isCNameTwoHoles lConst = The operators are represented by a list with @Hole@ 's . See cName == C.Name noRange [C.Hole, C.Id lConst, C.Hole] agdaTermToFormula term'@(Lam _ (Abs _ termLam)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Lam:\n" ++ show term' _ ← pushTNewVar f ← agdaTermToFormula termLam popTVar return f agdaTermToFormula (Pi domTy (Abs x absTy)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Pi _ (Abs _ _):\n" ++ "domTy: " ++ show domTy ++ "\n" ++ "absTy: " ++ show (Abs x absTy) freshVar ← pushTNewVar reportSLn "t2f" 20 $ "Starting processing in local environment with fresh variable " ++ show freshVar ++ " and type:\n" ++ show absTy f ← agdaTypeToFormula absTy popTVar reportSLn "t2f" 20 $ "Finalized processing in local environment with fresh variable " ++ show freshVar ++ " and type:\n" ++ show absTy reportDLn "t2f" 20 $ pretty "The formula f is: " <> pretty f case unDom domTy of e.g. the bounded variable is @d : where : Set@ , El (Type (Max [])) (Def _ []) → do reportSLn "t2f" 20 $ "Adding universal quantification on variable " ++ show freshVar return $ ForAll freshVar $ const f El (Type (Max [])) (Def _ _) → __IMPOSSIBLE__ Non - FOL translation : First - order logic universal quantified e.g. the bounded variable is @f : D → , where : Set@. In this case we handle the bounded variable / function as a FOL variable in @agdaTermToTerm ( Var n args)@ , which is processed El (Type (Max [])) (Pi (Dom _ _ (El (Type (Max [])) (Def _ []))) (NoAbs _ (El (Type (Max [])) (Def _ [])))) → do reportSLn "t2f" 20 "Removing a quantification on a function of a Set to a Set" return $ ForAll freshVar $ const f Non - FOL translation : First - order logic universal quantified e.g. the bounded variable is @f : D → D → , where @D   :   Set@. In this case we handle the bounded variable / function as a FOL variable in @agdaTermToTerm ( Var n args)@ , which is processed El (Type (Max [])) (Pi (Dom _ _ (El (Type (Max [])) (Def _ []))) (NoAbs _ (El (Type (Max [])) (Pi _ (NoAbs _ _))))) → do reportSLn "t2f" 20 "Removing a quantification on a function of a Set to a Set" 31 May 2012 . We do n't have an example of this case . __IMPOSSIBLE__ El (Type (Max [])) someTerm → do reportSLn "t2f" 20 $ "The term someterm is: " ++ show someTerm __IMPOSSIBLE__ Non - FOL translation : First - order logic universal quantified The bounded variable is quantified on a , e.g. the bounded variable is @A : D → D → Set@. A₂ x y ∨ B₂ x y → A₂ x y ∨ B₂ x y. El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy return $ ForAll freshVar $ const f Non - FOL translation : First - order logic universal quantified The bounded variable is quantified on a , e.g. the bounded variable is @A : Set@ , @agdaTermToFormula ( Var n args)@ , which is processed first due to El (Type (Max [ClosedLevel 1])) (Sort _) → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show domTy let p ∷ String p = "--schematic-propositional-symbols" ifM (askTOpt optSchematicPropositionalSymbols) (return f) (tErr $ UniversalQuantificationError p) someType → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType __IMPOSSIBLE__ agdaTermToFormula (Pi domTy (NoAbs x absTy)) = do reportSLn "t2f" 10 $ "agdaTermToFormula Pi _ (NoAbs _ _):\n" ++ "domTy: " ++ show domTy ++ "\n" ++ "absTy: " ++ show (NoAbs x absTy) f2 ← agdaTypeToFormula absTy if x /= "_" then case unDom domTy of used , thefefore we generate a quantified first - order El (Type (Max [])) (Def _ []) → do freshVar ← newTVar return $ ForAll freshVar $ const f2 El (Type (Max [])) (Def _ _) → do f1 ← agdaDomTypeToFormula domTy return $ Cond f1 f2 The variable in @domTy@ has type El (Type (Max [ClosedLevel 1])) (Pi _ (NoAbs _ _)) → return f2 someType → do reportSLn "t2f" 20 $ "The type domTy is: " ++ show someType __IMPOSSIBLE__ else do f1 ← agdaDomTypeToFormula domTy return $ Cond f1 f2 agdaTermToFormula term'@(I.Var n elims) = do reportSLn "t2f" 10 $ "agdaTermToFormula Var: " ++ show term' when (n < 0) (__IMPOSSIBLE__) vars ← getTVars We also test for equality because the first argument of @I.Var@ does n't start in one but in zero . when (length vars == n) (__IMPOSSIBLE__) when (length vars < n) (__IMPOSSIBLE__) case elims of N.B. In this case we * do n't * use 's approach . [] → return $ Predicate (vars !! n) [] Non - FOL translation : First - order logic universal quantified @Set@ to a , for example , the variable / function @A@ in @(A : D → Set ) → ( x : D ) → A x → A _ → do let p ∷ String p = "--schematic-propositional-functions" ifM (askTOpt optSchematicPropositionalFunctions) (ifM (askTOpt optNoPredicateConstants) (tErr $ IncompatibleCLOptions "--schematic-propositional-functions" "--no-predicate-constants" ) (propositionalFunctionScheme vars n elims) ) (tErr $ UniversalQuantificationError p) agdaTermToFormula term' = do reportSLn "t2f" 20 $ "term: " ++ show term' __IMPOSSIBLE__ Translate the function @foo x1 ... xn@. appArgsF ∷ String → Args → T LTerm appArgsF fn args = do lTerms ← mapM agdaArgTermToTerm args ifM (askTOpt optFnConstant) (return $ foldl' appF (Fun fn []) lTerms) (return $ Fun fn lTerms) | Translate an Agda internal ' Term ' to a target logic term . agdaTermToTerm ∷ Term → T LTerm agdaTermToTerm term'@(Con (ConHead (QName _ name) _ _) _ elims) = do reportSLn "t2t" 10 $ "agdaTermToTerm Con:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ a first - order logic function . C.Name _ [C.Id str] → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → return $ Fun str [] Just args → appArgsF str args The term @Con@ has holes . It is translated as a first - order C.Name _ _ → __IMPOSSIBLE__ 2012 - 04 - 22 : We do not have an example of it . agdaTermToTerm term'@(Def qName@(QName _ name) elims) = do reportSLn "t2t" 10 $ "agdaTermToTerm Def:\n" ++ show term' let cName ∷ C.Name cName = nameConcrete name case cName of C.NoName{} → __IMPOSSIBLE__ C.Name _ [] → __IMPOSSIBLE__ The term does n't have holes . It is translated as a first - order logic function . C.Name _ [C.Id _] → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → flip Fun [] <$> qNameToUniqueString qName Just args → qNameToUniqueString qName >>= flip appArgsF args The term has holes . It is translated as a first - order C.Name _ _ → case allApplyElims elims of Nothing → __IMPOSSIBLE__ Just [] → __IMPOSSIBLE__ Just args → qNameToUniqueString qName >>= flip appArgsF args agdaTermToTerm term'@(Lam ArgInfo{argInfoHiding = NotHidden} (Abs _ termLam)) = do reportSLn "t2f" 10 $ "agdaTermToTerm Lam:\n" ++ show term' _ ← pushTNewVar f ← agdaTermToTerm termLam popTVar return f agdaTermToTerm term'@(I.Var n args) = do reportSLn "t2t" 10 $ "agdaTermToTerm Var:\n" ++ show term' when (n < 0) (__IMPOSSIBLE__) vars ← getTVars We also test for equality because the first argument of @I.Var@ does n't start in one but in zero . when (length vars == n) (__IMPOSSIBLE__) when (length vars < n) (__IMPOSSIBLE__) case args of [] → return $ L.Var (vars !! n) Non - FOL translation : First - order logic universal quantified Set to a Set , for example , the variable / function @f@ in _varArgs → do let p ∷ String p = "--schematic-functions" ifM (askTOpt optSchematicFunctions) TODO ( 24 March 2013 ) . Implementation . (tErr $ NoImplementedOption "--schematic-functions") ( do lTerms ifM ( askTOpt optAppF ) ( return $ foldl ' app ( Var ( vars ! ! n ) ) lTerms ) (tErr $ UniversalQuantificationError p) agdaTermToTerm _ = __IMPOSSIBLE__ 27 June 2012 . After the patch We d Sep 21 04:50:43 COT 2011 Agda is using ( Pi _ ( NoAbs _ _ ) ) for the non - dependent functions . In a later patch , changed somes ( Pi _ ( Abs _ _ ) )
ed52386c1576aefe2d0a0fac55d27f9f7720e99e90939941d958ca990f67897f
abarbu/haskell-torch
Types.hs
# LANGUAGE OverloadedStrings , QuasiQuotes , ScopedTypeVariables , TemplateHaskell # module Foreign.Matio.Types where import qualified Data.Map as Map import Data.Monoid (mempty, (<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Vector as V' import Data.Vector.Storable (Vector) import qualified Data.Vector.Storable as V import Foreign.C.Types import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Cpp.Exceptions as C import qualified Language.C.Types as C import qualified Language.Haskell.TH as TH C.include "<matio.h>" data CMat data CMatVar matioCtx :: C.Context matioCtx = C.baseCtx <> C.funCtx <> C.vecCtx <> C.fptrCtx <> ctx where ctx = mempty { C.ctxTypesTable = matioTypesTable } matioTypesTable :: Map.Map C.TypeSpecifier TH.TypeQ matioTypesTable = Map.fromList [ (C.TypeName "bool", [t| C.CBool |]) , (C.TypeName "mat_t", [t| CMat |]) , (C.TypeName "matvar_t", [t| CMatVar |]) ] | NB This structure is incomplete but it is also not meant by a 1 - 1 map between matlab datatypes and haskell datatypes . For example , you get one text data type , you do n't get to redundantly pick between 3 . -- -- NB Matlab arrays are unfortunately column major! :( data MatValue = MatCellArray (Vector CSize) (V'.Vector MatValue) | MatInt8Array (Vector CSize) (Vector CChar) | MatUInt8Array (Vector CSize) (Vector CUChar) | MatText Text deriving (Show, Eq) data MatType = MatTypeInt8 | MatTypeUInt8 | MatTypeInt16 | MatTypeUInt16 | MatTypeInt32 | MatTypeUInt32 | MatTypeInt64 | MatTypeUInt64 | MatTypeFloat | MatTypeDouble | MatTypeMatrix | MatTypeCompressed | MatTypeUTF8 | MatTypeUTF16 | MatTypeUTF32 | MatTypeString | MatTypeCell | MatTypeStruct | MatTypeArray | MatTypeFunction | MatTypeUnknown deriving (Show, Eq) instance Enum MatType where toEnum x | x == fromIntegral [C.pure| int { (int)MAT_T_INT8 }|] = MatTypeInt8 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT8 }|] = MatTypeUInt8 | x == fromIntegral [C.pure| int { (int)MAT_T_INT16 }|] = MatTypeInt16 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT16 }|] = MatTypeUInt16 | x == fromIntegral [C.pure| int { (int)MAT_T_INT32 }|] = MatTypeInt32 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT32 }|] = MatTypeUInt32 | x == fromIntegral [C.pure| int { (int)MAT_T_INT64 }|] = MatTypeInt64 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT64 }|] = MatTypeUInt64 | x == fromIntegral [C.pure| int { (int)MAT_T_SINGLE }|] = MatTypeFloat | x == fromIntegral [C.pure| int { (int)MAT_T_DOUBLE }|] = MatTypeDouble | x == fromIntegral [C.pure| int { (int)MAT_T_MATRIX }|] = MatTypeMatrix | x == fromIntegral [C.pure| int { (int)MAT_T_COMPRESSED }|] = MatTypeCompressed | x == fromIntegral [C.pure| int { (int)MAT_T_UTF8 }|] = MatTypeUTF8 | x == fromIntegral [C.pure| int { (int)MAT_T_UTF16 }|] = MatTypeUTF16 | x == fromIntegral [C.pure| int { (int)MAT_T_UTF32 }|] = MatTypeUTF32 | x == fromIntegral [C.pure| int { (int)MAT_T_STRING }|] = MatTypeString | x == fromIntegral [C.pure| int { (int)MAT_T_CELL }|] = MatTypeCell | x == fromIntegral [C.pure| int { (int)MAT_T_STRUCT }|] = MatTypeStruct | x == fromIntegral [C.pure| int { (int)MAT_T_ARRAY }|] = MatTypeArray | x == fromIntegral [C.pure| int { (int)MAT_T_FUNCTION }|] = MatTypeFunction | x == fromIntegral [C.pure| int { (int)MAT_T_UNKNOWN }|] = MatTypeUnknown fromEnum MatTypeInt8 = fromIntegral [C.pure|int { (int)MAT_T_INT8 }|] fromEnum MatTypeUInt8 = fromIntegral [C.pure|int { (int)MAT_T_UINT8 }|] fromEnum MatTypeInt16 = fromIntegral [C.pure|int { (int)MAT_T_INT16 }|] fromEnum MatTypeUInt16 = fromIntegral [C.pure|int { (int)MAT_T_UINT16 }|] fromEnum MatTypeInt32 = fromIntegral [C.pure|int { (int)MAT_T_INT32 }|] fromEnum MatTypeUInt32 = fromIntegral [C.pure|int { (int)MAT_T_UINT32 }|] fromEnum MatTypeInt64 = fromIntegral [C.pure|int { (int)MAT_T_INT64 }|] fromEnum MatTypeUInt64 = fromIntegral [C.pure|int { (int)MAT_T_UINT64 }|] fromEnum MatTypeFloat = fromIntegral [C.pure|int { (int)MAT_T_SINGLE }|] fromEnum MatTypeDouble = fromIntegral [C.pure|int { (int)MAT_T_DOUBLE }|] fromEnum MatTypeMatrix = fromIntegral [C.pure|int { (int)MAT_T_MATRIX }|] fromEnum MatTypeCompressed = fromIntegral [C.pure|int { (int)MAT_T_COMPRESSED }|] fromEnum MatTypeUTF8 = fromIntegral [C.pure|int { (int)MAT_T_UTF8 }|] fromEnum MatTypeUTF16 = fromIntegral [C.pure|int { (int)MAT_T_UTF16 }|] fromEnum MatTypeUTF32 = fromIntegral [C.pure|int { (int)MAT_T_UTF32 }|] fromEnum MatTypeString = fromIntegral [C.pure|int { (int)MAT_T_STRING }|] fromEnum MatTypeCell = fromIntegral [C.pure|int { (int)MAT_T_CELL }|] fromEnum MatTypeStruct = fromIntegral [C.pure|int { (int)MAT_T_STRUCT }|] fromEnum MatTypeArray = fromIntegral [C.pure|int { (int)MAT_T_ARRAY }|] fromEnum MatTypeFunction = fromIntegral [C.pure|int { (int)MAT_T_FUNCTION }|] fromEnum MatTypeUnknown = fromIntegral [C.pure|int { (int)MAT_T_UNKNOWN }|] data MatClass = MatClassEmpty | MatClassCell | MatClassStruct | MatClassObject | MatClassChar | MatClassSparse | MatClassDouble | MatClassFloat | MatClassInt8 | MatClassUInt8 | MatClassInt16 | MatClassUInt16 | MatClassInt32 | MatClassUInt32 | MatClassInt64 | MatClassUInt64 | MatClassFunction | MatClassOpaque deriving (Show, Eq) instance Enum MatClass where toEnum x | x == fromIntegral [C.pure| int { (int) MAT_C_EMPTY }|] = MatClassEmpty | x == fromIntegral [C.pure| int { (int) MAT_C_CELL }|] = MatClassCell | x == fromIntegral [C.pure| int { (int) MAT_C_STRUCT }|] = MatClassStruct | x == fromIntegral [C.pure| int { (int) MAT_C_OBJECT }|] = MatClassObject | x == fromIntegral [C.pure| int { (int) MAT_C_CHAR }|] = MatClassChar | x == fromIntegral [C.pure| int { (int) MAT_C_SPARSE }|] = MatClassSparse | x == fromIntegral [C.pure| int { (int) MAT_C_DOUBLE }|] = MatClassDouble | x == fromIntegral [C.pure| int { (int) MAT_C_SINGLE }|] = MatClassFloat | x == fromIntegral [C.pure| int { (int) MAT_C_INT8 }|] = MatClassInt8 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT8 }|] = MatClassUInt8 | x == fromIntegral [C.pure| int { (int) MAT_C_INT16 }|] = MatClassInt16 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT16 }|] = MatClassUInt16 | x == fromIntegral [C.pure| int { (int) MAT_C_INT32 }|] = MatClassInt32 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT32 }|] = MatClassUInt32 | x == fromIntegral [C.pure| int { (int) MAT_C_INT64 }|] = MatClassInt64 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT64 }|] = MatClassUInt64 | x == fromIntegral [C.pure| int { (int) MAT_C_FUNCTION }|] = MatClassFunction | x == fromIntegral [C.pure| int { (int) MAT_C_OPAQUE }|] = MatClassOpaque fromEnum MatClassEmpty = fromIntegral [C.pure|int { (int)MAT_C_EMPTY }|] fromEnum MatClassCell = fromIntegral [C.pure|int { (int)MAT_C_CELL }|] fromEnum MatClassStruct = fromIntegral [C.pure|int { (int)MAT_C_STRUCT }|] fromEnum MatClassObject = fromIntegral [C.pure|int { (int)MAT_C_OBJECT }|] fromEnum MatClassChar = fromIntegral [C.pure|int { (int)MAT_C_CHAR }|] fromEnum MatClassSparse = fromIntegral [C.pure|int { (int)MAT_C_SPARSE }|] fromEnum MatClassDouble = fromIntegral [C.pure|int { (int)MAT_C_DOUBLE }|] fromEnum MatClassFloat = fromIntegral [C.pure|int { (int)MAT_C_SINGLE }|] fromEnum MatClassInt8 = fromIntegral [C.pure|int { (int)MAT_C_INT8 }|] fromEnum MatClassUInt8 = fromIntegral [C.pure|int { (int)MAT_C_UINT8 }|] fromEnum MatClassInt16 = fromIntegral [C.pure|int { (int)MAT_C_INT16 }|] fromEnum MatClassUInt16 = fromIntegral [C.pure|int { (int)MAT_C_UINT16 }|] fromEnum MatClassInt32 = fromIntegral [C.pure|int { (int)MAT_C_INT32 }|] fromEnum MatClassUInt32 = fromIntegral [C.pure|int { (int)MAT_C_UINT32 }|] fromEnum MatClassInt64 = fromIntegral [C.pure|int { (int)MAT_C_INT64 }|] fromEnum MatClassUInt64 = fromIntegral [C.pure|int { (int)MAT_C_UINT64 }|] fromEnum MatClassFunction = fromIntegral [C.pure|int { (int)MAT_C_FUNCTION }|] fromEnum MatClassOpaque = fromIntegral [C.pure|int { (int)MAT_C_OPAQUE }|]
null
https://raw.githubusercontent.com/abarbu/haskell-torch/03b2c10bf8ca3d4508d52c2123e753d93b3c4236/haskell-torch-matio/src/Foreign/Matio/Types.hs
haskell
NB Matlab arrays are unfortunately column major! :(
# LANGUAGE OverloadedStrings , QuasiQuotes , ScopedTypeVariables , TemplateHaskell # module Foreign.Matio.Types where import qualified Data.Map as Map import Data.Monoid (mempty, (<>)) import Data.Text (Text) import qualified Data.Text as T import qualified Data.Vector as V' import Data.Vector.Storable (Vector) import qualified Data.Vector.Storable as V import Foreign.C.Types import qualified Language.C.Inline as C import qualified Language.C.Inline.Context as C import qualified Language.C.Inline.Cpp as C import qualified Language.C.Inline.Cpp.Exceptions as C import qualified Language.C.Types as C import qualified Language.Haskell.TH as TH C.include "<matio.h>" data CMat data CMatVar matioCtx :: C.Context matioCtx = C.baseCtx <> C.funCtx <> C.vecCtx <> C.fptrCtx <> ctx where ctx = mempty { C.ctxTypesTable = matioTypesTable } matioTypesTable :: Map.Map C.TypeSpecifier TH.TypeQ matioTypesTable = Map.fromList [ (C.TypeName "bool", [t| C.CBool |]) , (C.TypeName "mat_t", [t| CMat |]) , (C.TypeName "matvar_t", [t| CMatVar |]) ] | NB This structure is incomplete but it is also not meant by a 1 - 1 map between matlab datatypes and haskell datatypes . For example , you get one text data type , you do n't get to redundantly pick between 3 . data MatValue = MatCellArray (Vector CSize) (V'.Vector MatValue) | MatInt8Array (Vector CSize) (Vector CChar) | MatUInt8Array (Vector CSize) (Vector CUChar) | MatText Text deriving (Show, Eq) data MatType = MatTypeInt8 | MatTypeUInt8 | MatTypeInt16 | MatTypeUInt16 | MatTypeInt32 | MatTypeUInt32 | MatTypeInt64 | MatTypeUInt64 | MatTypeFloat | MatTypeDouble | MatTypeMatrix | MatTypeCompressed | MatTypeUTF8 | MatTypeUTF16 | MatTypeUTF32 | MatTypeString | MatTypeCell | MatTypeStruct | MatTypeArray | MatTypeFunction | MatTypeUnknown deriving (Show, Eq) instance Enum MatType where toEnum x | x == fromIntegral [C.pure| int { (int)MAT_T_INT8 }|] = MatTypeInt8 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT8 }|] = MatTypeUInt8 | x == fromIntegral [C.pure| int { (int)MAT_T_INT16 }|] = MatTypeInt16 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT16 }|] = MatTypeUInt16 | x == fromIntegral [C.pure| int { (int)MAT_T_INT32 }|] = MatTypeInt32 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT32 }|] = MatTypeUInt32 | x == fromIntegral [C.pure| int { (int)MAT_T_INT64 }|] = MatTypeInt64 | x == fromIntegral [C.pure| int { (int)MAT_T_UINT64 }|] = MatTypeUInt64 | x == fromIntegral [C.pure| int { (int)MAT_T_SINGLE }|] = MatTypeFloat | x == fromIntegral [C.pure| int { (int)MAT_T_DOUBLE }|] = MatTypeDouble | x == fromIntegral [C.pure| int { (int)MAT_T_MATRIX }|] = MatTypeMatrix | x == fromIntegral [C.pure| int { (int)MAT_T_COMPRESSED }|] = MatTypeCompressed | x == fromIntegral [C.pure| int { (int)MAT_T_UTF8 }|] = MatTypeUTF8 | x == fromIntegral [C.pure| int { (int)MAT_T_UTF16 }|] = MatTypeUTF16 | x == fromIntegral [C.pure| int { (int)MAT_T_UTF32 }|] = MatTypeUTF32 | x == fromIntegral [C.pure| int { (int)MAT_T_STRING }|] = MatTypeString | x == fromIntegral [C.pure| int { (int)MAT_T_CELL }|] = MatTypeCell | x == fromIntegral [C.pure| int { (int)MAT_T_STRUCT }|] = MatTypeStruct | x == fromIntegral [C.pure| int { (int)MAT_T_ARRAY }|] = MatTypeArray | x == fromIntegral [C.pure| int { (int)MAT_T_FUNCTION }|] = MatTypeFunction | x == fromIntegral [C.pure| int { (int)MAT_T_UNKNOWN }|] = MatTypeUnknown fromEnum MatTypeInt8 = fromIntegral [C.pure|int { (int)MAT_T_INT8 }|] fromEnum MatTypeUInt8 = fromIntegral [C.pure|int { (int)MAT_T_UINT8 }|] fromEnum MatTypeInt16 = fromIntegral [C.pure|int { (int)MAT_T_INT16 }|] fromEnum MatTypeUInt16 = fromIntegral [C.pure|int { (int)MAT_T_UINT16 }|] fromEnum MatTypeInt32 = fromIntegral [C.pure|int { (int)MAT_T_INT32 }|] fromEnum MatTypeUInt32 = fromIntegral [C.pure|int { (int)MAT_T_UINT32 }|] fromEnum MatTypeInt64 = fromIntegral [C.pure|int { (int)MAT_T_INT64 }|] fromEnum MatTypeUInt64 = fromIntegral [C.pure|int { (int)MAT_T_UINT64 }|] fromEnum MatTypeFloat = fromIntegral [C.pure|int { (int)MAT_T_SINGLE }|] fromEnum MatTypeDouble = fromIntegral [C.pure|int { (int)MAT_T_DOUBLE }|] fromEnum MatTypeMatrix = fromIntegral [C.pure|int { (int)MAT_T_MATRIX }|] fromEnum MatTypeCompressed = fromIntegral [C.pure|int { (int)MAT_T_COMPRESSED }|] fromEnum MatTypeUTF8 = fromIntegral [C.pure|int { (int)MAT_T_UTF8 }|] fromEnum MatTypeUTF16 = fromIntegral [C.pure|int { (int)MAT_T_UTF16 }|] fromEnum MatTypeUTF32 = fromIntegral [C.pure|int { (int)MAT_T_UTF32 }|] fromEnum MatTypeString = fromIntegral [C.pure|int { (int)MAT_T_STRING }|] fromEnum MatTypeCell = fromIntegral [C.pure|int { (int)MAT_T_CELL }|] fromEnum MatTypeStruct = fromIntegral [C.pure|int { (int)MAT_T_STRUCT }|] fromEnum MatTypeArray = fromIntegral [C.pure|int { (int)MAT_T_ARRAY }|] fromEnum MatTypeFunction = fromIntegral [C.pure|int { (int)MAT_T_FUNCTION }|] fromEnum MatTypeUnknown = fromIntegral [C.pure|int { (int)MAT_T_UNKNOWN }|] data MatClass = MatClassEmpty | MatClassCell | MatClassStruct | MatClassObject | MatClassChar | MatClassSparse | MatClassDouble | MatClassFloat | MatClassInt8 | MatClassUInt8 | MatClassInt16 | MatClassUInt16 | MatClassInt32 | MatClassUInt32 | MatClassInt64 | MatClassUInt64 | MatClassFunction | MatClassOpaque deriving (Show, Eq) instance Enum MatClass where toEnum x | x == fromIntegral [C.pure| int { (int) MAT_C_EMPTY }|] = MatClassEmpty | x == fromIntegral [C.pure| int { (int) MAT_C_CELL }|] = MatClassCell | x == fromIntegral [C.pure| int { (int) MAT_C_STRUCT }|] = MatClassStruct | x == fromIntegral [C.pure| int { (int) MAT_C_OBJECT }|] = MatClassObject | x == fromIntegral [C.pure| int { (int) MAT_C_CHAR }|] = MatClassChar | x == fromIntegral [C.pure| int { (int) MAT_C_SPARSE }|] = MatClassSparse | x == fromIntegral [C.pure| int { (int) MAT_C_DOUBLE }|] = MatClassDouble | x == fromIntegral [C.pure| int { (int) MAT_C_SINGLE }|] = MatClassFloat | x == fromIntegral [C.pure| int { (int) MAT_C_INT8 }|] = MatClassInt8 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT8 }|] = MatClassUInt8 | x == fromIntegral [C.pure| int { (int) MAT_C_INT16 }|] = MatClassInt16 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT16 }|] = MatClassUInt16 | x == fromIntegral [C.pure| int { (int) MAT_C_INT32 }|] = MatClassInt32 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT32 }|] = MatClassUInt32 | x == fromIntegral [C.pure| int { (int) MAT_C_INT64 }|] = MatClassInt64 | x == fromIntegral [C.pure| int { (int) MAT_C_UINT64 }|] = MatClassUInt64 | x == fromIntegral [C.pure| int { (int) MAT_C_FUNCTION }|] = MatClassFunction | x == fromIntegral [C.pure| int { (int) MAT_C_OPAQUE }|] = MatClassOpaque fromEnum MatClassEmpty = fromIntegral [C.pure|int { (int)MAT_C_EMPTY }|] fromEnum MatClassCell = fromIntegral [C.pure|int { (int)MAT_C_CELL }|] fromEnum MatClassStruct = fromIntegral [C.pure|int { (int)MAT_C_STRUCT }|] fromEnum MatClassObject = fromIntegral [C.pure|int { (int)MAT_C_OBJECT }|] fromEnum MatClassChar = fromIntegral [C.pure|int { (int)MAT_C_CHAR }|] fromEnum MatClassSparse = fromIntegral [C.pure|int { (int)MAT_C_SPARSE }|] fromEnum MatClassDouble = fromIntegral [C.pure|int { (int)MAT_C_DOUBLE }|] fromEnum MatClassFloat = fromIntegral [C.pure|int { (int)MAT_C_SINGLE }|] fromEnum MatClassInt8 = fromIntegral [C.pure|int { (int)MAT_C_INT8 }|] fromEnum MatClassUInt8 = fromIntegral [C.pure|int { (int)MAT_C_UINT8 }|] fromEnum MatClassInt16 = fromIntegral [C.pure|int { (int)MAT_C_INT16 }|] fromEnum MatClassUInt16 = fromIntegral [C.pure|int { (int)MAT_C_UINT16 }|] fromEnum MatClassInt32 = fromIntegral [C.pure|int { (int)MAT_C_INT32 }|] fromEnum MatClassUInt32 = fromIntegral [C.pure|int { (int)MAT_C_UINT32 }|] fromEnum MatClassInt64 = fromIntegral [C.pure|int { (int)MAT_C_INT64 }|] fromEnum MatClassUInt64 = fromIntegral [C.pure|int { (int)MAT_C_UINT64 }|] fromEnum MatClassFunction = fromIntegral [C.pure|int { (int)MAT_C_FUNCTION }|] fromEnum MatClassOpaque = fromIntegral [C.pure|int { (int)MAT_C_OPAQUE }|]
370b91c2524f4c5512b62ed1a9857ea48e9dbf1624f4cbece9df270cf56ac246
JonathanLorimer/core-warn
Spec.hs
module Spec where
null
https://raw.githubusercontent.com/JonathanLorimer/core-warn/52b841253727e4085d1b2cb663d8bca23c4eb681/test/Spec.hs
haskell
module Spec where
8540e099fa0379da5510259264ef57fa762c9a0a3ec1bcc8c7f384a46130fab0
open-telemetry/opentelemetry-erlang-api
ot_meter_noop.erl
%%%------------------------------------------------------------------------ Copyright 2019 , OpenTelemetry Authors Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% @doc %% @end %%%------------------------------------------------------------------------- -module(ot_meter_noop). -behaviour(ot_meter). -export([new_instrument/4, new_instruments/2, labels/2, record/3, record/4, record_batch/3, bind/3, release/2, set_observer_callback/3, register_observer/3, observe/3]). new_instrument(_, _, _, _) -> true. new_instruments(_, _) -> true. labels(_, _) -> #{}. record(_, _, _) -> ok. record(_, _, _, _) -> ok. record_batch(_, _, _) -> ok. bind(_, _, _) -> []. release(_, _) -> ok. set_observer_callback(_, _, _) -> ok. register_observer(_, _, _) -> ok. observe(_, _, _) -> ok.
null
https://raw.githubusercontent.com/open-telemetry/opentelemetry-erlang-api/41cb700d60a7dcfdb4165aca73634bbe1c07a33f/src/ot_meter_noop.erl
erlang
------------------------------------------------------------------------ you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @doc @end -------------------------------------------------------------------------
Copyright 2019 , OpenTelemetry Authors Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(ot_meter_noop). -behaviour(ot_meter). -export([new_instrument/4, new_instruments/2, labels/2, record/3, record/4, record_batch/3, bind/3, release/2, set_observer_callback/3, register_observer/3, observe/3]). new_instrument(_, _, _, _) -> true. new_instruments(_, _) -> true. labels(_, _) -> #{}. record(_, _, _) -> ok. record(_, _, _, _) -> ok. record_batch(_, _, _) -> ok. bind(_, _, _) -> []. release(_, _) -> ok. set_observer_callback(_, _, _) -> ok. register_observer(_, _, _) -> ok. observe(_, _, _) -> ok.
c152f1b7fcb6529344d123b9099ece721555b9574dad38fe6de9e7133f3f6fb3
Shirakumo/kandria
achievements.lisp
(in-package #:org.shirakumo.fraf.kandria) (defun race-achieved-p (race) (let ((quest (quest:find-quest race (storyline +world+)))) (and (quest:var 'pb quest) (<= (quest:var 'pb quest) (quest:var 'gold quest))))) (define-achievement catherine-races task-completed :icon (// 'kandria 'ach-racecat) (every #'race-achieved-p '(sq3-race-1 sq3-race-2 sq3-race-3 sq3-race-4 sq3-race-5))) (define-achievement barkeep-races task-completed :icon (// 'kandria 'ach-racebar) (every #'race-achieved-p '(sq5-race-1 sq5-race-2 sq5-race-3 sq5-race-4 sq5-race-5 sq5-race-6))) (define-achievement spy-races task-completed :icon (// 'kandria 'ach-racespy) (every #'race-achieved-p '(sq9-race-1 sq9-race-2 sq9-race-3 sq9-race-4 sq9-race-5))) (define-achievement sergeant-races task-completed :icon (// 'kandria 'ach-racesarge) (every #'race-achieved-p '(sq10-race-1 sq10-race-2 sq10-race-3 sq10-race-4 sq10-race-5))) (define-achievement full-map switch-chunk :icon (// 'kandria 'ach-map) (and (string= "00000000-0000-0000-0000-000000000000" (id +world+)) (multiple-value-bind (total found) (chunk-find-rate (unit 'player +world+)) (<= total found)))) (define-achievement all-fish item-unlocked :icon (// 'kandria 'ach-fish) (loop with player = (unit 'player +world+) for fish in (c2mop:class-direct-subclasses (find-class 'fish)) always (item-unlocked-p (class-name fish) player))) (define-achievement game-complete game-over :icon (// 'kandria 'ach-end) (eql (ending game-over) :normal)) (define-achievement early-ending game-over :icon (// 'kandria 'ach-zelah) (eql (ending game-over) :zelah)) (defvar *last-death-count* (cons NIL 0)) (define-achievement persistence player-died :icon (// 'kandria 'ach-deaths) (unless (eq (car *last-death-count*) (chunk (unit 'player T))) (setf (car *last-death-count*) (chunk (unit 'player T))) (setf (cdr *last-death-count*) 0)) (<= 30 (incf (cdr *last-death-count*)))) (define-achievement accessibility NIL :icon (// 'kandria 'ach-access)) (define-achievement modder NIL :icon (// 'kandria 'ach-mod)) (define-setting-observer accessibility-achievement :gameplay (value) (when +world+ (when (or (/= 1.0 (getf value :rumble)) (/= 1.0 (getf value :screen-shake)) (getf value :god-mode) (getf value :infinite-dash) (getf value :infinite-climb) (/= 0.02 (getf value :text-speed)) (/= 3.0 (getf value :auto-advance-after)) (getf value :auto-advance-dialog) (null (getf value :display-text-effects)) (null (getf value :display-swears)) (getf value :visual-safe-mode) (getf value :allow-resuming-death) (/= 1.0 (getf value :game-speed)) (/= 1.0 (getf value :damage-input)) (/= 1.0 (getf value :damage-output)) (/= 1.0 (getf value :level-multiplier)) (null (getf value :show-hit-stings))) (award 'accessibility))))
null
https://raw.githubusercontent.com/Shirakumo/kandria/0eafe60b5f50c18980a6acc977dc45987e8e26c1/achievements.lisp
lisp
(in-package #:org.shirakumo.fraf.kandria) (defun race-achieved-p (race) (let ((quest (quest:find-quest race (storyline +world+)))) (and (quest:var 'pb quest) (<= (quest:var 'pb quest) (quest:var 'gold quest))))) (define-achievement catherine-races task-completed :icon (// 'kandria 'ach-racecat) (every #'race-achieved-p '(sq3-race-1 sq3-race-2 sq3-race-3 sq3-race-4 sq3-race-5))) (define-achievement barkeep-races task-completed :icon (// 'kandria 'ach-racebar) (every #'race-achieved-p '(sq5-race-1 sq5-race-2 sq5-race-3 sq5-race-4 sq5-race-5 sq5-race-6))) (define-achievement spy-races task-completed :icon (// 'kandria 'ach-racespy) (every #'race-achieved-p '(sq9-race-1 sq9-race-2 sq9-race-3 sq9-race-4 sq9-race-5))) (define-achievement sergeant-races task-completed :icon (// 'kandria 'ach-racesarge) (every #'race-achieved-p '(sq10-race-1 sq10-race-2 sq10-race-3 sq10-race-4 sq10-race-5))) (define-achievement full-map switch-chunk :icon (// 'kandria 'ach-map) (and (string= "00000000-0000-0000-0000-000000000000" (id +world+)) (multiple-value-bind (total found) (chunk-find-rate (unit 'player +world+)) (<= total found)))) (define-achievement all-fish item-unlocked :icon (// 'kandria 'ach-fish) (loop with player = (unit 'player +world+) for fish in (c2mop:class-direct-subclasses (find-class 'fish)) always (item-unlocked-p (class-name fish) player))) (define-achievement game-complete game-over :icon (// 'kandria 'ach-end) (eql (ending game-over) :normal)) (define-achievement early-ending game-over :icon (// 'kandria 'ach-zelah) (eql (ending game-over) :zelah)) (defvar *last-death-count* (cons NIL 0)) (define-achievement persistence player-died :icon (// 'kandria 'ach-deaths) (unless (eq (car *last-death-count*) (chunk (unit 'player T))) (setf (car *last-death-count*) (chunk (unit 'player T))) (setf (cdr *last-death-count*) 0)) (<= 30 (incf (cdr *last-death-count*)))) (define-achievement accessibility NIL :icon (// 'kandria 'ach-access)) (define-achievement modder NIL :icon (// 'kandria 'ach-mod)) (define-setting-observer accessibility-achievement :gameplay (value) (when +world+ (when (or (/= 1.0 (getf value :rumble)) (/= 1.0 (getf value :screen-shake)) (getf value :god-mode) (getf value :infinite-dash) (getf value :infinite-climb) (/= 0.02 (getf value :text-speed)) (/= 3.0 (getf value :auto-advance-after)) (getf value :auto-advance-dialog) (null (getf value :display-text-effects)) (null (getf value :display-swears)) (getf value :visual-safe-mode) (getf value :allow-resuming-death) (/= 1.0 (getf value :game-speed)) (/= 1.0 (getf value :damage-input)) (/= 1.0 (getf value :damage-output)) (/= 1.0 (getf value :level-multiplier)) (null (getf value :show-hit-stings))) (award 'accessibility))))
36622ffb5708e4fb9ca3a86464e5c81d7ea1d5c676b743ea1451c1a506172fe8
ruhler/smten
tests.hs
# LANGUAGE NoImplicitPrelude # import Smten.Compiled.Smten.Tests.STP
null
https://raw.githubusercontent.com/ruhler/smten/16dd37fb0ee3809408803d4be20401211b6c4027/smten-stp/tests.hs
haskell
# LANGUAGE NoImplicitPrelude # import Smten.Compiled.Smten.Tests.STP
6c8477b1c438b1c2d9cf26a13f019745eb36223eceb100f1077a35b66bcb9853
cassiel/thi-ng-geom-starter
t_demo.cljs
(ns thi-ng-geom-starter.t-demo (:require [reagent.core :as reagent] [thi.ng.math.core :as m :refer [PI HALF_PI TWO_PI]] [thi.ng.geom.gl.core :as gl] [thi.ng.geom.gl.webgl.constants :as glc] [thi.ng.geom.gl.webgl.animator :as anim] [thi.ng.geom.gl.buffers :as buf] [thi.ng.geom.gl.fx :as fx] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.glmesh :as glm] [thi.ng.geom.gl.camera :as cam] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.shaders.phong :as phong] [thi.ng.geom.gl.shaders.lambert :as lambert] [thi.ng.geom.core :as g] [thi.ng.geom.vector :as v :refer [vec2 vec3]] [thi.ng.geom.matrix :as mat :refer [M44]] [thi.ng.geom.aabb :as a] [thi.ng.geom.sphere :as s] [thi.ng.geom.attribs :as attr] [thi.ng.domus.core :as dom] [thi.ng.color.core :as col] [thi.ng.strf.core :as f] [thi-ng-geom-starter.shaders :as shaders] [geometer.turtle :as turtle]) (:require-macros [cljs-log.core :refer [debug info warn severe]])) (defonce app (reagent/atom {})) (def old-mesh (-> (a/aabb 0.8) (g/center) (g/as-mesh {:mesh (glm/indexed-gl-mesh 12 #{:col :fnorm}) ;;:flags :ewfbs #_ :attribs #_ {:col (->> [[1 0 0] [0 1 0] [0 0 1] [0 1 1] [1 0 1] [1 1 0]] (map col/rgba) (attr/const-face-attribs))}}))) (def turtle-mesh (turtle/plant)) (defn make-model [gl] (-> old-mesh (gl/as-gl-buffer-spec {}) (assoc :shader (sh/make-shader-from-spec gl phong/shader-spec)) (gl/make-buffers-in-spec gl glc/static-draw))) (defn rebuild-viewport [app] (let [gl (:gl app) _ (gl/set-viewport gl {:p [0 0] :size [(.-innerWidth js/window) (.-innerHeight js/window)]}) vr (gl/get-viewport-rect gl)] (assoc app :view-rect vr : model ( make - model gl vr ) ))) (defn init-app [_] (debug "INIT") (let [gl (gl/gl-context "main") view-rect (gl/get-viewport-rect gl) model (make-model gl)] (reset! app {:gl gl :view-rect view-rect :model model}))) (defn update-app [this] (fn [t frame] (when (:active (reagent/state this)) (let [{:keys [gl view-rect model]} @app] (doto gl (gl/set-viewport view-rect) (gl/clear-color-and-depth-buffer col/GRAY 1) (gl/draw-with-shader (-> model (cam/apply (cam/perspective-camera {:eye (vec3 0 0 1.25) : up ( m / normalize ( vec3 ( Math / sin t ) 1 0 ) ) :fov 90 :aspect view-rect})) (assoc-in [:uniforms :model] (-> M44 (g/rotate-x t) (g/rotate-y (* t 2)))))))) true)))
null
https://raw.githubusercontent.com/cassiel/thi-ng-geom-starter/f32a8a195f1b95da5e4e44228174b8db8a26fb87/src/cljs/thi_ng_geom_starter/t_demo.cljs
clojure
:flags :ewfbs
(ns thi-ng-geom-starter.t-demo (:require [reagent.core :as reagent] [thi.ng.math.core :as m :refer [PI HALF_PI TWO_PI]] [thi.ng.geom.gl.core :as gl] [thi.ng.geom.gl.webgl.constants :as glc] [thi.ng.geom.gl.webgl.animator :as anim] [thi.ng.geom.gl.buffers :as buf] [thi.ng.geom.gl.fx :as fx] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.glmesh :as glm] [thi.ng.geom.gl.camera :as cam] [thi.ng.geom.gl.shaders :as sh] [thi.ng.geom.gl.shaders.phong :as phong] [thi.ng.geom.gl.shaders.lambert :as lambert] [thi.ng.geom.core :as g] [thi.ng.geom.vector :as v :refer [vec2 vec3]] [thi.ng.geom.matrix :as mat :refer [M44]] [thi.ng.geom.aabb :as a] [thi.ng.geom.sphere :as s] [thi.ng.geom.attribs :as attr] [thi.ng.domus.core :as dom] [thi.ng.color.core :as col] [thi.ng.strf.core :as f] [thi-ng-geom-starter.shaders :as shaders] [geometer.turtle :as turtle]) (:require-macros [cljs-log.core :refer [debug info warn severe]])) (defonce app (reagent/atom {})) (def old-mesh (-> (a/aabb 0.8) (g/center) (g/as-mesh {:mesh (glm/indexed-gl-mesh 12 #{:col :fnorm}) #_ :attribs #_ {:col (->> [[1 0 0] [0 1 0] [0 0 1] [0 1 1] [1 0 1] [1 1 0]] (map col/rgba) (attr/const-face-attribs))}}))) (def turtle-mesh (turtle/plant)) (defn make-model [gl] (-> old-mesh (gl/as-gl-buffer-spec {}) (assoc :shader (sh/make-shader-from-spec gl phong/shader-spec)) (gl/make-buffers-in-spec gl glc/static-draw))) (defn rebuild-viewport [app] (let [gl (:gl app) _ (gl/set-viewport gl {:p [0 0] :size [(.-innerWidth js/window) (.-innerHeight js/window)]}) vr (gl/get-viewport-rect gl)] (assoc app :view-rect vr : model ( make - model gl vr ) ))) (defn init-app [_] (debug "INIT") (let [gl (gl/gl-context "main") view-rect (gl/get-viewport-rect gl) model (make-model gl)] (reset! app {:gl gl :view-rect view-rect :model model}))) (defn update-app [this] (fn [t frame] (when (:active (reagent/state this)) (let [{:keys [gl view-rect model]} @app] (doto gl (gl/set-viewport view-rect) (gl/clear-color-and-depth-buffer col/GRAY 1) (gl/draw-with-shader (-> model (cam/apply (cam/perspective-camera {:eye (vec3 0 0 1.25) : up ( m / normalize ( vec3 ( Math / sin t ) 1 0 ) ) :fov 90 :aspect view-rect})) (assoc-in [:uniforms :model] (-> M44 (g/rotate-x t) (g/rotate-y (* t 2)))))))) true)))
9216f547f3d51a192eb5b2be5ec6600b9da19ae83df4b8bf8ccfba0055b6f53e
heechul/crest-z3
bitmap.mli
(* Imperative bitmaps *) type t (* Create a bitmap given the number * of bits *) val make : int -> t val init : int -> (int -> bool) -> t (* Also initialize it *) val size : t -> int (* How much space it is reserved *) (* The cardinality of a set *) val card : t -> int (* Make a copy of a bitmap *) val clone : t -> t val cloneEmpty : t -> t (* An empty set with the same * dimensions *) (* Set the bit *) val setTo : t -> int -> bool -> unit val test : t -> int -> bool val testAndSetTo: t -> int -> bool -> bool (** Set the value and return the old * value *) * destructive union . The first * element is updated . Returns true * if any change was actually * necessary * element is updated. Returns true * if any change was actually * necessary *) val union : t -> t -> bool union_except def . * Does liveIn + = ( liveout - def ) . * Return true if the first set was * changed . * Does liveIn += (liveout - def). * Return true if the first set was * changed. *) val union_except : t -> t -> t -> bool Copy the second argument onto the * first * first *) val assign : t -> t -> unit val inters : t -> t -> unit val diff : t -> t -> unit val empty : t -> bool val equal : t -> t -> bool val toList : t -> int list val iter : (int -> unit) -> t -> unit val fold : ('a -> int -> 'a) -> t -> 'a -> 'a
null
https://raw.githubusercontent.com/heechul/crest-z3/cfcebadddb5e9d69e9956644fc37b46f6c2a21a0/cil/ocamlutil/bitmap.mli
ocaml
Imperative bitmaps Create a bitmap given the number * of bits Also initialize it How much space it is reserved The cardinality of a set Make a copy of a bitmap An empty set with the same * dimensions Set the bit * Set the value and return the old * value
type t val make : int -> t val card : t -> int val clone : t -> t val setTo : t -> int -> bool -> unit val test : t -> int -> bool * destructive union . The first * element is updated . Returns true * if any change was actually * necessary * element is updated. Returns true * if any change was actually * necessary *) val union : t -> t -> bool union_except def . * Does liveIn + = ( liveout - def ) . * Return true if the first set was * changed . * Does liveIn += (liveout - def). * Return true if the first set was * changed. *) val union_except : t -> t -> t -> bool Copy the second argument onto the * first * first *) val assign : t -> t -> unit val inters : t -> t -> unit val diff : t -> t -> unit val empty : t -> bool val equal : t -> t -> bool val toList : t -> int list val iter : (int -> unit) -> t -> unit val fold : ('a -> int -> 'a) -> t -> 'a -> 'a
da86d061f7495e2e324575be09fd316ecd7afdc4ef55d00be4c22069c8c5df73
mvoidex/hsdev
LookupTable.hs
module Data.LookupTable ( LookupTable, newLookupTable, lookupTable, lookupTableM, cacheInTableM, hasLookupTable, cachedInTable, insertTable, insertTableM, storeInTable, storeInTableM ) where import Control.Monad.IO.Class import Control.Concurrent.MVar import Data.Map (Map) import qualified Data.Map as M -- | k-v table type LookupTable k v = MVar (Map k v) newLookupTable :: (Ord k, MonadIO m) => m (LookupTable k v) newLookupTable = liftIO $ newMVar mempty -- | Lookup, or insert if not exists lookupTable :: (Ord k, MonadIO m) => k -> v -> LookupTable k v -> m v lookupTable key value tbl = liftIO $ modifyMVar tbl $ \tbl' -> case M.lookup key tbl' of Just value' -> return (tbl', value') Nothing -> return (M.insert key value tbl', value) -- | Lookup, or insert if not exists lookupTableM :: (Ord k, MonadIO m) => k -> m v -> LookupTable k v -> m v lookupTableM key mvalue tbl = do mv <- hasLookupTable key tbl case mv of Just value -> return value Nothing -> do value <- mvalue lookupTable key value tbl -- | @lookupTableM@ with swapped args cacheInTableM :: (Ord k, MonadIO m) => LookupTable k v -> k -> m v -> m v cacheInTableM tbl key mvalue = lookupTableM key mvalue tbl -- | Just check existable hasLookupTable :: (Ord k, MonadIO m) => k -> LookupTable k v -> m (Maybe v) hasLookupTable key tbl = liftIO $ withMVar tbl $ return . M.lookup key | Make function caching results in @LookupTable@ cachedInTable :: (Ord k, MonadIO m) => LookupTable k v -> (k -> m v) -> k -> m v cachedInTable tbl fn key = cacheInTableM tbl key (fn key) -- | Insert value into table and return it insertTable :: (Ord k, MonadIO m) => k -> v -> LookupTable k v -> m v insertTable key value tbl = liftIO $ modifyMVar tbl $ \tbl' -> return (M.insert key value tbl', value) -- | Insert value into table and return it insertTableM :: (Ord k, MonadIO m) => k -> m v -> LookupTable k v -> m v insertTableM key mvalue tbl = do value <- mvalue insertTable key value tbl -- | @insertTable@ with flipped args storeInTable :: (Ord k, MonadIO m) => LookupTable k v -> k -> v -> m v storeInTable tbl key value = insertTable key value tbl -- | @insertTable@ with flipped args storeInTableM :: (Ord k, MonadIO m) => LookupTable k v -> k -> m v -> m v storeInTableM tbl key mvalue = insertTableM key mvalue tbl
null
https://raw.githubusercontent.com/mvoidex/hsdev/016646080a6859e4d9b4a1935fc1d732e388db1a/src/Data/LookupTable.hs
haskell
| k-v table | Lookup, or insert if not exists | Lookup, or insert if not exists | @lookupTableM@ with swapped args | Just check existable | Insert value into table and return it | Insert value into table and return it | @insertTable@ with flipped args | @insertTable@ with flipped args
module Data.LookupTable ( LookupTable, newLookupTable, lookupTable, lookupTableM, cacheInTableM, hasLookupTable, cachedInTable, insertTable, insertTableM, storeInTable, storeInTableM ) where import Control.Monad.IO.Class import Control.Concurrent.MVar import Data.Map (Map) import qualified Data.Map as M type LookupTable k v = MVar (Map k v) newLookupTable :: (Ord k, MonadIO m) => m (LookupTable k v) newLookupTable = liftIO $ newMVar mempty lookupTable :: (Ord k, MonadIO m) => k -> v -> LookupTable k v -> m v lookupTable key value tbl = liftIO $ modifyMVar tbl $ \tbl' -> case M.lookup key tbl' of Just value' -> return (tbl', value') Nothing -> return (M.insert key value tbl', value) lookupTableM :: (Ord k, MonadIO m) => k -> m v -> LookupTable k v -> m v lookupTableM key mvalue tbl = do mv <- hasLookupTable key tbl case mv of Just value -> return value Nothing -> do value <- mvalue lookupTable key value tbl cacheInTableM :: (Ord k, MonadIO m) => LookupTable k v -> k -> m v -> m v cacheInTableM tbl key mvalue = lookupTableM key mvalue tbl hasLookupTable :: (Ord k, MonadIO m) => k -> LookupTable k v -> m (Maybe v) hasLookupTable key tbl = liftIO $ withMVar tbl $ return . M.lookup key | Make function caching results in @LookupTable@ cachedInTable :: (Ord k, MonadIO m) => LookupTable k v -> (k -> m v) -> k -> m v cachedInTable tbl fn key = cacheInTableM tbl key (fn key) insertTable :: (Ord k, MonadIO m) => k -> v -> LookupTable k v -> m v insertTable key value tbl = liftIO $ modifyMVar tbl $ \tbl' -> return (M.insert key value tbl', value) insertTableM :: (Ord k, MonadIO m) => k -> m v -> LookupTable k v -> m v insertTableM key mvalue tbl = do value <- mvalue insertTable key value tbl storeInTable :: (Ord k, MonadIO m) => LookupTable k v -> k -> v -> m v storeInTable tbl key value = insertTable key value tbl storeInTableM :: (Ord k, MonadIO m) => LookupTable k v -> k -> m v -> m v storeInTableM tbl key mvalue = insertTableM key mvalue tbl
e404e1ab505b4ed6d8a03f31d55e72802a41af42b4566420c1c1acf77a6aec3c
sysbio-bioinf/avatar
gene_data.clj
Copyright ( c ) . All rights reserved . ; The use and distribution terms for this software are covered by the Eclipse Public License 2.0 ( -v20.html ) ; which can be found in the file LICENSE at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns avatar.data.gene-data (:require [avatar.util :as u] [clojure.data.int-map :as im] [avatar.algorithms.common :as c] [clojure.string :as str] [avatar.algorithms.score :as score])) (defn filter-gene-indices [pred, {:keys [gene-list] :as gene-sample-data}] (persistent! (u/reduce-indexed (fn [gene-indices, index, gene] (cond-> gene-indices (pred gene) (conj! index))) (transient (im/dense-int-set)) gene-list))) (defn ->every-alteration-type? "Returns a predicate that checks whether the given predicate holds for all of the specified alteration types." [predicate-fn, alteration-types] (fn check [{:keys [alteration-data] :as gene-data}] (reduce (fn [result, alteration-type] (if (predicate-fn (get alteration-data alteration-type)) result ; short-circuiting false (reduced false))) true alteration-types))) (defn ->some-alteration-type? "Returns a predicate that checks whether the given predicate holds for some of the specified alteration types." [predicate-fn, alteration-types] (fn check [{:keys [alteration-data] :as gene-data}] (reduce (fn [result, alteration-type] (if (predicate-fn (get alteration-data alteration-type)) ; short-circuiting true (reduced true) result)) false alteration-types))) (defn find-genes-without-alterations [alteration-types, gene-sample-data] (filter-gene-indices (->every-alteration-type? (fn [{:keys [alterations]}] (zero? (count alterations))) alteration-types), gene-sample-data)) (defn find-samples-without-clinical-data [{:keys [clinical-data-map, sample-count] :as gene-sample-data}] (persistent! (reduce (fn [result-set, sample-index] (cond-> result-set (empty? (get clinical-data-map sample-index)) (conj! sample-index))) (transient #{}) (range sample-count)))) (defn find-genes-in-alteration-count-range [alteration-types, ^long min-alterations, ^long max-alterations, gene-sample-data] (filter-gene-indices (->every-alteration-type? (fn [{:keys [alterations]}] (<= min-alterations (count alterations) max-alterations)) alteration-types), gene-sample-data)) (defn find-genes-outside-alteration-count-range [alteration-types, ^long min-alterations, ^long max-alterations, gene-sample-data] (filter-gene-indices (->some-alteration-type? (fn [{:keys [alterations]}] (let [n (count alterations)] (or (< n min-alterations) (< max-alterations n)))) alteration-types), gene-sample-data)) (defn find-samples-without-alterations [alteration-types, {:keys [gene-list, sample-count] :as gene-sample-data}] (let [samples-with-alterations (->> alteration-types (mapv (fn [alteration-type] ; determine samples with alterations for the given type (->> gene-list (mapv #(get-in % [:alteration-data, alteration-type, :alterations])) (reduce im/union (im/dense-int-set))))) ; samples with alterations in any given type (reduce im/union))] ; determine samples without alterations in all alteration types (im/difference (c/populated-dense-int-set sample-count) samples-with-alterations))) (defn deletion-renaming-permuation [^long sample-count, samples-to-delete] (let [samples-to-delete (set samples-to-delete)] (loop [old-sample-index 0, new-sample-index 0, sample-renaming (transient [])] (if (< old-sample-index sample-count) (if (contains? samples-to-delete old-sample-index) (recur (unchecked-inc old-sample-index), new-sample-index, (conj! sample-renaming nil)) (recur (unchecked-inc old-sample-index), (unchecked-inc new-sample-index), (conj! sample-renaming new-sample-index))) (persistent! sample-renaming))))) (defn delete-gene-alterations "Create a new bitset where the alterations of the samples are shifted according to the given renaming map. Alterations of samples that do not occur in the renaming map are discarded." [alteration-set, sample-renaming-vec] (let [sample-count (count sample-renaming-vec)] (persistent! (reduce (fn [result-bitset, old-sample-index] (if-let [new-sample-index (when (< old-sample-index sample-count) (nth sample-renaming-vec old-sample-index))] (conj! result-bitset new-sample-index) result-bitset)) (transient (im/dense-int-set)) alteration-set)))) (defn delete-alterations "Deletes the alterations and rearranges the alteration according to the given sample renaming." [{:keys [alteration-type-set] :as gene-sample-data}, sample-renaming-vec] (update-in gene-sample-data [:gene-list] (fn [gene-list] (persistent! (reduce (fn [new-gene-list, gene-data] (conj! new-gene-list ; delete from every alteration type (reduce (fn [gene-data, alteration-type] (update-in gene-data [:alteration-data, alteration-type] #(-> % (update-in [:alterations] delete-gene-alterations sample-renaming-vec) (update-in [:missing-values] delete-gene-alterations sample-renaming-vec)))) gene-data alteration-type-set))) (transient []) gene-list))))) (defn delete-samples-from-permutation [{{:keys [column->sample]} :sample-permutation, :as gene-sample-data}, sample-renaming-vec] (let [new-column->sample (persistent! (reduce (fn [new-column->sample, old-sample-index] (if-let [new-sample-index (nth sample-renaming-vec old-sample-index)] ; rename sample in the current column (conj! new-column->sample new-sample-index) ; "delete" sample from the column - the column wil be taken by the next not delete sample new-column->sample)) (transient []) column->sample))] (-> gene-sample-data (update-in [:sample-permutation] assoc :column->sample new-column->sample, :sample->column (u/inverse-permutation new-column->sample)) (assoc :sample-count (count new-column->sample))))) (defn delete-samples-from-map [gene-sample-data, map-attribute-kw, sample-renaming-vec] (update-in gene-sample-data [map-attribute-kw] (fn [old-sample-map] (persistent! (u/reduce-indexed (fn [new-sample-map, old-sample-index, new-sample-index] ; if not deleted, rename sample in group map (cond-> new-sample-map new-sample-index (assoc! new-sample-index (get old-sample-map old-sample-index)))) (transient {}) sample-renaming-vec))))) (defn delete-samples-from-vector [gene-sample-data, vector-attribute-kw, sample-renaming-vec] (let [n (reduce #(cond-> %1 %2 inc) 0 sample-renaming-vec)] (update-in gene-sample-data [vector-attribute-kw] (fn [old-sample-vector] (persistent! (u/reduce-indexed (fn [new-sample-vector, old-sample-index, new-sample-index] ; if not deleted, rename sample in group map (cond-> new-sample-vector new-sample-index (assoc! new-sample-index (get old-sample-vector old-sample-index)))) (transient (vec (range n))) sample-renaming-vec)))))) (defn delete-samples [{:keys [sample-count], :as gene-sample-data}, selected-samples] (if (seq selected-samples) (let [sample-renaming-vec (deletion-renaming-permuation sample-count, selected-samples)] (-> gene-sample-data (delete-alterations sample-renaming-vec) (delete-samples-from-permutation sample-renaming-vec) (delete-samples-from-vector :sample-id-vec, sample-renaming-vec) (delete-samples-from-map :sample-group-map, sample-renaming-vec) (delete-samples-from-map :clinical-data-map, sample-renaming-vec))) gene-sample-data)) (defn reduce-over-all-alteration-data "Apply the given function in a reduce over all alteration types and all genes for each iteration type. The function is called as (f result alteration-type, gene-alteration-map). Note, that (reduced something) stops only the reduction for the current alteration type." [f, init, {:keys [alteration-type-set, gene-list] :as gene-sample-data}] (reduce (fn [result, alteration-type] (reduce (fn [result, gene-data] (let [alteration-map (get-in gene-data [:alteration-data, alteration-type])] (f result, alteration-type, alteration-map))) result gene-list)) init alteration-type-set)) (defn group->size-map [group-type, {:keys [sample-group-map, gene-list] :as gene-sample-data}] (let [group-list (case group-type :sample (vals sample-group-map) :gene (mapv :group gene-list))] (persistent! (reduce (fn [result-map, group] (cond-> result-map group (u/update! group (fnil inc 0)))) (transient {}) group-list)))) (defn find-gene-indices [gene-list, gene-search-set] (let [gene-search-set (if (set? gene-search-set) gene-search-set (set gene-search-set))] (persistent! (u/reduce-indexed (fn [result-vec, index, gene] (cond-> result-vec (contains? gene-search-set gene) (conj! index))) (transient []) gene-list)))) (defn find-gene-indices-by-gene-id [gene-list, gene-id-search-set] (let [gene-id-search-set (if (set? gene-id-search-set) gene-id-search-set (set gene-id-search-set))] (persistent! (u/reduce-indexed (fn [result-vec, index, gene] (cond-> result-vec (contains? gene-id-search-set (:gene-id gene)) (conj! index))) (transient []) gene-list)))) (defn clinical-attribute-coverage "Returns a map that contains a set of sample indices per clinical attribute indicating the samples that have values for the corresponding attribute." [{:keys [clinical-data-map] :as gene-sample-data}] (persistent! (reduce-kv (fn [coverage-map, sample-index, sample-attribute-map] (reduce (fn [coverage-map, attribute] (u/update-in! coverage-map [attribute] (fnil conj (im/dense-int-set)) sample-index)) coverage-map (keys sample-attribute-map))) (transient {}) clinical-data-map))) (def ^:const alteration-type-order-map (zipmap [:mutation-data, :fusion-data, :expression-data, :methylation-data] (range))) (def ^:const alteration-type-set (-> alteration-type-order-map keys set)) (defn sort-alteration-types [alteration-type-coll] (vec (sort-by alteration-type-order-map alteration-type-coll))) (defn sample-groups [{:keys [sample-group-map] :as gene-sample-data}] (persistent! (reduce-kv (fn [group-set, _, group] (conj! group-set group)) (transient #{}) sample-group-map))) (defn alteration-type-str [alteration-type] (-> alteration-type name (str/replace #"-" " "))) (defn gene-count [{:keys [gene-list] :as gene-sample-data}] (count gene-list)) (defn sample-count [gene-sample-data] (:sample-count gene-sample-data)) (defn alteration-contingency-tables [{:keys [sample-group-map, gene-list] :as gene-sample-data}] (let [grouped-samples (u/inverse-bit-map sample-group-map), groups (->> grouped-samples keys sort vec)] {:columns (vec (mapcat (fn [group] [(str group " altered") (str group " unaltered")]) groups)) :rows (mapv (fn [{:keys [alterations, gene]}] {:gene gene, :contingency-table (persistent! (reduce (fn [gene-row, group] (let [samples (get grouped-samples group) altered (count (im/intersection alterations, samples)) unaltered (- (count samples) altered)] (-> gene-row (conj! altered) (conj! unaltered)))) (transient []) groups))}) gene-list)})) (defn sample-group-size "Determine the number of samples in the given group. If no group is specified, the total number of samples is returned (assuming that all samples have a key in the given map)." [sample-group-map, select-only-for-sample-group] (if select-only-for-sample-group (->> sample-group-map vals (filter #(= % select-only-for-sample-group)) count) (count sample-group-map))) (defn remove-genes-with-less-alterations [^long minimum-alteration-count, gene-list] (filterv (fn [{:keys [alterations]}] (>= (count alterations) minimum-alteration-count)) gene-list)) (defn fixed? [{:keys [order-fixed?] :as gene-data}] order-fixed?) (defn sample-count-in-group ^long [sample-group, sample-group-map] (if sample-group (reduce-kv (fn [n, _, group] (cond-> n (= group sample-group) inc)) 0 sample-group-map) (count sample-group-map))) (defn relative-coverage ^double [alteration-type, sample-group, {:keys [gene-list, sample-group-map] :as gene-sample-data}] (let [gene-list (->> gene-list (c/select-alterations-in-gene-list alteration-type) (c/maybe-remove-sample-alterations-of-other-groups sample-group, sample-group-map)) max-coverage (sample-count-in-group sample-group, sample-group-map)] (/ (score/total-coverage :alterations, gene-list) (double max-coverage)))) (defn mean-overlap ^double [alteration-type, sample-group, {:keys [gene-list, sample-group-map] :as gene-sample-data}] (let [gene-list (->> gene-list (c/select-alterations-in-gene-list alteration-type) (c/maybe-remove-sample-alterations-of-other-groups sample-group, sample-group-map)) sample-count (sample-count-in-group sample-group, sample-group-map)] (/ (score/total-overlap :alterations, gene-list) (double sample-count)))) (defn gene-coverage-in-snapshot [alteration-type, snapshot] (let [{:keys [gene-list, sample-count, alteration-type-set]} (:data snapshot)] (if (contains? alteration-type-set alteration-type) (persistent! (reduce (fn [result-map, {:keys [gene, alteration-data] :as gene-data}] (assoc! result-map gene (-> (get-in alteration-data [alteration-type, :alterations]) count (* 100.0) (/ sample-count)))) (transient {}) gene-list)) (u/key-value-map :gene (constantly Double/NaN) gene-list)))) (defn objective-text [{:keys [objective, samples]}] (format "%s (%s)" (-> objective name str/capitalize) (cond (= samples :all) "all" (= samples :optimization-group) "optim. group" :else samples))) (defn objective-in-solution [selected-alteration-type, solutions, {:keys [objective, samples] :as objective-spec}] (let [objective-fn (case objective :coverage (comp #(some->> % (* 100.0) (format "%.1f%%")) (partial relative-coverage selected-alteration-type)) :overlap (comp #(some->> % (format "%.2f")) (partial mean-overlap selected-alteration-type)))] (persistent! (reduce (fn [row-map, {:keys [id, gene-sample-data, optimization-sample-group, type] :as solution}] (let [objective-value (if (contains? (:alteration-type-set gene-sample-data) selected-alteration-type) (cond (= samples :all) (objective-fn nil, gene-sample-data) (= samples :optimization-group) (if (= type :solution-item) (objective-fn optimization-sample-group, gene-sample-data) "N/A") :else (objective-fn samples, gene-sample-data)) ; snapshot does not contain the requested altertation type "N/A")] (assoc! row-map id objective-value))) (transient {:objective-text (objective-text objective-spec)}) solutions)))) (defn objective-in-snapshot [selected-alteration-type selected-snapshot solutions {:keys [objective, samples] :as objective-spec}] (let [objective-fn (case objective :coverage (comp #(some->> % (* 100.0) (format "%.1f%%")) (partial relative-coverage selected-alteration-type)) :overlap (comp #(some->> % (format "%.2f")) (partial mean-overlap selected-alteration-type))) sample-group-set (-> selected-snapshot (get-in [:data, :sample-group-map]) vals set)] (persistent! (reduce (fn [row-map, {:keys [id, optimization-sample-group, type] {solution-gene-list :gene-list} :gene-sample-data :as solution}] (let [solution-gene-indices (find-gene-indices-by-gene-id (get-in selected-snapshot [:data, :gene-list]) (into #{} (map :gene-id) solution-gene-list)) filtered-snapshot-gene-sample-data (update (:data selected-snapshot) :gene-list (partial u/filter-by-index solution-gene-indices)) objective-value (if (contains? (:alteration-type-set filtered-snapshot-gene-sample-data) selected-alteration-type) (cond (= samples :all) (objective-fn nil, filtered-snapshot-gene-sample-data) (= samples :optimization-group) (if (and (= type :solution-item) (or (nil? optimization-sample-group) (contains? sample-group-set optimization-sample-group))) (objective-fn optimization-sample-group, filtered-snapshot-gene-sample-data) "N/A") :else (if (contains? sample-group-set samples) (objective-fn samples, filtered-snapshot-gene-sample-data) "N/A")) ; snapshot does not contain the requested altertation type "N/A")] (assoc! row-map id objective-value))) (transient {:objective-text (objective-text objective-spec)}) solutions)))) (defn sample-indexes-by-id [{:keys [sample-id-vec] :as gene-sample-data}, sample-ids] (let [sample-id-set (set sample-ids)] (persistent! (u/reduce-indexed (fn [index-set, index, sample-id] (cond-> index-set (contains? sample-id-set, sample-id) (conj! index))) (transient #{}) sample-id-vec)))) (defn delete-samples-by-id [gene-sample-data, sample-ids] (delete-samples gene-sample-data, (sample-indexes-by-id gene-sample-data, sample-ids)))
null
https://raw.githubusercontent.com/sysbio-bioinf/avatar/cbf9968485f96fb61725aaa7381dba53624d6189/src/clojure/avatar/data/gene_data.clj
clojure
The use and distribution terms for this software are covered by the which can be found in the file LICENSE at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software. short-circuiting false short-circuiting true determine samples with alterations for the given type samples with alterations in any given type determine samples without alterations in all alteration types delete from every alteration type rename sample in the current column "delete" sample from the column - the column wil be taken by the next not delete sample if not deleted, rename sample in group map if not deleted, rename sample in group map snapshot does not contain the requested altertation type snapshot does not contain the requested altertation type
Copyright ( c ) . All rights reserved . Eclipse Public License 2.0 ( -v20.html ) (ns avatar.data.gene-data (:require [avatar.util :as u] [clojure.data.int-map :as im] [avatar.algorithms.common :as c] [clojure.string :as str] [avatar.algorithms.score :as score])) (defn filter-gene-indices [pred, {:keys [gene-list] :as gene-sample-data}] (persistent! (u/reduce-indexed (fn [gene-indices, index, gene] (cond-> gene-indices (pred gene) (conj! index))) (transient (im/dense-int-set)) gene-list))) (defn ->every-alteration-type? "Returns a predicate that checks whether the given predicate holds for all of the specified alteration types." [predicate-fn, alteration-types] (fn check [{:keys [alteration-data] :as gene-data}] (reduce (fn [result, alteration-type] (if (predicate-fn (get alteration-data alteration-type)) result (reduced false))) true alteration-types))) (defn ->some-alteration-type? "Returns a predicate that checks whether the given predicate holds for some of the specified alteration types." [predicate-fn, alteration-types] (fn check [{:keys [alteration-data] :as gene-data}] (reduce (fn [result, alteration-type] (if (predicate-fn (get alteration-data alteration-type)) (reduced true) result)) false alteration-types))) (defn find-genes-without-alterations [alteration-types, gene-sample-data] (filter-gene-indices (->every-alteration-type? (fn [{:keys [alterations]}] (zero? (count alterations))) alteration-types), gene-sample-data)) (defn find-samples-without-clinical-data [{:keys [clinical-data-map, sample-count] :as gene-sample-data}] (persistent! (reduce (fn [result-set, sample-index] (cond-> result-set (empty? (get clinical-data-map sample-index)) (conj! sample-index))) (transient #{}) (range sample-count)))) (defn find-genes-in-alteration-count-range [alteration-types, ^long min-alterations, ^long max-alterations, gene-sample-data] (filter-gene-indices (->every-alteration-type? (fn [{:keys [alterations]}] (<= min-alterations (count alterations) max-alterations)) alteration-types), gene-sample-data)) (defn find-genes-outside-alteration-count-range [alteration-types, ^long min-alterations, ^long max-alterations, gene-sample-data] (filter-gene-indices (->some-alteration-type? (fn [{:keys [alterations]}] (let [n (count alterations)] (or (< n min-alterations) (< max-alterations n)))) alteration-types), gene-sample-data)) (defn find-samples-without-alterations [alteration-types, {:keys [gene-list, sample-count] :as gene-sample-data}] (let [samples-with-alterations (->> alteration-types (mapv (fn [alteration-type] (->> gene-list (mapv #(get-in % [:alteration-data, alteration-type, :alterations])) (reduce im/union (im/dense-int-set))))) (reduce im/union))] (im/difference (c/populated-dense-int-set sample-count) samples-with-alterations))) (defn deletion-renaming-permuation [^long sample-count, samples-to-delete] (let [samples-to-delete (set samples-to-delete)] (loop [old-sample-index 0, new-sample-index 0, sample-renaming (transient [])] (if (< old-sample-index sample-count) (if (contains? samples-to-delete old-sample-index) (recur (unchecked-inc old-sample-index), new-sample-index, (conj! sample-renaming nil)) (recur (unchecked-inc old-sample-index), (unchecked-inc new-sample-index), (conj! sample-renaming new-sample-index))) (persistent! sample-renaming))))) (defn delete-gene-alterations "Create a new bitset where the alterations of the samples are shifted according to the given renaming map. Alterations of samples that do not occur in the renaming map are discarded." [alteration-set, sample-renaming-vec] (let [sample-count (count sample-renaming-vec)] (persistent! (reduce (fn [result-bitset, old-sample-index] (if-let [new-sample-index (when (< old-sample-index sample-count) (nth sample-renaming-vec old-sample-index))] (conj! result-bitset new-sample-index) result-bitset)) (transient (im/dense-int-set)) alteration-set)))) (defn delete-alterations "Deletes the alterations and rearranges the alteration according to the given sample renaming." [{:keys [alteration-type-set] :as gene-sample-data}, sample-renaming-vec] (update-in gene-sample-data [:gene-list] (fn [gene-list] (persistent! (reduce (fn [new-gene-list, gene-data] (conj! new-gene-list (reduce (fn [gene-data, alteration-type] (update-in gene-data [:alteration-data, alteration-type] #(-> % (update-in [:alterations] delete-gene-alterations sample-renaming-vec) (update-in [:missing-values] delete-gene-alterations sample-renaming-vec)))) gene-data alteration-type-set))) (transient []) gene-list))))) (defn delete-samples-from-permutation [{{:keys [column->sample]} :sample-permutation, :as gene-sample-data}, sample-renaming-vec] (let [new-column->sample (persistent! (reduce (fn [new-column->sample, old-sample-index] (if-let [new-sample-index (nth sample-renaming-vec old-sample-index)] (conj! new-column->sample new-sample-index) new-column->sample)) (transient []) column->sample))] (-> gene-sample-data (update-in [:sample-permutation] assoc :column->sample new-column->sample, :sample->column (u/inverse-permutation new-column->sample)) (assoc :sample-count (count new-column->sample))))) (defn delete-samples-from-map [gene-sample-data, map-attribute-kw, sample-renaming-vec] (update-in gene-sample-data [map-attribute-kw] (fn [old-sample-map] (persistent! (u/reduce-indexed (fn [new-sample-map, old-sample-index, new-sample-index] (cond-> new-sample-map new-sample-index (assoc! new-sample-index (get old-sample-map old-sample-index)))) (transient {}) sample-renaming-vec))))) (defn delete-samples-from-vector [gene-sample-data, vector-attribute-kw, sample-renaming-vec] (let [n (reduce #(cond-> %1 %2 inc) 0 sample-renaming-vec)] (update-in gene-sample-data [vector-attribute-kw] (fn [old-sample-vector] (persistent! (u/reduce-indexed (fn [new-sample-vector, old-sample-index, new-sample-index] (cond-> new-sample-vector new-sample-index (assoc! new-sample-index (get old-sample-vector old-sample-index)))) (transient (vec (range n))) sample-renaming-vec)))))) (defn delete-samples [{:keys [sample-count], :as gene-sample-data}, selected-samples] (if (seq selected-samples) (let [sample-renaming-vec (deletion-renaming-permuation sample-count, selected-samples)] (-> gene-sample-data (delete-alterations sample-renaming-vec) (delete-samples-from-permutation sample-renaming-vec) (delete-samples-from-vector :sample-id-vec, sample-renaming-vec) (delete-samples-from-map :sample-group-map, sample-renaming-vec) (delete-samples-from-map :clinical-data-map, sample-renaming-vec))) gene-sample-data)) (defn reduce-over-all-alteration-data "Apply the given function in a reduce over all alteration types and all genes for each iteration type. The function is called as (f result alteration-type, gene-alteration-map). Note, that (reduced something) stops only the reduction for the current alteration type." [f, init, {:keys [alteration-type-set, gene-list] :as gene-sample-data}] (reduce (fn [result, alteration-type] (reduce (fn [result, gene-data] (let [alteration-map (get-in gene-data [:alteration-data, alteration-type])] (f result, alteration-type, alteration-map))) result gene-list)) init alteration-type-set)) (defn group->size-map [group-type, {:keys [sample-group-map, gene-list] :as gene-sample-data}] (let [group-list (case group-type :sample (vals sample-group-map) :gene (mapv :group gene-list))] (persistent! (reduce (fn [result-map, group] (cond-> result-map group (u/update! group (fnil inc 0)))) (transient {}) group-list)))) (defn find-gene-indices [gene-list, gene-search-set] (let [gene-search-set (if (set? gene-search-set) gene-search-set (set gene-search-set))] (persistent! (u/reduce-indexed (fn [result-vec, index, gene] (cond-> result-vec (contains? gene-search-set gene) (conj! index))) (transient []) gene-list)))) (defn find-gene-indices-by-gene-id [gene-list, gene-id-search-set] (let [gene-id-search-set (if (set? gene-id-search-set) gene-id-search-set (set gene-id-search-set))] (persistent! (u/reduce-indexed (fn [result-vec, index, gene] (cond-> result-vec (contains? gene-id-search-set (:gene-id gene)) (conj! index))) (transient []) gene-list)))) (defn clinical-attribute-coverage "Returns a map that contains a set of sample indices per clinical attribute indicating the samples that have values for the corresponding attribute." [{:keys [clinical-data-map] :as gene-sample-data}] (persistent! (reduce-kv (fn [coverage-map, sample-index, sample-attribute-map] (reduce (fn [coverage-map, attribute] (u/update-in! coverage-map [attribute] (fnil conj (im/dense-int-set)) sample-index)) coverage-map (keys sample-attribute-map))) (transient {}) clinical-data-map))) (def ^:const alteration-type-order-map (zipmap [:mutation-data, :fusion-data, :expression-data, :methylation-data] (range))) (def ^:const alteration-type-set (-> alteration-type-order-map keys set)) (defn sort-alteration-types [alteration-type-coll] (vec (sort-by alteration-type-order-map alteration-type-coll))) (defn sample-groups [{:keys [sample-group-map] :as gene-sample-data}] (persistent! (reduce-kv (fn [group-set, _, group] (conj! group-set group)) (transient #{}) sample-group-map))) (defn alteration-type-str [alteration-type] (-> alteration-type name (str/replace #"-" " "))) (defn gene-count [{:keys [gene-list] :as gene-sample-data}] (count gene-list)) (defn sample-count [gene-sample-data] (:sample-count gene-sample-data)) (defn alteration-contingency-tables [{:keys [sample-group-map, gene-list] :as gene-sample-data}] (let [grouped-samples (u/inverse-bit-map sample-group-map), groups (->> grouped-samples keys sort vec)] {:columns (vec (mapcat (fn [group] [(str group " altered") (str group " unaltered")]) groups)) :rows (mapv (fn [{:keys [alterations, gene]}] {:gene gene, :contingency-table (persistent! (reduce (fn [gene-row, group] (let [samples (get grouped-samples group) altered (count (im/intersection alterations, samples)) unaltered (- (count samples) altered)] (-> gene-row (conj! altered) (conj! unaltered)))) (transient []) groups))}) gene-list)})) (defn sample-group-size "Determine the number of samples in the given group. If no group is specified, the total number of samples is returned (assuming that all samples have a key in the given map)." [sample-group-map, select-only-for-sample-group] (if select-only-for-sample-group (->> sample-group-map vals (filter #(= % select-only-for-sample-group)) count) (count sample-group-map))) (defn remove-genes-with-less-alterations [^long minimum-alteration-count, gene-list] (filterv (fn [{:keys [alterations]}] (>= (count alterations) minimum-alteration-count)) gene-list)) (defn fixed? [{:keys [order-fixed?] :as gene-data}] order-fixed?) (defn sample-count-in-group ^long [sample-group, sample-group-map] (if sample-group (reduce-kv (fn [n, _, group] (cond-> n (= group sample-group) inc)) 0 sample-group-map) (count sample-group-map))) (defn relative-coverage ^double [alteration-type, sample-group, {:keys [gene-list, sample-group-map] :as gene-sample-data}] (let [gene-list (->> gene-list (c/select-alterations-in-gene-list alteration-type) (c/maybe-remove-sample-alterations-of-other-groups sample-group, sample-group-map)) max-coverage (sample-count-in-group sample-group, sample-group-map)] (/ (score/total-coverage :alterations, gene-list) (double max-coverage)))) (defn mean-overlap ^double [alteration-type, sample-group, {:keys [gene-list, sample-group-map] :as gene-sample-data}] (let [gene-list (->> gene-list (c/select-alterations-in-gene-list alteration-type) (c/maybe-remove-sample-alterations-of-other-groups sample-group, sample-group-map)) sample-count (sample-count-in-group sample-group, sample-group-map)] (/ (score/total-overlap :alterations, gene-list) (double sample-count)))) (defn gene-coverage-in-snapshot [alteration-type, snapshot] (let [{:keys [gene-list, sample-count, alteration-type-set]} (:data snapshot)] (if (contains? alteration-type-set alteration-type) (persistent! (reduce (fn [result-map, {:keys [gene, alteration-data] :as gene-data}] (assoc! result-map gene (-> (get-in alteration-data [alteration-type, :alterations]) count (* 100.0) (/ sample-count)))) (transient {}) gene-list)) (u/key-value-map :gene (constantly Double/NaN) gene-list)))) (defn objective-text [{:keys [objective, samples]}] (format "%s (%s)" (-> objective name str/capitalize) (cond (= samples :all) "all" (= samples :optimization-group) "optim. group" :else samples))) (defn objective-in-solution [selected-alteration-type, solutions, {:keys [objective, samples] :as objective-spec}] (let [objective-fn (case objective :coverage (comp #(some->> % (* 100.0) (format "%.1f%%")) (partial relative-coverage selected-alteration-type)) :overlap (comp #(some->> % (format "%.2f")) (partial mean-overlap selected-alteration-type)))] (persistent! (reduce (fn [row-map, {:keys [id, gene-sample-data, optimization-sample-group, type] :as solution}] (let [objective-value (if (contains? (:alteration-type-set gene-sample-data) selected-alteration-type) (cond (= samples :all) (objective-fn nil, gene-sample-data) (= samples :optimization-group) (if (= type :solution-item) (objective-fn optimization-sample-group, gene-sample-data) "N/A") :else (objective-fn samples, gene-sample-data)) "N/A")] (assoc! row-map id objective-value))) (transient {:objective-text (objective-text objective-spec)}) solutions)))) (defn objective-in-snapshot [selected-alteration-type selected-snapshot solutions {:keys [objective, samples] :as objective-spec}] (let [objective-fn (case objective :coverage (comp #(some->> % (* 100.0) (format "%.1f%%")) (partial relative-coverage selected-alteration-type)) :overlap (comp #(some->> % (format "%.2f")) (partial mean-overlap selected-alteration-type))) sample-group-set (-> selected-snapshot (get-in [:data, :sample-group-map]) vals set)] (persistent! (reduce (fn [row-map, {:keys [id, optimization-sample-group, type] {solution-gene-list :gene-list} :gene-sample-data :as solution}] (let [solution-gene-indices (find-gene-indices-by-gene-id (get-in selected-snapshot [:data, :gene-list]) (into #{} (map :gene-id) solution-gene-list)) filtered-snapshot-gene-sample-data (update (:data selected-snapshot) :gene-list (partial u/filter-by-index solution-gene-indices)) objective-value (if (contains? (:alteration-type-set filtered-snapshot-gene-sample-data) selected-alteration-type) (cond (= samples :all) (objective-fn nil, filtered-snapshot-gene-sample-data) (= samples :optimization-group) (if (and (= type :solution-item) (or (nil? optimization-sample-group) (contains? sample-group-set optimization-sample-group))) (objective-fn optimization-sample-group, filtered-snapshot-gene-sample-data) "N/A") :else (if (contains? sample-group-set samples) (objective-fn samples, filtered-snapshot-gene-sample-data) "N/A")) "N/A")] (assoc! row-map id objective-value))) (transient {:objective-text (objective-text objective-spec)}) solutions)))) (defn sample-indexes-by-id [{:keys [sample-id-vec] :as gene-sample-data}, sample-ids] (let [sample-id-set (set sample-ids)] (persistent! (u/reduce-indexed (fn [index-set, index, sample-id] (cond-> index-set (contains? sample-id-set, sample-id) (conj! index))) (transient #{}) sample-id-vec)))) (defn delete-samples-by-id [gene-sample-data, sample-ids] (delete-samples gene-sample-data, (sample-indexes-by-id gene-sample-data, sample-ids)))
7aaa09145fad1c22ad068a56573277955605f8cdcdd1d37187fcd1c56f15123d
racket/drracket
syncheck-eval-compile-time.rkt
#lang racket/base (require "private/drracket-test-util.rkt" racket/class framework) (define (main) (fire-up-drracket-and-run-tests (λ () (let ([drs (wait-for-drracket-frame)]) (set-module-language!) (do-execute drs) (queue-callback/res (λ () (preferences:set 'framework:coloring-active #f) (handler:edit-file (collection-file-path "map.rkt" "racket" "private")))) (click-check-syntax-and-check-errors drs "syncheck-eval-compile-time.rkt"))))) ;; copied from syncheck-test.rkt .... (define (click-check-syntax-and-check-errors drs test) (click-check-syntax-button drs) (wait-for-computation drs) (when (queue-callback/res (λ () (send (send drs get-definitions-text) in-edit-sequence?))) (error 'syncheck-test.rkt "still in edit sequence for ~s" test)) (let ([err (queue-callback/res (λ () (send drs syncheck:get-error-report-contents)))]) (when err (eprintf "FAILED ~s\n error report window is visible:\n ~a\n" test err)))) (define (click-check-syntax-button drs) (test:run-one (lambda () (send (send drs syncheck:get-button) command)))) (main)
null
https://raw.githubusercontent.com/racket/drracket/2d7c2cded99e630a69f05fb135d1bf7543096a23/drracket-test/tests/drracket/syncheck-eval-compile-time.rkt
racket
copied from syncheck-test.rkt ....
#lang racket/base (require "private/drracket-test-util.rkt" racket/class framework) (define (main) (fire-up-drracket-and-run-tests (λ () (let ([drs (wait-for-drracket-frame)]) (set-module-language!) (do-execute drs) (queue-callback/res (λ () (preferences:set 'framework:coloring-active #f) (handler:edit-file (collection-file-path "map.rkt" "racket" "private")))) (click-check-syntax-and-check-errors drs "syncheck-eval-compile-time.rkt"))))) (define (click-check-syntax-and-check-errors drs test) (click-check-syntax-button drs) (wait-for-computation drs) (when (queue-callback/res (λ () (send (send drs get-definitions-text) in-edit-sequence?))) (error 'syncheck-test.rkt "still in edit sequence for ~s" test)) (let ([err (queue-callback/res (λ () (send drs syncheck:get-error-report-contents)))]) (when err (eprintf "FAILED ~s\n error report window is visible:\n ~a\n" test err)))) (define (click-check-syntax-button drs) (test:run-one (lambda () (send (send drs syncheck:get-button) command)))) (main)
02a0db0f39b4f5efe940f9e1b5af9cc83ca2a9da9b095b5146b2733652efa9db
Eduap-com/WordMat
minpack-interface.lisp
;;; -*- Mode: lisp -*- Simple Maxima interface to minpack routines (in-package #-gcl #:maxima #+gcl "MAXIMA") (defmvar $debug_minpack nil "Set to true to enable debugging messages from minpack routines") (defmfun $minpack_lsquares (fcns vars init-x &key (jacobian t) (tolerance #.(sqrt double-float-epsilon))) "Minimize the sum of the squares of m functions in n unknowns (n <= m) VARS list of the variables INIT-X initial guess FCNS list of the m functions Optional keyword args (key = val) TOLERANCE tolerance in solution JACOBIAN If true, maxima computes the Jacobian directly from FCNS. If false, the Jacobian is internally computed using a forward-difference approximation. Otherwise, it is a function returning the Jacobian" (unless (and (listp fcns) (eq (caar fcns) 'mlist)) (merror "~M: ~M is not a list of functions" %%pretty-fname fcns)) (unless (and (listp vars) (eq (caar vars) 'mlist)) (merror "~M: ~M is not a list of variables" %%pretty-fname vars)) (unless (and (listp init-x) (eq (caar init-x) 'mlist)) (merror "~M: ~M is not a list of initial values" %%pretty-fname init-x)) (setf tolerance ($float tolerance)) (unless (and (realp tolerance) (plusp tolerance)) (merror "~M: tolerance must be a non-negative real number, not: ~M" %%pretty-fname tolerance)) (let* ((n (length (cdr vars))) (m (length (cdr fcns))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) ($float z)) (cdr init-x)))) (fvec (make-array m :element-type 'double-float)) (fjac (make-array (* m n) :element-type 'double-float)) (ldfjac m) (info 0) (ipvt (make-array n :element-type 'f2cl-lib:integer4)) (fv (coerce-float-fun fcns vars)) (fj (cond ((eq jacobian t) ;; T means compute it ourselves (meval `(($jacobian) ,fcns ,vars))) (jacobian Use the specified Jacobian ) (t ;; No jacobian at all nil)))) Massage the Jacobian into a function (when jacobian (setf fj (coerce-float-fun fj vars))) (cond (jacobian ;; Jacobian given (or computed by maxima), so use lmder1 (let* ((lwa (+ m (* 5 n))) (wa (make-array lwa :element-type 'double-float))) (labels ((fcn-and-jacobian (m n x fvec fjac ldfjac iflag) (declare (type f2cl-lib:integer4 m n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) (ecase iflag (1 ;; Compute function at point x, placing result in fvec ( subseq needed because sometimes ;; we're called with vector that is longer than we want . Perfectly valid Fortran , though . ) (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (unless (consp val) (merror "Unable to evaluate function at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) (when $debug_minpack (format t "f(~{~A~^, ~}) =~%[~@<~{~A~^, ~:_~}~:>]~%" (coerce x 'list) (cdr val))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val))))) (2 Compute Jacobian at point x , placing result in fjac (let ((j (apply 'funcall fj (subseq (coerce x 'list) 0 n)))) (unless (consp j) (merror "Unable to evaluate Jacobian at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) Extract out elements of Jacobian and place into ;; fjac, in column-major order. (let ((row-index 0)) (dolist (row (cdr j)) (let ((col-index 0)) (dolist (col (cdr row)) (setf (aref fjac (+ row-index (* ldfjac col-index))) (cl:float col 1d0)) (incf col-index))) (incf row-index)))))) (values m n nil nil nil ldfjac iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 ldfjac var-6 info) (minpack:lmder1 #'fcn-and-jacobian m n x fvec fjac ldfjac tolerance info ipvt wa lwa) (declare (ignore ldfjac var-0 var-1 var-2 var-3 var-4 var-5 var-6)) ;; Return a list of the solution and the info flag (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm m fvec) info))))) (t ;; No Jacobian given so we need to use differences to compute a numerical Jacobian . Use . (let* ((lwa (+ m (* 5 n) (* m n))) (wa (make-array lwa :element-type 'double-float))) (labels ((fval (m n x fvec iflag) (declare (type f2cl-lib:integer4 m n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) Compute function at point x , placing result in fvec (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (unless (consp val) (merror "Unable to evaluate function at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) (when $debug_minpack (format t "f(~{~A~^, ~}) =~%[~@<~{~A~^, ~:_~}~:>]~%" (coerce x 'list) (cdr val))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val)))) (values m n nil nil iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 info) (minpack:lmdif1 #'fval m n x fvec tolerance info ipvt wa lwa) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5)) ;; Return a list of the solution and the info flag (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm m fvec) info)))))))) (defmfun $minpack_solve (fcns vars init-x &key (jacobian t) (tolerance #.(sqrt double-float-epsilon))) "Solve the system of n equations in n unknowns VARS list of the n variables INIT-X initial guess FCNS list of the n functions Optional keyword args (key = val) TOLERANCE tolerance in solution JACOBIAN If true, maxima computes the Jacobian directly from FCNS. If false, the Jacobian is internally computed using a forward-difference approximation. Otherwise, it is a function returning the Jacobian" (unless (and (listp fcns) (eq (caar fcns) 'mlist)) (merror "~M: ~M is not a list of functions" %%pretty-fname fcns)) (unless (and (listp vars) (eq (caar vars) 'mlist)) (merror "~M: ~M is not a list of variables" %%pretty-fname vars)) (unless (and (listp init-x) (eq (caar init-x) 'mlist)) (merror "~M: ~M is not a list of initial values" %%pretty-fname init-x)) (unless (and (realp tolerance) (plusp tolerance)) (merror "~M: tolerance must be a non-negative real number, not: ~M" %%pretty-fname tolerance)) (let* ((n (length (cdr vars))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) ($float z)) (cdr init-x)))) (fvec (make-array n :element-type 'double-float)) (fjac (make-array (* n n) :element-type 'double-float)) (ldfjac n) (info 0) (fv (coerce-float-fun fcns vars)) (fj (cond ((eq jacobian t) ;; T means compute it ourselves (mfuncall '$jacobian fcns vars)) (jacobian Use the specified Jacobian ) (t ;; No jacobian at all nil)))) Massage the Jacobian into a function (when jacobian (setf fj (coerce-float-fun fj vars))) (cond (jacobian ;; Jacobian given (or computed by maxima), so use lmder1 (let* ((lwa (/ (* n (+ n 13)) 2)) (wa (make-array lwa :element-type 'double-float))) (labels ((fcn-and-jacobian (n x fvec fjac ldfjac iflag) (declare (type f2cl-lib:integer4 n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) (ecase iflag (1 ;; Compute function at point x, placing result in fvec ( subseq needed because sometimes ;; we're called with vector that is longer than we want . Perfectly valid Fortran , though . ) (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val))))) (2 Compute Jacobian at point x , placing result in fjac (let ((j (apply 'funcall fj (subseq (coerce x 'list) 0 n)))) Extract out elements of Jacobian and place into ;; fjac, in column-major order. (let ((row-index 0)) (dolist (row (cdr j)) (let ((col-index 0)) (dolist (col (cdr row)) (setf (aref fjac (+ row-index (* ldfjac col-index))) (cl:float col 1d0)) (incf col-index))) (incf row-index)))))) (values n nil nil nil ldfjac iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 ldfjac var-6 info) (minpack:hybrj1 #'fcn-and-jacobian n x fvec fjac ldfjac tolerance info wa lwa) (declare (ignore ldfjac var-0 var-1 var-2 var-3 var-4 var-6)) ;; Return a list of the solution and the info flag (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm n fvec) info))))) (t ;; No Jacobian given so we need to use differences to compute a numerical Jacobian . Use . (let* ((lwa (/ (* n (+ (* 3 n) 13)) 2)) (wa (make-array lwa :element-type 'double-float))) (labels ((fval (n x fvec iflag) (declare (type f2cl-lib:integer4 n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) Compute function at point x , placing result in fvec (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val)))) (values n nil nil iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 info) (minpack:hybrd1 #'fval n x fvec tolerance info wa lwa) (declare (ignore var-0 var-1 var-2 var-3 var-4)) ;; Return a list of the solution and the info flag (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm n fvec) info))))))))
null
https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/share/minpack/minpack-interface.lisp
lisp
-*- Mode: lisp -*- T means compute it ourselves No jacobian at all Jacobian given (or computed by maxima), so use lmder1 Compute function at point x, placing result we're called with vector that is longer than fjac, in column-major order. Return a list of the solution and the info flag No Jacobian given so we need to use differences to compute Return a list of the solution and the info flag T means compute it ourselves No jacobian at all Jacobian given (or computed by maxima), so use lmder1 Compute function at point x, placing result we're called with vector that is longer than fjac, in column-major order. Return a list of the solution and the info flag No Jacobian given so we need to use differences to compute Return a list of the solution and the info flag
Simple Maxima interface to minpack routines (in-package #-gcl #:maxima #+gcl "MAXIMA") (defmvar $debug_minpack nil "Set to true to enable debugging messages from minpack routines") (defmfun $minpack_lsquares (fcns vars init-x &key (jacobian t) (tolerance #.(sqrt double-float-epsilon))) "Minimize the sum of the squares of m functions in n unknowns (n <= m) VARS list of the variables INIT-X initial guess FCNS list of the m functions Optional keyword args (key = val) TOLERANCE tolerance in solution JACOBIAN If true, maxima computes the Jacobian directly from FCNS. If false, the Jacobian is internally computed using a forward-difference approximation. Otherwise, it is a function returning the Jacobian" (unless (and (listp fcns) (eq (caar fcns) 'mlist)) (merror "~M: ~M is not a list of functions" %%pretty-fname fcns)) (unless (and (listp vars) (eq (caar vars) 'mlist)) (merror "~M: ~M is not a list of variables" %%pretty-fname vars)) (unless (and (listp init-x) (eq (caar init-x) 'mlist)) (merror "~M: ~M is not a list of initial values" %%pretty-fname init-x)) (setf tolerance ($float tolerance)) (unless (and (realp tolerance) (plusp tolerance)) (merror "~M: tolerance must be a non-negative real number, not: ~M" %%pretty-fname tolerance)) (let* ((n (length (cdr vars))) (m (length (cdr fcns))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) ($float z)) (cdr init-x)))) (fvec (make-array m :element-type 'double-float)) (fjac (make-array (* m n) :element-type 'double-float)) (ldfjac m) (info 0) (ipvt (make-array n :element-type 'f2cl-lib:integer4)) (fv (coerce-float-fun fcns vars)) (fj (cond ((eq jacobian t) (meval `(($jacobian) ,fcns ,vars))) (jacobian Use the specified Jacobian ) (t nil)))) Massage the Jacobian into a function (when jacobian (setf fj (coerce-float-fun fj vars))) (cond (jacobian (let* ((lwa (+ m (* 5 n))) (wa (make-array lwa :element-type 'double-float))) (labels ((fcn-and-jacobian (m n x fvec fjac ldfjac iflag) (declare (type f2cl-lib:integer4 m n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) (ecase iflag (1 in fvec ( subseq needed because sometimes we want . Perfectly valid Fortran , though . ) (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (unless (consp val) (merror "Unable to evaluate function at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) (when $debug_minpack (format t "f(~{~A~^, ~}) =~%[~@<~{~A~^, ~:_~}~:>]~%" (coerce x 'list) (cdr val))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val))))) (2 Compute Jacobian at point x , placing result in fjac (let ((j (apply 'funcall fj (subseq (coerce x 'list) 0 n)))) (unless (consp j) (merror "Unable to evaluate Jacobian at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) Extract out elements of Jacobian and place into (let ((row-index 0)) (dolist (row (cdr j)) (let ((col-index 0)) (dolist (col (cdr row)) (setf (aref fjac (+ row-index (* ldfjac col-index))) (cl:float col 1d0)) (incf col-index))) (incf row-index)))))) (values m n nil nil nil ldfjac iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 ldfjac var-6 info) (minpack:lmder1 #'fcn-and-jacobian m n x fvec fjac ldfjac tolerance info ipvt wa lwa) (declare (ignore ldfjac var-0 var-1 var-2 var-3 var-4 var-5 var-6)) (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm m fvec) info))))) (t a numerical Jacobian . Use . (let* ((lwa (+ m (* 5 n) (* m n))) (wa (make-array lwa :element-type 'double-float))) (labels ((fval (m n x fvec iflag) (declare (type f2cl-lib:integer4 m n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) Compute function at point x , placing result in fvec (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (unless (consp val) (merror "Unable to evaluate function at the point ~M" (list* '(mlist) (subseq (coerce x 'list) 0 n)))) (when $debug_minpack (format t "f(~{~A~^, ~}) =~%[~@<~{~A~^, ~:_~}~:>]~%" (coerce x 'list) (cdr val))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val)))) (values m n nil nil iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 var-5 info) (minpack:lmdif1 #'fval m n x fvec tolerance info ipvt wa lwa) (declare (ignore var-0 var-1 var-2 var-3 var-4 var-5)) (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm m fvec) info)))))))) (defmfun $minpack_solve (fcns vars init-x &key (jacobian t) (tolerance #.(sqrt double-float-epsilon))) "Solve the system of n equations in n unknowns VARS list of the n variables INIT-X initial guess FCNS list of the n functions Optional keyword args (key = val) TOLERANCE tolerance in solution JACOBIAN If true, maxima computes the Jacobian directly from FCNS. If false, the Jacobian is internally computed using a forward-difference approximation. Otherwise, it is a function returning the Jacobian" (unless (and (listp fcns) (eq (caar fcns) 'mlist)) (merror "~M: ~M is not a list of functions" %%pretty-fname fcns)) (unless (and (listp vars) (eq (caar vars) 'mlist)) (merror "~M: ~M is not a list of variables" %%pretty-fname vars)) (unless (and (listp init-x) (eq (caar init-x) 'mlist)) (merror "~M: ~M is not a list of initial values" %%pretty-fname init-x)) (unless (and (realp tolerance) (plusp tolerance)) (merror "~M: tolerance must be a non-negative real number, not: ~M" %%pretty-fname tolerance)) (let* ((n (length (cdr vars))) (x (make-array n :element-type 'double-float :initial-contents (mapcar #'(lambda (z) ($float z)) (cdr init-x)))) (fvec (make-array n :element-type 'double-float)) (fjac (make-array (* n n) :element-type 'double-float)) (ldfjac n) (info 0) (fv (coerce-float-fun fcns vars)) (fj (cond ((eq jacobian t) (mfuncall '$jacobian fcns vars)) (jacobian Use the specified Jacobian ) (t nil)))) Massage the Jacobian into a function (when jacobian (setf fj (coerce-float-fun fj vars))) (cond (jacobian (let* ((lwa (/ (* n (+ n 13)) 2)) (wa (make-array lwa :element-type 'double-float))) (labels ((fcn-and-jacobian (n x fvec fjac ldfjac iflag) (declare (type f2cl-lib:integer4 n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) (ecase iflag (1 in fvec ( subseq needed because sometimes we want . Perfectly valid Fortran , though . ) (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val))))) (2 Compute Jacobian at point x , placing result in fjac (let ((j (apply 'funcall fj (subseq (coerce x 'list) 0 n)))) Extract out elements of Jacobian and place into (let ((row-index 0)) (dolist (row (cdr j)) (let ((col-index 0)) (dolist (col (cdr row)) (setf (aref fjac (+ row-index (* ldfjac col-index))) (cl:float col 1d0)) (incf col-index))) (incf row-index)))))) (values n nil nil nil ldfjac iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 ldfjac var-6 info) (minpack:hybrj1 #'fcn-and-jacobian n x fvec fjac ldfjac tolerance info wa lwa) (declare (ignore ldfjac var-0 var-1 var-2 var-3 var-4 var-6)) (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm n fvec) info))))) (t a numerical Jacobian . Use . (let* ((lwa (/ (* n (+ (* 3 n) 13)) 2)) (wa (make-array lwa :element-type 'double-float))) (labels ((fval (n x fvec iflag) (declare (type f2cl-lib:integer4 n ldfjac iflag) (type (cl:array double-float (*)) x fvec fjac)) Compute function at point x , placing result in fvec (let ((val (apply 'funcall fv (subseq (coerce x 'list) 0 n)))) (replace fvec (mapcar #'(lambda (z) (cl:float z 1d0)) (cdr val)))) (values n nil nil iflag))) (multiple-value-bind (var-0 var-1 var-2 var-3 var-4 info) (minpack:hybrd1 #'fval n x fvec tolerance info wa lwa) (declare (ignore var-0 var-1 var-2 var-3 var-4)) (list '(mlist) (list* '(mlist) (coerce x 'list)) (minpack:enorm n fvec) info))))))))
d01efe6cc0d2b912778e63318cf238fbe69ad7b65d391a2427735a0c4cfca89b
portkey-cloud/aws-clj-sdk
machinelearning.clj
(ns portkey.aws.machinelearning (:require [portkey.aws])) (def endpoints '{"eu-west-1" {:credential-scope {:service "machinelearning", :region "eu-west-1"}, :ssl-common-name "machinelearning.eu-west-1.amazonaws.com", :endpoint "-west-1.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "machinelearning", :region "us-east-1"}, :ssl-common-name "machinelearning.us-east-1.amazonaws.com", :endpoint "-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
null
https://raw.githubusercontent.com/portkey-cloud/aws-clj-sdk/10623a5c86bd56c8b312f56b76ae5ff52c26a945/src/portkey/aws/machinelearning.clj
clojure
(ns portkey.aws.machinelearning (:require [portkey.aws])) (def endpoints '{"eu-west-1" {:credential-scope {:service "machinelearning", :region "eu-west-1"}, :ssl-common-name "machinelearning.eu-west-1.amazonaws.com", :endpoint "-west-1.amazonaws.com", :signature-version :v4}, "us-east-1" {:credential-scope {:service "machinelearning", :region "us-east-1"}, :ssl-common-name "machinelearning.us-east-1.amazonaws.com", :endpoint "-east-1.amazonaws.com", :signature-version :v4}}) (comment TODO support "json")
96032a097c5a476e2e8510f51142d2295dfb1d473ac5432293ba1a178273e59d
SNePS/SNePS2
imports.lisp
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*- Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : imports.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $ ;; This file is part of SNePS. $ BEGIN LICENSE$ The contents of this file are subject to the University at Buffalo Public License Version 1.0 ( the " License " ) ; you may ;;; not use this file except in compliance with the License. You ;;; may obtain a copy of the License at ;;; . edu/sneps/Downloads/ubpl.pdf. ;;; Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express ;;; or implied. See the License for the specific language gov ;;; erning rights and limitations under the License. ;;; The Original Code is SNePS 2.8 . ;;; The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . ;;; Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :sneps) ;;; Import the following symbols into the SNePS Package. #+symbolics (shadowing-import 'scl::beep (find-package 'sneps)) (import 'snip:act) (import 'snip:*infertrace*)
null
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/sneps/imports.lisp
lisp
Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*- This file is part of SNePS. you may not use this file except in compliance with the License. You may obtain a copy of the License at . edu/sneps/Downloads/ubpl.pdf. or implied. See the License for the specific language gov erning rights and limitations under the License. Import the following symbols into the SNePS Package.
Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : imports.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $ $ BEGIN LICENSE$ The contents of this file are subject to the University at Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express The Original Code is SNePS 2.8 . The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :sneps) #+symbolics (shadowing-import 'scl::beep (find-package 'sneps)) (import 'snip:act) (import 'snip:*infertrace*)
c98ffeb980b5f2205c8f96787afbecd896c5b0aef1c486a935e639e5a8799344
KestrelInstitute/Specware
seal-parser.lisp
-*- Mode : LISP ; Package : Parser4 ; Base : 10 ; Syntax : Common - Lisp -*- (in-package :Parser4) (defun load-parser (file &key (name (intern (format nil "PARSER-~D" (incf *gensym-counter*)) "KEYWORD")) (case-sensitive? nil) (rule-package (find-package "KEYWORD")) (symbol-package common-lisp::*package*)) (let ((new-parser (new-parser name :case-sensitive? case-sensitive? :rule-package rule-package :symbol-package symbol-package))) (setq *current-parser* new-parser) (when (null (pathname-type file)) (let ((fasl-file (make-pathname :type Specware::*fasl-type* :defaults file)) (lisp-file (make-pathname :type "lisp" :defaults file))) (unless (null lisp-file) (when (<= (or (file-write-date fasl-file) 0) (file-write-date lisp-file)) (compile-file lisp-file))))) (load file) ; see parse-add-rules.lisp (setf (parser-keywords-are-keywords-only? new-parser) t) (seal-parser new-parser) (when-debugging (comment "New parser is also in PARSER4::*CURRENT-PARSER*")) new-parser)) (defun seal-parser (parser) ;; (when-debugging (comment "============================================================================") (comment "Sealing parser") (comment "=================================")) ;; (when-debugging (verify-all-parser-rule-references parser)) (install-rules parser) ; sets parser-rules (bypass-superfluous-anyof-rules parser) (bypass-id-rules parser) (install-reductions parser) ; sets parser-ht-name-to-reductions (install-parents parser) ; sets parser-rule-reductions (install-bvs parser) ; sets parser-bv-size parser - scratch - bv , parser - zero - bv ; parser-rule-bvi ; parser-rule-item-possible-handles-bv ;; (install-default-semantic-alist parser) ; sets parser-default-semantic-alist (install-special-rules parser) ; finds toplevel, symbol, number, string, etc. ;; (propagate-optionals parser) ; items referencing optional rules become optional themselves (install-pprinters parser) ; sets parser-ht-expr-to-pprint, ; parser-ht-type-to-pprint, ; parser-ht-car-to-pprint ;; (when-debugging (comment "============================================================================")) ) ;;; ==================== (defun install-rules (parser) (when-debugging (comment "=================================") (comment "Installing rules") (comment "- - - - - - - - - - - - - - - - -")) (maphash #'(lambda (ignore-name rule) (declare (ignore ignore-name)) ;; (when (parental-parser-rule? rule)) (push rule (parser-rules parser)) ;; parser-total-rule-count is used only for commentary (incf (parser-total-rule-count parser))) (parser-ht-name-to-rule parser))) ;;; ==================== (defun bypass-id-rules (parser) (when-debugging (comment "=================================") (comment "Bypassing id rules") (comment "- - - - - - - - - - - - - - - - -")) ;; efficiency hack to eliminate id reductions ;; (A) avoids those reductions ;; (B) makes desired-bv's smaller (hence more efficeient) since id rules become irrelevant (dolist (rule (parser-rules parser)) (bypass-children-id-rules parser rule))) (defun bypass-children-id-rules (parser rule) (debugging-comment "Replacing any id rules in ~20A ~S" (structure-type-of rule) (parser-rule-name rule)) (do-parser-rule-items (item rule) (unless (null item) (bypass-any-id-rule-in-item parser item)))) (defun bypass-any-id-rule-in-item (parser item) (when-debugging (unless (parser-rule-item-p item) (break "Expected parser-rule-item: ~S" item))) (let* ((child-rule-name (parser-rule-item-rule item)) #+DEBUG-PARSER (original-name child-rule-name) (child-rule (find-parser-rule parser child-rule-name))) (when (parser-id-rule-p child-rule) (loop while (parser-id-rule-p child-rule) do (setq child-rule-name (parser-id-rule-subrule child-rule)) (setq child-rule (find-parser-rule parser child-rule-name))) (debugging-comment " Replacing ~S by ~S" original-name child-rule-name) (setf (parser-rule-item-rule item) child-rule-name)))) ;;; ==================== (defun bypass-superfluous-anyof-rules (parser &optional (round 0)) (when-debugging (comment "=================================") (comment "Bypassing superfluous anyof rules, round ~D" round) (comment "- - - - - - - - - - - - - - - - -")) (let ((revised? nil)) (dolist (rule (parser-rules parser)) (when (bypass-children-superfluous-anyof-rules parser rule) (setq revised? t))) (when revised? (bypass-superfluous-anyof-rules parser (1+ round))))) (defun bypass-children-superfluous-anyof-rules (parser rule) (when (parser-anyof-rule-p rule) (debugging-comment "Replacing any superfluous anyof rules in ~20A ~S" (structure-type-of rule) (parser-rule-name rule)) (let ((new-items nil) (revised? nil)) (do-parser-rule-items (item rule) ;; why distinguish (t nil) from (nil ...) ? ;; is it merely because the former is an error? (multiple-value-bind (expanded? revised-items) (expand-anyof-rule-in-item parser item) (when expanded? (setq revised? t)) (setq new-items (if expanded? (progn (when (null revised-items) (warn "Null revised items for ~A when bypassing superfluous anyof rules for ~A" (parser-rule-item-rule item) (parser-rule-name rule))) (append revised-items new-items)) (cons item new-items))))) (when revised? (setf (parser-rule-items rule) (coerce new-items 'vector))) revised?))) (defun expand-anyof-rule-in-item (parser item) (let* ((child-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser child-rule-name))) ;; maybe this should just be a list? (if (superfluous-anyof-rule? child-rule) (values t (coerce (parser-rule-items child-rule) 'list)) nil))) ;;; ==================== (defun install-reductions (parser) (when-debugging (comment "=================================") (comment "Installing reductions") (comment "- - - - - - - - - - - - - - - - -")) ;; (clrhash (parser-ht-name-to-reductions parser)) ;; (dolist (rule (parser-rules parser)) (note-reductions-to parser rule)) ;; (bypass-reductions-to-superfluous-anyof-rules parser) ) (defun note-reductions-to (parser parent-rule) (ecase (structure-type-of parent-rule) ; faster than etypecase since we're doing exact matches (parser-anyof-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-tuple-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-pieces-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-repeat-rule (note-reduction-to parser parent-rule 0 (parser-repeat-rule-element parent-rule)) (unless (null (parser-repeat-rule-separator parent-rule)) (note-reduction-to parser parent-rule 1 (parser-repeat-rule-separator parent-rule)))) (parser-id-rule nil) (parser-keyword-rule nil) (parser-atomic-rule nil) )) (defun note-reduction-to (parser parent-rule position item) (let ((child-name (parser-rule-item-rule item))) (when-debugging (unless (symbolp child-name) (break "Expected child to be a symbol: ~S" child-name))) (push (make-reduction :parent-rule parent-rule :child-index position) (gethash child-name (parser-ht-name-to-reductions parser))))) (defun bypass-reductions-to-superfluous-anyof-rules (parser) (let ((ht-name-to-reductions (parser-ht-name-to-reductions parser)) (done? nil)) (loop until done? do (let ((reductions-to-bypass nil)) (maphash #'(lambda (child-name reductions) (dolist (reduction reductions) (when (superfluous-anyof-rule? (reduction-parent-rule reduction)) (push (cons child-name reduction) reductions-to-bypass)))) ht-name-to-reductions) (setq done? (null reductions-to-bypass)) (dolist (bypass reductions-to-bypass) (let* ((child-name (car bypass)) (reduction-to-bypass (cdr bypass)) (parent-rule (reduction-parent-rule reduction-to-bypass)) (parent-name (parser-rule-name parent-rule)) (parent-reductions (gethash parent-name ht-name-to-reductions)) (old-child-reductions (gethash child-name ht-name-to-reductions)) (new-child-reductions (append (remove reduction-to-bypass ;; WARNING: without the following append, ;; sbcl signals a memory error upon exit from ;; bypass-reductions-to-superfluous-anyof-rules ;; Must have something to do with their ;; implementation of hash tables ;; Very strange... (append old-child-reductions)) parent-reductions)) ) (setf (gethash child-name ht-name-to-reductions) new-child-reductions) (gethash child-name ht-name-to-reductions) )))) )) ;;; ==================== (defun install-parents (parser) (when-debugging (comment "=================================") (comment "Installing rule parents") (comment "- - - - - - - - - - - - - - - - -")) ;; (maphash #'(lambda (child-name reductions) (add-parser-rule-parents parser child-name reductions)) (parser-ht-name-to-reductions parser))) (defun add-parser-rule-parents (parser child-name reductions) ;; child -> (... (parent . position) ...) (let* ((child-rule (find-parser-rule parser child-name)) (head-reductions (remove-if-not #'(lambda (reduction) (possible-start-of-reduction? child-rule reduction)) reductions))) (cond ((null head-reductions) (debugging-comment "~50S no head reductions" child-name) nil) ((keyword-triggered-rule? parser child-name) (debugging-comment "~50S -- Keyword triggered rule, head for reductions: ~:{~S.~D ~}" child-name (mapcar #'(lambda (reduction) (list (parser-rule-name (reduction-parent-rule reduction)) (reduction-child-index reduction))) head-reductions)) (dolist (reduction head-reductions) (push reduction (parser-rule-reductions child-rule)))) ((null (rest head-reductions)) (let ((only-head-reduction (first head-reductions))) (debugging-comment "~50S -- Head for just one reduction: ~S.~D)" child-name (parser-rule-name (reduction-parent-rule only-head-reduction)) (reduction-child-index only-head-reduction)) (push only-head-reduction (parser-rule-reductions child-rule)))) (t (debugging-comment "~50S -- Head for multiple reductions: ~:{~S.~D ~}" child-name (mapcar #'(lambda (reduction) (list (parser-rule-name (reduction-parent-rule reduction)) (reduction-child-index reduction))) head-reductions)) (dolist (reduction head-reductions) (push reduction (parser-rule-reductions child-rule))) )))) (defun possible-start-of-reduction? (child-rule reduction) (let* ((parent-rule (reduction-parent-rule reduction)) (child-index (reduction-child-index reduction))) (and (or (eq child-index 0) (parser-anyof-rule-p parent-rule) (parser-pieces-rule-p parent-rule) (and (parser-tuple-rule-p parent-rule) (let ((items (parser-tuple-rule-items parent-rule))) ;; following returns true iff all the items preceeding ;; child-index are optional, i.e. have a car of t (dotimes (i child-index t) (unless (parser-rule-item-optional? (svref items i)) (return nil)))))) (let ((child-precedence (parser-rule-precedence child-rule))) (or (null child-precedence) (or (not (parser-tuple-rule-p parent-rule)) (let* ((parent-item (svref (parser-tuple-rule-items parent-rule) child-index)) (parent-precedence (parser-rule-item-precedence parent-item))) (or (null parent-precedence) (>= parent-precedence child-precedence))))))))) (defun keyword-triggered-rule? (parser rule-name) (aux-keyword-triggered-rule? parser rule-name nil)) (defun aux-keyword-triggered-rule? (parser item-or-rule-name parent-rule-names) (let ((rule-name (if (parser-rule-item-p item-or-rule-name) (parser-rule-item-rule item-or-rule-name) item-or-rule-name))) (if (member rule-name parent-rule-names) nil (let ((rule (find-parser-rule parser rule-name))) (cond ((parser-keyword-rule-p rule) t) ((parser-id-rule-p rule) (aux-keyword-triggered-rule? parser (parser-id-rule-subrule rule) (push rule-name parent-rule-names))) ((parser-anyof-rule-p rule) (do-parser-rule-items (item rule t) (unless (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names)) (return nil)))) ((parser-tuple-rule-p rule) (do-parser-rule-items (item rule t) (cond ((not (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names))) (return nil)) ((not (parser-rule-item-optional? item)) (return t))))) ((parser-pieces-rule-p rule) (do-parser-rule-items (item rule t) (unless (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names)) (return nil)))) (t nil)))))) ;;; ==================== (defun install-bvs (parser) (when-debugging (comment "=================================") (comment "Installing bit vectors") (comment "- - - - - - - - - - - - - - - - -")) (install-p2bvi-keys parser) ; initializes parser-rule-p2bvi alist (install-p2bvi-values parser) ; puts values into parser-rule-p2bvi alist (install-rule-bvis parser) (install-bv-size parser) ; sets parser-bv-size sets parser - scratch - bv , parser - zero - bv (install-ht-rnp-to-handles-bv parser) ; sets parser-ht-rnp-to-handles-bv, ; parser-rule-item-possible-handles-bv, ; parser-rule-item-possible-children-bv ) ;;; ==================== (defun initialize-p2bvi-keys (parser) (when-debugging (comment "Initializing precedences")) (dolist (rule (parser-rules parser)) (let ((rule-precedence (parser-rule-precedence rule))) ;; default is 0, so null means user explicitly said "no (i.e. any) precedence" (setf (parser-rule-p2bvi-map rule) `((,rule-precedence)))))) (defun compute-closure-for-p2bvi-keys (parser) (when-debugging (comment "Computing fixpoint for precedences")) (let (#+DEBUG-PARSER (n 0) (rules (parser-rules parser)) (do-another-round? t)) ;; find fixpoint... ;; When done, p2bvi-map has alist for possible precedences for each rule. ;; If there is no explicit precedence for an anyof rule, it gets all the precedences ;; of it's child rules. (loop while do-another-round? do (when-debugging (comment " Precedences Round ~D" (incf n))) (setq do-another-round? nil) (dolist (rule rules) (when (case (structure-type-of rule) ; faster than etypecase since we are doing exact matches (parser-anyof-rule (update-p2bvi-keys-for-anyof-rule parser rule)) (otherwise nil)) (setq do-another-round? t)))))) (defun update-p2bvi-keys-for-anyof-rule (parser anyof-rule) (cond ((not (null (parser-rule-precedence anyof-rule))) ;; use explicit precedence nil) ((null (parser-rule-semantics anyof-rule)) ;; if there is no precedence but also no semantics, this anyof rule is superfluous ;; and will be bypassed.. nil) (t ;; Since we have semantics, we need to build explicit nodes for this rule. ;; But since we do not have an explicit precedence, we must effectively ;; create a version of this rule for each precedence from a child rule. ;; That versioning information is kept in parser-rule-p2bvi-map, ;; where each entry will get its own bit-veector-index.. (let* ((anyof-p2bvi-alist (parser-rule-p2bvi-map anyof-rule)) (changed? nil)) (do-parser-rule-items (item anyof-rule) (let* ((child-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser child-rule-name)) (child-rule-p2bvi-alist (parser-rule-p2bvi-map child-rule))) (dolist (p2bvi-pair child-rule-p2bvi-alist) (let ((child-rule-precedence (car p2bvi-pair))) (unless (assoc child-rule-precedence anyof-p2bvi-alist) (setq changed? t)) (push (cons child-rule-precedence nil) anyof-p2bvi-alist))))) (when changed? (setf (parser-rule-p2bvi-map anyof-rule) anyof-p2bvi-alist)) changed?)))) ;;; === (defun sort-using-cars (alist) (sort alist #'(lambda (x y) (< (car x) (car y))))) (defun finalize-p2bvi-keys (parser) ;; why bother sorting?? (dolist (rule (parser-rules parser)) (let* ((raw-p2bvi-alist (parser-rule-p2bvi-map rule)) (null-pair (assoc nil raw-p2bvi-alist)) (foo (remove null-pair raw-p2bvi-alist)) (sorted-p2bvi-alist (sort-using-cars foo))) ;; (when (null sorted-p2bvi-alist) (setq sorted-p2bvi-alist (list (cons 0 nil)))) (setf (parser-rule-p2bvi-map rule) (if (null null-pair) sorted-p2bvi-alist (cons null-pair sorted-p2bvi-alist)))))) (defun install-p2bvi-keys (parser) (initialize-p2bvi-keys parser) (compute-closure-for-p2bvi-keys parser) (finalize-p2bvi-keys parser)) ;;; ==================== (defun install-p2bvi-values (parser) (when-debugging (comment "Installing maps for precedence to bv indices")) (let ((bv-index -1)) (dolist (rule (parser-rules parser)) (when ;(and (parental-parser-rule? rule) (not (superfluous-anyof-rule? rule)) ;) (dolist (p2bvi-pair (parser-rule-p2bvi-map rule)) (setf (cdr p2bvi-pair) (incf bv-index))))))) ;;; ==================== (defun install-rule-bvis (parser) ;; why bother sorting?? (dolist (rule (parser-rules parser)) (let ((p2bvi-alist (parser-rule-p2bvi-map rule))) (when (null (rest p2bvi-alist)) (setf (parser-rule-bvi rule) (cdr (first p2bvi-alist))))))) ;;; ==================== (defun install-bv-size (parser) (when-debugging (comment "Computing bv size")) (dolist (rule (parser-rules parser)) (when ;;(and (parental-parser-rule? rule) (not (superfluous-anyof-rule? rule)) ;;) (incf (parser-bv-size parser) (length (parser-rule-p2bvi-map rule))))) (when-debugging (comment " bv-size = ~D" (parser-bv-size parser)))) ;;; ==================== (defun install-aux-bvs (parser) (when-debugging (comment "Installing aux bv's")) (let ((bv-size (parser-bv-size parser))) (setf (parser-scratch-bv parser) (make-array bv-size :element-type 'bit :initial-element 0)) (setf (parser-zero-bv parser) (make-array bv-size :element-type 'bit :initial-element 0)))) ;;; ==================== (defun install-ht-rnp-to-handles-bv (parser) ;; Create the mapping (rule . precedence) => bit-vector of handles (initialize-ht-rnp-to-handles-bv parser) (compute-closures-for-handles-bvs parser) (combine-handles parser 0) ) (defun combine-handles (parser level) (let* ((again1? (install-rule-item-bvs parser)) (again2? (install-possible-children-bvs parser)) (again3? (install-composite-handles-bvs parser))) (when (or again1? again2? again3?) (if (> level 300) (warn "Ooops -- problem installing handle vectors: ~S ~S ~S " again1? again2? again3?) (combine-handles parser (1+ level)))))) ;;; === (defun initialize-ht-rnp-to-handles-bv (parser) (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser))) (clrhash ht-rnp-to-handles-bv) (dolist (rule (parser-rules parser)) (let ((rule-name (parser-rule-name rule))) (dolist (p2bvi-pair (parser-rule-p2bvi-map rule)) (let* ((precedence (car p2bvi-pair)) (bv-index (cdr p2bvi-pair)) (rnp (cons rule-name precedence)) (handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (unless (null bv-index) (setf (sbit handles-bv bv-index) 1)) (setf (gethash rnp ht-rnp-to-handles-bv) handles-bv))))))) ;;; === (defun compute-closures-for-handles-bvs (parser) (when-debugging (comment "Computing fixpoint for desired bv's.")) (let ((rules (parser-rules parser)) #+DEBUG-PARSER (n 0) (do-another-round? t)) ;; ;; add entry for (rn . nil) ;; (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser))) (dolist (rule rules) (let* ((rule-name (parser-rule-name rule)) (rn-nullp (cons rule-name nil))) (when (null (gethash rn-nullp ht-rnp-to-handles-bv)) (let ((p2bvi-alist (parser-rule-p2bvi-map rule)) (null-p-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (dolist (p2bvi p2bvi-alist) (let* ((precedence (car p2bvi)) (rnp-handles-bv (gethash (cons rule-name precedence) ht-rnp-to-handles-bv))) (bit-ior null-p-handles-bv rnp-handles-bv null-p-handles-bv))) (setf (gethash rn-nullp ht-rnp-to-handles-bv) null-p-handles-bv)))))) ;; ;; Propagate until fixpoint ;; (loop while do-another-round? do (when-debugging (comment "Round ~D" (incf n))) (setq do-another-round? nil) (dolist (rule rules) (when (ecase (structure-type-of rule) ; faster than etypecase since we are doing exact matches (parser-anyof-rule (update-handles-bv-for-anyof-rule parser rule)) (parser-pieces-rule (update-handles-bv-for-pieces-rule parser rule)) (parser-tuple-rule (update-handles-bv-for-tuple-rule parser rule)) (parser-repeat-rule (update-handles-bv-for-repeat-rule parser rule)) (parser-id-rule nil) (parser-keyword-rule nil) (parser-atomic-rule nil) ) (setq do-another-round? t)))) )) (defun update-handles-bv-for-anyof-rule (parser rule) ;; ;; This code is tricky, and depends on the fact that an anyof rule may be used in three different ways , depending on exisitance of semantics ;; and/or explicit precedence. ;; Case 1 : precedence Case 2 : no precedence , but semantics Case 3 : no precedence , no semantics ;; In cases 1 and 2 , we need to build a node for occurrences of this rule , where in case 3 , we can bypass this rule . ;; In cases 2 , we do n't have a fixed precedence , but must carry along ;; the precedence we get from the child rule, which is a bit messy. ;; The net result in that case is that we have several bit vector indices ;; for the same rule, so it is really a concise implementation of a family ;; of rules. ;; (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) ;; ht-rnp-to-handles-bv: (rule . precedence) => handles-bv (anyof-rule-name (parser-rule-name rule)) (anyof-precedence (parser-rule-precedence rule)) (primary-anyof-handles-bv (if (null anyof-precedence) ;; no fixed precedence, so there is not just one handles-bv (see below) nil ;; fixed precedence, so there is just one handles-bv (gethash (cons anyof-rule-name anyof-precedence) ht-rnp-to-handles-bv))) ;; (scratch-bv (parser-scratch-bv parser)) (changed? nil)) ;; (do-parser-rule-items (item rule) (let* ((item-precedence (parser-rule-item-precedence item)) (item-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser item-rule-name)) (child-p2bvi-alist (parser-rule-p2bvi-map child-rule)) (max-pair (let ((local-max-pair nil)) (dolist (p2bvi-pair child-p2bvi-alist) (let ((child-possible-precedence (car p2bvi-pair))) (if (or (null item-precedence) (< child-possible-precedence item-precedence)) (setq local-max-pair p2bvi-pair) (return nil)))) local-max-pair)) (max-acceptable-child-precedence (car max-pair)) (item-rnp (cons item-rule-name max-acceptable-child-precedence)) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) ;; ;; ;; item-handles-bv will be nil for keywords, etc. ;; (unless (null item-handles-bv) (let ((anyof-handles-bv (or ;; if there is a fixed precedence for anyof rule, use ;; that, primary-anyof-handles-bv ;; else get bv for version of anyof rule with same precedence as child (gethash (cons anyof-rule-name max-acceptable-child-precedence) ht-rnp-to-handles-bv)))) ;; if rule is superfluous, the handles may be null (unless (null anyof-handles-bv) (bit-andc1 anyof-handles-bv item-handles-bv scratch-bv) (bit-ior anyof-handles-bv item-handles-bv anyof-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))))))) changed?)) (defun update-handles-bv-for-pieces-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) ;; (pieces-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (pieces-handles-bv (gethash pieces-rnp ht-rnp-to-handles-bv)) ;; (scratch-bv (parser-scratch-bv parser)) (changed? nil)) ;; (do-parser-rule-items (item rule) (let* ((item-rnp (cons (parser-rule-item-rule item) (parser-rule-item-precedence item))) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) ;; ;; ;; item-handles-bv will be nil for keywords, etc. ;; (unless (null item-handles-bv) (bit-andc1 pieces-handles-bv item-handles-bv scratch-bv) (bit-ior pieces-handles-bv item-handles-bv pieces-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))))) changed?)) (defun update-handles-bv-for-tuple-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) ;; (tuple-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (tuple-handles-bv (gethash tuple-rnp ht-rnp-to-handles-bv)) ;; (scratch-bv (parser-scratch-bv parser)) (changed? nil)) ;; (do-parser-rule-items (head-item rule) ;; repeat for each item that can start production (dotimes (i (length items)) (let* ((item-rule-name (parser-rule-item-rule head-item)) (item-precedence (parser-rule-item-precedence head-item)) (item-rnp (cons item-rule-name item-precedence)) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) ;; ;; item-handles-bv will be nil for keywords, etc. ;; (unless (null item-handles-bv) (bit-andc1 tuple-handles-bv item-handles-bv scratch-bv) (bit-ior tuple-handles-bv item-handles-bv tuple-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))) (unless (parser-rule-item-optional? head-item) (return nil)))) changed?)) (defun update-handles-bv-for-repeat-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) ;; (repeat-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (repeat-handles-bv (gethash repeat-rnp ht-rnp-to-handles-bv)) ;; (element-item (parser-repeat-rule-element rule)) (element-rnp (cons (parser-rule-item-rule element-item) (parser-rule-item-precedence element-item))) (element-handles-bv (gethash element-rnp ht-rnp-to-handles-bv)) ;; (scratch-bv (parser-scratch-bv parser)) (changed? nil)) ;; ;; element-handles-bv will be nil for :SYMBOL rule ;; (unless (null element-handles-bv) (bit-andc1 repeat-handles-bv element-handles-bv scratch-bv) (bit-ior repeat-handles-bv element-handles-bv repeat-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))) changed?)) ;;; === (defun install-rule-item-bvs (parser) (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser)) (again? nil)) ;; (dolist (rule (parser-rules parser)) (do-parser-rule-items (item rule) (unless (null item) ; can happen for repeat rules (let* ((item-precedence (parser-rule-item-precedence item)) (item-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser item-rule-name)) (child-p2bvi-alist (parser-rule-p2bvi-map child-rule)) (children-bv (make-array bv-size :element-type 'bit :initial-element 0)) (item-rnp (let ((max-allowed-precedence-seen nil)) (dolist (p2bvi-pair child-p2bvi-alist) (let ((child-possible-precedence (car p2bvi-pair)) (child-possible-bvi (cdr p2bvi-pair))) (cond ((null child-possible-bvi) nil) ((or (null item-precedence) (null child-possible-precedence) (<= child-possible-precedence item-precedence)) (setf (sbit children-bv child-possible-bvi) 1) (when (or (null max-allowed-precedence-seen) (> child-possible-precedence max-allowed-precedence-seen)) (setq max-allowed-precedence-seen child-possible-precedence)))))) (let ((effective-item-precedence (if (null item-precedence) item-precedence max-allowed-precedence-seen))) (cons item-rule-name effective-item-precedence)))) (handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) (case (structure-type-of child-rule) ; faster than etypecase since we are doing exact matches (parser-anyof-rule (let ((new (parser-anyof-rule-possible-handles-bv child-rule))) (unless (null new) (setq handles-bv (bit-ior handles-bv new))))) (parser-pieces-rule (let ((new (parser-pieces-rule-possible-handles-bv child-rule))) (unless (null new) (setq handles-bv (bit-ior handles-bv new))))) (t (do-parser-rule-items (head-item child-rule) ;; repeat for each item that can start child production (dotimes (i (length items)) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv head-item))) (unless (null item-handles-bv) (setq handles-bv (bit-ior handles-bv item-handles-bv))) (unless (parser-rule-item-optional? head-item) (return nil)))))) (unless (or (and (equalp (parser-zero-bv parser) children-bv) (not (null (parser-rule-item-possible-children-bv item)))) (equalp (parser-rule-item-possible-children-bv item) children-bv)) (setq again? 1) (setf (parser-rule-item-possible-children-bv item) children-bv)) (let ((new (bit-ior handles-bv children-bv))) (unless (equalp (parser-rule-item-possible-handles-bv item) new) (setq again? 2) (setf (parser-rule-item-possible-handles-bv item) new))))))) again?)) (defun install-possible-children-bvs (parser) ;; don't just look at parser-rule-reductions -- ;; those only include the reductions for which rule is a handle (let ((again? nil)) (maphash #'(lambda (rule-name reductions) (let ((child-rule (find-parser-rule parser rule-name))) (when (not (superfluous-anyof-rule? child-rule)) (let ((child-rule-bvi (parser-rule-bvi child-rule)) (child-rule-precedence (parser-rule-precedence child-rule))) (dolist (reduction reductions) (let* ((parent-rule (reduction-parent-rule reduction)) (child-index (reduction-child-index reduction)) (item (svref (parser-rule-items parent-rule) child-index)) (item-precedence (parser-rule-item-precedence item)) (children-bv (parser-rule-item-possible-children-bv item)) (handles-bv (parser-rule-item-possible-handles-bv item))) (when (or (null item-precedence) (null child-rule-precedence) (<= child-rule-precedence item-precedence)) (unless (and (eq (sbit children-bv child-rule-bvi) 1) (eq (sbit handles-bv child-rule-bvi) 1)) (setq again? 3) (setf (sbit children-bv child-rule-bvi) 1) (setf (sbit handles-bv child-rule-bvi) 1) )))))))) (parser-ht-name-to-reductions parser)) again?)) ;;; === (defun install-composite-handles-bvs (parser) (let ((bv-size (parser-bv-size parser)) (again? nil)) (dolist (rule (parser-rules parser)) (case (structure-type-of rule) ; faster than etypecase since we are doing exact matches (parser-anyof-rule (let ((composite-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (unless (null (parser-rule-bvi rule)) (setf (sbit composite-handles-bv (parser-rule-bvi rule)) 1)) (do-parser-rule-items (item rule) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv item))) (unless (null item-handles-bv) (bit-ior composite-handles-bv item-handles-bv composite-handles-bv)))) (unless (equalp (parser-anyof-rule-possible-handles-bv rule) composite-handles-bv) (setq again? 4)) (setf (parser-anyof-rule-possible-handles-bv rule) composite-handles-bv))) (parser-pieces-rule (let ((composite-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (setf (sbit composite-handles-bv (parser-rule-bvi rule)) 1) (do-parser-rule-items (item rule) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv item))) (unless (null item-handles-bv) (bit-ior composite-handles-bv item-handles-bv composite-handles-bv)))) (unless (equalp (parser-pieces-rule-possible-handles-bv rule) composite-handles-bv) (setq again? 5)) (setf (parser-pieces-rule-possible-handles-bv rule) composite-handles-bv))) )) again?)) ;;; ==================== (defun install-default-semantic-alist (parser) (when-debugging (comment "=================================") (comment "Installing default semantic alist") (comment "- - - - - - - - - - - - - - - - -")) (let ((all-numbers '()) (alist '())) (dolist (rule (parser-rules parser)) (let* ((pattern (parser-rule-semantics rule)) (numbers (find-numbers-in pattern))) (dolist (number numbers) (pushnew number all-numbers)))) (dolist (number all-numbers) (push (cons number :unspecified) alist)) (setf (parser-default-semantic-alist parser) alist))) (defun find-numbers-in (pattern) (cond ((numberp pattern) (list pattern)) ((atom pattern) nil) (t (nconc (find-numbers-in (car pattern)) (find-numbers-in (cdr pattern)))))) ;;; ==================== (defun install-special-rules (parser) (when-debugging (comment "=================================") (comment "Installing special rules") (comment "- - - - - - - - - - - - - - - - -")) (let ((symbol-rule (maybe-find-parser-rule parser :SYMBOL)) (string-rule (maybe-find-parser-rule parser :STRING)) (number-rule (maybe-find-parser-rule parser :NUMBER)) (character-rule (maybe-find-parser-rule parser :CHARACTER)) (pragma-rule (maybe-find-parser-rule parser :PRAGMA)) (toplevel-rule (maybe-find-parser-rule parser :TOPLEVEL))) (when (null symbol-rule) (warn "Cannot find rule named :SYMBOL")) (when (null string-rule) (warn "Cannot find rule named :STRING")) (when (null number-rule) (warn "Cannot find rule named :NUMBER")) (when (null character-rule) (warn "Cannot find rule named :CHARACTER")) (when (null toplevel-rule) (warn "Cannot find rule named :TOPLEVEL")) (when (null pragma-rule) (warn "Cannot find rule named :PRAGMA")) (setf (parser-symbol-rule parser) symbol-rule) (setf (parser-string-rule parser) string-rule) (setf (parser-number-rule parser) number-rule) (setf (parser-character-rule parser) character-rule) (setf (parser-toplevel-rule parser) toplevel-rule) (setf (parser-pragma-rule parser) pragma-rule) )) ;;; ==================== (defun install-pprinters (parser) (when-debugging (comment "=================================") (comment "Installing pprinters") (comment "- - - - - - - - - - - - - - - - -")) (let ((ht-expr-to-parser-rules (parser-ht-expr-to-parser-rules parser)) (ht-car-to-parser-rules (parser-ht-car-to-parser-rules parser))) (dolist (rule (parser-rules parser)) (install-pprinter-rule rule ht-expr-to-parser-rules ht-car-to-parser-rules)))) (defun install-pprinter-rule (rule ht-expr-to-parser-rules ht-car-to-parser-rules) (let ((semantics (parser-rule-semantics rule))) (cond ((consp semantics) (push rule (gethash (car semantics) ht-car-to-parser-rules))) ((null semantics) nil) (t (push rule (gethash semantics ht-expr-to-parser-rules)))))) ;;; ============================================================================ (defun propagate-optionals (&optional (parser *current-parser*)) (debugging-comment "========================================") (debugging-comment "First round: look for optional rules.") (loop ;; iterate to fixpoint (unless (propagate-optional-one-round parser) (return nil)) (debugging-comment "========================================") (debugging-comment "New round: look for more optional rules.")) (debugging-comment "========================================")) (defparameter *bogus-locations* (let ((*parser-source* '(:internal "parser initialization"))) (list (cons :left-pos -1) (cons :left-line -1) (cons :left-column -1) (cons :left-lc (cons -1 -1)) (cons :left-lcb (vector -1 -1 -1)) ;; (cons :right-pos -1) (cons :right-line -1) (cons :right-column -1) (cons :right-lc (cons -1 -1)) (cons :right-lcb (vector -1 -1 -1)) ;; (cons :region (make-region (vector -1 -1 -1) (vector -1 -1 -1)))))) (defun propagate-optional-one-round (parser) (let ((ht-name-to-rule (parser-ht-name-to-rule parser)) (changed? nil)) ;; ;; make rules optional if all their items are optional ;; (maphash #'(lambda (rule-name rule) (declare (ignore rule-name)) (let* ((items (parser-rule-items rule)) (n (length items)) (all-optional? (and (> n 0) (dotimes (i n t) (let ((item (svref items i))) (unless (null item) (when (not (parser-rule-item-optional? item)) (return nil)))))))) (when all-optional? (unless (parser-rule-optional? rule) (setq changed? t) (setf (parser-rule-optional? rule) t) (let ((semantic-pattern (parser-rule-semantics rule))) (when (not (null semantic-pattern)) (let ((semantic-alist *bogus-locations*) (items (parser-rule-items rule))) (dotimes (i n) (let ((item (svref items i))) (unless (null item) (let ((index (parser-rule-item-semantic-index item))) (unless (null index) (let ((default (parser-rule-item-default-semantics item))) (push (cons index (if (keywordp default) default (list 'quote default))) semantic-alist))))))) (setf (parser-rule-default-semantics rule) ;; eval... (sanitize-sexpression (sublis-result semantic-alist semantic-pattern)))))) ( when ( parser - repeat - rule - p rule ) ( setf ( parser - rule - default - semantics rule ) ' ( ) ) ) (debugging-comment "Rule ~S is now optional with semantics ~S." rule (parser-rule-default-semantics rule)) )))) ht-name-to-rule) ;; ;; make items optional if they invoke an optional rule ;; (maphash #'(lambda (rule-name rule) (declare (ignore rule-name)) (let* ((items (parser-rule-items rule)) (n (length items))) (dotimes (i n t) (let ((item (svref items i))) (unless (null item) (let* ((item-rule-name (parser-rule-item-rule item)) (item-rule (gethash item-rule-name ht-name-to-rule))) (when (parser-rule-optional? item-rule) (unless (parser-rule-item-optional? item) (setq changed? t) (setf (parser-rule-item-optional? item) t) (setf (parser-rule-item-default-semantics item) (parser-rule-default-semantics item-rule)) (debugging-comment "In rule ~30S, item ~D (~S) is now optional with semantics ~S." rule i item-rule-name (parser-rule-item-default-semantics item)))))))))) ht-name-to-rule) changed ? will be NIL once we reach a fixpoint ( probably about 2 rounds ) changed?)) (defun sanitize-sexpression (s) ;; not terribly smart, but handles some simple cases... (cond ((atom s) s) ((eq (car s) 'quote) (if (or (eq (cadr s) nil) (eq (cadr s) t) (keywordp (cadr s))) (cadr s) s)) ((and (eq (car s) 'if) (equal (cadr s) '(EQ (QUOTE :UNSPECIFIED) :UNSPECIFIED))) (sanitize-sexpression (caddr s))) ((and (atom (cdr s)) (not (null (cdr s)))) :ILLEGAL-SEXPRESSION) (t (mapcar #'sanitize-sexpression s))))
null
https://raw.githubusercontent.com/KestrelInstitute/Specware/2be6411c55f26432bf5c9e2f7778128898220c24/Library/Algorithms/Parsing/Chart/Handwritten/Lisp/seal-parser.lisp
lisp
Package : Parser4 ; Base : 10 ; Syntax : Common - Lisp -*- see parse-add-rules.lisp sets parser-rules sets parser-ht-name-to-reductions sets parser-rule-reductions sets parser-bv-size parser-rule-bvi parser-rule-item-possible-handles-bv sets parser-default-semantic-alist finds toplevel, symbol, number, string, etc. items referencing optional rules become optional themselves sets parser-ht-expr-to-pprint, parser-ht-type-to-pprint, parser-ht-car-to-pprint ==================== (when (parental-parser-rule? rule)) parser-total-rule-count is used only for commentary ==================== efficiency hack to eliminate id reductions (A) avoids those reductions (B) makes desired-bv's smaller (hence more efficeient) since id rules become irrelevant ==================== why distinguish (t nil) from (nil ...) ? is it merely because the former is an error? maybe this should just be a list? ==================== faster than etypecase since we're doing exact matches WARNING: without the following append, sbcl signals a memory error upon exit from bypass-reductions-to-superfluous-anyof-rules Must have something to do with their implementation of hash tables Very strange... ==================== child -> (... (parent . position) ...) following returns true iff all the items preceeding child-index are optional, i.e. have a car of t ==================== initializes parser-rule-p2bvi alist puts values into parser-rule-p2bvi alist sets parser-bv-size sets parser-ht-rnp-to-handles-bv, parser-rule-item-possible-handles-bv, parser-rule-item-possible-children-bv ==================== default is 0, so null means user explicitly said "no (i.e. any) precedence" find fixpoint... When done, p2bvi-map has alist for possible precedences for each rule. If there is no explicit precedence for an anyof rule, it gets all the precedences of it's child rules. faster than etypecase since we are doing exact matches use explicit precedence if there is no precedence but also no semantics, this anyof rule is superfluous and will be bypassed.. Since we have semantics, we need to build explicit nodes for this rule. But since we do not have an explicit precedence, we must effectively create a version of this rule for each precedence from a child rule. That versioning information is kept in parser-rule-p2bvi-map, where each entry will get its own bit-veector-index.. === why bother sorting?? (when (null sorted-p2bvi-alist) (setq sorted-p2bvi-alist (list (cons 0 nil)))) ==================== (and (parental-parser-rule? rule) ) ==================== why bother sorting?? ==================== (and (parental-parser-rule? rule) ) ==================== ==================== Create the mapping (rule . precedence) => bit-vector of handles === === add entry for (rn . nil) Propagate until fixpoint faster than etypecase since we are doing exact matches This code is tricky, and depends on the fact that an anyof rule may and/or explicit precedence. the precedence we get from the child rule, which is a bit messy. The net result in that case is that we have several bit vector indices for the same rule, so it is really a concise implementation of a family of rules. ht-rnp-to-handles-bv: (rule . precedence) => handles-bv no fixed precedence, so there is not just one handles-bv (see below) fixed precedence, so there is just one handles-bv item-handles-bv will be nil for keywords, etc. if there is a fixed precedence for anyof rule, use that, else get bv for version of anyof rule with same precedence as child if rule is superfluous, the handles may be null item-handles-bv will be nil for keywords, etc. repeat for each item that can start production (dotimes (i (length items)) item-handles-bv will be nil for keywords, etc. element-handles-bv will be nil for :SYMBOL rule === can happen for repeat rules faster than etypecase since we are doing exact matches repeat for each item that can start child production (dotimes (i (length items)) don't just look at parser-rule-reductions -- those only include the reductions for which rule is a handle === faster than etypecase since we are doing exact matches ==================== ==================== ==================== ============================================================================ iterate to fixpoint make rules optional if all their items are optional eval... make items optional if they invoke an optional rule not terribly smart, but handles some simple cases...
(in-package :Parser4) (defun load-parser (file &key (name (intern (format nil "PARSER-~D" (incf *gensym-counter*)) "KEYWORD")) (case-sensitive? nil) (rule-package (find-package "KEYWORD")) (symbol-package common-lisp::*package*)) (let ((new-parser (new-parser name :case-sensitive? case-sensitive? :rule-package rule-package :symbol-package symbol-package))) (setq *current-parser* new-parser) (when (null (pathname-type file)) (let ((fasl-file (make-pathname :type Specware::*fasl-type* :defaults file)) (lisp-file (make-pathname :type "lisp" :defaults file))) (unless (null lisp-file) (when (<= (or (file-write-date fasl-file) 0) (file-write-date lisp-file)) (compile-file lisp-file))))) (setf (parser-keywords-are-keywords-only? new-parser) t) (seal-parser new-parser) (when-debugging (comment "New parser is also in PARSER4::*CURRENT-PARSER*")) new-parser)) (defun seal-parser (parser) (when-debugging (comment "============================================================================") (comment "Sealing parser") (comment "=================================")) (when-debugging (verify-all-parser-rule-references parser)) (bypass-superfluous-anyof-rules parser) (bypass-id-rules parser) parser - scratch - bv , parser - zero - bv (when-debugging (comment "============================================================================")) ) (defun install-rules (parser) (when-debugging (comment "=================================") (comment "Installing rules") (comment "- - - - - - - - - - - - - - - - -")) (maphash #'(lambda (ignore-name rule) (declare (ignore ignore-name)) (push rule (parser-rules parser)) (incf (parser-total-rule-count parser))) (parser-ht-name-to-rule parser))) (defun bypass-id-rules (parser) (when-debugging (comment "=================================") (comment "Bypassing id rules") (comment "- - - - - - - - - - - - - - - - -")) (dolist (rule (parser-rules parser)) (bypass-children-id-rules parser rule))) (defun bypass-children-id-rules (parser rule) (debugging-comment "Replacing any id rules in ~20A ~S" (structure-type-of rule) (parser-rule-name rule)) (do-parser-rule-items (item rule) (unless (null item) (bypass-any-id-rule-in-item parser item)))) (defun bypass-any-id-rule-in-item (parser item) (when-debugging (unless (parser-rule-item-p item) (break "Expected parser-rule-item: ~S" item))) (let* ((child-rule-name (parser-rule-item-rule item)) #+DEBUG-PARSER (original-name child-rule-name) (child-rule (find-parser-rule parser child-rule-name))) (when (parser-id-rule-p child-rule) (loop while (parser-id-rule-p child-rule) do (setq child-rule-name (parser-id-rule-subrule child-rule)) (setq child-rule (find-parser-rule parser child-rule-name))) (debugging-comment " Replacing ~S by ~S" original-name child-rule-name) (setf (parser-rule-item-rule item) child-rule-name)))) (defun bypass-superfluous-anyof-rules (parser &optional (round 0)) (when-debugging (comment "=================================") (comment "Bypassing superfluous anyof rules, round ~D" round) (comment "- - - - - - - - - - - - - - - - -")) (let ((revised? nil)) (dolist (rule (parser-rules parser)) (when (bypass-children-superfluous-anyof-rules parser rule) (setq revised? t))) (when revised? (bypass-superfluous-anyof-rules parser (1+ round))))) (defun bypass-children-superfluous-anyof-rules (parser rule) (when (parser-anyof-rule-p rule) (debugging-comment "Replacing any superfluous anyof rules in ~20A ~S" (structure-type-of rule) (parser-rule-name rule)) (let ((new-items nil) (revised? nil)) (do-parser-rule-items (item rule) (multiple-value-bind (expanded? revised-items) (expand-anyof-rule-in-item parser item) (when expanded? (setq revised? t)) (setq new-items (if expanded? (progn (when (null revised-items) (warn "Null revised items for ~A when bypassing superfluous anyof rules for ~A" (parser-rule-item-rule item) (parser-rule-name rule))) (append revised-items new-items)) (cons item new-items))))) (when revised? (setf (parser-rule-items rule) (coerce new-items 'vector))) revised?))) (defun expand-anyof-rule-in-item (parser item) (let* ((child-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser child-rule-name))) (if (superfluous-anyof-rule? child-rule) (values t (coerce (parser-rule-items child-rule) 'list)) nil))) (defun install-reductions (parser) (when-debugging (comment "=================================") (comment "Installing reductions") (comment "- - - - - - - - - - - - - - - - -")) (clrhash (parser-ht-name-to-reductions parser)) (dolist (rule (parser-rules parser)) (note-reductions-to parser rule)) (bypass-reductions-to-superfluous-anyof-rules parser) ) (defun note-reductions-to (parser parent-rule) (parser-anyof-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-tuple-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-pieces-rule (do-parser-rule-items (item parent-rule nil i) (note-reduction-to parser parent-rule i item))) (parser-repeat-rule (note-reduction-to parser parent-rule 0 (parser-repeat-rule-element parent-rule)) (unless (null (parser-repeat-rule-separator parent-rule)) (note-reduction-to parser parent-rule 1 (parser-repeat-rule-separator parent-rule)))) (parser-id-rule nil) (parser-keyword-rule nil) (parser-atomic-rule nil) )) (defun note-reduction-to (parser parent-rule position item) (let ((child-name (parser-rule-item-rule item))) (when-debugging (unless (symbolp child-name) (break "Expected child to be a symbol: ~S" child-name))) (push (make-reduction :parent-rule parent-rule :child-index position) (gethash child-name (parser-ht-name-to-reductions parser))))) (defun bypass-reductions-to-superfluous-anyof-rules (parser) (let ((ht-name-to-reductions (parser-ht-name-to-reductions parser)) (done? nil)) (loop until done? do (let ((reductions-to-bypass nil)) (maphash #'(lambda (child-name reductions) (dolist (reduction reductions) (when (superfluous-anyof-rule? (reduction-parent-rule reduction)) (push (cons child-name reduction) reductions-to-bypass)))) ht-name-to-reductions) (setq done? (null reductions-to-bypass)) (dolist (bypass reductions-to-bypass) (let* ((child-name (car bypass)) (reduction-to-bypass (cdr bypass)) (parent-rule (reduction-parent-rule reduction-to-bypass)) (parent-name (parser-rule-name parent-rule)) (parent-reductions (gethash parent-name ht-name-to-reductions)) (old-child-reductions (gethash child-name ht-name-to-reductions)) (new-child-reductions (append (remove reduction-to-bypass (append old-child-reductions)) parent-reductions)) ) (setf (gethash child-name ht-name-to-reductions) new-child-reductions) (gethash child-name ht-name-to-reductions) )))) )) (defun install-parents (parser) (when-debugging (comment "=================================") (comment "Installing rule parents") (comment "- - - - - - - - - - - - - - - - -")) (maphash #'(lambda (child-name reductions) (add-parser-rule-parents parser child-name reductions)) (parser-ht-name-to-reductions parser))) (defun add-parser-rule-parents (parser child-name reductions) (let* ((child-rule (find-parser-rule parser child-name)) (head-reductions (remove-if-not #'(lambda (reduction) (possible-start-of-reduction? child-rule reduction)) reductions))) (cond ((null head-reductions) (debugging-comment "~50S no head reductions" child-name) nil) ((keyword-triggered-rule? parser child-name) (debugging-comment "~50S -- Keyword triggered rule, head for reductions: ~:{~S.~D ~}" child-name (mapcar #'(lambda (reduction) (list (parser-rule-name (reduction-parent-rule reduction)) (reduction-child-index reduction))) head-reductions)) (dolist (reduction head-reductions) (push reduction (parser-rule-reductions child-rule)))) ((null (rest head-reductions)) (let ((only-head-reduction (first head-reductions))) (debugging-comment "~50S -- Head for just one reduction: ~S.~D)" child-name (parser-rule-name (reduction-parent-rule only-head-reduction)) (reduction-child-index only-head-reduction)) (push only-head-reduction (parser-rule-reductions child-rule)))) (t (debugging-comment "~50S -- Head for multiple reductions: ~:{~S.~D ~}" child-name (mapcar #'(lambda (reduction) (list (parser-rule-name (reduction-parent-rule reduction)) (reduction-child-index reduction))) head-reductions)) (dolist (reduction head-reductions) (push reduction (parser-rule-reductions child-rule))) )))) (defun possible-start-of-reduction? (child-rule reduction) (let* ((parent-rule (reduction-parent-rule reduction)) (child-index (reduction-child-index reduction))) (and (or (eq child-index 0) (parser-anyof-rule-p parent-rule) (parser-pieces-rule-p parent-rule) (and (parser-tuple-rule-p parent-rule) (let ((items (parser-tuple-rule-items parent-rule))) (dotimes (i child-index t) (unless (parser-rule-item-optional? (svref items i)) (return nil)))))) (let ((child-precedence (parser-rule-precedence child-rule))) (or (null child-precedence) (or (not (parser-tuple-rule-p parent-rule)) (let* ((parent-item (svref (parser-tuple-rule-items parent-rule) child-index)) (parent-precedence (parser-rule-item-precedence parent-item))) (or (null parent-precedence) (>= parent-precedence child-precedence))))))))) (defun keyword-triggered-rule? (parser rule-name) (aux-keyword-triggered-rule? parser rule-name nil)) (defun aux-keyword-triggered-rule? (parser item-or-rule-name parent-rule-names) (let ((rule-name (if (parser-rule-item-p item-or-rule-name) (parser-rule-item-rule item-or-rule-name) item-or-rule-name))) (if (member rule-name parent-rule-names) nil (let ((rule (find-parser-rule parser rule-name))) (cond ((parser-keyword-rule-p rule) t) ((parser-id-rule-p rule) (aux-keyword-triggered-rule? parser (parser-id-rule-subrule rule) (push rule-name parent-rule-names))) ((parser-anyof-rule-p rule) (do-parser-rule-items (item rule t) (unless (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names)) (return nil)))) ((parser-tuple-rule-p rule) (do-parser-rule-items (item rule t) (cond ((not (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names))) (return nil)) ((not (parser-rule-item-optional? item)) (return t))))) ((parser-pieces-rule-p rule) (do-parser-rule-items (item rule t) (unless (aux-keyword-triggered-rule? parser item (push rule-name parent-rule-names)) (return nil)))) (t nil)))))) (defun install-bvs (parser) (when-debugging (comment "=================================") (comment "Installing bit vectors") (comment "- - - - - - - - - - - - - - - - -")) (install-rule-bvis parser) sets parser - scratch - bv , parser - zero - bv ) (defun initialize-p2bvi-keys (parser) (when-debugging (comment "Initializing precedences")) (dolist (rule (parser-rules parser)) (let ((rule-precedence (parser-rule-precedence rule))) (setf (parser-rule-p2bvi-map rule) `((,rule-precedence)))))) (defun compute-closure-for-p2bvi-keys (parser) (when-debugging (comment "Computing fixpoint for precedences")) (let (#+DEBUG-PARSER (n 0) (rules (parser-rules parser)) (do-another-round? t)) (loop while do-another-round? do (when-debugging (comment " Precedences Round ~D" (incf n))) (setq do-another-round? nil) (dolist (rule rules) (parser-anyof-rule (update-p2bvi-keys-for-anyof-rule parser rule)) (otherwise nil)) (setq do-another-round? t)))))) (defun update-p2bvi-keys-for-anyof-rule (parser anyof-rule) (cond ((not (null (parser-rule-precedence anyof-rule))) nil) ((null (parser-rule-semantics anyof-rule)) nil) (t (let* ((anyof-p2bvi-alist (parser-rule-p2bvi-map anyof-rule)) (changed? nil)) (do-parser-rule-items (item anyof-rule) (let* ((child-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser child-rule-name)) (child-rule-p2bvi-alist (parser-rule-p2bvi-map child-rule))) (dolist (p2bvi-pair child-rule-p2bvi-alist) (let ((child-rule-precedence (car p2bvi-pair))) (unless (assoc child-rule-precedence anyof-p2bvi-alist) (setq changed? t)) (push (cons child-rule-precedence nil) anyof-p2bvi-alist))))) (when changed? (setf (parser-rule-p2bvi-map anyof-rule) anyof-p2bvi-alist)) changed?)))) (defun sort-using-cars (alist) (sort alist #'(lambda (x y) (< (car x) (car y))))) (defun finalize-p2bvi-keys (parser) (dolist (rule (parser-rules parser)) (let* ((raw-p2bvi-alist (parser-rule-p2bvi-map rule)) (null-pair (assoc nil raw-p2bvi-alist)) (foo (remove null-pair raw-p2bvi-alist)) (sorted-p2bvi-alist (sort-using-cars foo))) (setf (parser-rule-p2bvi-map rule) (if (null null-pair) sorted-p2bvi-alist (cons null-pair sorted-p2bvi-alist)))))) (defun install-p2bvi-keys (parser) (initialize-p2bvi-keys parser) (compute-closure-for-p2bvi-keys parser) (finalize-p2bvi-keys parser)) (defun install-p2bvi-values (parser) (when-debugging (comment "Installing maps for precedence to bv indices")) (let ((bv-index -1)) (dolist (rule (parser-rules parser)) (not (superfluous-anyof-rule? rule)) (dolist (p2bvi-pair (parser-rule-p2bvi-map rule)) (setf (cdr p2bvi-pair) (incf bv-index))))))) (defun install-rule-bvis (parser) (dolist (rule (parser-rules parser)) (let ((p2bvi-alist (parser-rule-p2bvi-map rule))) (when (null (rest p2bvi-alist)) (setf (parser-rule-bvi rule) (cdr (first p2bvi-alist))))))) (defun install-bv-size (parser) (when-debugging (comment "Computing bv size")) (dolist (rule (parser-rules parser)) (not (superfluous-anyof-rule? rule)) (incf (parser-bv-size parser) (length (parser-rule-p2bvi-map rule))))) (when-debugging (comment " bv-size = ~D" (parser-bv-size parser)))) (defun install-aux-bvs (parser) (when-debugging (comment "Installing aux bv's")) (let ((bv-size (parser-bv-size parser))) (setf (parser-scratch-bv parser) (make-array bv-size :element-type 'bit :initial-element 0)) (setf (parser-zero-bv parser) (make-array bv-size :element-type 'bit :initial-element 0)))) (defun install-ht-rnp-to-handles-bv (parser) (initialize-ht-rnp-to-handles-bv parser) (compute-closures-for-handles-bvs parser) (combine-handles parser 0) ) (defun combine-handles (parser level) (let* ((again1? (install-rule-item-bvs parser)) (again2? (install-possible-children-bvs parser)) (again3? (install-composite-handles-bvs parser))) (when (or again1? again2? again3?) (if (> level 300) (warn "Ooops -- problem installing handle vectors: ~S ~S ~S " again1? again2? again3?) (combine-handles parser (1+ level)))))) (defun initialize-ht-rnp-to-handles-bv (parser) (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser))) (clrhash ht-rnp-to-handles-bv) (dolist (rule (parser-rules parser)) (let ((rule-name (parser-rule-name rule))) (dolist (p2bvi-pair (parser-rule-p2bvi-map rule)) (let* ((precedence (car p2bvi-pair)) (bv-index (cdr p2bvi-pair)) (rnp (cons rule-name precedence)) (handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (unless (null bv-index) (setf (sbit handles-bv bv-index) 1)) (setf (gethash rnp ht-rnp-to-handles-bv) handles-bv))))))) (defun compute-closures-for-handles-bvs (parser) (when-debugging (comment "Computing fixpoint for desired bv's.")) (let ((rules (parser-rules parser)) #+DEBUG-PARSER (n 0) (do-another-round? t)) (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser))) (dolist (rule rules) (let* ((rule-name (parser-rule-name rule)) (rn-nullp (cons rule-name nil))) (when (null (gethash rn-nullp ht-rnp-to-handles-bv)) (let ((p2bvi-alist (parser-rule-p2bvi-map rule)) (null-p-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (dolist (p2bvi p2bvi-alist) (let* ((precedence (car p2bvi)) (rnp-handles-bv (gethash (cons rule-name precedence) ht-rnp-to-handles-bv))) (bit-ior null-p-handles-bv rnp-handles-bv null-p-handles-bv))) (setf (gethash rn-nullp ht-rnp-to-handles-bv) null-p-handles-bv)))))) (loop while do-another-round? do (when-debugging (comment "Round ~D" (incf n))) (setq do-another-round? nil) (dolist (rule rules) (parser-anyof-rule (update-handles-bv-for-anyof-rule parser rule)) (parser-pieces-rule (update-handles-bv-for-pieces-rule parser rule)) (parser-tuple-rule (update-handles-bv-for-tuple-rule parser rule)) (parser-repeat-rule (update-handles-bv-for-repeat-rule parser rule)) (parser-id-rule nil) (parser-keyword-rule nil) (parser-atomic-rule nil) ) (setq do-another-round? t)))) )) (defun update-handles-bv-for-anyof-rule (parser rule) be used in three different ways , depending on exisitance of semantics Case 1 : precedence Case 2 : no precedence , but semantics Case 3 : no precedence , no semantics In cases 1 and 2 , we need to build a node for occurrences of this rule , where in case 3 , we can bypass this rule . In cases 2 , we do n't have a fixed precedence , but must carry along (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (anyof-rule-name (parser-rule-name rule)) (anyof-precedence (parser-rule-precedence rule)) (primary-anyof-handles-bv (if (null anyof-precedence) nil (gethash (cons anyof-rule-name anyof-precedence) ht-rnp-to-handles-bv))) (scratch-bv (parser-scratch-bv parser)) (changed? nil)) (do-parser-rule-items (item rule) (let* ((item-precedence (parser-rule-item-precedence item)) (item-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser item-rule-name)) (child-p2bvi-alist (parser-rule-p2bvi-map child-rule)) (max-pair (let ((local-max-pair nil)) (dolist (p2bvi-pair child-p2bvi-alist) (let ((child-possible-precedence (car p2bvi-pair))) (if (or (null item-precedence) (< child-possible-precedence item-precedence)) (setq local-max-pair p2bvi-pair) (return nil)))) local-max-pair)) (max-acceptable-child-precedence (car max-pair)) (item-rnp (cons item-rule-name max-acceptable-child-precedence)) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) (unless (null item-handles-bv) (let ((anyof-handles-bv (or primary-anyof-handles-bv (gethash (cons anyof-rule-name max-acceptable-child-precedence) ht-rnp-to-handles-bv)))) (unless (null anyof-handles-bv) (bit-andc1 anyof-handles-bv item-handles-bv scratch-bv) (bit-ior anyof-handles-bv item-handles-bv anyof-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))))))) changed?)) (defun update-handles-bv-for-pieces-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (pieces-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (pieces-handles-bv (gethash pieces-rnp ht-rnp-to-handles-bv)) (scratch-bv (parser-scratch-bv parser)) (changed? nil)) (do-parser-rule-items (item rule) (let* ((item-rnp (cons (parser-rule-item-rule item) (parser-rule-item-precedence item))) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) (unless (null item-handles-bv) (bit-andc1 pieces-handles-bv item-handles-bv scratch-bv) (bit-ior pieces-handles-bv item-handles-bv pieces-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))))) changed?)) (defun update-handles-bv-for-tuple-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (tuple-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (tuple-handles-bv (gethash tuple-rnp ht-rnp-to-handles-bv)) (scratch-bv (parser-scratch-bv parser)) (changed? nil)) (do-parser-rule-items (head-item rule) (let* ((item-rule-name (parser-rule-item-rule head-item)) (item-precedence (parser-rule-item-precedence head-item)) (item-rnp (cons item-rule-name item-precedence)) (item-handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) (unless (null item-handles-bv) (bit-andc1 tuple-handles-bv item-handles-bv scratch-bv) (bit-ior tuple-handles-bv item-handles-bv tuple-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))) (unless (parser-rule-item-optional? head-item) (return nil)))) changed?)) (defun update-handles-bv-for-repeat-rule (parser rule) (let* ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (repeat-rnp (cons (parser-rule-name rule) (parser-rule-precedence rule))) (repeat-handles-bv (gethash repeat-rnp ht-rnp-to-handles-bv)) (element-item (parser-repeat-rule-element rule)) (element-rnp (cons (parser-rule-item-rule element-item) (parser-rule-item-precedence element-item))) (element-handles-bv (gethash element-rnp ht-rnp-to-handles-bv)) (scratch-bv (parser-scratch-bv parser)) (changed? nil)) (unless (null element-handles-bv) (bit-andc1 repeat-handles-bv element-handles-bv scratch-bv) (bit-ior repeat-handles-bv element-handles-bv repeat-handles-bv) (unless (equal scratch-bv (parser-zero-bv parser)) (setq changed? t))) changed?)) (defun install-rule-item-bvs (parser) (let ((ht-rnp-to-handles-bv (parser-ht-rnp-to-handles-bv parser)) (bv-size (parser-bv-size parser)) (again? nil)) (dolist (rule (parser-rules parser)) (do-parser-rule-items (item rule) (let* ((item-precedence (parser-rule-item-precedence item)) (item-rule-name (parser-rule-item-rule item)) (child-rule (find-parser-rule parser item-rule-name)) (child-p2bvi-alist (parser-rule-p2bvi-map child-rule)) (children-bv (make-array bv-size :element-type 'bit :initial-element 0)) (item-rnp (let ((max-allowed-precedence-seen nil)) (dolist (p2bvi-pair child-p2bvi-alist) (let ((child-possible-precedence (car p2bvi-pair)) (child-possible-bvi (cdr p2bvi-pair))) (cond ((null child-possible-bvi) nil) ((or (null item-precedence) (null child-possible-precedence) (<= child-possible-precedence item-precedence)) (setf (sbit children-bv child-possible-bvi) 1) (when (or (null max-allowed-precedence-seen) (> child-possible-precedence max-allowed-precedence-seen)) (setq max-allowed-precedence-seen child-possible-precedence)))))) (let ((effective-item-precedence (if (null item-precedence) item-precedence max-allowed-precedence-seen))) (cons item-rule-name effective-item-precedence)))) (handles-bv (gethash item-rnp ht-rnp-to-handles-bv))) (parser-anyof-rule (let ((new (parser-anyof-rule-possible-handles-bv child-rule))) (unless (null new) (setq handles-bv (bit-ior handles-bv new))))) (parser-pieces-rule (let ((new (parser-pieces-rule-possible-handles-bv child-rule))) (unless (null new) (setq handles-bv (bit-ior handles-bv new))))) (t (do-parser-rule-items (head-item child-rule) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv head-item))) (unless (null item-handles-bv) (setq handles-bv (bit-ior handles-bv item-handles-bv))) (unless (parser-rule-item-optional? head-item) (return nil)))))) (unless (or (and (equalp (parser-zero-bv parser) children-bv) (not (null (parser-rule-item-possible-children-bv item)))) (equalp (parser-rule-item-possible-children-bv item) children-bv)) (setq again? 1) (setf (parser-rule-item-possible-children-bv item) children-bv)) (let ((new (bit-ior handles-bv children-bv))) (unless (equalp (parser-rule-item-possible-handles-bv item) new) (setq again? 2) (setf (parser-rule-item-possible-handles-bv item) new))))))) again?)) (defun install-possible-children-bvs (parser) (let ((again? nil)) (maphash #'(lambda (rule-name reductions) (let ((child-rule (find-parser-rule parser rule-name))) (when (not (superfluous-anyof-rule? child-rule)) (let ((child-rule-bvi (parser-rule-bvi child-rule)) (child-rule-precedence (parser-rule-precedence child-rule))) (dolist (reduction reductions) (let* ((parent-rule (reduction-parent-rule reduction)) (child-index (reduction-child-index reduction)) (item (svref (parser-rule-items parent-rule) child-index)) (item-precedence (parser-rule-item-precedence item)) (children-bv (parser-rule-item-possible-children-bv item)) (handles-bv (parser-rule-item-possible-handles-bv item))) (when (or (null item-precedence) (null child-rule-precedence) (<= child-rule-precedence item-precedence)) (unless (and (eq (sbit children-bv child-rule-bvi) 1) (eq (sbit handles-bv child-rule-bvi) 1)) (setq again? 3) (setf (sbit children-bv child-rule-bvi) 1) (setf (sbit handles-bv child-rule-bvi) 1) )))))))) (parser-ht-name-to-reductions parser)) again?)) (defun install-composite-handles-bvs (parser) (let ((bv-size (parser-bv-size parser)) (again? nil)) (dolist (rule (parser-rules parser)) (parser-anyof-rule (let ((composite-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (unless (null (parser-rule-bvi rule)) (setf (sbit composite-handles-bv (parser-rule-bvi rule)) 1)) (do-parser-rule-items (item rule) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv item))) (unless (null item-handles-bv) (bit-ior composite-handles-bv item-handles-bv composite-handles-bv)))) (unless (equalp (parser-anyof-rule-possible-handles-bv rule) composite-handles-bv) (setq again? 4)) (setf (parser-anyof-rule-possible-handles-bv rule) composite-handles-bv))) (parser-pieces-rule (let ((composite-handles-bv (make-array bv-size :element-type 'bit :initial-element 0))) (setf (sbit composite-handles-bv (parser-rule-bvi rule)) 1) (do-parser-rule-items (item rule) (let* ((item-handles-bv (parser-rule-item-possible-handles-bv item))) (unless (null item-handles-bv) (bit-ior composite-handles-bv item-handles-bv composite-handles-bv)))) (unless (equalp (parser-pieces-rule-possible-handles-bv rule) composite-handles-bv) (setq again? 5)) (setf (parser-pieces-rule-possible-handles-bv rule) composite-handles-bv))) )) again?)) (defun install-default-semantic-alist (parser) (when-debugging (comment "=================================") (comment "Installing default semantic alist") (comment "- - - - - - - - - - - - - - - - -")) (let ((all-numbers '()) (alist '())) (dolist (rule (parser-rules parser)) (let* ((pattern (parser-rule-semantics rule)) (numbers (find-numbers-in pattern))) (dolist (number numbers) (pushnew number all-numbers)))) (dolist (number all-numbers) (push (cons number :unspecified) alist)) (setf (parser-default-semantic-alist parser) alist))) (defun find-numbers-in (pattern) (cond ((numberp pattern) (list pattern)) ((atom pattern) nil) (t (nconc (find-numbers-in (car pattern)) (find-numbers-in (cdr pattern)))))) (defun install-special-rules (parser) (when-debugging (comment "=================================") (comment "Installing special rules") (comment "- - - - - - - - - - - - - - - - -")) (let ((symbol-rule (maybe-find-parser-rule parser :SYMBOL)) (string-rule (maybe-find-parser-rule parser :STRING)) (number-rule (maybe-find-parser-rule parser :NUMBER)) (character-rule (maybe-find-parser-rule parser :CHARACTER)) (pragma-rule (maybe-find-parser-rule parser :PRAGMA)) (toplevel-rule (maybe-find-parser-rule parser :TOPLEVEL))) (when (null symbol-rule) (warn "Cannot find rule named :SYMBOL")) (when (null string-rule) (warn "Cannot find rule named :STRING")) (when (null number-rule) (warn "Cannot find rule named :NUMBER")) (when (null character-rule) (warn "Cannot find rule named :CHARACTER")) (when (null toplevel-rule) (warn "Cannot find rule named :TOPLEVEL")) (when (null pragma-rule) (warn "Cannot find rule named :PRAGMA")) (setf (parser-symbol-rule parser) symbol-rule) (setf (parser-string-rule parser) string-rule) (setf (parser-number-rule parser) number-rule) (setf (parser-character-rule parser) character-rule) (setf (parser-toplevel-rule parser) toplevel-rule) (setf (parser-pragma-rule parser) pragma-rule) )) (defun install-pprinters (parser) (when-debugging (comment "=================================") (comment "Installing pprinters") (comment "- - - - - - - - - - - - - - - - -")) (let ((ht-expr-to-parser-rules (parser-ht-expr-to-parser-rules parser)) (ht-car-to-parser-rules (parser-ht-car-to-parser-rules parser))) (dolist (rule (parser-rules parser)) (install-pprinter-rule rule ht-expr-to-parser-rules ht-car-to-parser-rules)))) (defun install-pprinter-rule (rule ht-expr-to-parser-rules ht-car-to-parser-rules) (let ((semantics (parser-rule-semantics rule))) (cond ((consp semantics) (push rule (gethash (car semantics) ht-car-to-parser-rules))) ((null semantics) nil) (t (push rule (gethash semantics ht-expr-to-parser-rules)))))) (defun propagate-optionals (&optional (parser *current-parser*)) (debugging-comment "========================================") (debugging-comment "First round: look for optional rules.") (loop (unless (propagate-optional-one-round parser) (return nil)) (debugging-comment "========================================") (debugging-comment "New round: look for more optional rules.")) (debugging-comment "========================================")) (defparameter *bogus-locations* (let ((*parser-source* '(:internal "parser initialization"))) (list (cons :left-pos -1) (cons :left-line -1) (cons :left-column -1) (cons :left-lc (cons -1 -1)) (cons :left-lcb (vector -1 -1 -1)) (cons :right-pos -1) (cons :right-line -1) (cons :right-column -1) (cons :right-lc (cons -1 -1)) (cons :right-lcb (vector -1 -1 -1)) (cons :region (make-region (vector -1 -1 -1) (vector -1 -1 -1)))))) (defun propagate-optional-one-round (parser) (let ((ht-name-to-rule (parser-ht-name-to-rule parser)) (changed? nil)) (maphash #'(lambda (rule-name rule) (declare (ignore rule-name)) (let* ((items (parser-rule-items rule)) (n (length items)) (all-optional? (and (> n 0) (dotimes (i n t) (let ((item (svref items i))) (unless (null item) (when (not (parser-rule-item-optional? item)) (return nil)))))))) (when all-optional? (unless (parser-rule-optional? rule) (setq changed? t) (setf (parser-rule-optional? rule) t) (let ((semantic-pattern (parser-rule-semantics rule))) (when (not (null semantic-pattern)) (let ((semantic-alist *bogus-locations*) (items (parser-rule-items rule))) (dotimes (i n) (let ((item (svref items i))) (unless (null item) (let ((index (parser-rule-item-semantic-index item))) (unless (null index) (let ((default (parser-rule-item-default-semantics item))) (push (cons index (if (keywordp default) default (list 'quote default))) semantic-alist))))))) (setf (parser-rule-default-semantics rule) (sanitize-sexpression (sublis-result semantic-alist semantic-pattern)))))) ( when ( parser - repeat - rule - p rule ) ( setf ( parser - rule - default - semantics rule ) ' ( ) ) ) (debugging-comment "Rule ~S is now optional with semantics ~S." rule (parser-rule-default-semantics rule)) )))) ht-name-to-rule) (maphash #'(lambda (rule-name rule) (declare (ignore rule-name)) (let* ((items (parser-rule-items rule)) (n (length items))) (dotimes (i n t) (let ((item (svref items i))) (unless (null item) (let* ((item-rule-name (parser-rule-item-rule item)) (item-rule (gethash item-rule-name ht-name-to-rule))) (when (parser-rule-optional? item-rule) (unless (parser-rule-item-optional? item) (setq changed? t) (setf (parser-rule-item-optional? item) t) (setf (parser-rule-item-default-semantics item) (parser-rule-default-semantics item-rule)) (debugging-comment "In rule ~30S, item ~D (~S) is now optional with semantics ~S." rule i item-rule-name (parser-rule-item-default-semantics item)))))))))) ht-name-to-rule) changed ? will be NIL once we reach a fixpoint ( probably about 2 rounds ) changed?)) (defun sanitize-sexpression (s) (cond ((atom s) s) ((eq (car s) 'quote) (if (or (eq (cadr s) nil) (eq (cadr s) t) (keywordp (cadr s))) (cadr s) s)) ((and (eq (car s) 'if) (equal (cadr s) '(EQ (QUOTE :UNSPECIFIED) :UNSPECIFIED))) (sanitize-sexpression (caddr s))) ((and (atom (cdr s)) (not (null (cdr s)))) :ILLEGAL-SEXPRESSION) (t (mapcar #'sanitize-sexpression s))))
2253be9c48fa9990d5fe5c936ef6c16ba3999c7cd5bb585d2594ece3adc563b2
haslab/HAAP
minimalistic.hs
# LANGUAGE EmptyDataDecls , DeriveGeneric , OverloadedStrings , ScopedTypeVariables # | Module : Main Description : The @minimalistic@ HAAP example This module presents a minimalistic example of the usage of HAAP , consisting on testing an @HSpec@ specification , running several code analysis plugins , providing global feedback with the @ranking@ and @tournament@ plugins , visualization of solutions with @CodeWorld@ , all connected by a webpage generated by @Hakyll@. Module : Main Description : The @minimalistic@ HAAP example This module presents a minimalistic example of the usage of HAAP, consisting on testing an @HSpec@ specification, running several code analysis plugins, providing global feedback with the @ranking@ and @tournament@ plugins, visualization of solutions with @CodeWorld@, all connected by a webpage generated by @Hakyll@. -} module Main where import HAAP import Data.Default import Data.Binary import Data.Char import Data.Monoid hiding ((<>)) import qualified Data.Map as Map import Data.Unique import Control.DeepSeq import Control.Monad.IO.Class import System.Random.Shuffle import System.Process import GHC.Generics (Generic(..)) example :: Project example = Project { projectName = "minimalistic" , projectPath = "." , projectTmpPath = "tmp" , projectGroups = [] , projectTasks = [] } emptyLi1DB = Example_DB (HaapTourneyDB 1 []) data Example_DB = Example_DB { exTourneyDB :: HaapTourneyDB ExPlayer } deriving (Generic) instance Binary Example_DB lnsTourney :: DBLens (BinaryDB Example_DB) (HaapTourneyDB ExPlayer) lnsTourney = DBLens (BinaryDBQuery exTourneyDB) (\st -> BinaryDBUpdate $ \db -> ((),db { exTourneyDB = st }) ) | An HAAP script that runs tests with the plugin , runs several code analysis plugins , generates feedback with the @ranking@ and @tournament@ plugins , provides visualization with the @CodeWorld@ plugin and uses the @Hakyll@ plugin to generate a webpage that connects all artifacts . An HAAP script that runs tests with the @HSpec@ plugin, runs several code analysis plugins, generates feedback with the @ranking@ and @tournament@ plugins, provides visualization with the @CodeWorld@ plugin and uses the @Hakyll@ plugin to generate a webpage that connects all artifacts. -} main = do let hakyllArgs = HakyllArgs defaultConfiguration False True def let dbArgs = BinaryDBArgs "db" emptyLi1DB def let specArgs = HaapSpecArgs HaapSpecQuickCheck Nothing def let haddockArgs = HaddockArgs (Sandbox Nothing) "mininalistic" [] "." ["minimalistic.hs"] "doc" let hlintArgs = HLintArgs (Sandbox Nothing) [] "." ["minimalistic.hs"] "hlint.html" let homplexityArgs = HomplexityArgs (Sandbox Nothing) [] "." ["../../src/"] "homplexity.html" let hpcArgs = HpcArgs "HPCTest" def def (Just "hpc") False load the @Hakyll@ and database @DB@ plugins runHaap example $ useHakyll hakyllArgs $ useBinaryDB dbArgs $ do load the plugin (spec,rank,tour) <- useSpec specArgs $ do run and render the results in @spec.html@ spec <- renderHaapSpecs "spec.html" "Spec" [("spec1",exSpec)] run the @ranking@ and @tournament@ plugins and render the results (rank,tour) <- useRank $ do rank <- renderHaapSpecRank exRank tour <- useTourney $ renderHaapTourney exTourney return (rank,tour) return (spec,rank,tour) load and run the @Haddock@ plugin hadcks <- useAndRunHaddock haddockArgs load and run the @HLint@ plugin hlint <- useAndRunHLint hlintArgs load and run the @Homplexity@ plugin homplexity <- useAndRunHomplexity homplexityArgs -- load and run the @HPC@ plugin (_,hpc) <- useAndRunHpc hpcArgs () $ const $ do runBaseIO $ system "./HPCTest < ints" runBaseIO $ system "./HPCTest < ints" return () load and run the @CodeWorld@ plugin over two visualizations cw1 <- useAndRunCodeWorld codeworldDrawArgs cw2 <- useAndRunCodeWorld codeworldGameArgs -- create an @index.html@ webpage using the @Hakyll@ plugin and connect to other artifacts hakyllRules $ do match (fromGlob ("*.png")) $ do route idRoute compile copyFileCompiler match (fromGlob ("*.jpg")) $ do route idRoute compile copyFileCompiler match (fromGlob ("templates/minimalistic.html")) $ do route idRoute compile templateBodyCompiler create ["index.html"] $ do route idRoute compile $ do let exCtx = constField "projectpath" "." `mappend` constField "spec" spec `mappend` constField "rank" rank `mappend` constField "tour" tour `mappend` listField "haddocks" (field "haddock" (return . itemBody)) (mapM makeItem hadcks) `mappend` constField "hlint" hlint `mappend` constField "homplexity" homplexity `mappend` constField "hpc" hpc `mappend` listField "cws" (field "cw" (return . itemBody)) (mapM makeItem [cw1,cw2]) makeItem "" >>= loadAndApplyTemplate "templates/minimalistic.html" exCtx return () {-| A concrete specification to be tested. -} exSpec :: HaapSpec exSpec = bounded "x" [97,98,3,4] $ \x -> bounded "y" "abcd" $ \y -> testEqual x (ord y) {-| A specification to be used in a ranking, will be run for each group. -} exRankSpec :: Int -> HaapSpec exRankSpec i = bounded "x" [1,2,3,4,5] $ \x -> testEqual x i {-| Calculates a quantitative score from the results of the tests. -} exRankScore :: HaapTestRes -> FloatScore exRankScore HaapTestOk = FloatScore 1 exRankScore _ = FloatScore 0 | Builds a global ranking according to the result of for each group , normalized according to @exRankScore@. Builds a global ranking according to the result of @exRankSpec@ for each group, normalized according to @exRankScore@. -} exRank :: HaapStack t m => HaapSpecRank t m Int FloatScore exRank = HaapSpecRank "ranks.html" "Ranks" "Group" "Ranking" [1..10::Int] (exRankSpec) (return . exRankScore) data ExPlayer = ExPlayer (String,Bool) deriving (Eq,Ord,Show,Generic) instance Binary ExPlayer instance NFData ExPlayer instance Pretty ExPlayer where pretty (ExPlayer x) = text (fst x) instance TourneyPlayer ExPlayer where isDefaultPlayer (ExPlayer (_,b)) = b defaultPlayer = do i <- newUnique return $ ExPlayer ("random" ++ show (hashUnique i),True) exTourney :: MonadIO m => HaapTourney t m (BinaryDB Example_DB) ExPlayer Link exTourney = HaapTourney 10 "Tourney" bestof "Group" grupos "torneio" lnsTourney match (return) (const $ return ()) where bestof = const 1 grupos = Left $ map (ExPlayer . mapFst show) $ zip [1..] (replicate 4 False ++ replicate 10 True) match tno rno mno players = do players' <- runBaseIO' $ shuffleM players return (zip players' [1..],"link") {-| Arguments for the @CodeWorld@ plugin to draw maps. -} codeworldDrawArgs :: CodeWorldArgs codeworldDrawArgs = CodeWorldArgs (Left "MMDraw.hs") "Draw" (CWDraw CWDrawButton "[Avanca,Avanca]") ghcjs def "codeworld" imgs [] where ghcjs = def { ghcjsSafe = False } -- db = ["../.cabal-sandbox/x86_64-osx-ghcjs-0.2.1.9007019-ghc8_0_1-packages.conf.d/"] imgs = [("recta","recta.png"),("curva","curva.png"),("lava","lava.jpg"),("carro","carro.png")] {-| Arguments for the @CodeWorld@ plugin to play a game. -} codeworldGameArgs :: CodeWorldArgs codeworldGameArgs = CodeWorldArgs (Left "MMGame.hs") "Game" (CWGame CWGameConsole) ghcjs def "codeworld" [] [] where ghcjs = def { ghcjsSafe = False } -- db = ["../.cabal-sandbox/x86_64-osx-ghcjs-0.2.1.9007019-ghc8_0_1-packages.conf.d/"]
null
https://raw.githubusercontent.com/haslab/HAAP/5acf9efaf0e5f6cba1c2482e51bda703f405a86f/examples/minimalistic/minimalistic.hs
haskell
load and run the @HPC@ plugin create an @index.html@ webpage using the @Hakyll@ plugin and connect to other artifacts | A concrete specification to be tested. | A specification to be used in a ranking, will be run for each group. | Calculates a quantitative score from the results of the tests. | Arguments for the @CodeWorld@ plugin to draw maps. db = ["../.cabal-sandbox/x86_64-osx-ghcjs-0.2.1.9007019-ghc8_0_1-packages.conf.d/"] | Arguments for the @CodeWorld@ plugin to play a game. db = ["../.cabal-sandbox/x86_64-osx-ghcjs-0.2.1.9007019-ghc8_0_1-packages.conf.d/"]
# LANGUAGE EmptyDataDecls , DeriveGeneric , OverloadedStrings , ScopedTypeVariables # | Module : Main Description : The @minimalistic@ HAAP example This module presents a minimalistic example of the usage of HAAP , consisting on testing an @HSpec@ specification , running several code analysis plugins , providing global feedback with the @ranking@ and @tournament@ plugins , visualization of solutions with @CodeWorld@ , all connected by a webpage generated by @Hakyll@. Module : Main Description : The @minimalistic@ HAAP example This module presents a minimalistic example of the usage of HAAP, consisting on testing an @HSpec@ specification, running several code analysis plugins, providing global feedback with the @ranking@ and @tournament@ plugins, visualization of solutions with @CodeWorld@, all connected by a webpage generated by @Hakyll@. -} module Main where import HAAP import Data.Default import Data.Binary import Data.Char import Data.Monoid hiding ((<>)) import qualified Data.Map as Map import Data.Unique import Control.DeepSeq import Control.Monad.IO.Class import System.Random.Shuffle import System.Process import GHC.Generics (Generic(..)) example :: Project example = Project { projectName = "minimalistic" , projectPath = "." , projectTmpPath = "tmp" , projectGroups = [] , projectTasks = [] } emptyLi1DB = Example_DB (HaapTourneyDB 1 []) data Example_DB = Example_DB { exTourneyDB :: HaapTourneyDB ExPlayer } deriving (Generic) instance Binary Example_DB lnsTourney :: DBLens (BinaryDB Example_DB) (HaapTourneyDB ExPlayer) lnsTourney = DBLens (BinaryDBQuery exTourneyDB) (\st -> BinaryDBUpdate $ \db -> ((),db { exTourneyDB = st }) ) | An HAAP script that runs tests with the plugin , runs several code analysis plugins , generates feedback with the @ranking@ and @tournament@ plugins , provides visualization with the @CodeWorld@ plugin and uses the @Hakyll@ plugin to generate a webpage that connects all artifacts . An HAAP script that runs tests with the @HSpec@ plugin, runs several code analysis plugins, generates feedback with the @ranking@ and @tournament@ plugins, provides visualization with the @CodeWorld@ plugin and uses the @Hakyll@ plugin to generate a webpage that connects all artifacts. -} main = do let hakyllArgs = HakyllArgs defaultConfiguration False True def let dbArgs = BinaryDBArgs "db" emptyLi1DB def let specArgs = HaapSpecArgs HaapSpecQuickCheck Nothing def let haddockArgs = HaddockArgs (Sandbox Nothing) "mininalistic" [] "." ["minimalistic.hs"] "doc" let hlintArgs = HLintArgs (Sandbox Nothing) [] "." ["minimalistic.hs"] "hlint.html" let homplexityArgs = HomplexityArgs (Sandbox Nothing) [] "." ["../../src/"] "homplexity.html" let hpcArgs = HpcArgs "HPCTest" def def (Just "hpc") False load the @Hakyll@ and database @DB@ plugins runHaap example $ useHakyll hakyllArgs $ useBinaryDB dbArgs $ do load the plugin (spec,rank,tour) <- useSpec specArgs $ do run and render the results in @spec.html@ spec <- renderHaapSpecs "spec.html" "Spec" [("spec1",exSpec)] run the @ranking@ and @tournament@ plugins and render the results (rank,tour) <- useRank $ do rank <- renderHaapSpecRank exRank tour <- useTourney $ renderHaapTourney exTourney return (rank,tour) return (spec,rank,tour) load and run the @Haddock@ plugin hadcks <- useAndRunHaddock haddockArgs load and run the @HLint@ plugin hlint <- useAndRunHLint hlintArgs load and run the @Homplexity@ plugin homplexity <- useAndRunHomplexity homplexityArgs (_,hpc) <- useAndRunHpc hpcArgs () $ const $ do runBaseIO $ system "./HPCTest < ints" runBaseIO $ system "./HPCTest < ints" return () load and run the @CodeWorld@ plugin over two visualizations cw1 <- useAndRunCodeWorld codeworldDrawArgs cw2 <- useAndRunCodeWorld codeworldGameArgs hakyllRules $ do match (fromGlob ("*.png")) $ do route idRoute compile copyFileCompiler match (fromGlob ("*.jpg")) $ do route idRoute compile copyFileCompiler match (fromGlob ("templates/minimalistic.html")) $ do route idRoute compile templateBodyCompiler create ["index.html"] $ do route idRoute compile $ do let exCtx = constField "projectpath" "." `mappend` constField "spec" spec `mappend` constField "rank" rank `mappend` constField "tour" tour `mappend` listField "haddocks" (field "haddock" (return . itemBody)) (mapM makeItem hadcks) `mappend` constField "hlint" hlint `mappend` constField "homplexity" homplexity `mappend` constField "hpc" hpc `mappend` listField "cws" (field "cw" (return . itemBody)) (mapM makeItem [cw1,cw2]) makeItem "" >>= loadAndApplyTemplate "templates/minimalistic.html" exCtx return () exSpec :: HaapSpec exSpec = bounded "x" [97,98,3,4] $ \x -> bounded "y" "abcd" $ \y -> testEqual x (ord y) exRankSpec :: Int -> HaapSpec exRankSpec i = bounded "x" [1,2,3,4,5] $ \x -> testEqual x i exRankScore :: HaapTestRes -> FloatScore exRankScore HaapTestOk = FloatScore 1 exRankScore _ = FloatScore 0 | Builds a global ranking according to the result of for each group , normalized according to @exRankScore@. Builds a global ranking according to the result of @exRankSpec@ for each group, normalized according to @exRankScore@. -} exRank :: HaapStack t m => HaapSpecRank t m Int FloatScore exRank = HaapSpecRank "ranks.html" "Ranks" "Group" "Ranking" [1..10::Int] (exRankSpec) (return . exRankScore) data ExPlayer = ExPlayer (String,Bool) deriving (Eq,Ord,Show,Generic) instance Binary ExPlayer instance NFData ExPlayer instance Pretty ExPlayer where pretty (ExPlayer x) = text (fst x) instance TourneyPlayer ExPlayer where isDefaultPlayer (ExPlayer (_,b)) = b defaultPlayer = do i <- newUnique return $ ExPlayer ("random" ++ show (hashUnique i),True) exTourney :: MonadIO m => HaapTourney t m (BinaryDB Example_DB) ExPlayer Link exTourney = HaapTourney 10 "Tourney" bestof "Group" grupos "torneio" lnsTourney match (return) (const $ return ()) where bestof = const 1 grupos = Left $ map (ExPlayer . mapFst show) $ zip [1..] (replicate 4 False ++ replicate 10 True) match tno rno mno players = do players' <- runBaseIO' $ shuffleM players return (zip players' [1..],"link") codeworldDrawArgs :: CodeWorldArgs codeworldDrawArgs = CodeWorldArgs (Left "MMDraw.hs") "Draw" (CWDraw CWDrawButton "[Avanca,Avanca]") ghcjs def "codeworld" imgs [] where ghcjs = def { ghcjsSafe = False } imgs = [("recta","recta.png"),("curva","curva.png"),("lava","lava.jpg"),("carro","carro.png")] codeworldGameArgs :: CodeWorldArgs codeworldGameArgs = CodeWorldArgs (Left "MMGame.hs") "Game" (CWGame CWGameConsole) ghcjs def "codeworld" [] [] where ghcjs = def { ghcjsSafe = False }
71479895cc5f14cc39b41f4e735209b8dc0f1d569aa7217117661f1aeb4718ee
tlaplus/tlapm
index.ml
Copyright 2004 INRIA open Expr;; open Misc;; open Mlproof;; open Printf;; let ( === ) = ( = );; let ( = ) = ();; let string_equal x y = String.compare x y == 0;; reduce to 17 for debugging module HE = Hashtbl.Make (Expr);; let allforms = (HE.create tblsize : int HE.t);; type sym_table = (string, expr list ref) Hashtbl.t;; let posforms = (Hashtbl.create tblsize : sym_table);; let negforms = (Hashtbl.create tblsize : sym_table);; type formula_rec = { mutable present : bool; mutable proofs : (Mlproof.proof * int ref * formula_rec array) list; };; let proofs = (HE.create tblsize : formula_rec HE.t);; let new_forms = ref [];; exception No_head;; type head = Sym of string | Tau of expr | Meta of expr;; let get_head e = match e with | Eapp (s, _, _) | Evar (s, _) -> Sym s | Emeta _ -> Meta e | Etau _ -> Tau e | Etrue -> Sym "$true" | Efalse -> Sym "$false" | Eall _ -> Sym "A." | Eex _ -> Sym "E." | _ -> raise No_head ;; let add_element tbl k v = try let lr = Hashtbl.find tbl k in lr := v :: !lr with Not_found -> Hashtbl.add tbl k (ref [v]); ;; let remove_element tbl k v = let lr = Hashtbl.find tbl k in match !lr with | [] -> assert false | [h] -> Hashtbl.remove tbl k; | h::t when Expr.equal h v -> lr := t; | _ -> () ;; (* ==== *) let act_head action tbl key v = try match get_head key with | Sym s -> action tbl s v | Tau e -> action tbl "t." v | Meta e -> action tbl "" v with No_head -> () ;; let negpos action e = match e with | Enot (f, _) -> act_head action negforms f e; | f -> act_head action posforms f e; ;; let cur_num_forms = ref 0;; let get_all () = HE.fold (fun e g l -> (e, g) :: l) allforms [];; let member e = HE.mem allforms e;; let get_goalness e = HE.find allforms e;; let add_g e = (e, get_goalness e);; let find_pos s = try List.map add_g !(Hashtbl.find posforms s) with Not_found -> [] ;; let find_neg s = try List.map add_g !(Hashtbl.find negforms s) with Not_found -> [] ;; (* ==== *) type direction = Left | Right | Both;; type trans_table = (string * head, expr list ref) Hashtbl.t;; let pos_trans_left = (Hashtbl.create tblsize : trans_table);; let pos_trans_right = (Hashtbl.create tblsize : trans_table);; let rec do_trans action e = match e with | Eapp (r, [e1; e2], _) -> action pos_trans_left (r, get_head e1) e; action pos_trans_right (r, get_head e2) e; | _ -> assert false ;; let add_trans e = do_trans add_element e; ;; let try_find tbl k = try !(Hashtbl.find tbl k) with Not_found -> [] ;; let find_all_rel tbl rel = let f (r, _) elr accu = if string_equal r rel then !elr @@ accu else accu in Hashtbl.fold f tbl [] ;; let find_trans_left rel head = List.map add_g (try_find pos_trans_left (rel, head)) ;; let find_trans_right rel head = List.map add_g (try_find pos_trans_right (rel, head)) ;; let find_all_head tbl head = let f (_, h) elr accu = match head, h with | Meta e1, Meta e2 when e1 == e2 -> !elr @@ accu | Sym s1, Sym s2 when s1 === s2 -> !elr @@ accu | Tau t1, Tau t2 when t1 === t2 -> !elr @@ accu | _, _ -> accu in Hashtbl.fold f tbl [] ;; let remove_trans e = match e with | Eapp (r, [e1; e2], _) -> begin try remove_element pos_trans_left (r, get_head e1) e; with No_head | Not_found -> () end; begin try remove_element pos_trans_right (r, get_head e2) e; with No_head | Not_found -> () end; | _ -> () ;; let neg_trans_left = (Hashtbl.create tblsize : trans_table);; let neg_trans_right = (Hashtbl.create tblsize : trans_table);; type head_table = (head, expr list ref) Hashtbl.t;; let all_neg_trans_left = (Hashtbl.create tblsize : head_table);; let all_neg_trans_right = (Hashtbl.create tblsize : head_table);; let add_negtrans e = match e with | Enot (Eapp (r, [e1; e2], _), _) -> begin try add_element neg_trans_left (r, get_head e1) e; add_element all_neg_trans_left (get_head e1) e; with No_head -> () end; begin try add_element neg_trans_right (r, get_head e2) e; add_element all_neg_trans_right (get_head e2) e; with No_head -> () end; | _ -> assert false; ;; let remove_negtrans e = match e with | Enot (Eapp (r, [e1; e2], _), _) -> begin try remove_element neg_trans_left (r, get_head e1) e; remove_element all_neg_trans_left (get_head e1) e; with No_head | Not_found -> () end; begin try remove_element neg_trans_right (r, get_head e2) e; remove_element all_neg_trans_right (get_head e2) e; with No_head | Not_found -> () end; | _ -> () ;; let find_negtrans_left rel head = List.map add_g (try_find neg_trans_left (rel, head)) ;; let find_negtrans_right rel head = List.map add_g (try_find neg_trans_right (rel, head)) ;; let find_all_negtrans_left head = List.map add_g (try_find all_neg_trans_left head) ;; let find_all_negtrans_right head = List.map add_g (try_find all_neg_trans_right head) ;; (* ==== *) let eq_lr = (HE.create tblsize : Expr.t HE.t);; let eq_rl = (HE.create tblsize : Expr.t HE.t);; let neq_lr = (HE.create tblsize : Expr.t HE.t);; let neq_rl = (HE.create tblsize : Expr.t HE.t);; let add_eq e = match e with | Eapp ("=", [e1; e2], _) -> HE.add eq_lr e1 e2; HE.add eq_rl e2 e1; | Enot (Eapp ("=", [e1; e2], _), _) -> HE.add neq_lr e1 e2; HE.add neq_rl e2 e1; | _ -> () ;; let remove_eq e = match e with | Eapp ("=", [e1; e2], _) -> HE.remove eq_lr e1; HE.remove eq_rl e2; | Enot (Eapp ("=", [e1; e2], _), _) -> HE.remove neq_lr e1; HE.remove neq_rl e2; | _ -> () ;; let find_eq_lr e = HE.find_all eq_lr e;; let find_eq_rl e = HE.find_all eq_rl e;; let find_neq_lr e = HE.find_all neq_lr e;; let find_neq_rl e = HE.find_all neq_rl e;; let find_eq e = List.map (fun x -> eapp ("=", [e; x])) (find_eq_lr e) @ List.map (fun x -> eapp ("=", [x; e])) (find_eq_rl e);; let find_neq e = List.map (fun x -> enot (eapp ("=", [e; x]))) (find_neq_lr e) @ List.map (fun x -> enot (eapp ("=", [x; e]))) (find_neq_rl e);; (* ==== *) let meta_set = (HE.create tblsize : unit HE.t);; let add_meta_set e = match e with | Eapp ("TLA.in", [Emeta _; e1], _) | Enot (Eapp ("TLA.in", [Emeta _; e1], _), _) -> HE.add meta_set e1 () | _ -> () ;; let remove_meta_set e = match e with | Eapp ("TLA.in", [Emeta _; e1], _) | Enot (Eapp ("TLA.in", [Emeta _; e1], _), _) -> HE.remove meta_set e1 | _ -> () ;; let is_meta_set e = HE.mem meta_set e;; (* ==== *) let eq_str = ref [];; let str_eq = ref [];; let add_str e = match e with | Eapp ("=", [e1; Eapp ("$string", [Evar (str, _)], _)], _) -> eq_str := (e1, str) :: !eq_str | Eapp ("=", [Eapp ("$string", [Evar (str, _)], _); e2], _) -> str_eq := (e2, str) :: !str_eq | _ -> () ;; let remove_str e = match e with | Eapp ("=", [e1; Eapp ("$string", [Evar (str, _)], _)], _) -> eq_str := (match !eq_str with _ :: t -> t | _ -> assert false) | Eapp ("=", [Eapp ("$string", [Evar (str, _)], _); e2], _) -> str_eq := (match !str_eq with _ :: t -> t | _ -> assert false) | _ -> () ;; let find_eq_str () = !eq_str;; let find_str_eq () = !str_eq;; (* ==== *) let add e g = HE.add allforms e g; add_eq e; add_str e; incr cur_num_forms; if !cur_num_forms > !Globals.top_num_forms then Globals.top_num_forms := !cur_num_forms; negpos add_element e; begin try (HE.find proofs e).present <- true with Not_found -> (); end; new_forms := e :: !new_forms; ;; let remove e = decr cur_num_forms; remove_trans e; remove_negtrans e; negpos remove_element e; remove_str e; remove_eq e; HE.remove allforms e; begin try (HE.find proofs e).present <- false with Not_found -> (); end; ;; (* ==== *) let suspects = ref [];; let add_proof p = incr Globals.stored_lemmas; let get_record f = begin try HE.find proofs f with Not_found -> let r = {present = HE.mem allforms f; proofs = []} in HE.add proofs f r; r end in let recs = Array.of_list (List.map get_record p.mlconc) in suspects := [(p, ref 0, recs)] :: !suspects; ;; FIXME essayer : changer la structure pour utiliser des refcounts changer la structure de donnees pour utiliser des refcounts *) let search_proof () = let do_form f = try let r = HE.find proofs f in if r.present then begin suspects := r.proofs :: !suspects; r.proofs <- []; end; with Not_found -> () in let fs = !new_forms in new_forms := []; List.iter do_form fs; let rec loop () = match !suspects with | [] -> None | [] :: t2 -> suspects := t2; loop () | ((p, cur, recs) as lem :: t1) :: t2 -> begin try for i = !cur to Array.length recs - 1 do if not recs.(i).present then begin suspects := t1 :: t2; recs.(i).proofs <- lem :: recs.(i).proofs; cur := i+1; raise Exit; end done; for i = 0 to !cur-1 do if not recs.(i).present then begin suspects := t1 :: t2; recs.(i).proofs <- lem :: recs.(i).proofs; cur := i+1; raise Exit; end done; Some p with Exit -> loop () end in loop () ;; (* ==== *) let defs = (Hashtbl.create tblsize : (string, definition) Hashtbl.t);; let add_def d = match d with | DefReal (_, s, args, body, _) -> Hashtbl.add defs s d; | DefPseudo (h, s, args, body) -> Hashtbl.add defs s d; | DefRec (_, s, args, body) -> Hashtbl.add defs s d; ;; let has_def s = Hashtbl.mem defs s;; let get_def s = let d = Hashtbl.find defs s in match d with | DefReal (_, s, params, body, _) -> (d, params, body) | DefPseudo (hyp, s, params, body) -> (d, params, body) | DefRec (_, s, params, body) -> (d, params, body) ;; (* ==== *) let metas = (HE.create tblsize : int HE.t);; let add_meta e i = HE.add metas e i;; let remove_meta e = HE.remove metas e;; let get_meta e = HE.find metas e;; (* ==== *) let cur_num = ref (-1);; let numforms = (HE.create tblsize : int HE.t);; let formnums = ref ([| |] : expr array);; let dummy = evar " *** Index.dummy *** ";; let ext_set tbl i x = while i >= Array.length !tbl do let len = Array.length !tbl in let new_len = 2 * len + 1 in let new_tbl = Array.make new_len dummy in Array.blit !tbl 0 new_tbl 0 len; tbl := new_tbl; done; !tbl.(i) <- x; ;; let rec expr o ex = let pr = eprintf in let print_var b v = match v with | Evar (s, _) -> eprintf "%s" s | _ -> assert false in match ex with | Evar (v, _) -> pr "%s" v; | Emeta (e, _) -> pr "%s#" Namespace.meta_prefix; | Eapp (s, es, _) -> pr "(%s" s; List.iter (fun x -> pr " "; expr o x) es; pr ")"; | Enot (e, _) -> pr "(-. "; expr o e; pr ")"; | Eand (e1, e2, _) -> pr "(/\\ "; expr o e1; pr " "; expr o e2; pr ")"; | Eor (e1, e2, _) -> pr "(\\/ "; expr o e1; pr " "; expr o e2; pr ")"; | Eimply (e1, e2, _) -> pr "(=> "; expr o e1; pr " "; expr o e2; pr ")"; | Eequiv (e1, e2, _) -> pr "(<=> "; expr o e1; pr " "; expr o e2; pr ")"; | Etrue -> pr "(True)"; | Efalse -> pr "(False)"; | Eall (v, t, e, _) when t === Namespace.univ_name -> pr "(A. ((%a) " print_var v; expr o e; pr "))"; | Eall (v, t, e, _) -> pr "(A. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Eex (v, t, e, _) when t === Namespace.univ_name -> pr "(E. ((%a) " print_var v; expr o e; pr "))"; | Eex (v, t, e, _) -> pr "(E. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Etau (v, t, e, _) when t === Namespace.univ_name -> pr "(t. ((%a) " print_var v; expr o e; pr "))"; | Etau (v, t, e, _) -> pr "(t. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Elam (v, t, e, _) when t === Namespace.univ_name -> pr "((%a) " print_var v; expr o e; pr ")"; | Elam (v, t, e, _) -> pr "((%a \"%s\") " print_var v t; expr o e; pr ")"; ;; let dprint_expr e = expr () e;; let get_number e = begin try HE.find numforms e with Not_found -> incr cur_num; HE.add numforms e !cur_num; ext_set formnums !cur_num e; if !Globals.debug_flag then begin Printf.eprintf "%x --> " !cur_num; dprint_expr e; Printf.eprintf "\n"; end; !cur_num end ;; let get_formula i = if i < 0 || i >= Array.length !formnums then raise Not_found; if !formnums.(i) == dummy then raise Not_found; !formnums.(i) ;; let make_tau_name p = match p with | Etau (Evar (v, _), _, _, _) when is_prefix "zenon_" v -> Printf.sprintf "%s_%s" Namespace.tau_prefix (base26 (get_number p)) | Etau (Evar (v, _), _, _, _) -> Printf.sprintf "%s%s_%s" Namespace.tau_prefix v (base26 (get_number p)) | _ -> assert false ;;
null
https://raw.githubusercontent.com/tlaplus/tlapm/b82e2fd049c5bc1b14508ae16890666c6928975f/zenon/index.ml
ocaml
==== ==== ==== ==== ==== ==== ==== ==== ==== ====
Copyright 2004 INRIA open Expr;; open Misc;; open Mlproof;; open Printf;; let ( === ) = ( = );; let ( = ) = ();; let string_equal x y = String.compare x y == 0;; reduce to 17 for debugging module HE = Hashtbl.Make (Expr);; let allforms = (HE.create tblsize : int HE.t);; type sym_table = (string, expr list ref) Hashtbl.t;; let posforms = (Hashtbl.create tblsize : sym_table);; let negforms = (Hashtbl.create tblsize : sym_table);; type formula_rec = { mutable present : bool; mutable proofs : (Mlproof.proof * int ref * formula_rec array) list; };; let proofs = (HE.create tblsize : formula_rec HE.t);; let new_forms = ref [];; exception No_head;; type head = Sym of string | Tau of expr | Meta of expr;; let get_head e = match e with | Eapp (s, _, _) | Evar (s, _) -> Sym s | Emeta _ -> Meta e | Etau _ -> Tau e | Etrue -> Sym "$true" | Efalse -> Sym "$false" | Eall _ -> Sym "A." | Eex _ -> Sym "E." | _ -> raise No_head ;; let add_element tbl k v = try let lr = Hashtbl.find tbl k in lr := v :: !lr with Not_found -> Hashtbl.add tbl k (ref [v]); ;; let remove_element tbl k v = let lr = Hashtbl.find tbl k in match !lr with | [] -> assert false | [h] -> Hashtbl.remove tbl k; | h::t when Expr.equal h v -> lr := t; | _ -> () ;; let act_head action tbl key v = try match get_head key with | Sym s -> action tbl s v | Tau e -> action tbl "t." v | Meta e -> action tbl "" v with No_head -> () ;; let negpos action e = match e with | Enot (f, _) -> act_head action negforms f e; | f -> act_head action posforms f e; ;; let cur_num_forms = ref 0;; let get_all () = HE.fold (fun e g l -> (e, g) :: l) allforms [];; let member e = HE.mem allforms e;; let get_goalness e = HE.find allforms e;; let add_g e = (e, get_goalness e);; let find_pos s = try List.map add_g !(Hashtbl.find posforms s) with Not_found -> [] ;; let find_neg s = try List.map add_g !(Hashtbl.find negforms s) with Not_found -> [] ;; type direction = Left | Right | Both;; type trans_table = (string * head, expr list ref) Hashtbl.t;; let pos_trans_left = (Hashtbl.create tblsize : trans_table);; let pos_trans_right = (Hashtbl.create tblsize : trans_table);; let rec do_trans action e = match e with | Eapp (r, [e1; e2], _) -> action pos_trans_left (r, get_head e1) e; action pos_trans_right (r, get_head e2) e; | _ -> assert false ;; let add_trans e = do_trans add_element e; ;; let try_find tbl k = try !(Hashtbl.find tbl k) with Not_found -> [] ;; let find_all_rel tbl rel = let f (r, _) elr accu = if string_equal r rel then !elr @@ accu else accu in Hashtbl.fold f tbl [] ;; let find_trans_left rel head = List.map add_g (try_find pos_trans_left (rel, head)) ;; let find_trans_right rel head = List.map add_g (try_find pos_trans_right (rel, head)) ;; let find_all_head tbl head = let f (_, h) elr accu = match head, h with | Meta e1, Meta e2 when e1 == e2 -> !elr @@ accu | Sym s1, Sym s2 when s1 === s2 -> !elr @@ accu | Tau t1, Tau t2 when t1 === t2 -> !elr @@ accu | _, _ -> accu in Hashtbl.fold f tbl [] ;; let remove_trans e = match e with | Eapp (r, [e1; e2], _) -> begin try remove_element pos_trans_left (r, get_head e1) e; with No_head | Not_found -> () end; begin try remove_element pos_trans_right (r, get_head e2) e; with No_head | Not_found -> () end; | _ -> () ;; let neg_trans_left = (Hashtbl.create tblsize : trans_table);; let neg_trans_right = (Hashtbl.create tblsize : trans_table);; type head_table = (head, expr list ref) Hashtbl.t;; let all_neg_trans_left = (Hashtbl.create tblsize : head_table);; let all_neg_trans_right = (Hashtbl.create tblsize : head_table);; let add_negtrans e = match e with | Enot (Eapp (r, [e1; e2], _), _) -> begin try add_element neg_trans_left (r, get_head e1) e; add_element all_neg_trans_left (get_head e1) e; with No_head -> () end; begin try add_element neg_trans_right (r, get_head e2) e; add_element all_neg_trans_right (get_head e2) e; with No_head -> () end; | _ -> assert false; ;; let remove_negtrans e = match e with | Enot (Eapp (r, [e1; e2], _), _) -> begin try remove_element neg_trans_left (r, get_head e1) e; remove_element all_neg_trans_left (get_head e1) e; with No_head | Not_found -> () end; begin try remove_element neg_trans_right (r, get_head e2) e; remove_element all_neg_trans_right (get_head e2) e; with No_head | Not_found -> () end; | _ -> () ;; let find_negtrans_left rel head = List.map add_g (try_find neg_trans_left (rel, head)) ;; let find_negtrans_right rel head = List.map add_g (try_find neg_trans_right (rel, head)) ;; let find_all_negtrans_left head = List.map add_g (try_find all_neg_trans_left head) ;; let find_all_negtrans_right head = List.map add_g (try_find all_neg_trans_right head) ;; let eq_lr = (HE.create tblsize : Expr.t HE.t);; let eq_rl = (HE.create tblsize : Expr.t HE.t);; let neq_lr = (HE.create tblsize : Expr.t HE.t);; let neq_rl = (HE.create tblsize : Expr.t HE.t);; let add_eq e = match e with | Eapp ("=", [e1; e2], _) -> HE.add eq_lr e1 e2; HE.add eq_rl e2 e1; | Enot (Eapp ("=", [e1; e2], _), _) -> HE.add neq_lr e1 e2; HE.add neq_rl e2 e1; | _ -> () ;; let remove_eq e = match e with | Eapp ("=", [e1; e2], _) -> HE.remove eq_lr e1; HE.remove eq_rl e2; | Enot (Eapp ("=", [e1; e2], _), _) -> HE.remove neq_lr e1; HE.remove neq_rl e2; | _ -> () ;; let find_eq_lr e = HE.find_all eq_lr e;; let find_eq_rl e = HE.find_all eq_rl e;; let find_neq_lr e = HE.find_all neq_lr e;; let find_neq_rl e = HE.find_all neq_rl e;; let find_eq e = List.map (fun x -> eapp ("=", [e; x])) (find_eq_lr e) @ List.map (fun x -> eapp ("=", [x; e])) (find_eq_rl e);; let find_neq e = List.map (fun x -> enot (eapp ("=", [e; x]))) (find_neq_lr e) @ List.map (fun x -> enot (eapp ("=", [x; e]))) (find_neq_rl e);; let meta_set = (HE.create tblsize : unit HE.t);; let add_meta_set e = match e with | Eapp ("TLA.in", [Emeta _; e1], _) | Enot (Eapp ("TLA.in", [Emeta _; e1], _), _) -> HE.add meta_set e1 () | _ -> () ;; let remove_meta_set e = match e with | Eapp ("TLA.in", [Emeta _; e1], _) | Enot (Eapp ("TLA.in", [Emeta _; e1], _), _) -> HE.remove meta_set e1 | _ -> () ;; let is_meta_set e = HE.mem meta_set e;; let eq_str = ref [];; let str_eq = ref [];; let add_str e = match e with | Eapp ("=", [e1; Eapp ("$string", [Evar (str, _)], _)], _) -> eq_str := (e1, str) :: !eq_str | Eapp ("=", [Eapp ("$string", [Evar (str, _)], _); e2], _) -> str_eq := (e2, str) :: !str_eq | _ -> () ;; let remove_str e = match e with | Eapp ("=", [e1; Eapp ("$string", [Evar (str, _)], _)], _) -> eq_str := (match !eq_str with _ :: t -> t | _ -> assert false) | Eapp ("=", [Eapp ("$string", [Evar (str, _)], _); e2], _) -> str_eq := (match !str_eq with _ :: t -> t | _ -> assert false) | _ -> () ;; let find_eq_str () = !eq_str;; let find_str_eq () = !str_eq;; let add e g = HE.add allforms e g; add_eq e; add_str e; incr cur_num_forms; if !cur_num_forms > !Globals.top_num_forms then Globals.top_num_forms := !cur_num_forms; negpos add_element e; begin try (HE.find proofs e).present <- true with Not_found -> (); end; new_forms := e :: !new_forms; ;; let remove e = decr cur_num_forms; remove_trans e; remove_negtrans e; negpos remove_element e; remove_str e; remove_eq e; HE.remove allforms e; begin try (HE.find proofs e).present <- false with Not_found -> (); end; ;; let suspects = ref [];; let add_proof p = incr Globals.stored_lemmas; let get_record f = begin try HE.find proofs f with Not_found -> let r = {present = HE.mem allforms f; proofs = []} in HE.add proofs f r; r end in let recs = Array.of_list (List.map get_record p.mlconc) in suspects := [(p, ref 0, recs)] :: !suspects; ;; FIXME essayer : changer la structure pour utiliser des refcounts changer la structure de donnees pour utiliser des refcounts *) let search_proof () = let do_form f = try let r = HE.find proofs f in if r.present then begin suspects := r.proofs :: !suspects; r.proofs <- []; end; with Not_found -> () in let fs = !new_forms in new_forms := []; List.iter do_form fs; let rec loop () = match !suspects with | [] -> None | [] :: t2 -> suspects := t2; loop () | ((p, cur, recs) as lem :: t1) :: t2 -> begin try for i = !cur to Array.length recs - 1 do if not recs.(i).present then begin suspects := t1 :: t2; recs.(i).proofs <- lem :: recs.(i).proofs; cur := i+1; raise Exit; end done; for i = 0 to !cur-1 do if not recs.(i).present then begin suspects := t1 :: t2; recs.(i).proofs <- lem :: recs.(i).proofs; cur := i+1; raise Exit; end done; Some p with Exit -> loop () end in loop () ;; let defs = (Hashtbl.create tblsize : (string, definition) Hashtbl.t);; let add_def d = match d with | DefReal (_, s, args, body, _) -> Hashtbl.add defs s d; | DefPseudo (h, s, args, body) -> Hashtbl.add defs s d; | DefRec (_, s, args, body) -> Hashtbl.add defs s d; ;; let has_def s = Hashtbl.mem defs s;; let get_def s = let d = Hashtbl.find defs s in match d with | DefReal (_, s, params, body, _) -> (d, params, body) | DefPseudo (hyp, s, params, body) -> (d, params, body) | DefRec (_, s, params, body) -> (d, params, body) ;; let metas = (HE.create tblsize : int HE.t);; let add_meta e i = HE.add metas e i;; let remove_meta e = HE.remove metas e;; let get_meta e = HE.find metas e;; let cur_num = ref (-1);; let numforms = (HE.create tblsize : int HE.t);; let formnums = ref ([| |] : expr array);; let dummy = evar " *** Index.dummy *** ";; let ext_set tbl i x = while i >= Array.length !tbl do let len = Array.length !tbl in let new_len = 2 * len + 1 in let new_tbl = Array.make new_len dummy in Array.blit !tbl 0 new_tbl 0 len; tbl := new_tbl; done; !tbl.(i) <- x; ;; let rec expr o ex = let pr = eprintf in let print_var b v = match v with | Evar (s, _) -> eprintf "%s" s | _ -> assert false in match ex with | Evar (v, _) -> pr "%s" v; | Emeta (e, _) -> pr "%s#" Namespace.meta_prefix; | Eapp (s, es, _) -> pr "(%s" s; List.iter (fun x -> pr " "; expr o x) es; pr ")"; | Enot (e, _) -> pr "(-. "; expr o e; pr ")"; | Eand (e1, e2, _) -> pr "(/\\ "; expr o e1; pr " "; expr o e2; pr ")"; | Eor (e1, e2, _) -> pr "(\\/ "; expr o e1; pr " "; expr o e2; pr ")"; | Eimply (e1, e2, _) -> pr "(=> "; expr o e1; pr " "; expr o e2; pr ")"; | Eequiv (e1, e2, _) -> pr "(<=> "; expr o e1; pr " "; expr o e2; pr ")"; | Etrue -> pr "(True)"; | Efalse -> pr "(False)"; | Eall (v, t, e, _) when t === Namespace.univ_name -> pr "(A. ((%a) " print_var v; expr o e; pr "))"; | Eall (v, t, e, _) -> pr "(A. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Eex (v, t, e, _) when t === Namespace.univ_name -> pr "(E. ((%a) " print_var v; expr o e; pr "))"; | Eex (v, t, e, _) -> pr "(E. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Etau (v, t, e, _) when t === Namespace.univ_name -> pr "(t. ((%a) " print_var v; expr o e; pr "))"; | Etau (v, t, e, _) -> pr "(t. ((%a \"%s\") " print_var v t; expr o e; pr "))"; | Elam (v, t, e, _) when t === Namespace.univ_name -> pr "((%a) " print_var v; expr o e; pr ")"; | Elam (v, t, e, _) -> pr "((%a \"%s\") " print_var v t; expr o e; pr ")"; ;; let dprint_expr e = expr () e;; let get_number e = begin try HE.find numforms e with Not_found -> incr cur_num; HE.add numforms e !cur_num; ext_set formnums !cur_num e; if !Globals.debug_flag then begin Printf.eprintf "%x --> " !cur_num; dprint_expr e; Printf.eprintf "\n"; end; !cur_num end ;; let get_formula i = if i < 0 || i >= Array.length !formnums then raise Not_found; if !formnums.(i) == dummy then raise Not_found; !formnums.(i) ;; let make_tau_name p = match p with | Etau (Evar (v, _), _, _, _) when is_prefix "zenon_" v -> Printf.sprintf "%s_%s" Namespace.tau_prefix (base26 (get_number p)) | Etau (Evar (v, _), _, _, _) -> Printf.sprintf "%s%s_%s" Namespace.tau_prefix v (base26 (get_number p)) | _ -> assert false ;;
d11115e73ecd47fc4d5bcf08dad083cd95ff5ce187175d1a8e7c1daf9b3cbfba
5outh/chaosbox
Sequence.hs
module ChaosBox.Sequence ( lerpSeq , lerpSeq2 , lerpSeqWith ) where import ChaosBox.Math (clamp) import Data.Sequence (Seq, index) import Linear.V2 -- | Get the element of a sequence some percentage through it -- -- For a non-empty sequence: -- -- @lerpSeq 0 seq = head seq@ @lerpSeq 1 seq = last seq@ -- lerpSeq :: Double -> Seq a -> a lerpSeq perc xs = xs `index` lerpSeqIndex perc xs lerpSeqIndex :: Double -> Seq a -> Int lerpSeqIndex perc xs = floor $ perc * fromIntegral (length xs - 1) lerpSeqWith :: (Double -> Double) -> Double -> Seq a -> a lerpSeqWith f perc xs = lerpSeq (f perc) xs lerpSeq2 :: V2 Double -> Seq (Seq a) -> a lerpSeq2 (V2 x0 y0) xs = row `index` (floor $ y * fromIntegral (length row - 1)) where row = xs `index` (floor $ x * fromIntegral (length xs - 1)) x = clamp (0, 1) x0 y = clamp (0, 1) y0
null
https://raw.githubusercontent.com/5outh/chaosbox/991ca3db48d8828287567302ba3293314b9127bd/src/ChaosBox/Sequence.hs
haskell
| Get the element of a sequence some percentage through it For a non-empty sequence: @lerpSeq 0 seq = head seq@
module ChaosBox.Sequence ( lerpSeq , lerpSeq2 , lerpSeqWith ) where import ChaosBox.Math (clamp) import Data.Sequence (Seq, index) import Linear.V2 @lerpSeq 1 seq = last seq@ lerpSeq :: Double -> Seq a -> a lerpSeq perc xs = xs `index` lerpSeqIndex perc xs lerpSeqIndex :: Double -> Seq a -> Int lerpSeqIndex perc xs = floor $ perc * fromIntegral (length xs - 1) lerpSeqWith :: (Double -> Double) -> Double -> Seq a -> a lerpSeqWith f perc xs = lerpSeq (f perc) xs lerpSeq2 :: V2 Double -> Seq (Seq a) -> a lerpSeq2 (V2 x0 y0) xs = row `index` (floor $ y * fromIntegral (length row - 1)) where row = xs `index` (floor $ x * fromIntegral (length xs - 1)) x = clamp (0, 1) x0 y = clamp (0, 1) y0
8b01b33f0195c1309e30159ba728820e65f2fb1326326e31aea124714cfbcb1f
noinia/hgeometry
LowerTangent.hs
module Geometry.Polygon.Convex.LowerTangent( lowerTangent , upperTangent ) where import Control.Lens hiding ((:<), (:>)) import Data.Vector.Circular (CircularVector) import qualified Data.Vector.Circular as CV import Data.Ext import Geometry.LineSegment import Geometry.Point import Geometry.Polygon (outerBoundaryVector) import Geometry.Polygon.Convex(ConvexPolygon(..), simplePolygon) import Data.Ord (comparing) -- Old implementation of lowerTangent that we know is correct. | Compute the lower tangent of the two polgyons -- pre : - polygons lp and rp have at least 1 vertex -- - lp and rp are disjoint, and there is a vertical line separating the two polygons . -- - The vertices of the polygons are given in clockwise order -- Running time : \ ( O(n+m ) \ ) , where n and m are the sizes of the two polygons respectively lowerTangent :: (Num r, Ord r) => ConvexPolygon p r -> ConvexPolygon p r -> LineSegment 2 p r lowerTangent (getVertices -> l) (getVertices -> r) = rotate xx yy zz zz'' where xx = rightMost l yy = leftMost r zz = pred' yy zz'' = succ' xx rotate x y z z'' | CV.head z `isRightOf` (CV.head x, CV.head y) = rotate x z (pred' z) z'' rotate the right polygon CCW | CV.head z'' `isRightOf` (CV.head x, CV.head y) = rotate z'' y z (succ' z'') rotate the left polygon CW | otherwise = ClosedLineSegment (CV.head x) (CV.head y) | Compute the upper tangent of the two polgyons -- pre : - polygons lp and rp have at least 1 vertex -- - lp and rp are disjoint, and there is a vertical line separating the two polygons . -- - The vertices of the polygons are given in clockwise order -- Running time : \ ( O(n+m ) \ ) , where n and m are the sizes of the two polygons respectively upperTangent :: (Num r, Ord r) => ConvexPolygon p r -> ConvexPolygon p r -> LineSegment 2 p r upperTangent (getVertices -> l) (getVertices -> r) = rotate xx yy zz zz' where xx = rightMost l yy = leftMost r zz = succ' yy zz' = pred' xx rotate x y z z' | CV.head z `isLeftOf` (CV.head x, CV.head y) = rotate x z (succ' z) z' rotate the right polygon CW | CV.head z' `isLeftOf` (CV.head x, CV.head y) = rotate z' y z (pred' z') rotate the left polygon CCW | otherwise = ClosedLineSegment (CV.head x) (CV.head y) -------------------------------------------------------------------------------- -- * Helper Stuff succ' :: CircularVector a -> CircularVector a succ' = CV.rotateRight 1 pred' :: CircularVector a -> CircularVector a pred' = CV.rotateLeft 1 -- | Rotate to the rightmost point (rightmost and topmost in case of ties) rightMost :: Ord r => CircularVector (Point 2 r :+ p) -> CircularVector (Point 2 r :+ p) rightMost = CV.rotateToMaximumBy (comparing (^.core)) -- | Rotate to the leftmost point (and bottommost in case of ties) leftMost :: Ord r => CircularVector (Point 2 r :+ p) -> CircularVector (Point 2 r :+ p) leftMost = CV.rotateToMinimumBy (comparing (^.core)) -- | Helper to get the vertices of a convex polygon getVertices :: ConvexPolygon p r -> CircularVector (Point 2 r :+ p) getVertices = view (simplePolygon.outerBoundaryVector) isRightOf :: (Num r, Ord r) => Point 2 r :+ p -> (Point 2 r :+ p', Point 2 r :+ p'') -> Bool a `isRightOf` (b,c) = ccw (b^.core) (c^.core) (a^.core) == CW isLeftOf :: (Num r, Ord r) => Point 2 r :+ p -> (Point 2 r :+ p', Point 2 r :+ p'') -> Bool a `isLeftOf` (b,c) = ccw (b^.core) (c^.core) (a^.core) == CCW
null
https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry/test/src/Geometry/Polygon/Convex/LowerTangent.hs
haskell
Old implementation of lowerTangent that we know is correct. - lp and rp are disjoint, and there is a vertical line separating - The vertices of the polygons are given in clockwise order - lp and rp are disjoint, and there is a vertical line separating - The vertices of the polygons are given in clockwise order ------------------------------------------------------------------------------ * Helper Stuff | Rotate to the rightmost point (rightmost and topmost in case of ties) | Rotate to the leftmost point (and bottommost in case of ties) | Helper to get the vertices of a convex polygon
module Geometry.Polygon.Convex.LowerTangent( lowerTangent , upperTangent ) where import Control.Lens hiding ((:<), (:>)) import Data.Vector.Circular (CircularVector) import qualified Data.Vector.Circular as CV import Data.Ext import Geometry.LineSegment import Geometry.Point import Geometry.Polygon (outerBoundaryVector) import Geometry.Polygon.Convex(ConvexPolygon(..), simplePolygon) import Data.Ord (comparing) | Compute the lower tangent of the two polgyons pre : - polygons lp and rp have at least 1 vertex the two polygons . Running time : \ ( O(n+m ) \ ) , where n and m are the sizes of the two polygons respectively lowerTangent :: (Num r, Ord r) => ConvexPolygon p r -> ConvexPolygon p r -> LineSegment 2 p r lowerTangent (getVertices -> l) (getVertices -> r) = rotate xx yy zz zz'' where xx = rightMost l yy = leftMost r zz = pred' yy zz'' = succ' xx rotate x y z z'' | CV.head z `isRightOf` (CV.head x, CV.head y) = rotate x z (pred' z) z'' rotate the right polygon CCW | CV.head z'' `isRightOf` (CV.head x, CV.head y) = rotate z'' y z (succ' z'') rotate the left polygon CW | otherwise = ClosedLineSegment (CV.head x) (CV.head y) | Compute the upper tangent of the two polgyons pre : - polygons lp and rp have at least 1 vertex the two polygons . Running time : \ ( O(n+m ) \ ) , where n and m are the sizes of the two polygons respectively upperTangent :: (Num r, Ord r) => ConvexPolygon p r -> ConvexPolygon p r -> LineSegment 2 p r upperTangent (getVertices -> l) (getVertices -> r) = rotate xx yy zz zz' where xx = rightMost l yy = leftMost r zz = succ' yy zz' = pred' xx rotate x y z z' | CV.head z `isLeftOf` (CV.head x, CV.head y) = rotate x z (succ' z) z' rotate the right polygon CW | CV.head z' `isLeftOf` (CV.head x, CV.head y) = rotate z' y z (pred' z') rotate the left polygon CCW | otherwise = ClosedLineSegment (CV.head x) (CV.head y) succ' :: CircularVector a -> CircularVector a succ' = CV.rotateRight 1 pred' :: CircularVector a -> CircularVector a pred' = CV.rotateLeft 1 rightMost :: Ord r => CircularVector (Point 2 r :+ p) -> CircularVector (Point 2 r :+ p) rightMost = CV.rotateToMaximumBy (comparing (^.core)) leftMost :: Ord r => CircularVector (Point 2 r :+ p) -> CircularVector (Point 2 r :+ p) leftMost = CV.rotateToMinimumBy (comparing (^.core)) getVertices :: ConvexPolygon p r -> CircularVector (Point 2 r :+ p) getVertices = view (simplePolygon.outerBoundaryVector) isRightOf :: (Num r, Ord r) => Point 2 r :+ p -> (Point 2 r :+ p', Point 2 r :+ p'') -> Bool a `isRightOf` (b,c) = ccw (b^.core) (c^.core) (a^.core) == CW isLeftOf :: (Num r, Ord r) => Point 2 r :+ p -> (Point 2 r :+ p', Point 2 r :+ p'') -> Bool a `isLeftOf` (b,c) = ccw (b^.core) (c^.core) (a^.core) == CCW
ac662012b6530a34db7d46663b5c56c3321fe9cdfd0ff4db0b52cdca89363ebd
shirok/Gauche
www.scm
;; ;; test www.* modules ;; (use gauche.test) (use gauche.charconv) (use text.tree) (use rfc.822) (use file.util) (test-start "www.* modules") ;;------------------------------------------------ (test-section "www.cgi") (use www.cgi) (test-module 'www.cgi) (define params #f) (define qs1 "a=foo+bar&boo=baz=doo&z%3Dz=%21%26&a=+%20&#=#&z=z=8&r&r=2") (define qr1 '(("boo" "baz=doo") ("z=z" "!&") ("a" "foo bar" " ") ("#" "#") ("z" "z=8") ("r" #t "2"))) (define qs1b "a=foo+bar;boo=baz=doo;z%3Dz=%21%26;a=+%20;#=#;z=z=8;r;r=2") (define qs2 "zz=aa&aa=zz") (define qr2 '(("zz" "aa") ("aa" "zz"))) (test* "cgi-parse-parameters" qr1 (cgi-parse-parameters :query-string qs1)) (test* "cgi-parse-parameters" qr1 (cgi-parse-parameters :query-string qs1b)) (define ps1 "--boundary Content-Disposition: form-data; name=\"aaa\" 111 --boundary Content-Disposition: form-data; name=\"bbb\"; filename=\"x.txt\" Content-Type: text/plain abc def ghi --boundary Content-Disposition: form-data; name=\"ccc\"; filename=\"\" --boundary Content-Disposition: form-data: name=\"ddd\"; filename=\"ttt\\bbb\" Content-Type: application/octet-stream Content-Transfer-Encoding: base64 VGhpcyBpcyBhIHRlc3Qgc2VudGVuY2Uu --boundary-- ") (define ps2 "--boundary Content-Disposition: form-data; name=aaa 111 --boundary name = bbb ; filename = x.txt Content-Type: text/plain abc def ghi --boundary name ; filename=\"\ " --boundary name = ddd ; filename=\"ttt\\bbb\ " Content-Type: application/octet-stream Content-Transfer-Encoding: base64 VGhpcyBpcyBhIHRlc3Qgc2VudGVuY2Uu --boundary-- ") (define pr1 '(("aaa" "111") ("bbb" "abc\ndef\nghi\n") ("ccc" #f) ("ddd" "This is a test sentence."))) (define pr2 '(("aaa" "111") ("bbb" "x.txt") ("ccc" #f) ("ddd" "ttt\\bbb"))) (define (multipart-parse-test src) (test* "cgi-parse-parameters (multipart)" pr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (with-input-from-string src (lambda () (cgi-parse-parameters))))) (test* "cgi-parse-parameters (multipart, custom handler)" pr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `((#t ,(lambda (name filename info inp) (let loop ((line (read-line inp))) (if (eof-object? line) filename (loop (read-line inp)))))))))) )) (test* "cgi-parse-parameters (multipart, custom handler 2)" "abc\ndef\nghi\n" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (let1 r (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `(("bbb" file :prefix "./bbb"))))) (let* ((tmpfile (cgi-get-parameter "bbb" r)) (content (file->string tmpfile))) (sys-unlink tmpfile) content)))) (test* "cgi-parse-parameters (multipart, custom handler 3)" "abc\ndef\nghi\n" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (let1 r (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `((#/b{3}/ file :prefix "./bbb"))))) (let* ((tmpfile (cgi-get-parameter "bbb" r)) (content (file->string tmpfile))) (sys-unlink tmpfile) content)))) ) (multipart-parse-test ps1) (multipart-parse-test ps2) (define ps3 "--boundary Content-Disposition: form-data; name=aaa 111 --boundary name = 000 --boundary Content-Disposition: form-data; name=aaa 222 --boundary Content-Disposition: form-data; name=\"aaa\" 333 --boundary name = 999 --boundary--") (define pr3 '(("aaa" "111" "222" "333") ("bbb" "000" "999"))) (test* "cgi-parse-parameter (multipart, multivalue)" pr3 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size ps3))))) (with-input-from-string ps3 cgi-parse-parameters))) (test* "cgi-get-parameter" "foo bar" (cgi-get-parameter "a" qr1)) (test* "cgi-get-parameter" '("foo bar" " ") (cgi-get-parameter "a" qr1 :list #t)) (test* "cgi-get-parameter" #t (cgi-get-parameter "r" qr1)) (test* "cgi-get-parameter" '(#t "2") (cgi-get-parameter "r" qr1 :list #t)) (test* "cgi-get-parameter" '("baz=doo") (cgi-get-parameter "boo" qr1 :list #t)) (test* "cgi-get-parameter" 'none (cgi-get-parameter "booz" qr1 :default 'none)) (test* "cgi-get-parameter" #f (cgi-get-parameter "booz" qr1)) (test* "cgi-get-parameter" '() (cgi-get-parameter "booz" qr1 :list #t)) (test* "cgi-get-parameter" '(0 2) (cgi-get-parameter "r" qr1 :convert x->integer :list #t)) (test* "cgi-get-query (GET)" qr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (HEAD)" qr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "HEAD") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" qr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" qr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_LENGTH" ,(string-length qs2))))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" '(("zz" "aa")) (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_LENGTH" 5)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-header" "Content-type: text/html\r\n\r\n" (tree->string (cgi-header))) (test* "cgi-header" "Location: /\r\n\r\n" (tree->string (cgi-header :location "/"))) (test* "cgi-header" "Content-type: hoge\r\nLocation: /\r\n\r\n" (tree->string (cgi-header :location "/" :content-type "hoge"))) (test* "cgi-header" "Content-type: text/plain; charset=utf-8\r\n\r\n" (tree->string (cgi-header :content-type "text/plain; charset=utf-8"))) (test* "cgi-header" "Content-type: text/html\r\nSet-cookie: hoge\r\nSet-cookie: poge\r\n\r\n" (tree->string (cgi-header :cookies '("hoge" "poge")))) (test* "cgi-header" "Content-type: text/html\r\nSet-cookie: hoge\r\nSet-cookie: poge\r\nx-foo: foo\r\n\r\n" (tree->string (cgi-header :x-foo "foo" :cookies '("hoge" "poge")))) (test* "cgi-main" "Content-type: text/plain\r\n\r\na=foo bar" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ,qs1)))) (with-output-to-string (lambda () (cgi-main (lambda (params) `(,(cgi-header :content-type "text/plain") "a=" ,(cgi-get-parameter "a" params)))))))) (unless (eq? (gauche-character-encoding) 'none) (test* "cgi-output-character-encoding" #*"\xe3\x81\x82" (string-complete->incomplete (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ""))) (cgi-output-character-encoding 'utf8)) (with-output-to-string (lambda () (cgi-main (lambda (params) (string #\u3042))))))))) ;;------------------------------------------------ (test-section "www.cgi.test") (use www.cgi.test) (test-module 'www.cgi.test) (test* "cgi-test-environment-ref" "remote" (cgi-test-environment-ref "REMOTE_HOST")) (test* "cgi-test-environment-ref" "zzz" (cgi-test-environment-ref 'ZZZ "zzz")) (test* "cgi-test-environment-set!" "foo.com" (begin (set! (cgi-test-environment-ref 'REMOTE_HOST) "foo.com") (cgi-test-environment-ref "REMOTE_HOST"))) (cond-expand [gauche.os.windows ;; windows can't support #! magic anyways. ] [else (sys-system "rm -rf test.o") (sys-mkdir "test.o" #o755) (with-output-to-file "test.o/cgitest.cgi" (lambda () (print "#!/bin/sh") (print "echo Content-type: text/plain") (print "echo") (print "echo \"SERVER_NAME = $SERVER_NAME\"") (print "echo \"REMOTE_HOST = $REMOTE_HOST\"") (print "echo \"REQUEST_METHOD = $REQUEST_METHOD\"") (print "echo \"CONTENT_TYPE = $CONTENT_TYPE\"") (print "echo \"QUERY_STRING = $QUERY_STRING\""))) (sys-chmod "test.o/cgitest.cgi" #o755) (test* "call-with-cgi-script" '(("content-type" "text/plain")) (call-with-cgi-script "test.o/cgitest.cgi" (lambda (p) (rfc822-header->list p))) ) (test* "run-cgi-script->string-list" '((("content-type" "text/plain")) ("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = GET" "CONTENT_TYPE = " "QUERY_STRING = ")) (receive r (run-cgi-script->string-list "test.o/cgitest.cgi") r) ) (test* "run-cgi-script->string-list (using parameters/GET)" '("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = GET" "CONTENT_TYPE = " "QUERY_STRING = a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :parameters '((a . b) (&&$& . !@!@))) body)) (test* "run-cgi-script->string-list (using parameters/HEAD)" '("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = HEAD" "CONTENT_TYPE = " "QUERY_STRING = a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :environment '((REQUEST_METHOD . HEAD)) :parameters '((a . b) (&&$& . !@!@))) body)) (with-output-to-file "test.o/cgitest.cgi" (lambda () (print "#!/bin/sh") (print "echo Content-type: text/plain") (print "echo") (print "echo \"REQUEST_METHOD = $REQUEST_METHOD\"") (print "echo \"CONTENT_TYPE = $CONTENT_TYPE\"") (print "echo \"CONTENT_LENGTH = $CONTENT_LENGTH\"") (print "echo \"QUERY_STRING = $QUERY_STRING\"") (print "cat"))) (test* "run-cgi-script->string-list (using parameters)" '("REQUEST_METHOD = POST" "CONTENT_TYPE = application/x-www-form-urlencoded" "CONTENT_LENGTH = 29" "QUERY_STRING = " "a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :environment '((REQUEST_METHOD . POST)) :parameters '((a . b) (&&$& . !@!@))) body)) (sys-system "rm -rf test.o")]) ;;------------------------------------------------ (test-section "www.css") (use www.css) (test-module 'www.css) NB : this assumes the test is run either under src/ or test/ (define (run-css-test) (dolist [infile (glob "../test/data/css-*.css")] (define sxcss (call-with-input-file (path-swap-extension infile "sxcss") read)) (test* #"css parser ~infile" sxcss (parse-css-file infile) equal?) (test* #"css constructor ~infile" sxcss (with-input-from-string (with-output-to-string (cut construct-css sxcss)) parse-css) equal?))) (run-css-test) (test* "parse-css-selector-string (failure)" #f (parse-css-selector-string ":::")) (test* "parse-css-selector-string (nth-child)" '(* (: (nth-child 1))) (parse-css-selector-string ":nth-child(1)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 2 1)))) (parse-css-selector-string ":nth-child(2n+1)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 1 0)))) (parse-css-selector-string ":nth-child(n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -1 0)))) (parse-css-selector-string ":nth-child(-n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -1 -6)))) (parse-css-selector-string ":nth-child(-n-6)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -3 4)))) (parse-css-selector-string ":nth-child(-3n+4)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -3 -4)))) (parse-css-selector-string ":nth-child(-3n-4)")) (test* "parse-css-selector-string (nth-child an+b)" #f (parse-css-selector-string ":nth-child(- n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (:not (: (nth-child (:an+b -1 0))))) (parse-css-selector-string ":not(:nth-child(-n))")) (test* "parse-css-selector-string (nth-child an+b)" #f (parse-css-selector-string ":not(:nth-child(- n))")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 2 -1)))) (parse-css-selector-string ":nth-child(2n- 1)")) (test-end)
null
https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/test/www.scm
scheme
test www.* modules ------------------------------------------------ name=\"aaa\" name=\"bbb\"; filename=\"x.txt\" name=\"ccc\"; filename=\"\" filename=\"ttt\\bbb\" name=aaa filename = x.txt filename=\"\ " filename=\"ttt\\bbb\ " name=aaa name=aaa name=\"aaa\" ------------------------------------------------ windows can't support #! magic anyways. ------------------------------------------------
(use gauche.test) (use gauche.charconv) (use text.tree) (use rfc.822) (use file.util) (test-start "www.* modules") (test-section "www.cgi") (use www.cgi) (test-module 'www.cgi) (define params #f) (define qs1 "a=foo+bar&boo=baz=doo&z%3Dz=%21%26&a=+%20&#=#&z=z=8&r&r=2") (define qr1 '(("boo" "baz=doo") ("z=z" "!&") ("a" "foo bar" " ") ("#" "#") ("z" "z=8") ("r" #t "2"))) (define qs1b "a=foo+bar;boo=baz=doo;z%3Dz=%21%26;a=+%20;#=#;z=z=8;r;r=2") (define qs2 "zz=aa&aa=zz") (define qr2 '(("zz" "aa") ("aa" "zz"))) (test* "cgi-parse-parameters" qr1 (cgi-parse-parameters :query-string qs1)) (test* "cgi-parse-parameters" qr1 (cgi-parse-parameters :query-string qs1b)) (define ps1 "--boundary 111 --boundary Content-Type: text/plain abc def ghi --boundary --boundary Content-Type: application/octet-stream Content-Transfer-Encoding: base64 VGhpcyBpcyBhIHRlc3Qgc2VudGVuY2Uu --boundary-- ") (define ps2 "--boundary 111 --boundary Content-Type: text/plain abc def ghi --boundary --boundary Content-Type: application/octet-stream Content-Transfer-Encoding: base64 VGhpcyBpcyBhIHRlc3Qgc2VudGVuY2Uu --boundary-- ") (define pr1 '(("aaa" "111") ("bbb" "abc\ndef\nghi\n") ("ccc" #f) ("ddd" "This is a test sentence."))) (define pr2 '(("aaa" "111") ("bbb" "x.txt") ("ccc" #f) ("ddd" "ttt\\bbb"))) (define (multipart-parse-test src) (test* "cgi-parse-parameters (multipart)" pr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (with-input-from-string src (lambda () (cgi-parse-parameters))))) (test* "cgi-parse-parameters (multipart, custom handler)" pr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `((#t ,(lambda (name filename info inp) (let loop ((line (read-line inp))) (if (eof-object? line) filename (loop (read-line inp)))))))))) )) (test* "cgi-parse-parameters (multipart, custom handler 2)" "abc\ndef\nghi\n" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (let1 r (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `(("bbb" file :prefix "./bbb"))))) (let* ((tmpfile (cgi-get-parameter "bbb" r)) (content (file->string tmpfile))) (sys-unlink tmpfile) content)))) (test* "cgi-parse-parameters (multipart, custom handler 3)" "abc\ndef\nghi\n" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size src))))) (let1 r (with-input-from-string src (lambda () (cgi-parse-parameters :part-handlers `((#/b{3}/ file :prefix "./bbb"))))) (let* ((tmpfile (cgi-get-parameter "bbb" r)) (content (file->string tmpfile))) (sys-unlink tmpfile) content)))) ) (multipart-parse-test ps1) (multipart-parse-test ps2) (define ps3 "--boundary 111 --boundary name = 000 --boundary 222 --boundary 333 --boundary name = 999 --boundary--") (define pr3 '(("aaa" "111" "222" "333") ("bbb" "000" "999"))) (test* "cgi-parse-parameter (multipart, multivalue)" pr3 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_TYPE" "multipart/form-data; boundary=boundary") ("CONTENT_LENGTH" ,(string-size ps3))))) (with-input-from-string ps3 cgi-parse-parameters))) (test* "cgi-get-parameter" "foo bar" (cgi-get-parameter "a" qr1)) (test* "cgi-get-parameter" '("foo bar" " ") (cgi-get-parameter "a" qr1 :list #t)) (test* "cgi-get-parameter" #t (cgi-get-parameter "r" qr1)) (test* "cgi-get-parameter" '(#t "2") (cgi-get-parameter "r" qr1 :list #t)) (test* "cgi-get-parameter" '("baz=doo") (cgi-get-parameter "boo" qr1 :list #t)) (test* "cgi-get-parameter" 'none (cgi-get-parameter "booz" qr1 :default 'none)) (test* "cgi-get-parameter" #f (cgi-get-parameter "booz" qr1)) (test* "cgi-get-parameter" '() (cgi-get-parameter "booz" qr1 :list #t)) (test* "cgi-get-parameter" '(0 2) (cgi-get-parameter "r" qr1 :convert x->integer :list #t)) (test* "cgi-get-query (GET)" qr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (HEAD)" qr1 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "HEAD") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" qr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("QUERY_STRING" ,qs1)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" qr2 (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_LENGTH" ,(string-length qs2))))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-get-query (POST)" '(("zz" "aa")) (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "POST") ("CONTENT_LENGTH" 5)))) (with-input-from-string qs2 cgi-parse-parameters))) (test* "cgi-header" "Content-type: text/html\r\n\r\n" (tree->string (cgi-header))) (test* "cgi-header" "Location: /\r\n\r\n" (tree->string (cgi-header :location "/"))) (test* "cgi-header" "Content-type: hoge\r\nLocation: /\r\n\r\n" (tree->string (cgi-header :location "/" :content-type "hoge"))) (test* "cgi-header" "Content-type: text/plain; charset=utf-8\r\n\r\n" (tree->string (cgi-header :content-type "text/plain; charset=utf-8"))) (test* "cgi-header" "Content-type: text/html\r\nSet-cookie: hoge\r\nSet-cookie: poge\r\n\r\n" (tree->string (cgi-header :cookies '("hoge" "poge")))) (test* "cgi-header" "Content-type: text/html\r\nSet-cookie: hoge\r\nSet-cookie: poge\r\nx-foo: foo\r\n\r\n" (tree->string (cgi-header :x-foo "foo" :cookies '("hoge" "poge")))) (test* "cgi-main" "Content-type: text/plain\r\n\r\na=foo bar" (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ,qs1)))) (with-output-to-string (lambda () (cgi-main (lambda (params) `(,(cgi-header :content-type "text/plain") "a=" ,(cgi-get-parameter "a" params)))))))) (unless (eq? (gauche-character-encoding) 'none) (test* "cgi-output-character-encoding" #*"\xe3\x81\x82" (string-complete->incomplete (parameterize ((cgi-metavariables `(("REQUEST_METHOD" "GET") ("QUERY_STRING" ""))) (cgi-output-character-encoding 'utf8)) (with-output-to-string (lambda () (cgi-main (lambda (params) (string #\u3042))))))))) (test-section "www.cgi.test") (use www.cgi.test) (test-module 'www.cgi.test) (test* "cgi-test-environment-ref" "remote" (cgi-test-environment-ref "REMOTE_HOST")) (test* "cgi-test-environment-ref" "zzz" (cgi-test-environment-ref 'ZZZ "zzz")) (test* "cgi-test-environment-set!" "foo.com" (begin (set! (cgi-test-environment-ref 'REMOTE_HOST) "foo.com") (cgi-test-environment-ref "REMOTE_HOST"))) (cond-expand [gauche.os.windows ] [else (sys-system "rm -rf test.o") (sys-mkdir "test.o" #o755) (with-output-to-file "test.o/cgitest.cgi" (lambda () (print "#!/bin/sh") (print "echo Content-type: text/plain") (print "echo") (print "echo \"SERVER_NAME = $SERVER_NAME\"") (print "echo \"REMOTE_HOST = $REMOTE_HOST\"") (print "echo \"REQUEST_METHOD = $REQUEST_METHOD\"") (print "echo \"CONTENT_TYPE = $CONTENT_TYPE\"") (print "echo \"QUERY_STRING = $QUERY_STRING\""))) (sys-chmod "test.o/cgitest.cgi" #o755) (test* "call-with-cgi-script" '(("content-type" "text/plain")) (call-with-cgi-script "test.o/cgitest.cgi" (lambda (p) (rfc822-header->list p))) ) (test* "run-cgi-script->string-list" '((("content-type" "text/plain")) ("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = GET" "CONTENT_TYPE = " "QUERY_STRING = ")) (receive r (run-cgi-script->string-list "test.o/cgitest.cgi") r) ) (test* "run-cgi-script->string-list (using parameters/GET)" '("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = GET" "CONTENT_TYPE = " "QUERY_STRING = a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :parameters '((a . b) (&&$& . !@!@))) body)) (test* "run-cgi-script->string-list (using parameters/HEAD)" '("SERVER_NAME = localhost" "REMOTE_HOST = foo.com" "REQUEST_METHOD = HEAD" "CONTENT_TYPE = " "QUERY_STRING = a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :environment '((REQUEST_METHOD . HEAD)) :parameters '((a . b) (&&$& . !@!@))) body)) (with-output-to-file "test.o/cgitest.cgi" (lambda () (print "#!/bin/sh") (print "echo Content-type: text/plain") (print "echo") (print "echo \"REQUEST_METHOD = $REQUEST_METHOD\"") (print "echo \"CONTENT_TYPE = $CONTENT_TYPE\"") (print "echo \"CONTENT_LENGTH = $CONTENT_LENGTH\"") (print "echo \"QUERY_STRING = $QUERY_STRING\"") (print "cat"))) (test* "run-cgi-script->string-list (using parameters)" '("REQUEST_METHOD = POST" "CONTENT_TYPE = application/x-www-form-urlencoded" "CONTENT_LENGTH = 29" "QUERY_STRING = " "a=b&%26%26%24%26=%21%40%21%40") (receive (_ body) (run-cgi-script->string-list "test.o/cgitest.cgi" :environment '((REQUEST_METHOD . POST)) :parameters '((a . b) (&&$& . !@!@))) body)) (sys-system "rm -rf test.o")]) (test-section "www.css") (use www.css) (test-module 'www.css) NB : this assumes the test is run either under src/ or test/ (define (run-css-test) (dolist [infile (glob "../test/data/css-*.css")] (define sxcss (call-with-input-file (path-swap-extension infile "sxcss") read)) (test* #"css parser ~infile" sxcss (parse-css-file infile) equal?) (test* #"css constructor ~infile" sxcss (with-input-from-string (with-output-to-string (cut construct-css sxcss)) parse-css) equal?))) (run-css-test) (test* "parse-css-selector-string (failure)" #f (parse-css-selector-string ":::")) (test* "parse-css-selector-string (nth-child)" '(* (: (nth-child 1))) (parse-css-selector-string ":nth-child(1)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 2 1)))) (parse-css-selector-string ":nth-child(2n+1)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 1 0)))) (parse-css-selector-string ":nth-child(n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -1 0)))) (parse-css-selector-string ":nth-child(-n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -1 -6)))) (parse-css-selector-string ":nth-child(-n-6)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -3 4)))) (parse-css-selector-string ":nth-child(-3n+4)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b -3 -4)))) (parse-css-selector-string ":nth-child(-3n-4)")) (test* "parse-css-selector-string (nth-child an+b)" #f (parse-css-selector-string ":nth-child(- n)")) (test* "parse-css-selector-string (nth-child an+b)" '(* (:not (: (nth-child (:an+b -1 0))))) (parse-css-selector-string ":not(:nth-child(-n))")) (test* "parse-css-selector-string (nth-child an+b)" #f (parse-css-selector-string ":not(:nth-child(- n))")) (test* "parse-css-selector-string (nth-child an+b)" '(* (: (nth-child (:an+b 2 -1)))) (parse-css-selector-string ":nth-child(2n- 1)")) (test-end)
026e30751d675892015106515aae5cecbbd0a3e142767d46418357fdbcef376c
achirkin/qua-kit
Common.hs
{-# OPTIONS_HADDOCK hide, prune #-} module Handler.Common where import Data.FileEmbed (embedFile) import Import -- These handlers embed files in the executable at compile time to avoid a -- runtime dependency, and for efficiency. getFaviconR :: Handler TypedContent cache for a month return $ TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico") getRobotsR :: Handler TypedContent getRobotsR = return $ TypedContent typePlain $ toContent $(embedFile "config/robots.txt")
null
https://raw.githubusercontent.com/achirkin/qua-kit/9f859e2078d5f059fb87b2f6baabcde7170d4e95/apps/hs/qua-server/src/Handler/Common.hs
haskell
# OPTIONS_HADDOCK hide, prune # These handlers embed files in the executable at compile time to avoid a runtime dependency, and for efficiency.
module Handler.Common where import Data.FileEmbed (embedFile) import Import getFaviconR :: Handler TypedContent cache for a month return $ TypedContent "image/x-icon" $ toContent $(embedFile "config/favicon.ico") getRobotsR :: Handler TypedContent getRobotsR = return $ TypedContent typePlain $ toContent $(embedFile "config/robots.txt")
a8f37b357f19cd55016498dfa5837ca6f9533ea05fbe208c6272558f114e982c
NorfairKing/validity
AesonSpec.hs
# LANGUAGE DeriveGeneric # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # module Test.Validity.AesonSpec where import Data.Aeson import Data.GenValidity import Data.GenValidity.Aeson () import Data.GenValidity.Text () import Data.Text (Text) import GHC.Generics import Test.Hspec import Test.Validity.Aeson spec :: Spec spec = do jsonSpecOnGen (genListOf $ pure 'a') "sequence of 'a's" (const []) jsonSpec DOES NOT HOLD jsonSpec @Rational jsonSpec @Int jsonSpecOnArbitrary @Int jsonSpec @ForShow jsonSpec @Value shrinkValidSpec @Value newtype ForShow = ForShow Text deriving (Show, Eq, Generic) instance Validity ForShow instance GenValid ForShow where genValid = genValidStructurally shrinkValid = shrinkValidStructurally instance FromJSON ForShow instance ToJSON ForShow > > > decode ( ( ForShow " \248 " ) ) : : Maybe ForShow -- Just (ForShow "\248")
null
https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-hspec-aeson/test/Test/Validity/AesonSpec.hs
haskell
# LANGUAGE OverloadedStrings # Just (ForShow "\248")
# LANGUAGE DeriveGeneric # # LANGUAGE TypeApplications # module Test.Validity.AesonSpec where import Data.Aeson import Data.GenValidity import Data.GenValidity.Aeson () import Data.GenValidity.Text () import Data.Text (Text) import GHC.Generics import Test.Hspec import Test.Validity.Aeson spec :: Spec spec = do jsonSpecOnGen (genListOf $ pure 'a') "sequence of 'a's" (const []) jsonSpec DOES NOT HOLD jsonSpec @Rational jsonSpec @Int jsonSpecOnArbitrary @Int jsonSpec @ForShow jsonSpec @Value shrinkValidSpec @Value newtype ForShow = ForShow Text deriving (Show, Eq, Generic) instance Validity ForShow instance GenValid ForShow where genValid = genValidStructurally shrinkValid = shrinkValidStructurally instance FromJSON ForShow instance ToJSON ForShow > > > decode ( ( ForShow " \248 " ) ) : : Maybe ForShow
444eec299d8cc0c2730b2d06f9295146999d24e5569154f9270eb78338327f0c
gedge-platform/gedge-platform
jose_jwa_curve25519.erl
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- %% vim: ts=4 sw=4 ft=erlang noet %%%------------------------------------------------------------------- @author < > 2014 - 2016 , %%% @doc %%% %%% @end Created : 07 Jan 2016 by < > %%%------------------------------------------------------------------- -module(jose_jwa_curve25519). -behaviour(jose_curve25519). %% jose_curve25519 callbacks -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed25519_sign/2]). -export([ed25519_verify/3]). -export([ed25519ph_sign/2]). -export([ed25519ph_verify/3]). -export([x25519_keypair/0]). -export([x25519_keypair/1]). -export([x25519_secret_to_public/1]). -export([x25519_shared_secret/2]). %%==================================================================== %% jose_curve25519 callbacks %%==================================================================== EdDSA eddsa_keypair() -> jose_jwa_ed25519:keypair(). eddsa_keypair(Seed) when is_binary(Seed) -> jose_jwa_ed25519:keypair(Seed). eddsa_secret_to_public(SecretKey) when is_binary(SecretKey) -> jose_jwa_ed25519:secret_to_pk(SecretKey). % Ed25519 ed25519_sign(Message, SecretKey) when is_binary(Message) andalso is_binary(SecretKey) -> jose_jwa_ed25519:sign(Message, SecretKey). ed25519_verify(Signature, Message, PublicKey) when is_binary(Signature) andalso is_binary(Message) andalso is_binary(PublicKey) -> try jose_jwa_ed25519:verify(Signature, Message, PublicKey) catch _:_ -> false end. % Ed25519ph ed25519ph_sign(Message, SecretKey) when is_binary(Message) andalso is_binary(SecretKey) -> jose_jwa_ed25519:sign_with_prehash(Message, SecretKey). ed25519ph_verify(Signature, Message, PublicKey) when is_binary(Signature) andalso is_binary(Message) andalso is_binary(PublicKey) -> try jose_jwa_ed25519:verify_with_prehash(Signature, Message, PublicKey) catch _:_ -> false end. % X25519 x25519_keypair() -> jose_jwa_x25519:keypair(). x25519_keypair(Seed) when is_binary(Seed) -> jose_jwa_x25519:keypair(Seed). x25519_secret_to_public(SecretKey) when is_binary(SecretKey) -> jose_jwa_x25519:sk_to_pk(SecretKey). x25519_shared_secret(MySecretKey, YourPublicKey) when is_binary(MySecretKey) andalso is_binary(YourPublicKey) -> jose_jwa_x25519:x25519(MySecretKey, YourPublicKey).
null
https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/jose/src/jwa/jose_jwa_curve25519.erl
erlang
vim: ts=4 sw=4 ft=erlang noet ------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- jose_curve25519 callbacks ==================================================================== jose_curve25519 callbacks ==================================================================== Ed25519 Ed25519ph X25519
-*- mode : erlang ; tab - width : 4 ; indent - tabs - mode : 1 ; st - rulers : [ 70 ] -*- @author < > 2014 - 2016 , Created : 07 Jan 2016 by < > -module(jose_jwa_curve25519). -behaviour(jose_curve25519). -export([eddsa_keypair/0]). -export([eddsa_keypair/1]). -export([eddsa_secret_to_public/1]). -export([ed25519_sign/2]). -export([ed25519_verify/3]). -export([ed25519ph_sign/2]). -export([ed25519ph_verify/3]). -export([x25519_keypair/0]). -export([x25519_keypair/1]). -export([x25519_secret_to_public/1]). -export([x25519_shared_secret/2]). EdDSA eddsa_keypair() -> jose_jwa_ed25519:keypair(). eddsa_keypair(Seed) when is_binary(Seed) -> jose_jwa_ed25519:keypair(Seed). eddsa_secret_to_public(SecretKey) when is_binary(SecretKey) -> jose_jwa_ed25519:secret_to_pk(SecretKey). ed25519_sign(Message, SecretKey) when is_binary(Message) andalso is_binary(SecretKey) -> jose_jwa_ed25519:sign(Message, SecretKey). ed25519_verify(Signature, Message, PublicKey) when is_binary(Signature) andalso is_binary(Message) andalso is_binary(PublicKey) -> try jose_jwa_ed25519:verify(Signature, Message, PublicKey) catch _:_ -> false end. ed25519ph_sign(Message, SecretKey) when is_binary(Message) andalso is_binary(SecretKey) -> jose_jwa_ed25519:sign_with_prehash(Message, SecretKey). ed25519ph_verify(Signature, Message, PublicKey) when is_binary(Signature) andalso is_binary(Message) andalso is_binary(PublicKey) -> try jose_jwa_ed25519:verify_with_prehash(Signature, Message, PublicKey) catch _:_ -> false end. x25519_keypair() -> jose_jwa_x25519:keypair(). x25519_keypair(Seed) when is_binary(Seed) -> jose_jwa_x25519:keypair(Seed). x25519_secret_to_public(SecretKey) when is_binary(SecretKey) -> jose_jwa_x25519:sk_to_pk(SecretKey). x25519_shared_secret(MySecretKey, YourPublicKey) when is_binary(MySecretKey) andalso is_binary(YourPublicKey) -> jose_jwa_x25519:x25519(MySecretKey, YourPublicKey).
90dd269676725be565c124a70a7a2b6e6bbe6c1c9805ae481860344c4cd5d427
ocamllabs/ocaml-modular-implicits
lists.ml
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Gallium , INRIA Rocquencourt (* *) Copyright 2012 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (* a test with lists, because cyclic lists are fun *) let test = let rec li = 0::1::2::3::4::5::6::7::8::9::li in match li with | 0::1::2::3::4::5::6::7::8::9:: 0::1::2::3::4::5::6::7::8::9::li' -> assert (li == li') | _ -> assert false
null
https://raw.githubusercontent.com/ocamllabs/ocaml-modular-implicits/92e45da5c8a4c2db8b2cd5be28a5bec2ac2181f1/testsuite/tests/letrec/lists.ml
ocaml
********************************************************************* OCaml ********************************************************************* a test with lists, because cyclic lists are fun
, projet Gallium , INRIA Rocquencourt Copyright 2012 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . let test = let rec li = 0::1::2::3::4::5::6::7::8::9::li in match li with | 0::1::2::3::4::5::6::7::8::9:: 0::1::2::3::4::5::6::7::8::9::li' -> assert (li == li') | _ -> assert false
21edd49e7981baf701a93c95de06e42ac70b8773222123199008755af5a312cc
scalaris-team/scalaris
sup_wpool.erl
2007 - 2013 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; % you may not use this file except in compliance with the License. % You may obtain a copy of the License at % % -2.0 % % Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % See the License for the specific language governing permissions and % limitations under the License. @author < > @doc supervisor for wpool workers %% @end %% @version $Id$ -module(sup_wpool). -author(''). -vsn('$Id$ '). -behaviour(supervisor). -include("scalaris.hrl"). -export([start_link/1, init/1]). -export([supspec/1]). -spec start_link(pid_groups:groupname()) -> {ok, Pid::pid(), pid_groups:groupname()} | ignore | {error, Error::{already_started, Pid::pid()} | shutdown | term()}. start_link(DHTNodeGroup) -> case supervisor:start_link(?MODULE, DHTNodeGroup) of {ok, Pid} -> {ok, Pid, DHTNodeGroup}; X -> X end. -spec init(pid_groups:groupname()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. init(DHTNodeGroup) -> pid_groups:join_as(DHTNodeGroup, sup_wpool), supspec([DHTNodeGroup]). -spec supspec(any()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. supspec(_) -> {ok, {{one_for_one, 10, 1}, []}}.
null
https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/src/sup_wpool.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. @end @version $Id$
2007 - 2013 Zuse Institute Berlin Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , @author < > @doc supervisor for wpool workers -module(sup_wpool). -author(''). -vsn('$Id$ '). -behaviour(supervisor). -include("scalaris.hrl"). -export([start_link/1, init/1]). -export([supspec/1]). -spec start_link(pid_groups:groupname()) -> {ok, Pid::pid(), pid_groups:groupname()} | ignore | {error, Error::{already_started, Pid::pid()} | shutdown | term()}. start_link(DHTNodeGroup) -> case supervisor:start_link(?MODULE, DHTNodeGroup) of {ok, Pid} -> {ok, Pid, DHTNodeGroup}; X -> X end. -spec init(pid_groups:groupname()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. init(DHTNodeGroup) -> pid_groups:join_as(DHTNodeGroup, sup_wpool), supspec([DHTNodeGroup]). -spec supspec(any()) -> {ok, {{one_for_one, MaxRetries::pos_integer(), PeriodInSeconds::pos_integer()}, []}}. supspec(_) -> {ok, {{one_for_one, 10, 1}, []}}.
145c190d8d1c5dfbe5f6228d3013877eace3748b654cdaba068c3f967823266a
realworldocaml/book
test_clz.ml
[%%import "config.h"] open Base open Stdio let test ~op ~op_name ~to_string x = printf "%s %s = %d\n" op_name (to_string x) (op x) let%expect_test "clz int64" = let open Int64 in let numbers = [ 0L (* Int.num_bits *) ; 1L (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1L ] in let f = test ~op:Ocaml_intrinsics.Int64.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 64 clz 0x1 = 63 clz 0x7 = 61 clz 0x7fff_ffff_ffff_ffff = 1 clz -0x8000_0000_0000_0000 = 0 clz -0x1 = 0 |}] ;; let%expect_test "clz int32" = let open Int32 in let numbers = [ 0l (* Int.num_bits *) ; 1l (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1l ] in let f = test ~op:Ocaml_intrinsics.Int32.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 32 clz 0x1 = 31 clz 0x7 = 29 clz 0x7fff_ffff = 1 clz -0x8000_0000 = 0 clz -0x1 = 0 |}] ;; [%%ifdef JSC_ARCH_SIXTYFOUR] let%expect_test "clz int" = let open Int in let numbers = [ 0 (* Int.num_bits *) ; 1 (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1 ] in let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 63 clz 0x1 = 62 clz 0x7 = 60 clz 0x3fff_ffff_ffff_ffff = 1 clz -0x4000_0000_0000_0000 = 0 clz -0x1 = 0 |}]; let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros2 ~op_name:"clz2" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz2 0x0 = 63 clz2 0x1 = 62 clz2 0x7 = 60 clz2 0x3fff_ffff_ffff_ffff = 1 clz2 -0x4000_0000_0000_0000 = 0 clz2 -0x1 = 0 |}] ;; let%expect_test "clz nativeint" = let open Nativeint in let numbers = [ 0n (* Int.num_bits *) ; 1n (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1n ] in let f = test ~op:Ocaml_intrinsics.Nativeint.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 64 clz 0x1 = 63 clz 0x7 = 61 clz 0x7fff_ffff_ffff_ffff = 1 clz -0x8000_0000_0000_0000 = 0 clz -0x1 = 0 |}] ;; [%%else] let%expect_test "clz int" = let open Int in let numbers = [ 0 (* Int.num_bits *) ; 1 (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1 ] in let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 31 clz 0x1 = 30 clz 0x7 = 28 clz 0x3fff_ffff = 1 clz -0x4000_0000 = 0 clz -0x1 = 0 |}]; let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros2 ~op_name:"clz2" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz2 0x0 = 31 clz2 0x1 = 30 clz2 0x7 = 28 clz2 0x3fff_ffff = 1 clz2 -0x4000_0000 = 0 clz2 -0x1 = 0 |}] ;; let%expect_test "clz nativeint" = let open Nativeint in let numbers = [ 0n (* Int.num_bits *) ; 1n (* Int.num_bits - 1 *) Int.num_bits - 3 ; max_value ; min_value ; -1n ] in let f = test ~op:Ocaml_intrinsics.Nativeint.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 32 clz 0x1 = 31 clz 0x7 = 29 clz 0x7fff_ffff = 1 clz -0x8000_0000 = 0 clz -0x1 = 0 |}] ;; [%%endif]
null
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/ocaml_intrinsics/test/test_clz.ml
ocaml
Int.num_bits Int.num_bits - 1 Int.num_bits Int.num_bits - 1 Int.num_bits Int.num_bits - 1 Int.num_bits Int.num_bits - 1 Int.num_bits Int.num_bits - 1 Int.num_bits Int.num_bits - 1
[%%import "config.h"] open Base open Stdio let test ~op ~op_name ~to_string x = printf "%s %s = %d\n" op_name (to_string x) (op x) let%expect_test "clz int64" = let open Int64 in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1L ] in let f = test ~op:Ocaml_intrinsics.Int64.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 64 clz 0x1 = 63 clz 0x7 = 61 clz 0x7fff_ffff_ffff_ffff = 1 clz -0x8000_0000_0000_0000 = 0 clz -0x1 = 0 |}] ;; let%expect_test "clz int32" = let open Int32 in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1l ] in let f = test ~op:Ocaml_intrinsics.Int32.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 32 clz 0x1 = 31 clz 0x7 = 29 clz 0x7fff_ffff = 1 clz -0x8000_0000 = 0 clz -0x1 = 0 |}] ;; [%%ifdef JSC_ARCH_SIXTYFOUR] let%expect_test "clz int" = let open Int in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1 ] in let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 63 clz 0x1 = 62 clz 0x7 = 60 clz 0x3fff_ffff_ffff_ffff = 1 clz -0x4000_0000_0000_0000 = 0 clz -0x1 = 0 |}]; let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros2 ~op_name:"clz2" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz2 0x0 = 63 clz2 0x1 = 62 clz2 0x7 = 60 clz2 0x3fff_ffff_ffff_ffff = 1 clz2 -0x4000_0000_0000_0000 = 0 clz2 -0x1 = 0 |}] ;; let%expect_test "clz nativeint" = let open Nativeint in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1n ] in let f = test ~op:Ocaml_intrinsics.Nativeint.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 64 clz 0x1 = 63 clz 0x7 = 61 clz 0x7fff_ffff_ffff_ffff = 1 clz -0x8000_0000_0000_0000 = 0 clz -0x1 = 0 |}] ;; [%%else] let%expect_test "clz int" = let open Int in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1 ] in let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 31 clz 0x1 = 30 clz 0x7 = 28 clz 0x3fff_ffff = 1 clz -0x4000_0000 = 0 clz -0x1 = 0 |}]; let f = test ~op:Ocaml_intrinsics.Int.count_leading_zeros2 ~op_name:"clz2" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz2 0x0 = 31 clz2 0x1 = 30 clz2 0x7 = 28 clz2 0x3fff_ffff = 1 clz2 -0x4000_0000 = 0 clz2 -0x1 = 0 |}] ;; let%expect_test "clz nativeint" = let open Nativeint in let numbers = Int.num_bits - 3 ; max_value ; min_value ; -1n ] in let f = test ~op:Ocaml_intrinsics.Nativeint.count_leading_zeros ~op_name:"clz" ~to_string:Hex.to_string_hum in List.iter ~f numbers; [%expect {| clz 0x0 = 32 clz 0x1 = 31 clz 0x7 = 29 clz 0x7fff_ffff = 1 clz -0x8000_0000 = 0 clz -0x1 = 0 |}] ;; [%%endif]
54f2aea3b385bec7e320b1aa526e7328f1cf6c9b2f49430cdce44cf170272670
EFanZh/EOPL-Exercises
exercise-5.2.rkt
#lang eopl ;; Exercise 5.2 [★] Implement this data type of continuations using a data-structure representation. ;; Grammar. (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" identifier ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("letrec" identifier "(" identifier ")" "=" expression "in" expression) letrec-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) ;; Data structures. (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-var symbol?] [p-body expression?] [saved-env environment?]]) (define identifier? symbol?) (define-datatype continuation continuation? [end-cont] [zero1-cont [saved-cont continuation?]] [let-exp-cont [var identifier?] [body expression?] [saved-env environment?] [saved-cont continuation?]] [if-test-cont [exp2 expression?] [exp3 expression?] [saved-env environment?] [saved-cont continuation?]] [diff1-cont [exp2 expression?] [saved-env environment?] [saved-cont continuation?]] [diff2-cont [val1 expval?] [saved-cont continuation?]] [rator-cont [rand expression?] [saved-env environment?] [saved-cont continuation?]] [rand-cont [val1 expval?] [saved-cont continuation?]]) ;; Interpreter. (define apply-procedure/k (lambda (proc1 arg cont) (cases proc proc1 [procedure (var body saved-env) (value-of/k body (extend-env var arg saved-env) cont)]))) (define used-end-conts '()) (define apply-cont (lambda (cont val) (cases continuation cont [end-cont () (if (memq cont used-end-conts) (eopl:error "Continuation is already used.") (begin (set! used-end-conts (cons cont used-end-conts)) val))] [zero1-cont (saved-cont) (apply-cont saved-cont (bool-val (zero? (expval->num val))))] [let-exp-cont (var body saved-env saved-cont) (value-of/k body (extend-env var val saved-env) saved-cont)] [if-test-cont (exp2 exp3 saved-env saved-cont) (if (expval->bool val) (value-of/k exp2 saved-env saved-cont) (value-of/k exp3 saved-env saved-cont))] [diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))] [diff2-cont (val1 saved-cont) (let ([num1 (expval->num val1)] [num2 (expval->num val)]) (apply-cont saved-cont (num-val (- num1 num2))))] [rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))] [rand-cont (val1 saved-cont) (let ([proc (expval->proc val1)]) (apply-procedure/k proc val saved-cont))]))) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (var val saved-env) (if (eqv? search-sym var) val (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) (define value-of/k (lambda (exp env cont) (cases expression exp [const-exp (num) (apply-cont cont (num-val num))] [var-exp (var) (apply-cont cont (apply-env env var))] [proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))] [letrec-exp (p-name b-var p-body letrec-body) (value-of/k letrec-body (extend-env-rec p-name b-var p-body env) cont)] [zero?-exp (exp1) (value-of/k exp1 env (zero1-cont cont))] [let-exp (var exp1 body) (value-of/k exp1 env (let-exp-cont var body env cont))] [if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))] [diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))] [call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))]))) (define (init-env) (empty-env)) (define value-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (value-of/k exp1 (init-env) (end-cont))]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val num-val run)
null
https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-5.2.rkt
racket
Exercise 5.2 [★] Implement this data type of continuations using a data-structure representation. Grammar. Data structures. Interpreter.
#lang eopl (define the-lexical-spec '([whitespace (whitespace) skip] [comment ("%" (arbno (not #\newline))) skip] [identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol] [number (digit (arbno digit)) number] [number ("-" digit (arbno digit)) number])) (define the-grammar '([program (expression) a-program] [expression (number) const-exp] [expression ("-" "(" expression "," expression ")") diff-exp] [expression ("zero?" "(" expression ")") zero?-exp] [expression ("if" expression "then" expression "else" expression) if-exp] [expression (identifier) var-exp] [expression ("let" identifier "=" expression "in" expression) let-exp] [expression ("proc" "(" identifier ")" expression) proc-exp] [expression ("(" expression expression ")") call-exp] [expression ("letrec" identifier "(" identifier ")" "=" expression "in" expression) letrec-exp])) (sllgen:make-define-datatypes the-lexical-spec the-grammar) (define scan&parse (sllgen:make-string-parser the-lexical-spec the-grammar)) (define-datatype proc proc? [procedure [bvar symbol?] [body expression?] [env environment?]]) (define-datatype expval expval? [num-val [value number?]] [bool-val [boolean boolean?]] [proc-val [proc proc?]]) (define expval-extractor-error (lambda (variant value) (eopl:error 'expval-extractors "Looking for a ~s, found ~s" variant value))) (define expval->num (lambda (v) (cases expval v [num-val (num) num] [else (expval-extractor-error 'num v)]))) (define expval->bool (lambda (v) (cases expval v [bool-val (bool) bool] [else (expval-extractor-error 'bool v)]))) (define expval->proc (lambda (v) (cases expval v [proc-val (proc) proc] [else (expval-extractor-error 'proc v)]))) (define-datatype environment environment? [empty-env] [extend-env [bvar symbol?] [bval expval?] [saved-env environment?]] [extend-env-rec [p-name symbol?] [b-var symbol?] [p-body expression?] [saved-env environment?]]) (define identifier? symbol?) (define-datatype continuation continuation? [end-cont] [zero1-cont [saved-cont continuation?]] [let-exp-cont [var identifier?] [body expression?] [saved-env environment?] [saved-cont continuation?]] [if-test-cont [exp2 expression?] [exp3 expression?] [saved-env environment?] [saved-cont continuation?]] [diff1-cont [exp2 expression?] [saved-env environment?] [saved-cont continuation?]] [diff2-cont [val1 expval?] [saved-cont continuation?]] [rator-cont [rand expression?] [saved-env environment?] [saved-cont continuation?]] [rand-cont [val1 expval?] [saved-cont continuation?]]) (define apply-procedure/k (lambda (proc1 arg cont) (cases proc proc1 [procedure (var body saved-env) (value-of/k body (extend-env var arg saved-env) cont)]))) (define used-end-conts '()) (define apply-cont (lambda (cont val) (cases continuation cont [end-cont () (if (memq cont used-end-conts) (eopl:error "Continuation is already used.") (begin (set! used-end-conts (cons cont used-end-conts)) val))] [zero1-cont (saved-cont) (apply-cont saved-cont (bool-val (zero? (expval->num val))))] [let-exp-cont (var body saved-env saved-cont) (value-of/k body (extend-env var val saved-env) saved-cont)] [if-test-cont (exp2 exp3 saved-env saved-cont) (if (expval->bool val) (value-of/k exp2 saved-env saved-cont) (value-of/k exp3 saved-env saved-cont))] [diff1-cont (exp2 saved-env saved-cont) (value-of/k exp2 saved-env (diff2-cont val saved-cont))] [diff2-cont (val1 saved-cont) (let ([num1 (expval->num val1)] [num2 (expval->num val)]) (apply-cont saved-cont (num-val (- num1 num2))))] [rator-cont (rand saved-env saved-cont) (value-of/k rand saved-env (rand-cont val saved-cont))] [rand-cont (val1 saved-cont) (let ([proc (expval->proc val1)]) (apply-procedure/k proc val saved-cont))]))) (define apply-env (lambda (env search-sym) (cases environment env [empty-env () (eopl:error 'apply-env "No binding for ~s" search-sym)] [extend-env (var val saved-env) (if (eqv? search-sym var) val (apply-env saved-env search-sym))] [extend-env-rec (p-name b-var p-body saved-env) (if (eqv? search-sym p-name) (proc-val (procedure b-var p-body env)) (apply-env saved-env search-sym))]))) (define value-of/k (lambda (exp env cont) (cases expression exp [const-exp (num) (apply-cont cont (num-val num))] [var-exp (var) (apply-cont cont (apply-env env var))] [proc-exp (var body) (apply-cont cont (proc-val (procedure var body env)))] [letrec-exp (p-name b-var p-body letrec-body) (value-of/k letrec-body (extend-env-rec p-name b-var p-body env) cont)] [zero?-exp (exp1) (value-of/k exp1 env (zero1-cont cont))] [let-exp (var exp1 body) (value-of/k exp1 env (let-exp-cont var body env cont))] [if-exp (exp1 exp2 exp3) (value-of/k exp1 env (if-test-cont exp2 exp3 env cont))] [diff-exp (exp1 exp2) (value-of/k exp1 env (diff1-cont exp2 env cont))] [call-exp (rator rand) (value-of/k rator env (rator-cont rand env cont))]))) (define (init-env) (empty-env)) (define value-of-program (lambda (pgm) (cases program pgm [a-program (exp1) (value-of/k exp1 (init-env) (end-cont))]))) Interface . (define run (lambda (string) (value-of-program (scan&parse string)))) (provide bool-val num-val run)
a4b6f7544eeddc75f49cbd4be9ecd9682d128e0b93993ab7d5f21ed153b67215
essiene/smpp34
smpp34_snum.erl
-module(smpp34_snum). -include("../util.hrl"). -behaviour(gen_server). -export([start_link/2,start_link/3,stop/1]). -export([next/1, ping/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(st_snum, {owner, count, monitref, log}). start_link(Owner, Logger) -> start_link(Owner, 0, Logger). start_link(Owner, Start, Logger) -> gen_server:start_link(?MODULE, [Owner, Start, Logger], []). stop(Pid) -> gen_server:cast(Pid, stop). next(Pid) -> gen_server:call(Pid, next). ping(Pid) -> gen_server:call(Pid, ping). init([Owner, Start, Logger]) -> process_flag(trap_exit, true), MonitorRef = erlang:monitor(process, Owner), {ok, #st_snum{owner=Owner, count=Start, monitref=MonitorRef, log=Logger}}. handle_call(ping, _From, #st_snum{owner=Owner, count=Count}=St) -> {reply, {pong, [{owner=Owner}, {count,Count}]}, St}; handle_call(next, _From, #st_snum{count=?SNUM_MAX}=St) -> N1 = 1, {reply, {ok, N1}, St#st_snum{count=N1}}; handle_call(next, _From, #st_snum{count=N}=St) -> N1 = N+1, {reply, {ok, N1}, St#st_snum{count=N1}}; handle_call(Req, _From, St) -> {reply, {error, Req}, St}. handle_cast(stop, St) -> {stop, normal, St}; handle_cast(_Req, St) -> {noreply, St}. handle_info(#'DOWN'{ref=MonitorRef}, #st_snum{monitref=MonitorRef}=St) -> {stop, normal, St}; handle_info(_Req, St) -> {noreply, St}. terminate(_, _) -> ok. code_change(_OldVsn, St, _Extra) -> {noreply, St}.
null
https://raw.githubusercontent.com/essiene/smpp34/9206b1d270dc77d65a64a539cbca41b8b003956a/src/mod/smpp34_snum.erl
erlang
-module(smpp34_snum). -include("../util.hrl"). -behaviour(gen_server). -export([start_link/2,start_link/3,stop/1]). -export([next/1, ping/1]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(st_snum, {owner, count, monitref, log}). start_link(Owner, Logger) -> start_link(Owner, 0, Logger). start_link(Owner, Start, Logger) -> gen_server:start_link(?MODULE, [Owner, Start, Logger], []). stop(Pid) -> gen_server:cast(Pid, stop). next(Pid) -> gen_server:call(Pid, next). ping(Pid) -> gen_server:call(Pid, ping). init([Owner, Start, Logger]) -> process_flag(trap_exit, true), MonitorRef = erlang:monitor(process, Owner), {ok, #st_snum{owner=Owner, count=Start, monitref=MonitorRef, log=Logger}}. handle_call(ping, _From, #st_snum{owner=Owner, count=Count}=St) -> {reply, {pong, [{owner=Owner}, {count,Count}]}, St}; handle_call(next, _From, #st_snum{count=?SNUM_MAX}=St) -> N1 = 1, {reply, {ok, N1}, St#st_snum{count=N1}}; handle_call(next, _From, #st_snum{count=N}=St) -> N1 = N+1, {reply, {ok, N1}, St#st_snum{count=N1}}; handle_call(Req, _From, St) -> {reply, {error, Req}, St}. handle_cast(stop, St) -> {stop, normal, St}; handle_cast(_Req, St) -> {noreply, St}. handle_info(#'DOWN'{ref=MonitorRef}, #st_snum{monitref=MonitorRef}=St) -> {stop, normal, St}; handle_info(_Req, St) -> {noreply, St}. terminate(_, _) -> ok. code_change(_OldVsn, St, _Extra) -> {noreply, St}.
15ebc81f3b5ad5afbf1c289009d68abdcf88e3d4b662f68179ad9de2372b01a3
tailrecursion/javastar
project.clj
(defproject tailrecursion/javastar "1.1.6" :description "Write Java inside Clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"] [alandipert/interpol8 "0.0.3"] [org.clojure/core.cache "0.6.3"]])
null
https://raw.githubusercontent.com/tailrecursion/javastar/d4da13cca6ae1a83575abba6aec40aa88db3b3e8/project.clj
clojure
(defproject tailrecursion/javastar "1.1.6" :description "Write Java inside Clojure" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.5.1"] [alandipert/interpol8 "0.0.3"] [org.clojure/core.cache "0.6.3"]])
48c9f33dfac04733f282e3b9c7f5fbabf0ce1bc23f5abf3d119104d0d30d95ee
haskell-tools/haskell-tools
MergeFields_RenameY.hs
module Refactor.RenameDefinition.MergeFields_RenameY where data A = B { x :: Double } | C { y :: Double } f a = case a of B {} -> x a C {} -> y a
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/builtin-refactorings/examples/Refactor/RenameDefinition/MergeFields_RenameY.hs
haskell
module Refactor.RenameDefinition.MergeFields_RenameY where data A = B { x :: Double } | C { y :: Double } f a = case a of B {} -> x a C {} -> y a
20cc6325b6f87ec5a8b7fed8d4257b73d189637af3760df50186e0bf159a33c0
orbitz/oort
mdb_bhv_say.erl
%%% File : mdb_bhv_say.erl Author : < > %%% Purpose : Say the data in the channel or to the speaker Created : 12 Aug 2003 by < > %%%---------------------------------------------------------------------- %%% This file is part of Manderlbot . %%% Manderlbot 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. %%% Manderlbot 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. %%% %%% See LICENSE for detailled license %%% %%% In addition, as a special exception, you have the permission to %%% link the code of this program with any library released under the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception %%% to your version of the file, but you are not obligated to do %%% so. If you do not wish to do so, delete this exception %%% statement from your version. %%% %%%---------------------------------------------------------------------- -module(mdb_bhv_say). -vc('$Id: mdb_bhv_say.erl,v 1.2 2003/08/20 16:26:28 nico Exp $ '). -author(''). -export([behaviour/5]). % MDB behaviour API -include("mdb.hrl"). %%%---------------------------------------------------------------------- %%% Function: behaviour/5 %%% Purpose: Say the data in the channel or to the speaker %%%---------------------------------------------------------------------- behaviour(Input = #data{header_to=BotName}, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, String, NickFrom) end, Data); behaviour(Input, BotName, Data, BotPid, Channel) -> lists:map(fun(String) -> mdb_bot:say(BotPid, String) end, Data).
null
https://raw.githubusercontent.com/orbitz/oort/a61ec85508917ae9a3f6672a0b708d47c23bb260/manderlbot-0.9.2/src/mdb_bhv_say.erl
erlang
File : mdb_bhv_say.erl Purpose : Say the data in the channel or to the speaker ---------------------------------------------------------------------- (at your option) any later version. 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. See LICENSE for detailled license In addition, as a special exception, you have the permission to link the code of this program with any library released under to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. ---------------------------------------------------------------------- MDB behaviour API ---------------------------------------------------------------------- Function: behaviour/5 Purpose: Say the data in the channel or to the speaker ----------------------------------------------------------------------
Author : < > Created : 12 Aug 2003 by < > This file is part of Manderlbot . Manderlbot 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 Manderlbot is distributed in the hope that it will be useful , the EPL license and distribute linked combinations including the two . If you modify this file , you may extend this exception -module(mdb_bhv_say). -vc('$Id: mdb_bhv_say.erl,v 1.2 2003/08/20 16:26:28 nico Exp $ '). -author(''). -include("mdb.hrl"). behaviour(Input = #data{header_to=BotName}, BotName, Data, BotPid, Channel) -> [NickFrom|IpFrom] = string:tokens(Input#data.header_from, "!"), lists:map(fun(String) -> mdb_bot:say(BotPid, String, NickFrom) end, Data); behaviour(Input, BotName, Data, BotPid, Channel) -> lists:map(fun(String) -> mdb_bot:say(BotPid, String) end, Data).
3dedb56d0ad395d8e9c46512cf27e1ae4c383ad8ed58d7c95a2d282defabc967
gheber/kenzo
simplicial-groups-test.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Base : 10 - * (in-package :kenzo-test-9) (in-suite :kenzo-9) (test check-kan (cat-9:cat-init) (let* ((k (cat-9:k-z-1)) (rslt '(1 10 100)) (hat (mapcar #'(lambda (i) (cat-9:face k i 3 rslt)) (cat-9:<a-b> 0 3)))) (dotimes (i 4) (cat-9:check-kan k i 3 (remove (nth i hat) hat :test #'equal)))))
null
https://raw.githubusercontent.com/gheber/kenzo/48e2ea398b80f39d3b5954157a7df57e07a362d7/test/kenzo-9/simplicial-groups-test.lisp
lisp
Syntax : ANSI - Common - Lisp ; Base : 10 - *
(in-package :kenzo-test-9) (in-suite :kenzo-9) (test check-kan (cat-9:cat-init) (let* ((k (cat-9:k-z-1)) (rslt '(1 10 100)) (hat (mapcar #'(lambda (i) (cat-9:face k i 3 rslt)) (cat-9:<a-b> 0 3)))) (dotimes (i 4) (cat-9:check-kan k i 3 (remove (nth i hat) hat :test #'equal)))))
f633041830e1c67b7d89bff287ec98c52c6574c5ac9f786500b3eb27eb80fa5e
nodew/haskell-dapr
Configuration.hs
-- | Module : . Client . HttpClient . Configuration -- Description : Manage Configuration stores -- Copyright : (c) -- License : Apache-2.0 -- This module manages Configuration stores which can then be read by application instances on startup or notified of when changes occur. This allows for dynamic configuration. module Dapr.Client.HttpClient.Configuration where import Dapr.Client.HttpClient.Internal import Dapr.Client.HttpClient.Req import Dapr.Core.Types import Dapr.Core.Types.Internal import Data.Aeson (FromJSON (parseJSON)) import Data.Bifunctor (bimap) import Data.Map (fromList) import Data.Text (Text) import GHC.Generics (Generic) import Network.HTTP.Req data ConfigurationItem' = ConfigurationItem' { configurationItemKey :: ConfigurationKey, configurationItemValue :: Text, configurationItemVersion :: Text, configurationItemMetadata :: ExtendedMetadata } deriving (Generic) instance FromJSON ConfigurationItem' where parseJSON = customParseJSON 17 -- | Get a list of configuration items based on keys from the given statestore getConfiguration :: GetConfigurationRequest -> DaprHttpClient (Either DaprClientError GetConfigurationResponse) getConfiguration GetConfigurationRequest {..} = do let url = ["configuration", getConfigStoreName storeName] params = mapKeysToParam "key" keys response <- makeHttpRequest GET url NoReqBody jsonResponse params return $ bimap DaprHttpException (toGetConfigurationResponse . responseBody) response where toGetConfigurationResponse :: [ConfigurationItem'] -> GetConfigurationResponse toGetConfigurationResponse = GetConfigurationResponse . fromList . map (\ConfigurationItem' {..} -> (configurationItemKey, ConfigurationItem {..})) -- | Subscribe to a configuration store for the specified keys and receive an updated value whenever the key is updated in the store subscribeConfiguration :: SubscribeConfigurationRequest -> DaprHttpClient (Either DaprClientError SubscribeConfigurationResponse) subscribeConfiguration SubscribeConfigurationRequest {..} = do let url = ["configuration", getConfigStoreName storeName, "subscribe"] params = mapKeysToParam "key" keys response <- makeHttpRequest GET url NoReqBody jsonResponse params return $ bimap DaprHttpException responseBody response -- | Unsubscribe from a configuration store using given subscription Id unsubscribeConfiguration :: SubscriptionId -> DaprHttpClient (Either DaprClientError ()) unsubscribeConfiguration subscriptionId = do let url = ["configuration", getSubscriptionId subscriptionId, "unsubscribe"] response <- makeHttpRequest GET url NoReqBody ignoreResponse mempty return $ bimap DaprHttpException (const ()) response
null
https://raw.githubusercontent.com/nodew/haskell-dapr/7e3a47835b479f5a54f79bbe3fce303428e55c75/dapr-http-client/src/Dapr/Client/HttpClient/Configuration.hs
haskell
| Description : Manage Configuration stores Copyright : (c) License : Apache-2.0 This module manages Configuration stores which can then be read by application instances on startup or notified of when changes occur. This allows for dynamic configuration. | Get a list of configuration items based on keys from the given statestore | Subscribe to a configuration store for the specified keys and receive an updated value whenever the key is updated in the store | Unsubscribe from a configuration store using given subscription Id
Module : . Client . HttpClient . Configuration module Dapr.Client.HttpClient.Configuration where import Dapr.Client.HttpClient.Internal import Dapr.Client.HttpClient.Req import Dapr.Core.Types import Dapr.Core.Types.Internal import Data.Aeson (FromJSON (parseJSON)) import Data.Bifunctor (bimap) import Data.Map (fromList) import Data.Text (Text) import GHC.Generics (Generic) import Network.HTTP.Req data ConfigurationItem' = ConfigurationItem' { configurationItemKey :: ConfigurationKey, configurationItemValue :: Text, configurationItemVersion :: Text, configurationItemMetadata :: ExtendedMetadata } deriving (Generic) instance FromJSON ConfigurationItem' where parseJSON = customParseJSON 17 getConfiguration :: GetConfigurationRequest -> DaprHttpClient (Either DaprClientError GetConfigurationResponse) getConfiguration GetConfigurationRequest {..} = do let url = ["configuration", getConfigStoreName storeName] params = mapKeysToParam "key" keys response <- makeHttpRequest GET url NoReqBody jsonResponse params return $ bimap DaprHttpException (toGetConfigurationResponse . responseBody) response where toGetConfigurationResponse :: [ConfigurationItem'] -> GetConfigurationResponse toGetConfigurationResponse = GetConfigurationResponse . fromList . map (\ConfigurationItem' {..} -> (configurationItemKey, ConfigurationItem {..})) subscribeConfiguration :: SubscribeConfigurationRequest -> DaprHttpClient (Either DaprClientError SubscribeConfigurationResponse) subscribeConfiguration SubscribeConfigurationRequest {..} = do let url = ["configuration", getConfigStoreName storeName, "subscribe"] params = mapKeysToParam "key" keys response <- makeHttpRequest GET url NoReqBody jsonResponse params return $ bimap DaprHttpException responseBody response unsubscribeConfiguration :: SubscriptionId -> DaprHttpClient (Either DaprClientError ()) unsubscribeConfiguration subscriptionId = do let url = ["configuration", getSubscriptionId subscriptionId, "unsubscribe"] response <- makeHttpRequest GET url NoReqBody ignoreResponse mempty return $ bimap DaprHttpException (const ()) response
0a65c07ebd0cf1f90b0e2152189572b7be270d26d8b7e8e597fa9f0a7cfc4887
xu-hao/QueryArrow
Plugin.hs
# LANGUAGE MultiParamTypeClasses , GADTs , RankNTypes # module QueryArrow.Plugin where import QueryArrow.Config import QueryArrow.DB.DB import QueryArrow.Syntax.Term import QueryArrow.Semantics.TypeChecker import QueryArrow.DB.AbstractDatabaseList import QueryArrow.Data.Heterogeneous.List type GetDBFunction row = ICATDBConnInfo -> IO (AbstractDatabase row FormulaT) getDBs :: GetDBFunction row -> [ICATDBConnInfo] -> IO (AbstractDBList row) getDBs _ [] = return (AbstractDBList HNil) getDBs getDB0 (transinfo : l) = do db0 <- getDB0 transinfo case db0 of AbstractDatabase db -> do dbs0 <- getDBs getDB0 l case dbs0 of AbstractDBList dbs -> return (AbstractDBList (HCons db dbs)) class Plugin a row where getDB :: a -> GetDBFunction row -> GetDBFunction row data AbstractPlugin row = forall a. (Plugin a row) => AbstractPlugin a
null
https://raw.githubusercontent.com/xu-hao/QueryArrow/4dd5b8a22c8ed2d24818de5b8bcaa9abc456ef0d/QueryArrow-common/src/QueryArrow/Plugin.hs
haskell
# LANGUAGE MultiParamTypeClasses , GADTs , RankNTypes # module QueryArrow.Plugin where import QueryArrow.Config import QueryArrow.DB.DB import QueryArrow.Syntax.Term import QueryArrow.Semantics.TypeChecker import QueryArrow.DB.AbstractDatabaseList import QueryArrow.Data.Heterogeneous.List type GetDBFunction row = ICATDBConnInfo -> IO (AbstractDatabase row FormulaT) getDBs :: GetDBFunction row -> [ICATDBConnInfo] -> IO (AbstractDBList row) getDBs _ [] = return (AbstractDBList HNil) getDBs getDB0 (transinfo : l) = do db0 <- getDB0 transinfo case db0 of AbstractDatabase db -> do dbs0 <- getDBs getDB0 l case dbs0 of AbstractDBList dbs -> return (AbstractDBList (HCons db dbs)) class Plugin a row where getDB :: a -> GetDBFunction row -> GetDBFunction row data AbstractPlugin row = forall a. (Plugin a row) => AbstractPlugin a
7cf45b235cea0490a7578596d85050abaeecd1b8bbca9b21e9cad58d1a4f34b4
bobzhang/ocaml-book
sexp.ml
TYPE_CONV_PATH "" open Sexplib open Sexplib.Sexp open Sexplib.Conv let (|>) x f = f x (** if you don't provide, it will infer sexp.ml.t *) type t = A | B with sexp (** debug camlp4o -parser Pa_type_conv.cma pa_sexp_conv.cma sexp.ml -printer o *) type reco = { foo : int; bar : string; } with sexp (** To make use of sexp_option, Conv is required to open *) open Conv type reco2 = { x : int option; y : int sexp_option; } with sexp let a = {x=Some 3 ; y = None} |> sexp_of_reco2;; (** sexp_list sexp_array sexp_bool assumes empty as default value *) type sum2 = A | B of int * float * sum2 with sexp (** polymorphic variants here *) type ('a,'b) pv = [`X of ('a,'b) pv | `Y of 'a * 'b ] with sexp type 'a pt = A | B of 'a with sexp type foo = int pt with sexp * ADT here write your own here write your own *) * Hashtbl *) (** opaque type *) type foo2 = A of int * char sexp_opaque with sexp module M = struct exception Foo of int with sexp end let b = M.Foo 3 |> sexp_of_exn exception Foo2 of int with sexp let c = Foo2 4 |> sexp_of_exn open Batteries let _ = prerr_endline "uh"; prerr_endline (dump b); prerr_endline (dump c); * FIXME I do n't know why this fails let = c | > string_of_sexp in I don't know why this fails let strc = c |> string_of_sexp in *) let strc = c |> to_string_hum in prerr_endline strc; prerr_endline "xx"; let str = c |> to_string_hum in (** let str = b |> string_of_sexp in *) prerr_endline str let _ = prerr_endline "uh"; prerr_endline (dump b); prerr_endline (dump c); let strc = c |> string_of_sexp in prerr_endline strc; prerr_endline "xx"; let str = b |> string_of_sexp in prerr_endline str (** load_sexp_conv load_sexp_conv_exn *)
null
https://raw.githubusercontent.com/bobzhang/ocaml-book/09a575b0d1fedfce565ecb9a0ae9cf0df37fdc75/library/code/sexp.ml
ocaml
* if you don't provide, it will infer sexp.ml.t * debug camlp4o -parser Pa_type_conv.cma pa_sexp_conv.cma sexp.ml -printer o * To make use of sexp_option, Conv is required to open * sexp_list sexp_array sexp_bool assumes empty as default value * polymorphic variants here * opaque type * let str = b |> string_of_sexp in * load_sexp_conv load_sexp_conv_exn
TYPE_CONV_PATH "" open Sexplib open Sexplib.Sexp open Sexplib.Conv let (|>) x f = f x type t = A | B with sexp type reco = { foo : int; bar : string; } with sexp open Conv type reco2 = { x : int option; y : int sexp_option; } with sexp let a = {x=Some 3 ; y = None} |> sexp_of_reco2;; type sum2 = A | B of int * float * sum2 with sexp type ('a,'b) pv = [`X of ('a,'b) pv | `Y of 'a * 'b ] with sexp type 'a pt = A | B of 'a with sexp type foo = int pt with sexp * ADT here write your own here write your own *) * Hashtbl *) type foo2 = A of int * char sexp_opaque with sexp module M = struct exception Foo of int with sexp end let b = M.Foo 3 |> sexp_of_exn exception Foo2 of int with sexp let c = Foo2 4 |> sexp_of_exn open Batteries let _ = prerr_endline "uh"; prerr_endline (dump b); prerr_endline (dump c); * FIXME I do n't know why this fails let = c | > string_of_sexp in I don't know why this fails let strc = c |> string_of_sexp in *) let strc = c |> to_string_hum in prerr_endline strc; prerr_endline "xx"; let str = c |> to_string_hum in prerr_endline str let _ = prerr_endline "uh"; prerr_endline (dump b); prerr_endline (dump c); let strc = c |> string_of_sexp in prerr_endline strc; prerr_endline "xx"; let str = b |> string_of_sexp in prerr_endline str
6e12d17779a7a3aba28a9c5a48c68b2a63abc0399986905733a83b0dccc2d9e3
bennn/dissertation
get-typed-racket-base-types.rkt
#lang racket/base ;; Count number of Typed Racket base types ;; TODO some types are not exported from 'base-types'! ;; - Immutable-Vector ;; - Mutable-Vectorof ;; - Sequenceof ;; - Vector so , the total is 199 + 4 = 203 (require typed-racket/base-env/base-types racket/pretty) (define-values [var* stx*] (module->exports 'typed-racket/base-env/base-types)) (define type-name* (for*/list ((phase+export* (in-list stx*)) (export* (in-list (cdr phase+export*)))) (car export*))) (printf "'typed-racket/base-env/base-types' exports ~a syntax identifiers~n" (length type-name*)) #;(pretty-print type-name*)
null
https://raw.githubusercontent.com/bennn/dissertation/779bfe6f8fee19092849b7e2cfc476df33e9357b/proposal/talk/src/get-typed-racket-base-types.rkt
racket
Count number of Typed Racket base types TODO some types are not exported from 'base-types'! - Immutable-Vector - Mutable-Vectorof - Sequenceof - Vector (pretty-print type-name*)
#lang racket/base so , the total is 199 + 4 = 203 (require typed-racket/base-env/base-types racket/pretty) (define-values [var* stx*] (module->exports 'typed-racket/base-env/base-types)) (define type-name* (for*/list ((phase+export* (in-list stx*)) (export* (in-list (cdr phase+export*)))) (car export*))) (printf "'typed-racket/base-env/base-types' exports ~a syntax identifiers~n" (length type-name*))
fbd7eed0af8b2c883ed14e69e1c740fc4621be8f1e3efc3df63cad066671a5b2
jiesoul/soul-talk
views.cljs
(ns soul-talk.views (:require [reagent.core :as r] [re-frame.core :refer [subscribe dispatch]] [soul-talk.routes :refer [navigate!]] [soul-talk.common.views :as c] [soul-talk.pages :as page] [soul-talk.article.views :as article] [soul-talk.tag.views :as tag] [soul-talk.series.views :as series] [soul-talk.utils :as utils])) (defmulti pages (fn [page _] page)) ;; (defmethod pages :home [_ _] [page/home]) ;; article (defmethod pages :articles [_ _] [page/articles]) (defmethod pages :articles/view [_ _] [article/view]) (defmethod pages :series [_ _] [page/series]) (defmethod pages :tags [_ _] [page/tags]) (defmethod pages :about [_ _] [page/about]) ;; default (defmethod pages :default [_ _] [page/home]) ;; 根据配置加载不同页面 (defn main-page [] (let [ready? (subscribe [:initialised?]) active-page (subscribe [:active-page])] (when @ready? [:<> [c/lading] (pages @active-page)])))
null
https://raw.githubusercontent.com/jiesoul/soul-talk/630de08c6549b206d59023764d5f2576d97d1030/home/src/soul_talk/views.cljs
clojure
article default 根据配置加载不同页面
(ns soul-talk.views (:require [reagent.core :as r] [re-frame.core :refer [subscribe dispatch]] [soul-talk.routes :refer [navigate!]] [soul-talk.common.views :as c] [soul-talk.pages :as page] [soul-talk.article.views :as article] [soul-talk.tag.views :as tag] [soul-talk.series.views :as series] [soul-talk.utils :as utils])) (defmulti pages (fn [page _] page)) (defmethod pages :home [_ _] [page/home]) (defmethod pages :articles [_ _] [page/articles]) (defmethod pages :articles/view [_ _] [article/view]) (defmethod pages :series [_ _] [page/series]) (defmethod pages :tags [_ _] [page/tags]) (defmethod pages :about [_ _] [page/about]) (defmethod pages :default [_ _] [page/home]) (defn main-page [] (let [ready? (subscribe [:initialised?]) active-page (subscribe [:active-page])] (when @ready? [:<> [c/lading] (pages @active-page)])))