_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
a7b2cfc78d07d7a4aef50d9dc75685844bb6ef189147ff5b6e3344d2c183f7cd
egonSchiele/dominion
Types.hs
# LANGUAGE TemplateHaskell # module Dominion.Types ( | This module uses the ` Lens ` library . So you might notice that the -- fields for the constructors look strange: they all have underscores. -- Given a card, you can see the cost like this: -- -- > _cost card -- -- But you can also use a lens: -- -- > card ^. cost -- -- The lens library is very useful for modifying deeply nested data -- structures, and it's been very useful for this module. module Dominion.Types ) where import Control.Lens import Control.Monad.State import qualified Data.Map.Lazy as M --------------------------- CARD --------------------------- data CardType = Action | Attack | Reaction | Treasure | Victory | Duration deriving (Show, Eq, Ord) data CardEffect = CoinValue Int | VPValue Int | PlusCard Int | PlusCoin Int | PlusBuy Int | PlusAction Int | DurationDraw Int | DurationAction Int | DurationCoin Int | DurationBuy Int | TrashCards Int | TrashThisCard | GainCardUpto Int | PlayActionCard Int | AdventurerEffect | BureaucratEffect | CellarEffect | ChancellorEffect | GardensEffect | LibraryEffect | MineEffect | MoneylenderEffect | RemodelEffect | SpyEffect | ThiefEffect | OthersPlusCard Int | OthersDiscardTo Int | OthersGainCurse Int deriving (Show, Eq, Ord) data Card = Card { _name :: String, _cost :: Int, _cardType :: [CardType], _effects :: [CardEffect] } deriving (Show, Eq, Ord) makeLenses ''Card -- | Used with the `thief` card. data ThiefTrashAction = TrashOnly Card | GainTrashedCard Card -- | Some cards have a followup action associated with them. For example, -- when you play a `workshop`, you need to choose what card you're going to -- get. To use the followup action, you need to use the relevant data -- constructor. See the documentation for each card to find out how to use each type of ` FollowupAction ` . data FollowupAction = ThroneRoom Card -- | Takes a list of cards to discard. | Cellar [Card] -- | Boolean value representing whether you want to -- move your deck into the discard pile. | Chancellor Bool -- | Takes a list of cards to trash. | Chapel [Card] -- | Takes the card you want to gain. | Feast Card -- | Takes the card you want to trash. | Mine Card | The first card is the card you are trashing , the second card is the card you are gaining . | Remodel (Card, Card) | The first element is the list of cards you would discard for yourself , the second is the lsit of cards you want others to discard . | Spy ([Card], [Card]) -- | The function gets a list of treasure cards. had . You return either ` TrashOnly ` to have the player -- trash a card, or `GainTrashedCard` to gain the trashed -- card. This function is called for every other -- player in the game. | Thief ([Card] -> ThiefTrashAction) -- | Takes the card you want to gain. | Workshop Card --------------------------- -- PLAYER --------------------------- data Player = Player { _playerName :: String, _deck :: [Card], _discard :: [Card], _hand :: [Card], _actions :: Int, _buys :: Int, -- | Extra money gained from an action card (like +1 money -- from market). _extraMoney :: Int } deriving Show makeLenses ''Player type PlayerId = Int --------------------------- -- GAME STATE --------------------------- -- | This is what keeps track of all the state in the whole game. -- Get the round number like this: -- -- > state <- get -- > let roundNum = state ^. round data GameState = GameState { _players :: [Player], -- | all the cards still in play. _cards :: M.Map Card Int, -- | round number _round :: Int, _verbose :: Bool } makeLenses ''GameState instance Show GameState where show gs = "GameState {players: " ++ show (_players gs) ++ ", cards: " ++ show (M.mapKeys _name (_cards gs)) ++ ", round: " ++ show (_round gs) ++ ", verbose: " ++ show (_verbose gs) ++ "}" The Dominion monad is just the ` StateT ` monad that has a ` GameState ` plus the IO monad . type Dominion a = StateT GameState IO a -- | Given a playerId, run some actions for this player. Example: -- -- > bigMoney playerId = playerId `buysByPreference` [province, gold, duchy, silver, copper] type Strategy = PlayerId -> Dominion () -- | When you use a card (either you play it or you buy something), you get a ` PlayResult ` . A ` PlayResult ` is either a ` Left ` with an error message , -- or a `Right` with a value. type PlayResult a = Either String a -- | When you play an action card that needs a decision on your part, -- `plays` will return a Followup. type Followup = (PlayerId, CardEffect) -- | You can set these options if you use `dominionWithOpts`. Example: -- > main = dominionWithOpts [ Iterations 1 , Log True , Cards [ smithy ] ] ... data Option = -- | Number of iterations to run. Iterations Int -- | Enable logging | Log Bool -- | A list of cards that you definitely want in the game. -- Useful if you are testing a strategy that relies on -- a particular card. | Cards [Card] deriving (Show) -- | Each `PlayerResult` is a tuple of a player and their final score. type PlayerResult = (Player, Int) -- | Players and their scores. data Result = Result { playerResults :: [PlayerResult], winner :: String } deriving (Show)
null
https://raw.githubusercontent.com/egonSchiele/dominion/a4b7300f2e445da5e7cfcc1cf9029243a3561ed6/src/Dominion/Types.hs
haskell
fields for the constructors look strange: they all have underscores. Given a card, you can see the cost like this: > _cost card But you can also use a lens: > card ^. cost The lens library is very useful for modifying deeply nested data structures, and it's been very useful for this module. ------------------------- ------------------------- | Used with the `thief` card. | Some cards have a followup action associated with them. For example, when you play a `workshop`, you need to choose what card you're going to get. To use the followup action, you need to use the relevant data constructor. See the documentation for each card to find out how to use | Takes a list of cards to discard. | Boolean value representing whether you want to move your deck into the discard pile. | Takes a list of cards to trash. | Takes the card you want to gain. | Takes the card you want to trash. | The function gets a list of treasure cards. trash a card, or `GainTrashedCard` to gain the trashed card. This function is called for every other player in the game. | Takes the card you want to gain. ------------------------- PLAYER ------------------------- | Extra money gained from an action card (like +1 money from market). ------------------------- GAME STATE ------------------------- | This is what keeps track of all the state in the whole game. Get the round number like this: > state <- get > let roundNum = state ^. round | all the cards still in play. | round number | Given a playerId, run some actions for this player. Example: > bigMoney playerId = playerId `buysByPreference` [province, gold, duchy, silver, copper] | When you use a card (either you play it or you buy something), or a `Right` with a value. | When you play an action card that needs a decision on your part, `plays` will return a Followup. | You can set these options if you use `dominionWithOpts`. Example: | Number of iterations to run. | Enable logging | A list of cards that you definitely want in the game. Useful if you are testing a strategy that relies on a particular card. | Each `PlayerResult` is a tuple of a player and their final score. | Players and their scores.
# LANGUAGE TemplateHaskell # module Dominion.Types ( | This module uses the ` Lens ` library . So you might notice that the module Dominion.Types ) where import Control.Lens import Control.Monad.State import qualified Data.Map.Lazy as M CARD data CardType = Action | Attack | Reaction | Treasure | Victory | Duration deriving (Show, Eq, Ord) data CardEffect = CoinValue Int | VPValue Int | PlusCard Int | PlusCoin Int | PlusBuy Int | PlusAction Int | DurationDraw Int | DurationAction Int | DurationCoin Int | DurationBuy Int | TrashCards Int | TrashThisCard | GainCardUpto Int | PlayActionCard Int | AdventurerEffect | BureaucratEffect | CellarEffect | ChancellorEffect | GardensEffect | LibraryEffect | MineEffect | MoneylenderEffect | RemodelEffect | SpyEffect | ThiefEffect | OthersPlusCard Int | OthersDiscardTo Int | OthersGainCurse Int deriving (Show, Eq, Ord) data Card = Card { _name :: String, _cost :: Int, _cardType :: [CardType], _effects :: [CardEffect] } deriving (Show, Eq, Ord) makeLenses ''Card data ThiefTrashAction = TrashOnly Card | GainTrashedCard Card each type of ` FollowupAction ` . data FollowupAction = ThroneRoom Card | Cellar [Card] | Chancellor Bool | Chapel [Card] | Feast Card | Mine Card | The first card is the card you are trashing , the second card is the card you are gaining . | Remodel (Card, Card) | The first element is the list of cards you would discard for yourself , the second is the lsit of cards you want others to discard . | Spy ([Card], [Card]) had . You return either ` TrashOnly ` to have the player | Thief ([Card] -> ThiefTrashAction) | Workshop Card data Player = Player { _playerName :: String, _deck :: [Card], _discard :: [Card], _hand :: [Card], _actions :: Int, _buys :: Int, _extraMoney :: Int } deriving Show makeLenses ''Player type PlayerId = Int data GameState = GameState { _players :: [Player], _cards :: M.Map Card Int, _round :: Int, _verbose :: Bool } makeLenses ''GameState instance Show GameState where show gs = "GameState {players: " ++ show (_players gs) ++ ", cards: " ++ show (M.mapKeys _name (_cards gs)) ++ ", round: " ++ show (_round gs) ++ ", verbose: " ++ show (_verbose gs) ++ "}" The Dominion monad is just the ` StateT ` monad that has a ` GameState ` plus the IO monad . type Dominion a = StateT GameState IO a type Strategy = PlayerId -> Dominion () you get a ` PlayResult ` . A ` PlayResult ` is either a ` Left ` with an error message , type PlayResult a = Either String a type Followup = (PlayerId, CardEffect) > main = dominionWithOpts [ Iterations 1 , Log True , Cards [ smithy ] ] ... data Option = Iterations Int | Log Bool | Cards [Card] deriving (Show) type PlayerResult = (Player, Int) data Result = Result { playerResults :: [PlayerResult], winner :: String } deriving (Show)
0a05da5b7cddd6899538697d748d991eb1c40561479a790bab2cfe6eeab18664
Tim-ats-d/Tim-lang
compiler.ml
let from_lexbuf lexbuf = match Parsing.parse lexbuf with | Ok ast -> Ast.Eval.eval_program ast | Error err -> prerr_endline err let from_str str = Lexing.from_string str |> from_lexbuf let from_file filename = let lexbuf = Lexing.from_channel (open_in filename) in Lexing.set_filename lexbuf filename; from_lexbuf lexbuf
null
https://raw.githubusercontent.com/Tim-ats-d/Tim-lang/005d04de07871fe464fadbb80c3050b9bc9b0ace/src/core/compiler.ml
ocaml
let from_lexbuf lexbuf = match Parsing.parse lexbuf with | Ok ast -> Ast.Eval.eval_program ast | Error err -> prerr_endline err let from_str str = Lexing.from_string str |> from_lexbuf let from_file filename = let lexbuf = Lexing.from_channel (open_in filename) in Lexing.set_filename lexbuf filename; from_lexbuf lexbuf
e5ab4c57d830d0fef5bd45a9f0fcebb536ecacf8aaa69ef4d2c1a77a3fdb8e4e
brownplt/TeJaS
typeScript_kinding.ml
open Prelude open Sig open TypeScript_sigs open Strobe_sigs module Make (TypeScript : TYPESCRIPT_MODULE) (StrobeKind : STROBE_KINDING with type typ = TypeScript.baseTyp with type kind = TypeScript.baseKind with type binding = TypeScript.baseBinding with type extTyp = TypeScript.typ with type extKind = TypeScript.kind with type extBinding = TypeScript.binding with type env = TypeScript.env) = struct include TypeScript open TypeScript let list_prims = StrobeKind.list_prims let new_prim_typ = StrobeKind.new_prim_typ let kind_mismatch typ calculated_kind expected_kind = raise (Strobe.Kind_error (sprintf "Expected kind %s, but got kind %s for type:\n%s" (string_of_kind expected_kind) (string_of_kind calculated_kind) (string_of_typ typ))) let rec kind_check_typ (env : env) (recIds : id list) (typ : typ) : kind = match typ with | TStrobe t -> embed_k (StrobeKind.kind_check env recIds t) | TArrow (args, varargs, ret) -> let assert_kind t = match extract_k (kind_check_typ env recIds t) with | Strobe.KStar -> () | k -> kind_mismatch t (embed_k k) (embed_k Strobe.KStar) in List.iter assert_kind (ret :: args); (match varargs with None -> () | Some v -> assert_kind v); embed_k Strobe.KStar let kind_check = kind_check_typ end
null
https://raw.githubusercontent.com/brownplt/TeJaS/a8ad7e5e9ad938db205074469bbde6a688ec913e/src/typescript/typeScript_kinding.ml
ocaml
open Prelude open Sig open TypeScript_sigs open Strobe_sigs module Make (TypeScript : TYPESCRIPT_MODULE) (StrobeKind : STROBE_KINDING with type typ = TypeScript.baseTyp with type kind = TypeScript.baseKind with type binding = TypeScript.baseBinding with type extTyp = TypeScript.typ with type extKind = TypeScript.kind with type extBinding = TypeScript.binding with type env = TypeScript.env) = struct include TypeScript open TypeScript let list_prims = StrobeKind.list_prims let new_prim_typ = StrobeKind.new_prim_typ let kind_mismatch typ calculated_kind expected_kind = raise (Strobe.Kind_error (sprintf "Expected kind %s, but got kind %s for type:\n%s" (string_of_kind expected_kind) (string_of_kind calculated_kind) (string_of_typ typ))) let rec kind_check_typ (env : env) (recIds : id list) (typ : typ) : kind = match typ with | TStrobe t -> embed_k (StrobeKind.kind_check env recIds t) | TArrow (args, varargs, ret) -> let assert_kind t = match extract_k (kind_check_typ env recIds t) with | Strobe.KStar -> () | k -> kind_mismatch t (embed_k k) (embed_k Strobe.KStar) in List.iter assert_kind (ret :: args); (match varargs with None -> () | Some v -> assert_kind v); embed_k Strobe.KStar let kind_check = kind_check_typ end
b53837ad71810f3544a0f9c65ef370fced7222b1ffa9fd676728519828bc8c7d
ChrisPenner/rasa
Base.hs
# LANGUAGE TemplateHaskell , OverloadedStrings , Rank2Types # module Rasa.Ext.Cursors.Internal.Base ( rangeDo , rangeDo_ , overRanges , getRanges , setRanges , overEachRange , addRange , setStyleProvider ) where import Rasa.Ext import Control.Monad.State import Control.Lens import Data.Typeable import Data.List import Data.Default import qualified Yi.Rope as Y -- | Stores the cursor ranges in each buffer. data Cursors = Cursors [CrdRange] deriving (Typeable, Show) instance Default Cursors where def = Cursors [Range (Coord 0 0) (Coord 0 1)] | Adjusts input ranges to contain at least one character . ensureSize :: CrdRange -> CrdRange ensureSize r@(Range start end) | start == end = if start^.coordCol == 0 then r & rEnd %~ moveCursorByN 1 else r & rStart %~ moveCursorByN (-1) | otherwise = r | Sorts Ranges , removes duplicates , ensures they contain at least one character -- and restricts them to fit within the given text. cleanRanges :: Y.YiString -> [CrdRange] -> [CrdRange] cleanRanges txt = fmap (ensureSize . clampRange txt) . reverse . nub . sort -- | Get the list of ranges getRanges :: BufAction [CrdRange] getRanges = do Cursors ranges <- getBufExt return ranges setRanges :: [CrdRange] -> BufAction () setRanges new = do txt <- getText setBufExt . Cursors $ cleanRanges txt new overRanges :: ([CrdRange] -> [CrdRange]) -> BufAction () overRanges f = getRanges >>= setRanges . f | Sequences actions over each range as a ' BufAction ' rangeDo :: (CrdRange -> BufAction a) -> BufAction [a] rangeDo f = getRanges >>= mapM f -- | 'rangeDo' with void return. rangeDo_ :: (CrdRange -> BufAction a) -> BufAction () rangeDo_ = void . rangeDo -- | Sequences actions over each range and replaces each range with its result. overEachRange :: (CrdRange -> BufAction CrdRange) -> BufAction () overEachRange f = rangeDo f >>= setRanges -- | Adds a new range to the list of ranges. addRange :: CrdRange -> BufAction () addRange r = overRanges (r:) -- | Adds cursor specific styles setStyleProvider :: BufAction () setStyleProvider = void . addStyleProvider $ rangeDo setStyle where setStyle :: CrdRange -> BufAction (Span CrdRange Style) setStyle r = return $ Span r (flair ReverseVideo)
null
https://raw.githubusercontent.com/ChrisPenner/rasa/a2680324849088ee92f063fab091de21c4c2c086/rasa-ext-cursors/src/Rasa/Ext/Cursors/Internal/Base.hs
haskell
| Stores the cursor ranges in each buffer. and restricts them to fit within the given text. | Get the list of ranges | 'rangeDo' with void return. | Sequences actions over each range and replaces each range with its result. | Adds a new range to the list of ranges. | Adds cursor specific styles
# LANGUAGE TemplateHaskell , OverloadedStrings , Rank2Types # module Rasa.Ext.Cursors.Internal.Base ( rangeDo , rangeDo_ , overRanges , getRanges , setRanges , overEachRange , addRange , setStyleProvider ) where import Rasa.Ext import Control.Monad.State import Control.Lens import Data.Typeable import Data.List import Data.Default import qualified Yi.Rope as Y data Cursors = Cursors [CrdRange] deriving (Typeable, Show) instance Default Cursors where def = Cursors [Range (Coord 0 0) (Coord 0 1)] | Adjusts input ranges to contain at least one character . ensureSize :: CrdRange -> CrdRange ensureSize r@(Range start end) | start == end = if start^.coordCol == 0 then r & rEnd %~ moveCursorByN 1 else r & rStart %~ moveCursorByN (-1) | otherwise = r | Sorts Ranges , removes duplicates , ensures they contain at least one character cleanRanges :: Y.YiString -> [CrdRange] -> [CrdRange] cleanRanges txt = fmap (ensureSize . clampRange txt) . reverse . nub . sort getRanges :: BufAction [CrdRange] getRanges = do Cursors ranges <- getBufExt return ranges setRanges :: [CrdRange] -> BufAction () setRanges new = do txt <- getText setBufExt . Cursors $ cleanRanges txt new overRanges :: ([CrdRange] -> [CrdRange]) -> BufAction () overRanges f = getRanges >>= setRanges . f | Sequences actions over each range as a ' BufAction ' rangeDo :: (CrdRange -> BufAction a) -> BufAction [a] rangeDo f = getRanges >>= mapM f rangeDo_ :: (CrdRange -> BufAction a) -> BufAction () rangeDo_ = void . rangeDo overEachRange :: (CrdRange -> BufAction CrdRange) -> BufAction () overEachRange f = rangeDo f >>= setRanges addRange :: CrdRange -> BufAction () addRange r = overRanges (r:) setStyleProvider :: BufAction () setStyleProvider = void . addStyleProvider $ rangeDo setStyle where setStyle :: CrdRange -> BufAction (Span CrdRange Style) setStyle r = return $ Span r (flair ReverseVideo)
d46a7654b1eb418cb9bc054e64d482b5d8264041e561bb8661b742b83847ff5b
ska80/thinlisp
tlt-prim.lisp
(in-package "TLI") ;;;; Module TL-PRIM Copyright ( c ) 1999 - 2001 The ThinLisp Group Copyright ( c ) 1995 Gensym Corporation . ;;; All rights reserved. This file is part of ThinLisp . ThinLisp is open source ; you can redistribute it and/or modify it under the terms of the ThinLisp License as published by the ThinLisp Group ; either version 1 or ( at your option ) any later version . ThinLisp 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. For additional information see < / > Author : Primitive Operations for TL This module implements facilities in TL that have direct translations into C ;;; code or are present at compile time only. ;;;; Arrays (tl:declaim (tl:functional length-trans tl:fill-pointer tl:aref tl:elt tl:svref tl:schar)) (tl:define-compiler-macro tl:length (sequence) `(length-trans ,sequence)) (def-c-translation length-trans (sequence) ((lisp-specs :ftype ((t) fixnum)) `(length ,sequence)) ((trans-specs :lisp-type ((simple-vector) fixnum) :c-type (((pointer sv)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr sequence "length"))) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr sequence "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) sequence) "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) sequence) "fill_length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) sequence) "fill_length"))) ((trans-specs :lisp-type (((array double-float)) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-double) sequence) "length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "length" '(obj)) (make-c-function-call-expr (make-c-name-expr "length") (list sequence)))) (def-tl-macro tl:array-dimension (vector axis) (unless (eql axis 0) (error "Arrays in TL are all vectors, so the axis must be 0.")) `(array-dimension-1 ,vector)) (def-tl-macro tl:array-total-size (vector) `(array-dimension-1 ,vector)) (def-c-translation array-dimension-1 (vector) ((lisp-specs :ftype ((t) fixnum)) `(array-dimension ,vector 0)) ((trans-specs :lisp-type ((simple-vector) fixnum) :c-type (((pointer sv)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "length"))) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "length"))) ((trans-specs :lisp-type (((array double-float)) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-double) vector) "length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_array_dimension" '(obj)) (make-c-function-call-expr (make-c-name-expr "generic_array_dimension") (list vector)))) (def-c-translation tl:fill-pointer (vector) ((lisp-specs :ftype ((array) fixnum)) `(fill-pointer ,vector)) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "fill_length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "fill_length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_fill_pointer" '(obj)) (make-c-function-call-expr (make-c-name-expr "generic_fill_pointer") (list vector)))) (tl:defsetf tl:fill-pointer set-fill-pointer) (def-c-translation set-fill-pointer (vector new-fill-pointer) ((lisp-specs :ftype ((t fixnum) fixnum)) (let ((vector-var (gensym)) (new-fill-pointer-var (gensym))) `(let ((,vector-var ,vector) (,new-fill-pointer-var ,new-fill-pointer)) (when (and (stringp ,vector-var) (< ,new-fill-pointer-var (array-dimension ,vector-var 0))) (setf (char ,vector-var ,new-fill-pointer-var) #\null)) (setf (fill-pointer ,vector-var) ,new-fill-pointer-var)))) ((trans-specs :lisp-type ((simple-vector fixnum) fixnum) :c-type ((obj sint32) sint32)) (translation-error "Cannot set the fill-pointer of a simple-vector, it doesn't have one.")) ((trans-specs :lisp-type ((string fixnum) fixnum) :c-type (((pointer str) sint32) sint32)) (let* ((env (l-expr-env function-call-l-expr)) (string-ref (reusable-c-variable-identifier 'string c-func '(pointer str) env)) (fill-ref? (unless (c-name-expr-p new-fill-pointer) (reusable-c-variable-identifier 'fill c-func 'sint32 env)))) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr string-ref) "=" vector) c-compound-statement) (when fill-ref? (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr fill-ref?) "=" new-fill-pointer) c-compound-statement)) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-subscript-expr (make-c-indirect-selection-expr (make-c-name-expr string-ref) "body") (if fill-ref? (make-c-name-expr fill-ref?) new-fill-pointer)) "=" (make-c-literal-expr (code-char 0))) c-compound-statement) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-name-expr string-ref) "fill_length") "=" (if fill-ref? (make-c-name-expr fill-ref?) new-fill-pointer)))) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array double-float) fixnum) fixnum) :c-type ((obj sint32) sint32)) (translation-error "The type (array double-float) doesn't have a fill-pointer.")) ((trans-specs :lisp-type ((t fixnum) fixnum) :c-type ((obj sint32) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_set_fill_pointer" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_set_fill_pointer") (list vector new-fill-pointer)))) (def-c-translation tl:elt (sequence index) ((lisp-specs :ftype ((sequence fixnum) t)) `(elt ,sequence ,index)) ((trans-specs :lisp-type ((list fixnum) t) :c-type ((obj sint32) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "nth" '(sint32 obj)) (make-c-function-call-expr (make-c-name-expr "nth") (list index sequence))) ((trans-specs :lisp-type ((simple-vector fixnum) t) :c-type (((array obj) sint32) obj)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type ((string fixnum) character) :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type (((array uint8) sint32) uint8)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type (((array sint16) sint32) sint16)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type (((array uint16) sint32) uint16)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array double-float) fixnum) double-float) :c-type (((array double) sint32) double)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type ((sequence fixnum) t) :c-type ((obj sint32) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) 'tl:elt (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_elt" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_elt") (list sequence index)))) (def-c-translation set-elt (sequence index value) ((lisp-specs :ftype ((sequence fixnum t) t)) `(setf (elt ,sequence ,index) ,value)) ((trans-specs :lisp-type ((list fixnum t) t) :c-type ((obj sint32 obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "nthcdr" '(sint32 obj)) (make-c-infix-expr (make-c-indirect-selection-expr (coerce-c-expr-result-to-type (make-c-function-call-expr (make-c-name-expr "nthcdr") (list index sequence)) 'obj '(pointer cons) (l-expr-env function-call-l-expr)) "car") "=" value)) ((trans-specs :lisp-type ((simple-vector fixnum t) t) :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type ((string fixnum character) character) :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum fixnum) fixnum) :c-type (((array uint8) sint32 uint8) uint8)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum fixnum) fixnum) :c-type (((array sint16) sint32 sint16) sint16)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum fixnum) fixnum) :c-type (((array uint16) sint32 uint16) uint16)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array double-float) fixnum double-float) double-float) :c-type (((array double) sint32 double) double)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type ((sequence fixnum t) t) :c-type ((obj sint32 obj) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) "SET-ELT" (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_set_elt" '(obj sint32 obj)) (make-c-function-call-expr (make-c-name-expr "generic_set_elt") (list sequence index value)))) (tl:defsetf tl:elt set-elt) (def-c-translation tl:aref (array index) ((lisp-specs :ftype ((array fixnum) t)) `(aref ,array ,index)) ((trans-specs :lisp-type ((simple-vector fixnum) t) :c-type (((array obj) sint32) obj)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type ((string fixnum) character) :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type (((array uint8) sint32) uint8)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type (((array sint16) sint32) sint16)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type (((array uint16) sint32) uint16)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array double-float) fixnum) double-float) :c-type (((array double) sint32) double)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type ((array fixnum) t) :c-type ((obj sint32) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) 'tl:aref (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_aref" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_aref") (list array index)))) (defparameter primitive-array-types ;; Format is: ( array-type array-element-type type-name ) ;; The type-name is to be used to create type-specific function names. '((simple-vector T simple-vector) (string character string) ((array (unsigned-byte 8)) (unsigned-byte 8) array-unsigned-byte-8) ((array (unsigned-byte 16)) (unsigned-byte 16) array-unsigned-byte-16) ((array (signed-byte 16)) (signed-byte 16) array-signed-byte-16) ((array double-float) double-float array-double-float))) (def-c-translation set-aref (array index value) ((lisp-specs :ftype ((array fixnum t) t)) `(setf (aref ,array ,index) ,value)) ((trans-specs :lisp-type ((simple-vector fixnum t) t) :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type ((string fixnum character) character) :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum fixnum) fixnum) :c-type (((array uint8) sint32 uint8) uint8)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum fixnum) fixnum) :c-type (((array sint16) sint32 sint16) sint16)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum fixnum) fixnum) :c-type (((array uint16) sint32 uint16) uint16)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array double-float) fixnum double-float) double-float) :c-type (((array double) sint32 double) double)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type ((array fixnum t) t) :c-type ((obj sint32 obj) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) "SET-AREF" (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_set_aref" '(obj sint32 obj)) (make-c-function-call-expr (make-c-name-expr "generic_set_aref") (list array index value)))) (tl:defsetf tl:aref set-aref) (def-c-translation tl:svref (simple-vector index) ((lisp-specs :ftype ((simple-vector fixnum) t)) `(svref ,simple-vector ,index)) ((trans-specs :c-type (((array obj) sint32) obj)) (make-c-subscript-expr simple-vector index))) (def-c-translation set-svref (simple-vector index value) ((lisp-specs :ftype ((simple-vector fixnum t) t)) `(setf (svref ,simple-vector ,index) ,value)) ((trans-specs :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr simple-vector index) "=" value))) (tl:defsetf tl:svref set-svref) (def-c-translation tl:schar (string index) Note that within TL , schar can be applied to strings with fill - pointers . ;; This means that in development Lisp images, we must always use char to ;; implement this operation. ((lisp-specs :ftype ((string fixnum) character)) `(char ,string ,index)) ((trans-specs :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr string index))) (def-tl-macro tl:char (string index) `(tl:schar ,string ,index)) (def-c-translation set-schar (string index value) Note that within TL , schar can be applied to strings with fill - pointers . ;; This means that in development Lisp images, we must always use char to ;; implement this operation. ((lisp-specs :ftype ((string fixnum character) character)) `(setf (char ,string ,index) ,value)) ((trans-specs :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr string index) "=" value))) (tl:defsetf tl:schar set-schar) ;;; The following provides direct access to the C strcmp facility, returning the integer values it does . For reference , a negative value means was less than string2 , a zero means they are equal strings , and positive if string1 is greater than string2 . (tl:declaim (tl:functional string-compare)) (def-c-translation string-compare (string1 string2) ((lisp-specs :ftype ((string string) fixnum)) (let ((str1 (gensym)) (str2 (gensym))) `(let ((,str1 ,string1) (,str2 ,string2)) (cond ((string< ,str1 ,str2) -1) ((string= ,str1 ,str2) 0) (t 1))))) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char)) sint32)) (make-c-function-call-expr (make-c-name-expr "strcmp") (list (make-c-cast-expr '(pointer char) string1) (make-c-cast-expr '(pointer char) string2))))) ;;; The macro `tl:replace-strings' is a version of replace optimized for string ;;; copying. Note that there is purposefully no :END1 argument. There must be enough room in the first string to hold the values being copied , or else ;;; this operation will overwrite whatever object arbitrarily follows it in ;;; memory. (def-tl-macro tl:replace-strings (to-string from-string &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let* ((,to ,to-string) (,from ,from-string) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length-trans ,from)))) (tl:declare (string ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-strings-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(tl:- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-strings-1 (to from start1 start2 count) ((lisp-specs :ftype ((string string fixnum fixnum fixnum) string)) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char) sint32 sint32 sint32) (pointer unsigned-char))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) count)))) (def-tl-macro tl:replace-simple-vectors (to-simple-vector from-simple-vector &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let* ((,to ,to-simple-vector) (,from ,from-simple-vector) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length-trans ,from)))) (tl:declare (simple-vector ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-simple-vectors-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-simple-vectors-1 (to from start1 start2 count) ((lisp-specs :ftype ((simple-vector simple-vector fixnum fixnum fixnum) simple-vector)) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer obj) (pointer obj) sint32 sint32 sint32) (pointer obj))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list ;; Let the C compiler multiply the start args by sizeof(Obj) as a ;; side-effect of adding them to the Obj* arrays. (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) (make-c-infix-expr (make-c-sizeof-expr (c-type-string 'obj)) "*" count))))) ;;; The macro `tl:replace-uint16-arrays' is a version of replace optimized for arrays of ( unsigned - byte 16 ) . Note that there is purposefully no : END1 argument . There must be enough room in the first array to hold the values ;;; being copied, or else this operation will overwrite whatever object ;;; arbitrarily follows it in memory. (def-tl-macro tl:replace-uint16-arrays (to-array from-array &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let ((,to ,to-array) (,from ,from-array) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length ,from)))) (tl:declare (type (array (unsigned-byte 16)) ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-uint16-arrays-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(tl:- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-uint16-arrays-1 (to from start1 start2 count) ((lisp-specs :ftype (((array (unsigned-byte 16)) (array (unsigned-byte 16)) fixnum fixnum fixnum) (array (unsigned-byte 16)))) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer uint16) (pointer uint16) sint32 sint32 sint32) (pointer uint16))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) (make-c-infix-expr count "*" 2))))) (def-tl-macro tl:fill-string (string character &key (start nil) (end nil)) (if (and (null start) (null end)) (if (symbolp string) `(tl:progn (fill-string-1 ,string ,character 0 (length-trans (tl:the string ,string))) ,string) (let ((string-var (gensym))) `(tl:let ((,string-var ,string)) (tl:declare (string ,string-var)) (fill-string-1 ,string-var ,character 0 (length-trans ,string-var)) ,string-var))) (let ((string-var (gensym)) (char-var (gensym)) (start-var (gensym)) (end-var (gensym))) `(tl:let* ((,string-var ,string) (,char-var ,character) (,start-var ,(or start 0)) (,end-var ,(or end `(length-trans (tl:the string ,string-var))))) (tl:declare (string ,string-var) (character ,char-var) (fixnum ,start-var ,end-var)) (fill-string-1 ,string-var ,char-var ,start-var (- ,end-var ,start-var)) ,string-var)))) (def-c-translation fill-string-1 (string char start count) ((lisp-specs :ftype ((string character fixnum fixnum) void)) ;; Note that tl:fill-string (the only caller for fill-string-1) guarantees ;; that I can eval the start argument twice. `(fill ,string ,char :start ,start :end (+ ,start ,count))) ((trans-specs :c-type (((pointer unsigned-char) unsigned-char sint32 sint32) void)) (make-c-function-call-expr (make-c-name-expr "memset") (list (make-c-cast-expr '(pointer void) (make-c-infix-expr string "+" start)) char count)))) (tl:declaim (tl:functional search-string-1 position-in-string-1)) (def-c-translation search-string-1 (pattern searched start1 start2) ((lisp-specs :ftype ((string string fixnum fixnum) t)) `(search ,pattern ,searched :start1 ,start1 :start2 ,start2)) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char) sint32 sint32) obj)) (let ((result-var (reusable-c-variable-identifier 'strstr-result c-func '(pointer char) (l-expr-env function-call-l-expr)))) (make-c-conditional-expr (make-c-infix-expr (make-c-infix-expr (make-c-name-expr result-var) "=" (make-c-function-call-expr (make-c-name-expr "strstr") (list (make-c-infix-expr (make-c-cast-expr '(pointer char) searched) "+" start1) (make-c-infix-expr (make-c-cast-expr '(pointer char) pattern) "+" start2)))) "==" "NULL") (make-c-cast-expr 'obj (make-c-name-expr "NULL")) (coerce-c-expr-result-to-type (make-c-infix-expr (make-c-cast-expr 'uint32 (make-c-name-expr result-var)) "-" (make-c-cast-expr 'uint32 searched)) 'uint32 'obj (l-expr-env function-call-l-expr)))))) (def-c-translation position-in-string-1 (target-char searched start) ((lisp-specs :ftype ((character string fixnum) t)) `(position ,target-char ,searched :start ,start)) ((trans-specs :c-type ((unsigned-char (pointer unsigned-char) sint32) obj)) (let ((result-var (reusable-c-variable-identifier 'strchr-result c-func '(pointer char) (l-expr-env function-call-l-expr)))) (make-c-conditional-expr (make-c-infix-expr (make-c-infix-expr (make-c-name-expr result-var) "=" (make-c-function-call-expr (make-c-name-expr "strchr") (list (make-c-cast-expr '(pointer char) (make-c-add-expr searched "+" start)) (make-c-cast-expr 'int target-char)))) "==" "NULL") (make-c-cast-expr 'obj (make-c-name-expr "NULL")) (coerce-c-expr-result-to-type (make-c-infix-expr (make-c-cast-expr 'uint32 (make-c-name-expr result-var)) "-" (make-c-cast-expr 'uint32 searched)) 'uint32 'obj (l-expr-env function-call-l-expr)))))) (defun l-expr-wants-unsigned-char-type-p (l-expr) (and (not (l-expr-constant-p l-expr)) (satisfies-c-required-type-p (uncoerced-l-expr-c-return-type l-expr) 'unsigned-char))) (tl:declaim (tl:functional tl:char-code tl:code-char)) (def-c-translation tl:char-code (char) ((lisp-specs :ftype ((character) fixnum)) `(char-code ,char)) ;; Note that the existing type coercions will do exactly the right thing with ;; this. ((trans-specs :c-type ((unsigned-char) sint32)) (make-c-cast-expr 'sint32 char))) (def-c-translation tl:code-char (integer) ((lisp-specs :ftype ((fixnum) character)) `(code-char ,integer)) ((trans-specs :c-type ((sint32) unsigned-char)) (make-c-cast-expr 'unsigned-char integer))) (defmacro def-char-comparitors (lisp-and-c-op-pairs) (cons 'progn (loop for (lisp-op c-op) in lisp-and-c-op-pairs for lisp-sym = (intern (symbol-name lisp-op) *lisp-package*) for tl-sym = (intern (format nil "TWO-ARG-~a" (symbol-name lisp-sym))) append `((tl:declaim (tl:functional ,tl-sym)) (def-c-translation ,tl-sym (char1 char2) ((lisp-specs :ftype ((character character) t)) `(,',lisp-sym ,char1 ,char2)) ((trans-specs :test (or (l-expr-wants-unsigned-char-type-p char1-l-expr) (l-expr-wants-unsigned-char-type-p char2-l-expr)) :c-type ((unsigned-char unsigned-char) boolean)) (make-c-infix-expr char1 ,c-op char2)) ((trans-specs :c-type ((obj obj) boolean)) (make-c-infix-expr char1 ,c-op char2))))))) (def-char-comparitors ((char= "==") (char/= "!=") (char< "<") (char<= "<=") (char> ">") (char>= ">="))) (def-c-translation make-simple-vector (length) ((lisp-specs :ftype ((fixnum) simple-vector)) `(make-array ,length)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_simple_vector") (list length (make-c-literal-expr (region-number-for-type-and-area 'simple-vector (declared-area-name (l-expr-env function-call-l-expr) 'simple-vector))) (make-c-literal-expr (c-type-tag 'sv)))))) (def-c-translation make-string-1 (length) ((lisp-specs :ftype ((fixnum) string)) `(make-string-array ,length :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_string") (list length (make-c-literal-expr (region-number-for-type-and-area 'string (declared-area-name (l-expr-env function-call-l-expr) 'string))) (make-c-literal-expr (c-type-tag 'str)))))) (def-tl-macro tl:make-string (length &key (initial-element #\null) (dont-initialize nil)) (if dont-initialize `(make-string-1 ,length) (let ((new-string (gensym))) `(tl:let ((,new-string (make-string-1 ,length))) (tl:declare (string ,new-string)) (tl:fill-string ,new-string ,initial-element) ,new-string)))) (def-c-translation make-uint8-array (length) ((lisp-specs :ftype ((fixnum) (array (unsigned-byte 8)))) `(make-array ,length :element-type '(unsigned-byte 8) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_uint8_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (unsigned-byte 8)) (declared-area-name (l-expr-env function-call-l-expr) '(array (unsigned-byte 8))))) (make-c-literal-expr (c-type-tag 'sa-uint8)))))) (def-c-translation make-sint16-array (length) ((lisp-specs :ftype ((fixnum) (array (signed-byte 16)))) `(make-array ,length :element-type '(signed-byte 16) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_sint16_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (signed-byte 16)) (declared-area-name (l-expr-env function-call-l-expr) '(array (signed-byte 16))))) (make-c-literal-expr (c-type-tag 'sa-sint16)))))) (def-c-translation make-uint16-array (length) ((lisp-specs :ftype ((fixnum) (array (unsigned-byte 16)))) `(make-array ,length :element-type '(unsigned-byte 16) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_uint16_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (unsigned-byte 16)) (declared-area-name (l-expr-env function-call-l-expr) '(array (unsigned-byte 16))))) (make-c-literal-expr (c-type-tag 'sa-uint16)))))) (def-c-translation make-double-array (length) ((lisp-specs :ftype ((fixnum) (array double-float))) `(make-array ,length :element-type 'double-float)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_double_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array double-float) (declared-area-name (l-expr-env function-call-l-expr) '(array double-float)))) (make-c-literal-expr (c-type-tag 'sa-double)))))) (def-tl-macro tl:make-array (&environment env dimensions &key (element-type t) (initial-element nil element-supplied?) initial-contents fill-pointer) (let* ((expanded-element-type (tl:macroexpand-all element-type env)) (upgraded-type (if (constantp expanded-element-type) (upgraded-tl-array-element-type (eval expanded-element-type)) (error "TL:make-array :element-type arguments must be constants, was ~s" element-type))) (array-var (gensym)) (index-var (gensym)) (iteration-length-var (gensym)) (initial-var (gensym)) (constant-length? (and (constantp dimensions) (let ((dim (eval dimensions))) (or (and (fixnump dim) dim) (and (consp dim) (null (cdr dim)) (fixnump (car dim)) (car dim)) (error "Bad make-array dimensions: ~s" dimensions))))) (fixnum-dims? (tl-subtypep (expression-result-type dimensions env) 'fixnum))) ;; We have no fast implementation for initial-contents, so we should always ;; complain when it is used, unless the user has already admitted that this ;; is fat-and-slow. (when initial-contents (fat-and-slow-warning env "INITIAL-CONTENTS argument to MAKE-ARRAY" initial-contents)) ;; Some varieties of our arrays have fill-pointers always, and some don't. ;; If they ask for a fill-pointer on an array type that doesn't support it, ;; complain here, else just do the default thing. (when (and (memqp upgraded-type '(t tl:double-float)) fill-pointer) (error "Make-array with upgraded-array-element-type ~S can't have a fill-pointer." upgraded-type)) (multiple-value-bind (maker-function array-type) (array-maker-function-and-type-for-element-type upgraded-type) (let ((length-form (cond (constant-length? constant-length?) (fixnum-dims? dimensions) (t `(tl::check-make-array-dimensions ,dimensions))))) (cond (element-supplied? (if (eq array-type 'tl:string) `(tl:make-string ,length-form :initial-element ,initial-element) `(tl:let* ((,iteration-length-var ,length-form) (,array-var (,maker-function ,iteration-length-var)) (,initial-var ,initial-element)) (tl:declare (tl:fixnum ,iteration-length-var) (tl:type ,array-type ,array-var) (tl:type ,upgraded-type ,initial-var)) (tl:dotimes (,index-var ,iteration-length-var) (tl:declare (tl:fixnum ,index-var)) (tl:setf (tl:aref ,array-var ,index-var) ,initial-var)) ,array-var))) (initial-contents `(tl:let* ((,iteration-length-var ,length-form) (,array-var (,maker-function ,iteration-length-var)) (,initial-var ,initial-contents)) (tl:declare (tl:fixnum ,iteration-length-var) (tl:type ,array-type ,array-var)) (tl:dotimes (,index-var ,iteration-length-var) (tl:declare (tl:fixnum ,index-var)) (tl:setf (tl:aref ,array-var ,index-var) (tl:the ,upgraded-type (tl:car (tl:the tl:cons ,initial-var)))) (tl:setq ,initial-var (tl:cdr (tl:the tl:cons ,initial-var)))) ,array-var)) (t `(,maker-function ,length-form))))))) (defun array-maker-function-and-type-for-element-type (upgraded-type) (cond ((eq upgraded-type 'tl:character) (values 'make-string-1 'tl:string)) ((equal upgraded-type '(tl:unsigned-byte 8)) (values 'make-uint8-array '(tl:array (tl:unsigned-byte 8)))) ((equal upgraded-type '(tl:signed-byte 16)) (values 'make-sint16-array '(tl:array (tl:signed-byte 16)))) ((equal upgraded-type '(tl:unsigned-byte 16)) (values 'make-uint16-array '(tl:array (tl:unsigned-byte 16)))) ((eq upgraded-type 'tl:double-float) (values 'make-double-array '(tl:array tl:double-float))) ((eq upgraded-type t) (values 'make-simple-vector 'tl:simple-vector)) (t (error "Unrecognized upgraded-array-element-type ~s" upgraded-type)))) ;;;; Managed-floats The type ` tl : managed - float ' has been added to TL to provide low level ;;; support for a type that can hold double-floats or a pointer to an object. ;;; The memory for these locations may be allowed to overlap if that aids in ;;; making these objects as small as possible. The goal of this object is to ;;; store a floating point value as efficiently as possible while they are ;;; allocated and to store a pointer to the next managed-float in a resource ;;; pool while they are reclaimed. The operations available on managed floats ;;; are `tl:make-managed-float', `tl:managed-float-value' (which is setfable), ;;; `tl:managed-float-next-object' (which is setfable), and ;;; `tl:managed-float-p'. #+c-managed-floats (def-c-translation tl:make-managed-float (new-value) ((lisp-specs :ftype ((double-float) managed-float)) (let ((new-array (gensym)) (new-obj (gensym))) `(let* ((,new-array (make-array 1 :element-type 'double-float)) (,new-obj (cons ,new-array 'managed-float))) (setf (aref (the (array double-float) ,new-array) 0) ,new-value) ,new-obj))) ((trans-specs :c-type ((double) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_mdouble") (list new-value (make-c-literal-expr (region-number-for-type-and-area 'managed-float (declared-area-name (l-expr-env function-call-l-expr) 'managed-float))) (make-c-literal-expr (c-type-tag 'mdouble)))))) #+c-managed-floats (tl:declaim (tl:side-effect-free tl:managed-float-value)) #+c-managed-floats (def-c-translation tl:managed-float-value (managed-float) ((lisp-specs :ftype ((managed-float) double-float)) `(aref (the (array double-float) (car ,managed-float)) 0)) ((trans-specs :c-type ((obj) double)) (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "value"))) #+c-managed-floats (tl:defsetf tl:managed-float-value set-managed-float-value) #+c-managed-floats (def-c-translation set-managed-float-value (managed-float new-value) ((lisp-specs :ftype ((managed-float double-float) double-float)) (let ((mfloat (gensym))) `(let ((,mfloat ,managed-float)) (setf (cdr ,mfloat) 'managed-float) (setf (aref (the (array double-float) (car ,mfloat)) 0) ,new-value)))) ((trans-specs :c-type ((obj double) double)) (make-c-infix-expr (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "value") "=" new-value))) #-c-managed-floats (def-tl-macro set-managed-float-value (managed-float new-value) `(tl:setf (tl:aref (tl:the (tl:array tl:double-float) (tl:car (tl:the tl:cons ,managed-float))) 0) (tl:the tl:double-float ,new-value))) #+c-managed-floats (tl:declaim (tl:side-effect-free tl:managed-float-next-object)) #+c-managed-floats (def-c-translation tl:managed-float-next-object (managed-float) ((lisp-specs :ftype ((managed-float) t)) `(cdr ,managed-float)) ((trans-specs :c-type ((obj) obj)) (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "next_object"))) #+c-managed-floats (tl:defsetf tl:managed-float-next-object set-managed-float-next-object) #+c-managed-floats (def-c-translation set-managed-float-next-object (managed-float new-value) ((lisp-specs :ftype ((managed-float t) t)) `(setf (cdr ,managed-float) ,new-value)) ((trans-specs :c-type ((obj double) double)) (make-c-infix-expr (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "next_object") "=" new-value))) #+c-managed-floats (tl:declaim (tl:functional tl:managed-float-p)) #+c-managed-floats (def-c-translation tl:managed-float-p (object) ((lisp-specs :ftype ((t) t)) (let ((thing (gensym))) `(let ((,thing ,object)) (and (consp ,thing) (typep (car ,thing) '(array double-float)) (eq (cdr ,thing) 'managed-float))))) ((trans-specs :c-type ((obj) boolean)) (if (c-name-expr-p object) (translate-type-check-predicate object 'managed-float 't) (let ((temp (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr)))) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr temp) "=" object) c-compound-statement) (translate-type-check-predicate (make-c-name-expr temp) 'managed-float t))))) ;;;; Streams Within TL only two kinds of Common Lisp streams are implemented . They are ;;; string-streams and file-streams. File-streams are currently only used to implement the * terminal - io * stream to " stdout " and " stdin " . (def-c-translation tl:make-string-output-stream () ((lisp-specs :ftype (() tl-string-stream)) `(make-tl-string-stream)) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_string_strm") (list (make-c-literal-expr (region-number-for-type-and-area 'tl-string-stream (declared-area-name (l-expr-env function-call-l-expr) 'tl-string-stream))) (make-c-literal-expr (c-type-tag 'string-strm)))))) (def-tl-macro tl:make-string-input-stream (string) `(tl:let ((in-stream (tl:make-string-output-stream)) (in-string ,string)) (tl:setf (string-stream-input-string in-stream) in-string) (tl:setf (string-stream-input-index in-stream) 0) (tl:setf (string-stream-input-index-bounds in-stream) (length-trans in-string)) in-stream)) (tl:declaim (tl:side-effect-free string-stream-strings)) (def-c-translation string-stream-strings (string-stream) ((lisp-trans :ftype ((tl-string-stream) list)) `(tl-string-stream-strings ,string-stream)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "strings"))) (def-c-translation set-string-stream-strings (string-stream list) ((lisp-trans :ftype ((tl-string-stream list) list)) `(setf (tl-string-stream-strings ,string-stream) ,list)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "strings") "=" list))) (tl:defsetf string-stream-strings set-string-stream-strings) (tl:declaim (tl:side-effect-free string-stream-input-string)) (def-c-translation string-stream-input-string (string-stream) ((lisp-trans :ftype ((tl-string-stream) string)) `(tl-string-stream-input-string ,string-stream)) ((trans-specs :c-type ((obj) (array unsigned-char))) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_string"))) (def-c-translation set-string-stream-input-string (string-stream string) ((lisp-trans :ftype ((tl-string-stream string) string)) `(setf (tl-string-stream-input-string ,string-stream) ,string)) ((trans-specs :c-type ((obj (array unsigned-char)) (array unsigned-char))) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_string") "=" string))) (tl:defsetf string-stream-input-string set-string-stream-input-string) (tl:declaim (tl:side-effect-free string-stream-input-index)) (def-c-translation string-stream-input-index (string-stream) ((lisp-trans :ftype ((tl-string-stream) fixnum)) `(tl-string-stream-input-index ,string-stream)) ((trans-specs :c-type ((obj) sint32)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index"))) (def-c-translation set-string-stream-input-index (string-stream fixnum) ((lisp-trans :ftype ((tl-string-stream fixnum) fixnum)) `(setf (tl-string-stream-input-index ,string-stream) ,fixnum)) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index") "=" fixnum))) (tl:defsetf string-stream-input-index set-string-stream-input-index) (tl:declaim (tl:side-effect-free string-stream-input-index-bounds)) (def-c-translation string-stream-input-index-bounds (string-stream) ((lisp-trans :ftype ((tl-string-stream) fixnum)) `(tl-string-stream-input-index-bounds ,string-stream)) ((trans-specs :c-type ((obj) sint32)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index_bounds"))) (def-c-translation set-string-stream-input-index-bounds (string-stream fixnum) ((lisp-trans :ftype ((tl-string-stream fixnum) fixnum)) `(setf (tl-string-stream-input-index-bounds ,string-stream) ,fixnum)) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index_bounds") "=" fixnum))) (tl:defsetf string-stream-input-index-bounds set-string-stream-input-index-bounds) ;;; The following function is used to compute the initial value for ;;; *terminal-io* in tl/lisp/format.lisp. (def-c-translation make-terminal-io-file-stream () ((lisp-specs :ftype (() file-stream)) '*terminal-io*) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_file_strm") (list (make-c-name-expr "stdin") (make-c-name-expr "stdout") (make-c-name-expr "NULL") (make-c-name-expr "NULL") (make-c-literal-expr (region-number-for-type-and-area 'file-stream (declared-area-name (l-expr-env function-call-l-expr) 'file-stream))) (make-c-literal-expr (c-type-tag 'file-strm)))))) (def-c-translation make-error-output-file-stream () ((lisp-specs :ftype (() file-stream)) '*terminal-io*) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_file_strm") (list (make-c-name-expr "NULL") (make-c-name-expr "stderr") (make-c-name-expr "NULL") (make-c-name-expr "NULL") (make-c-literal-expr (region-number-for-type-and-area 'file-stream (declared-area-name (l-expr-env function-call-l-expr) 'file-stream))) (make-c-literal-expr (c-type-tag 'file-strm)))))) Conses Note that TL : CONS is declared side - effect free since allocators modify no ;;; existing structures. This works fine as long as the memory meter functions ;;; (which are rarely called) are not declared side-effect free. (tl:declaim (tl:side-effect-free tl:cons)) (def-c-translation tl:cons (car cdr) ((lisp-specs :ftype ((t t) cons)) `(cons ,car ,cdr)) ((trans-specs :c-type ((obj obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_cons") (list car cdr (make-c-literal-expr (region-number-for-type-and-area 'cons (declared-area-name (l-expr-env function-call-l-expr) 'cons))))))) (tl:declaim (tl:side-effect-free make-list-1)) (def-c-translation make-list-1 (length init-elements-p initial-elt) Note that the result type is T since a zero elt list returns NIL . ((lisp-specs :ftype ((fixnum fixnum t) t)) `(make-list ,length :initial-element (and (not (zerop ,init-elements-p)) ,initial-elt))) ((trans-specs :c-type ((sint32 sint32 obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_list") (list length init-elements-p initial-elt (make-c-literal-expr (region-number-for-type-and-area 'cons (declared-area-name (l-expr-env function-call-l-expr) 'cons))))))) ;;; The macro `set-list-contents' and `set-list-contents*' will modify a list ;;; such that it contains as elements the new contents passed as the rest argument . It is more efficient than calling setf on the first , then second , ;;; etc. in that it will not traverse the conses of a list more than once. It ;;; returns the passed list. This macro is used by the implementations of ;;; TL:LIST and friends in tlt/lisp/tl-types.lisp (def-tl-macro set-list-contents (list &rest new-contents) (cond ((null new-contents) list) ((null (cdr new-contents)) (if (symbolp list) `(tl:progn (tl:setf (tl:car ,list) ,(car new-contents)) ,list) (let ((list-evaled (gensym))) `(tl:let ((,list-evaled ,list)) (tl:setf (tl:car ,list-evaled) ,(car new-contents)) ,list-evaled)))) (t (let* ((eval-needed? (not (symbolp list))) (new-list (if eval-needed? (gensym) list)) (current-cons (gensym))) `(tl:let* (,@(if eval-needed? `((,new-list ,list))) (,current-cons ,new-list)) (tl:setf (tl:car ,current-cons) ,(car new-contents)) ,@(loop with lines = nil for element in (cdr new-contents) do (push `(tl:setq ,current-cons (tl:cdr-of-cons ,current-cons)) lines) (push `(tl:setf (tl:car ,current-cons) ,element) lines) finally (return (nreverse lines))) ,new-list))))) (def-tl-macro set-list-contents* (list &rest new-contents) (cond ((null (cdr new-contents)) (error "SET-LIST-CONTENTS* must be called with at least 2 new-value ~ arguments.")) (t (let* ((eval-needed? (not (symbolp list))) (new-list (if eval-needed? (gensym) list)) (current-cons (gensym))) `(tl:let* (,@(if eval-needed? `((,new-list ,list))) (,current-cons ,new-list)) (tl:setf (tl:car ,current-cons) ,(car new-contents)) ,@(loop with lines = nil for element-cons on (cdr new-contents) for element = (car element-cons) do (cond ((cons-cdr element-cons) (push `(tl:setq ,current-cons (tl:cdr-of-cons ,current-cons)) lines) (push `(tl:setf (tl:car ,current-cons) ,element) lines)) (t (push `(tl:setf (tl:cdr ,current-cons) ,element) lines))) finally (return (nreverse lines))) ,new-list))))) (tl:declaim (tl:functional car-trans cdr-trans)) (def-c-translation car-trans (list) ((lisp-specs :ftype ((list) t)) `(car ,list)) ((trans-specs :lisp-type ((cons) t) :c-type ((obj) obj)) (make-c-function-call-expr (make-c-name-expr "CAR") (list list))) ((trans-specs :lisp-type ((list) t) :c-type ((obj) obj)) (let ((var? nil) (expr list)) (unless (c-name-expr-p expr) (setq var? (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr))) (setq expr (make-c-name-expr var?)) (emit-expr-to-compound-statement (make-c-infix-expr expr "=" list) c-compound-statement)) (make-c-conditional-expr (make-c-infix-expr expr "!=" "NULL") (make-c-function-call-expr (make-c-name-expr "CAR") (list expr)) (make-c-cast-expr 'obj (make-c-name-expr "NULL")))))) (def-c-translation set-car (cons value) ((lisp-specs :ftype ((cons t) t)) `(setf (car ,cons) ,value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-function-call-expr (make-c-name-expr "CAR") (list cons)) "=" value))) (tl:defsetf tl:car set-car) (def-tl-macro tl:rplaca (cons new-car) (if (symbolp cons) `(tl:progn (tl:setf (tl:car ,cons) ,new-car) ,cons) (let ((cons-var (gensym))) `(tl:let ((,cons-var ,cons)) (tl:setf (tl:car ,cons-var) ,new-car) ,cons-var)))) (def-c-translation cdr-trans (list) ((lisp-specs :ftype ((list) t)) `(cdr ,list)) ((trans-specs :lisp-type ((cons) t) :c-type ((obj) obj)) (make-c-function-call-expr (make-c-name-expr "CDR") (list list))) ((trans-specs :lisp-type ((list) t) :c-type ((obj) obj)) (let ((var? nil) (expr list)) (unless (c-name-expr-p expr) (setq var? (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr))) (setq expr (make-c-name-expr var?)) (emit-expr-to-compound-statement (make-c-infix-expr expr "=" list) c-compound-statement)) (make-c-conditional-expr (make-c-infix-expr expr "!=" "NULL") (make-c-function-call-expr (make-c-name-expr "CDR") (list expr)) (make-c-cast-expr 'obj (make-c-name-expr "NULL")))))) (def-c-translation set-cdr (cons value) ((lisp-specs :ftype ((cons t) t)) `(setf (cdr ,cons) ,value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-function-call-expr (make-c-name-expr "CDR") (list cons)) "=" value))) (tl:defsetf tl:cdr set-cdr) (def-tl-macro tl:rplacd (cons new-car) (if (symbolp cons) `(tl:progn (tl:setf (tl:cdr ,cons) ,new-car) ,cons) (let ((cons-var (gensym))) `(tl:let ((,cons-var ,cons)) (tl:setf (tl:cdr ,cons-var) ,new-car) ,cons-var)))) (def-tl-macro tl:car-of-cons (tl:cons) `(tl:car (tl:the tl:cons ,tl:cons))) (def-tl-macro tl:cdr-of-cons (tl:cons) `(tl:cdr (tl:the tl:cons ,tl:cons))) The macro ` def - car - cdr - suite ' will be called from within TL , where the ;;; functions being defined here can be translated. This macro is defined here so that we can use Lisp , since the CxR suite must be defined before tl : loop . (defmacro def-car-cdr-suite (from-level to-level) (cons 'tl:progn (loop for levels from from-level to to-level append (loop for op-index from 0 below (expt 2 levels) for selector-list = (loop for char-index from 0 below levels collect (if (logbitp char-index op-index) #\D #\A)) for car-cdr-list = (loop for char-index from 0 below levels collect (if (logbitp char-index op-index) 'tl:cdr 'tl:car)) for op-name = (intern (concatenate 'string '(#\C) selector-list '(#\R)) *tl-package*) for op-of-conses = (intern (format nil "~a-OF-CONSES" op-name) *tl-package*) for setter-name = (intern (format nil "SET-~a" op-name) *tli-package*) for outer-op = (intern (format nil "C~aR" (car selector-list)) *tl-package*) for inner-op = (intern (concatenate 'string '(#\C) (cdr selector-list) '(#\R)) *tl-package*) for inner-op-of-conses = (intern (format nil "~a-OF-CONS~a" inner-op (if (cddr selector-list) "ES" "")) *tl-package*) append `((tl:declaim (tl:functional ,op-name) ,@(if (<= levels 3) `((tl:inline ,op-name)) nil)) (tl:defun ,op-name (tl:list) (tl:declare (tl:type tl:list tl:list) (tl:return-type t)) ,@(loop for op-cons on (reverse car-cdr-list) for op = (car op-cons) collect (if (null (cons-cdr op-cons)) `(tl:if tl:list (,op (tl:the tl:cons tl:list)) nil) `(tl:if tl:list (tl:setq tl:list (,op (tl:the tl:cons tl:list))) (tl:return-from ,op-name nil))))) (tl:defmacro ,op-of-conses (tl:list) `(,',outer-op (tl:the tl:cons (,',inner-op-of-conses ,tl:list)))) (tl:defsetf ,op-name ,setter-name) (tl:defmacro ,setter-name (list value) `(tl:setf (,',outer-op (,',inner-op-of-conses ,list)) ,value))))))) (def-tl-macro tl:push (&environment env item list-place) (if (and (symbolp list-place) (not (eq (tl:variable-information list-place env) :symbol-macro))) `(tl:setf ,list-place (tl:cons ,item ,list-place)) (multiple-value-bind (temps vals stores store-form access-form) (tl:get-setf-expansion list-place env) (let ((item-var (gensym))) `(tl:let* ,(cons (list item-var item) (loop for var in (append temps stores) for val in (append vals `((tl:cons ,item-var ,access-form))) collect (list var val))) ,store-form))))) (def-tl-macro tl:pop (&environment env list-place) (if (and (symbolp list-place) (not (eq (tl:variable-information list-place env) :symbol-macro))) `(tl:prog1 (tl:car ,list-place) (tl:setq ,list-place (tl:cdr ,list-place))) (multiple-value-bind (temps vals stores store-form access-form) (tl:get-setf-expansion list-place env) `(tl:let* ,(loop for var in (append temps stores) for val in (append vals `((tl:cdr ,access-form))) collect (list var val)) (tl:prog1 (tl:car ,access-form) ,store-form))))) ;;;; Symbols ;;; This section implements the lowest level primitives for symbols. Many other ;;; features, such as interning and gensyming, are implemented in ;;; tl/lisp/packages.lisp. ;;; The `make-empty-symbol' mallocs and type tags the memory for a symbol, but ;;; does not yet install a print-name or any other characteristics. They all happen in the TL libraries for packages . (def-c-translation make-empty-symbol () ((lisp-specs :ftype (() symbol)) `(derror "There is no development time expansion for make-empty-symbol.")) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_symbol") (list (make-c-literal-expr (region-number-for-type-and-area 'symbol (declared-area-name (l-expr-env function-call-l-expr) 'symbol))) (make-c-literal-expr (c-type-tag 'sym)))))) ;;; The translated form `set-symbol-type-tag' takes a symbol and installs the ;;; appropriate type tag onto it. This is needed to initialize C symbol ;;; structures that were allocated in arrays, i.e. the constant symbols of a ;;; translated file. (def-c-translation set-symbol-type-tag (symbol) ((lisp-specs :ftype ((symbol) fixnum)) `(derror "No development translation for set-symbol-type-tag of ~s." ,symbol)) ((trans-specs :c-type ((obj) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "type") "=" (make-c-literal-expr (c-type-tag 'sym))))) (tl:declaim (tl:side-effect-free symbol-local-value)) (def-c-translation symbol-local-value (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "local_value"))) (tl:defsetf symbol-local-value set-symbol-local-value) (def-c-translation set-symbol-local-value (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Cant set-symbol-local-value of ~s to ~s in development." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "local_value") "=" flag))) (tl:declaim (tl:side-effect-free symbol-external)) (def-c-translation symbol-external (symbol) ((lisp-specs :ftype ((symbol) t)) (let ((sym (gensym))) `(let ((,sym ,symbol)) (multiple-value-bind (new-sym internal) (find-symbol (symbol-name ,sym) (symbol-package ,sym)) (declare (ignore new-sym)) (eq internal :external))))) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "external"))) (tl:defsetf symbol-external set-symbol-external) (def-c-translation set-symbol-external (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-external of ~s to ~s in development." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "external") "=" flag))) (tl:declaim (tl:side-effect-free symbol-balance)) (def-c-translation symbol-balance (symbol) ((lisp-specs :ftype ((symbol) fixnum)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "balance")))) (tl:defsetf symbol-balance set-symbol-balance) (def-c-translation set-symbol-balance (symbol fixnum) ((lisp-specs :ftype ((symbol fixnum) fixnum)) (declare (ignore symbol)) fixnum) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "balance") "=" fixnum))) (tl:declaim (tl:side-effect-free symbol-imported)) (def-c-translation symbol-imported (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "imported"))) (tl:defsetf symbol-imported set-symbol-imported) (def-c-translation set-symbol-imported (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-imported of ~s to ~s." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "imported") "=" flag))) (tl:declaim (tl:side-effect-free symbol-name-hash)) (def-c-translation symbol-name-hash (symbol) ((lisp-specs :ftype ((symbol) fixnum)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "name_hash")))) (tl:defsetf symbol-name-hash set-symbol-name-hash) (def-c-translation set-symbol-name-hash (symbol fixnum) ((lisp-specs :ftype ((symbol fixnum) fixnum)) (declare (ignore symbol)) fixnum) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "name_hash") "=" fixnum))) (def-tl-macro tl:symbol-name (symbol) `(tl:the tl:string ,(if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (non-null-symbol-name ,symbol) "NIL") (let ((sym (gensym))) `(tl:let ((,sym ,symbol)) (tl:symbol-name ,sym)))))) (tl:declaim (tl:functional non-null-symbol-name)) (def-c-translation non-null-symbol-name (symbol) ((lisp-specs :ftype ((symbol) string)) `(symbol-name ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_name"))) (def-c-translation set-symbol-name (symbol string) ((lisp-specs :ftype ((t t) t)) `(derror "Can't actually set the symbol name in development: ~s ~s" ,symbol ,string)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_name") "=" string))) (def-tl-macro tl:symbol-value (symbol) (if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (tl:if (symbol-local-value ,symbol) (symbol-value-pointer ,symbol) (symbol-non-local-value ,symbol)) nil) (let ((var (gensym))) `(tl:let ((,var ,symbol)) (tl:symbol-value ,var))))) (tl:defsetf tl:symbol-value tl:set) (def-tl-macro tl:set (symbol new-value) (let ((sym (gensym)) (val (gensym))) `(tl:let ((,sym ,symbol) (,val ,new-value)) (tl:if ,sym (tl:if (symbol-local-value ,sym) (set-symbol-value-pointer ,sym ,val) (set-symbol-non-local-value ,sym ,val)) (tl:error "Can't set the symbol-value of NIL.")) ,val))) (tl:declaim (tl:side-effect-free symbol-value-pointer)) (def-c-translation symbol-value-pointer (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-value ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))) (tl:defsetf symbol-value-pointer set-symbol-value-pointer) (def-c-translation set-symbol-value-pointer (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-value ,symbol) ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value") "=" new-value))) (tl:declaim (tl:side-effect-free symbol-non-local-value)) (def-c-translation symbol-non-local-value (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-value ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-unary-expr #\* (make-c-cast-expr '(pointer obj) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))))) (def-c-translation set-symbol-non-local-value (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-value ,symbol) ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-unary-expr #\* (make-c-cast-expr '(pointer obj) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))) "=" new-value))) (def-tl-macro tl:symbol-plist (symbol) (if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (non-null-symbol-plist ,symbol) symbol-plist-of-nil) (let ((var (gensym))) `(tl:let ((,var ,symbol)) (tl:symbol-plist ,var))))) (tl:declaim (tl:side-effect-free non-null-symbol-plist)) (def-c-translation non-null-symbol-plist (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-plist ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_plist"))) (tl:defsetf tl:symbol-plist set-symbol-plist) (def-tl-macro set-symbol-plist (symbol new-plist) (let ((sym (gensym)) (new (gensym))) `(tl:let ((,sym ,symbol) (,new ,new-plist)) (tl:if ,sym (set-non-null-symbol-plist ,sym ,new) (tl:setq symbol-plist-of-nil ,new))))) (def-c-translation set-non-null-symbol-plist (symbol new-plist) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-plist ,symbol) ,new-plist)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_plist") "=" new-plist))) (tl:declaim (tl:side-effect-free tl:symbol-package)) (def-c-translation tl:symbol-package (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-package ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_package"))) (def-c-translation set-symbol-package (symbol package-or-nil) ((lisp-specs :ftype ((symbol t) t)) `(derror "There is no development implementation of set-symbol-package: ~ args = ~s, ~s" ,symbol ,package-or-nil)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_package") "=" package-or-nil))) (tl:declaim (tl:side-effect-free tl:symbol-function)) (def-c-translation tl:symbol-function (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-function ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_function"))) (def-c-translation set-symbol-function (symbol function) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-function ,symbol) ,function)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_function") "=" function))) (tl:defsetf tl:symbol-function set-symbol-function) (tl:declaim (tl:side-effect-free symbol-left-branch)) ;;; The macro `fboundp' takes a symbol and returns whether or not the symbol - function cell of the symbol is to a compiled - function . Note that TL does not allow function names of the ( setf < symbol > ) style , and so this ;;; function takes only symbols and not generalized function names. (def-tl-macro tl:fboundp (symbol) (if (eval-feature :translator) `(tl:not (tl:eq (tl:symbol-function ,symbol) (the-unbound-value))) `(ab-lisp::fboundp ,symbol))) (def-c-translation symbol-left-branch (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "left_branch"))) (tl:defsetf symbol-left-branch set-symbol-left-branch) (def-c-translation set-symbol-left-branch (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-left-branch of ~s to ~s in development." ,symbol ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "left_branch") "=" new-value))) (tl:declaim (tl:side-effect-free symbol-right-branch)) (def-c-translation symbol-right-branch (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "right_branch"))) (tl:defsetf symbol-right-branch set-symbol-right-branch) (def-c-translation set-symbol-right-branch (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-right-branch of ~s to ~s in development." ,symbol ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "right_branch") "=" new-value))) (tl:declaim (tl:side-effect-free not-unbound-value-p)) (def-c-translation not-unbound-value-p (value) ((lisp-specs :ftype ((t) t)) `(derror "Not-unbound-value-p has no development implementation: ~s" ,value)) ((trans-specs :c-type ((obj) boolean)) (make-c-infix-expr value "!=" (make-c-cast-expr 'obj (make-c-unary-expr #\& (make-c-name-expr "Unbound")))))) (tl:declaim (tl:side-effect-free the-unbound-value)) (def-c-translation the-unbound-value () ((lisp-specs :ftype (() t)) `(derror "The-unbound-value cannot be returned in development Lisp.")) ((trans-specs :c-type (() obj)) (c-unbound-value-expr))) In CMU Lisp , if you give a fill - pointered string to make - symbol , the compiler can croak on that later on . Since TL always allocates ;;; fill-pointered strings, this is especially a problem. So, within the base ;;; Lisp environment, make sure that all strings given to make-symbol are in ;;; fact simple-strings. (defun make-symbol-safely (string) (when (not (simple-string-p string)) (let ((new-string (make-string (length string)))) (replace new-string string) (setq string new-string))) (make-symbol string)) ;;;; Compiled Functions (tl:declaim (tl:side-effect-free compiled-function-arg-count compiled-function-optional-arguments compiled-function-default-arguments compiled-function-closure-environment compiled-function-name)) (def-c-translation compiled-function-arg-count (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-arg-count ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "arg_count")))) (def-c-translation compiled-function-optional-arguments (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-optional-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "optional_arguments")))) (def-c-translation compiled-function-sets-values-count (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-optional-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "sets_values_count")))) (defvar variable-of-unknown-value nil) (def-c-translation compiled-function-default-arguments (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) `(derror "No Lisp env implementation of (compiled-function-default-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "default_arguments"))) (def-c-translation compiled-function-closure-environment (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) `(derror "No Lisp env implementation of (compiled-function-closure-environment ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "closure_environment"))) (def-c-translation set-compiled-function-closure-environment (compiled-function closure-env) ((lisp-specs :ftype ((compiled-function t) t)) `(derror "No Lisp env implementation of (set-compiled-function-closure-environment ~s ~s)" ,compiled-function ,closure-env)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "closure_environment") "=" closure-env))) (tl:defsetf compiled-function-closure-environment set-compiled-function-closure-environment) (def-c-translation set-thread-closure-env (new-closure-env) ((lisp-specs :ftype ((t) t)) new-closure-env) ((trans-specs :c-type ((obj) obj)) (make-c-infix-expr (make-c-name-expr "Closure_env") "=" new-closure-env))) (def-c-translation compiled-function-name (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) #+lucid `(lucid::function-name ,compiled-function) #+cmu `(kernel:%function-name ,compiled-function) #-(or lucid cmu) `(derror "No Lisp env implementation of (compiled-function-name ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "name"))) ;;;; Packages ;;; The macro `tl:make-package' takes a name and a :use keyword argument, and ;;; returns a new package with that name. If a package with that name already ;;; exists, this function signals an error. (def-tl-macro tl:make-package (name &key (use ''("TL"))) (if (eval-feature :translator) `(tl::make-package-1 ,name ,use) `(lisp:make-package ,name :use ,use))) (def-tl-macro tl:find-package (string-or-symbol-or-package) (if (eval-feature :translator) `(tl::find-package-1 ,string-or-symbol-or-package) Note that the Lucid implementation of find - package has an error , in ;; that it signals an error when given a package object instead of just ;; returning it. This macroexpansion will work around that bug. -jallard , 5/1/97 `(find-package-safely ,string-or-symbol-or-package))) (defun find-package-safely (arg) (if (typep arg 'package) arg (lisp:find-package arg))) (def-c-translation make-new-package (name use-list) ((lisp-specs :ftype ((string t) package)) `(make-package ,name :use ,use-list)) ((trans-specs :c-type ((obj obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_package") (list name use-list (make-c-literal-expr (region-number-for-type-and-area 'package (declared-area-name (l-expr-env function-call-l-expr) 'package))) (make-c-literal-expr (c-type-tag 'pkg)))))) (tl:declaim (tl:functional tl:package-name)) (def-c-translation tl:package-name (package) ((lisp-specs :ftype ((package) string)) `(package-name ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "name"))) (tl:declaim (tl:side-effect-free package-use-list-internal)) (def-c-translation package-use-list-internal (package) ((lisp-specs :ftype ((package) t)) `(package-use-list ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "used_packages"))) (tl:declaim (tl:side-effect-free package-root-symbol)) (def-c-translation package-root-symbol (package) ((lisp-specs :ftype ((package) t)) `(derror "Package-root-symbol has no development implementation: ~s" ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "root_symbol"))) (tl:defsetf package-root-symbol set-package-root-symbol) (def-c-translation set-package-root-symbol (package symbol) ((lisp-specs :ftype ((package t) t)) `(derror "Set-package-root-symbol has no development implementation: ~s to ~s" ,package ,symbol)) ((c-type :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "root_symbol") "=" symbol))) Typep ;;; The macro `typep' implements runtime type checking for Lisp objects but has ;;; the restriction that the type argument must be a constant. (def-tl-macro tl:typep (&environment env object type) (let ((expanded-type (tl:macroexpand type env))) (unless (tl:constantp expanded-type) (error "TL:typep can only handle constant types, not ~s" expanded-type)) (setq type (expand-type (eval expanded-type))) (if (and (symbolp object) (not (eq (tl:variable-information object env) :symbol-macro))) (cond ((consp type) (let ((first (cons-car type))) (case first ((and or not) `(,(cdr (assq first '((and . tl:and) (or . tl:or) (not . tl:not)))) ,@(loop for subtype in (cons-cdr type) collect `(tl:typep ,object (tl:quote ,subtype))))) ((satisfies tl:satisfies) `(,(cons-second type) ,object)) ((integer) `(tl:and (inlined-typep ,object 'tl:fixnum) ,@(cond ((eq (cons-second type) '*) nil) ((atom (cons-second type)) `((tl:>= (tl:the tl:fixnum ,object) ,(cons-second type)))) (t `((tl:> (tl:the tl:fixnum ,object) ,(car (cons-second type)))))) ,@(cond ((eq (cons-third type) '*) nil) ((atom (cons-third type)) `((tl:<= (tl:the tl:fixnum ,object) ,(cons-third type)))) (t `((tl:< (tl:the tl:fixnum ,object) ,(car (cons-third type)))))))) (t `(inlined-typep ,object (tl:quote ,type)))))) ((and (class-type-p type) structure-type-tags-assigned) (let* ((tag-var (gensym)) (info (structure-info type)) (min-type-tag (struct-type-tag info)) (max-type-tag (struct-maximum-subtype-tag info))) (declare (fixnum min-type-tag max-type-tag)) (if (= min-type-tag max-type-tag) `(tl:= (type-tag ,object) ,min-type-tag) `(tl:let ((,tag-var (type-tag ,object))) (tl:declare (tl:fixnum ,tag-var)) (tl:and (tl:<= ,min-type-tag ,tag-var) (tl:<= ,tag-var ,max-type-tag)))))) (t `(inlined-typep ,object (tl:quote ,type)))) (let ((object-var (gensym))) `(tl:let ((,object-var ,object)) (tl:typep ,object-var (tl:quote ,type))))))) (def-c-translation type-tag (object) ((lisp-specs :ftype ((t) fixnum)) `(car (type-tags-for-lisp-type (type-of ,object)))) ((trans-specs :c-type ((obj) sint32)) (let ((tag-var (reusable-c-variable-identifier 'temp c-func 'sint32 (l-expr-env function-call-l-expr)))) (make-c-function-call-expr (make-c-name-expr "TYPE_TAG") (list object (make-c-name-expr tag-var)))))) (def-tl-macro tl:typecase (keyform &rest clauses) ;; Note that tli::type-tag is not a proper macro, and can evaluate its ;; argument multiple times. (if (eval-feature :translator) (if (symbolp keyform) `(fixnum-case (type-tag ,keyform) ,@(loop with tags-so-far = nil for (type . forms) in clauses for type-tags? = (unless (eq type t) (type-tags-for-lisp-type type)) for unused-tags = (loop for tag in type-tags? unless (member tag tags-so-far) collect (progn (push tag tags-so-far) tag)) when (eq type t) collect `(t ,@forms) when (and (not (eq type t)) unused-tags) collect `(,unused-tags ,@forms))) (let ((key-var (gensym))) `(tl:let ((,key-var ,keyform)) (tl:typecase ,key-var ,@clauses)))) (let ((key-var (gensym))) `(tl:let ((,key-var ,keyform)) (tl:cond ,@(loop for (type . forms) in clauses collect (if (memqp type '(tl:t tl:otherwise)) `(t ,@forms) `((tl:typep ,key-var ',type) ,@forms)))))))) (tl:declaim (tl:functional tl:not)) (def-c-translation tl:not (object) ((lisp-specs :ftype ((t) t)) `(not ,object)) ((trans-specs :c-type ((boolean) boolean)) ;; Perform some optimizations when negating an argument. If this is a not of ;; a not, just return the argument to the inner not. If this is a not of a ;; c-equality-expr, replace the argument with a new c-equality-expr using the ;; opposite equality string. Otherwise, just negate the argument. (cond ((and (c-unary-expr-p object) (char= (c-unary-expr-op-char object) #\!)) (c-unary-expr-arg-expr object)) ((c-equality-expr-p object) (let ((op-string (c-equality-expr-op-string object))) (make-c-equality-expr (c-equality-expr-left-arg object) (cond ((string= op-string "==") "!=") ((string= op-string "!=") "==") (t (translation-error "Can't translate NOT of ~s, bad string ~s" object op-string))) (c-equality-expr-right-arg object)))) (t (make-c-unary-expr #\! object))))) (def-c-translation eq-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(eq ,object1 ,object2)) ((trans-specs :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2))) (tl:define-compiler-macro tl:eql (object1 object2) `(eql-trans ,object1 ,object2)) (tl:declaim (tl:functional eql-trans)) (def-c-translation eql-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(eql ,object1 ,object2)) ((trans-specs :lisp-type (((or symbol fixnum character) t) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t (or symbol fixnum character)) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t t) t) :c-type ((obj obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "eql" '(obj obj)) (make-c-function-call-expr (make-c-name-expr "eql") (list object1 object2)))) (tl:define-compiler-macro tl:equal (object1 object2) `(equal-trans ,object1 ,object2)) (tl:declaim (tl:functional equal-trans)) (def-c-translation equal-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(equal ,object1 ,object2)) ((trans-specs :lisp-type (((or symbol fixnum character) t) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t (or symbol fixnum character)) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t t) t) :c-type ((obj obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "equal" '(obj obj)) (make-c-function-call-expr (make-c-name-expr "equal") (list object1 object2)))) (defun process-cond-clauses (clauses) (let ((clause (cons-car clauses)) (rest-clauses (cons-cdr clauses))) (unless (consp clause) (error "Malformed cond clause ~s" clause)) (let ((test (cons-car clause)) (forms (cons-cdr clause))) (cond ((eq test t) (if forms `(tl:progn ,@forms) t)) (forms `(tl:if ,test (tl:progn ,@forms) ,(when rest-clauses (process-cond-clauses rest-clauses)))) (t (let ((test-value (gensym))) `(tl:let ((,test-value ,test)) (tl:if ,test-value ,test-value ,(when rest-clauses (process-cond-clauses rest-clauses)))))))))) (def-tl-macro tl:cond (&rest clauses) (if clauses (process-cond-clauses clauses) nil)) (def-tl-macro tl:when (test &body body) `(tl:if ,test (tl:progn ,@body))) (def-tl-macro tl:unless (test &body body) `(tl:if (tl:not ,test) (tl:progn ,@body))) ;;;; Case (def-tl-macro tl:case (&environment env keyform &rest case-clauses) (cond ((and (tl-subtypep (expression-result-type keyform env) 'fixnum) (loop for (keys) in case-clauses always (or (fixnump keys) (memqp keys '(t tl:otherwise)) (and (consp keys) (loop for key in keys always (fixnump key)))))) `(fixnum-case ,keyform ,@case-clauses)) ((and (tl-subtypep (expression-result-type keyform env) 'character) (loop for (keys) in case-clauses always (or (characterp keys) (memqp keys '(t tl:otherwise)) (and (consp keys) (loop for key in keys always (characterp key)))))) `(fixnum-case (tl:char-code ,keyform) ,@(loop for (keys . forms) in case-clauses collect `(,(cond ((characterp keys) (list (char-code keys))) ((memqp keys '(t tl:otherwise)) keys) (t (loop for key in keys collect (char-code key)))) ,@forms)))) (t (let ((key-val (gensym))) `(tl:let ((,key-val ,keyform)) (tl:cond ,@(loop for (keylist . forms) in case-clauses when keylist collect (cond ((memqp keylist '(tl:t tl:otherwise)) `(tl:t ,@forms)) ((atom keylist) `((tl:eql ,key-val ',keylist) ,@forms)) ((null (cdr keylist)) `((tl:eql ,key-val ',(car keylist)) ,@forms)) (t `((tl:or ,@(loop for key in keylist collect `(tl:eql ,key-val ',key))) ,@forms)))))))))) (def-tl-macro tl:ecase (&rest args) `(tl:case ,@args (t (tl:error "Fell off end of ECASE - no matching clause")))) (def-tl-macro tl:psetq (&rest vars-and-values) (cond ((null vars-and-values) nil) ((null (cons-cddr vars-and-values)) `(tl:progn (tl:setq ,(cons-car vars-and-values) ,(cons-second vars-and-values)) nil)) (t (let ((settings nil)) `(tl:let ,(loop for (var value) on vars-and-values by #'cddr for temp-var = (gensym) collect (list temp-var value) do (push `(tl:setq ,var ,temp-var) settings)) ,@(nreverse settings) nil))))) (def-tl-macro tl:multiple-value-setq (variables form) (let ((bind-vars (loop repeat (length variables) collect (gensym)))) `(tl:multiple-value-bind ,bind-vars ,form ,@(when (memq nil (cdr variables)) `((tl:declare (tl:ignore ,@(loop for first = t then nil for set in variables for bind in bind-vars when (and (null set) (not first)) collect bind))))) ,@(loop for set in variables for bind in bind-vars when set collect `(tl:setq ,set ,bind)) ,(car bind-vars)))) Pointers ;;; The following forms implement operations for fetching the integer values of ;;; object pointers. These are used for printing and for computing hash numbers ;;; of objects. ;;; The translatable form `pointer-as-fixnum' returns the value of the pointer ;;; as a fixnum. Note that if the uppemost bits of this value are on, then the result will be a negative value . Also note that informatoin will be lost of ;;; the result of this form is allowed to be tagged as a Lisp fixnum. If the ;;; value is carefully used, it can be passed through fixnum-declared forms which are implemented as sint32 values , in which case it will retain all its ;;; bits. This is primarily used for the random object Lisp printer forms. (def-c-translation pointer-as-fixnum (object) ((lisp-specs :ftype ((t) fixnum)) #+lucid `(sys:%pointer ,object) #-lucid `(progn ,object -1)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 object))) ;;; The translatable form `pointer-as-positive-fixnum' returns a positive, 29 - bit fixnum that can be used as a good hashing number for Lisp objects . ;;; The returned value is likely to be unique for the given Lisp object. The value is the pointer shifted right by 3 bits . Since we allocate items on 4 byte boundaries , not 8 , this could lead to two objects whose addresses are within 4 bytes of each to return the same value from this operation . However , since all of our Lisp objects are at least 8 bytes wide , I believe ;;; that this cannot happen. In any case, the returned value is more than ;;; adequate as a hashing number for the given Lisp object. If we had a garbage ;;; collector that could relocate items, this could cause problems, but we don't ;;; so it can't. (def-c-translation pointer-as-positive-fixnum (object) ((lisp-specs :ftype ((t) fixnum)) #+lucid `(sys:%pointer ,object) #-lucid `(sxhash ,object)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-infix-expr (make-c-cast-expr 'uint32 object) ">>" (make-c-literal-expr 3))))) ;;;; Machine Type ;;; The function `get-platform-code' returns an integer which identifies the ;;; currently running system. See code in tl/lisp/tl-util.lisp for how to add ;;; further machines to this set. (def-c-translation get-platform-code () ((lisp-specs :ftype (() fixnum)) '(if nonnil-variable-of-unknowable-value-and-type the code for Sun4 nonnil-variable-of-unknowable-value-and-type)) ((trans-specs :c-type (() sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "get_platform_code" nil) (make-c-function-call-expr (make-c-name-expr "get_platform_code") nil))) ;;;; Memory Management ;;; The following functions can allocate more memory into a running TL image and ;;; query about the amount of memory used. (def-c-translation malloc-block-into-region (region-number byte-count silent) ((lisp-specs :ftype ((fixnum fixnum fixnum) void)) `(derror "No Lisp type expansion for (malloc_block_into_region ~a ~a)" ,region-number ,byte-count ,silent)) ((trans-specs :c-type ((sint32 sint32 sint32) void)) (make-c-function-call-expr (make-c-name-expr "malloc_block_into_region") (list region-number byte-count silent)))) (def-c-translation internal-region-bytes-size (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-size ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_size") (list region-number)))) (def-c-translation internal-region-bytes-used (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-used ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_used") (list region-number)))) (def-c-translation internal-region-bytes-available (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-available ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_available") (list region-number))))
null
https://raw.githubusercontent.com/ska80/thinlisp/173573a723256d901887f1cbc26d5403025879ca/tlt/lisp/tlt-prim.lisp
lisp
Module TL-PRIM All rights reserved. you can redistribute it and/or modify it either version 1 or ( at your option ) any later version . WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. code or are present at compile time only. Arrays Format is: ( array-type array-element-type type-name ) The type-name is to be used to create type-specific function names. This means that in development Lisp images, we must always use char to implement this operation. This means that in development Lisp images, we must always use char to implement this operation. The following provides direct access to the C strcmp facility, returning the The macro `tl:replace-strings' is a version of replace optimized for string copying. Note that there is purposefully no :END1 argument. There must be this operation will overwrite whatever object arbitrarily follows it in memory. Let the C compiler multiply the start args by sizeof(Obj) as a side-effect of adding them to the Obj* arrays. The macro `tl:replace-uint16-arrays' is a version of replace optimized for being copied, or else this operation will overwrite whatever object arbitrarily follows it in memory. Note that tl:fill-string (the only caller for fill-string-1) guarantees that I can eval the start argument twice. Note that the existing type coercions will do exactly the right thing with this. We have no fast implementation for initial-contents, so we should always complain when it is used, unless the user has already admitted that this is fat-and-slow. Some varieties of our arrays have fill-pointers always, and some don't. If they ask for a fill-pointer on an array type that doesn't support it, complain here, else just do the default thing. Managed-floats support for a type that can hold double-floats or a pointer to an object. The memory for these locations may be allowed to overlap if that aids in making these objects as small as possible. The goal of this object is to store a floating point value as efficiently as possible while they are allocated and to store a pointer to the next managed-float in a resource pool while they are reclaimed. The operations available on managed floats are `tl:make-managed-float', `tl:managed-float-value' (which is setfable), `tl:managed-float-next-object' (which is setfable), and `tl:managed-float-p'. Streams string-streams and file-streams. File-streams are currently only used to The following function is used to compute the initial value for *terminal-io* in tl/lisp/format.lisp. existing structures. This works fine as long as the memory meter functions (which are rarely called) are not declared side-effect free. The macro `set-list-contents' and `set-list-contents*' will modify a list such that it contains as elements the new contents passed as the rest etc. in that it will not traverse the conses of a list more than once. It returns the passed list. This macro is used by the implementations of TL:LIST and friends in tlt/lisp/tl-types.lisp functions being defined here can be translated. This macro is defined here Symbols This section implements the lowest level primitives for symbols. Many other features, such as interning and gensyming, are implemented in tl/lisp/packages.lisp. The `make-empty-symbol' mallocs and type tags the memory for a symbol, but does not yet install a print-name or any other characteristics. They all The translated form `set-symbol-type-tag' takes a symbol and installs the appropriate type tag onto it. This is needed to initialize C symbol structures that were allocated in arrays, i.e. the constant symbols of a translated file. The macro `fboundp' takes a symbol and returns whether or not the function takes only symbols and not generalized function names. fill-pointered strings, this is especially a problem. So, within the base Lisp environment, make sure that all strings given to make-symbol are in fact simple-strings. Compiled Functions Packages The macro `tl:make-package' takes a name and a :use keyword argument, and returns a new package with that name. If a package with that name already exists, this function signals an error. that it signals an error when given a package object instead of just returning it. This macroexpansion will work around that bug. The macro `typep' implements runtime type checking for Lisp objects but has the restriction that the type argument must be a constant. Note that tli::type-tag is not a proper macro, and can evaluate its argument multiple times. Perform some optimizations when negating an argument. If this is a not of a not, just return the argument to the inner not. If this is a not of a c-equality-expr, replace the argument with a new c-equality-expr using the opposite equality string. Otherwise, just negate the argument. Case The following forms implement operations for fetching the integer values of object pointers. These are used for printing and for computing hash numbers of objects. The translatable form `pointer-as-fixnum' returns the value of the pointer as a fixnum. Note that if the uppemost bits of this value are on, then the the result of this form is allowed to be tagged as a Lisp fixnum. If the value is carefully used, it can be passed through fixnum-declared forms bits. This is primarily used for the random object Lisp printer forms. The translatable form `pointer-as-positive-fixnum' returns a positive, The returned value is likely to be unique for the given Lisp object. The that this cannot happen. In any case, the returned value is more than adequate as a hashing number for the given Lisp object. If we had a garbage collector that could relocate items, this could cause problems, but we don't so it can't. Machine Type The function `get-platform-code' returns an integer which identifies the currently running system. See code in tl/lisp/tl-util.lisp for how to add further machines to this set. Memory Management The following functions can allocate more memory into a running TL image and query about the amount of memory used.
(in-package "TLI") Copyright ( c ) 1999 - 2001 The ThinLisp Group Copyright ( c ) 1995 Gensym Corporation . This file is part of ThinLisp . under the terms of the ThinLisp License as published by the ThinLisp ThinLisp is distributed in the hope that it will be useful , but For additional information see < / > Author : Primitive Operations for TL This module implements facilities in TL that have direct translations into C (tl:declaim (tl:functional length-trans tl:fill-pointer tl:aref tl:elt tl:svref tl:schar)) (tl:define-compiler-macro tl:length (sequence) `(length-trans ,sequence)) (def-c-translation length-trans (sequence) ((lisp-specs :ftype ((t) fixnum)) `(length ,sequence)) ((trans-specs :lisp-type ((simple-vector) fixnum) :c-type (((pointer sv)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr sequence "length"))) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr sequence "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) sequence) "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) sequence) "fill_length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) sequence) "fill_length"))) ((trans-specs :lisp-type (((array double-float)) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-double) sequence) "length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "length" '(obj)) (make-c-function-call-expr (make-c-name-expr "length") (list sequence)))) (def-tl-macro tl:array-dimension (vector axis) (unless (eql axis 0) (error "Arrays in TL are all vectors, so the axis must be 0.")) `(array-dimension-1 ,vector)) (def-tl-macro tl:array-total-size (vector) `(array-dimension-1 ,vector)) (def-c-translation array-dimension-1 (vector) ((lisp-specs :ftype ((t) fixnum)) `(array-dimension ,vector 0)) ((trans-specs :lisp-type ((simple-vector) fixnum) :c-type (((pointer sv)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "length"))) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "length"))) ((trans-specs :lisp-type (((array double-float)) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-double) vector) "length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_array_dimension" '(obj)) (make-c-function-call-expr (make-c-name-expr "generic_array_dimension") (list vector)))) (def-c-translation tl:fill-pointer (vector) ((lisp-specs :ftype ((array) fixnum)) `(fill-pointer ,vector)) ((trans-specs :lisp-type ((string) fixnum) :c-type (((pointer str)) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr vector "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 8))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "fill_length"))) ((trans-specs :lisp-type (((array (signed-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "fill_length"))) ((trans-specs :lisp-type (((array (unsigned-byte 16))) fixnum) :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "fill_length"))) ((trans-specs :lisp-type ((t) fixnum) :c-type ((obj) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_fill_pointer" '(obj)) (make-c-function-call-expr (make-c-name-expr "generic_fill_pointer") (list vector)))) (tl:defsetf tl:fill-pointer set-fill-pointer) (def-c-translation set-fill-pointer (vector new-fill-pointer) ((lisp-specs :ftype ((t fixnum) fixnum)) (let ((vector-var (gensym)) (new-fill-pointer-var (gensym))) `(let ((,vector-var ,vector) (,new-fill-pointer-var ,new-fill-pointer)) (when (and (stringp ,vector-var) (< ,new-fill-pointer-var (array-dimension ,vector-var 0))) (setf (char ,vector-var ,new-fill-pointer-var) #\null)) (setf (fill-pointer ,vector-var) ,new-fill-pointer-var)))) ((trans-specs :lisp-type ((simple-vector fixnum) fixnum) :c-type ((obj sint32) sint32)) (translation-error "Cannot set the fill-pointer of a simple-vector, it doesn't have one.")) ((trans-specs :lisp-type ((string fixnum) fixnum) :c-type (((pointer str) sint32) sint32)) (let* ((env (l-expr-env function-call-l-expr)) (string-ref (reusable-c-variable-identifier 'string c-func '(pointer str) env)) (fill-ref? (unless (c-name-expr-p new-fill-pointer) (reusable-c-variable-identifier 'fill c-func 'sint32 env)))) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr string-ref) "=" vector) c-compound-statement) (when fill-ref? (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr fill-ref?) "=" new-fill-pointer) c-compound-statement)) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-subscript-expr (make-c-indirect-selection-expr (make-c-name-expr string-ref) "body") (if fill-ref? (make-c-name-expr fill-ref?) new-fill-pointer)) "=" (make-c-literal-expr (code-char 0))) c-compound-statement) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-name-expr string-ref) "fill_length") "=" (if fill-ref? (make-c-name-expr fill-ref?) new-fill-pointer)))) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint8) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-sint16) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sa-uint16) vector) "fill_length") "=" new-fill-pointer)) ((trans-specs :lisp-type (((array double-float) fixnum) fixnum) :c-type ((obj sint32) sint32)) (translation-error "The type (array double-float) doesn't have a fill-pointer.")) ((trans-specs :lisp-type ((t fixnum) fixnum) :c-type ((obj sint32) sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "generic_set_fill_pointer" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_set_fill_pointer") (list vector new-fill-pointer)))) (def-c-translation tl:elt (sequence index) ((lisp-specs :ftype ((sequence fixnum) t)) `(elt ,sequence ,index)) ((trans-specs :lisp-type ((list fixnum) t) :c-type ((obj sint32) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "nth" '(sint32 obj)) (make-c-function-call-expr (make-c-name-expr "nth") (list index sequence))) ((trans-specs :lisp-type ((simple-vector fixnum) t) :c-type (((array obj) sint32) obj)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type ((string fixnum) character) :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type (((array uint8) sint32) uint8)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type (((array sint16) sint32) sint16)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type (((array uint16) sint32) uint16)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type (((array double-float) fixnum) double-float) :c-type (((array double) sint32) double)) (make-c-subscript-expr sequence index)) ((trans-specs :lisp-type ((sequence fixnum) t) :c-type ((obj sint32) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) 'tl:elt (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_elt" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_elt") (list sequence index)))) (def-c-translation set-elt (sequence index value) ((lisp-specs :ftype ((sequence fixnum t) t)) `(setf (elt ,sequence ,index) ,value)) ((trans-specs :lisp-type ((list fixnum t) t) :c-type ((obj sint32 obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "nthcdr" '(sint32 obj)) (make-c-infix-expr (make-c-indirect-selection-expr (coerce-c-expr-result-to-type (make-c-function-call-expr (make-c-name-expr "nthcdr") (list index sequence)) 'obj '(pointer cons) (l-expr-env function-call-l-expr)) "car") "=" value)) ((trans-specs :lisp-type ((simple-vector fixnum t) t) :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type ((string fixnum character) character) :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum fixnum) fixnum) :c-type (((array uint8) sint32 uint8) uint8)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum fixnum) fixnum) :c-type (((array sint16) sint32 sint16) sint16)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum fixnum) fixnum) :c-type (((array uint16) sint32 uint16) uint16)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type (((array double-float) fixnum double-float) double-float) :c-type (((array double) sint32 double) double)) (make-c-infix-expr (make-c-subscript-expr sequence index) "=" value)) ((trans-specs :lisp-type ((sequence fixnum t) t) :c-type ((obj sint32 obj) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) "SET-ELT" (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_set_elt" '(obj sint32 obj)) (make-c-function-call-expr (make-c-name-expr "generic_set_elt") (list sequence index value)))) (tl:defsetf tl:elt set-elt) (def-c-translation tl:aref (array index) ((lisp-specs :ftype ((array fixnum) t)) `(aref ,array ,index)) ((trans-specs :lisp-type ((simple-vector fixnum) t) :c-type (((array obj) sint32) obj)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type ((string fixnum) character) :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum) fixnum) :c-type (((array uint8) sint32) uint8)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum) fixnum) :c-type (((array sint16) sint32) sint16)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum) fixnum) :c-type (((array uint16) sint32) uint16)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type (((array double-float) fixnum) double-float) :c-type (((array double) sint32) double)) (make-c-subscript-expr array index)) ((trans-specs :lisp-type ((array fixnum) t) :c-type ((obj sint32) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) 'tl:aref (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_aref" '(obj sint32)) (make-c-function-call-expr (make-c-name-expr "generic_aref") (list array index)))) (defparameter primitive-array-types '((simple-vector T simple-vector) (string character string) ((array (unsigned-byte 8)) (unsigned-byte 8) array-unsigned-byte-8) ((array (unsigned-byte 16)) (unsigned-byte 16) array-unsigned-byte-16) ((array (signed-byte 16)) (signed-byte 16) array-signed-byte-16) ((array double-float) double-float array-double-float))) (def-c-translation set-aref (array index value) ((lisp-specs :ftype ((array fixnum t) t)) `(setf (aref ,array ,index) ,value)) ((trans-specs :lisp-type ((simple-vector fixnum t) t) :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type ((string fixnum character) character) :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 8)) fixnum fixnum) fixnum) :c-type (((array uint8) sint32 uint8) uint8)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (signed-byte 16)) fixnum fixnum) fixnum) :c-type (((array sint16) sint32 sint16) sint16)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array (unsigned-byte 16)) fixnum fixnum) fixnum) :c-type (((array uint16) sint32 uint16) uint16)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type (((array double-float) fixnum double-float) double-float) :c-type (((array double) sint32 double) double)) (make-c-infix-expr (make-c-subscript-expr array index) "=" value)) ((trans-specs :lisp-type ((array fixnum t) t) :c-type ((obj sint32 obj) obj)) (fat-and-slow-warning (l-expr-env function-call-l-expr) "SET-AREF" (l-expr-pretty-form function-call-l-expr)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "generic_set_aref" '(obj sint32 obj)) (make-c-function-call-expr (make-c-name-expr "generic_set_aref") (list array index value)))) (tl:defsetf tl:aref set-aref) (def-c-translation tl:svref (simple-vector index) ((lisp-specs :ftype ((simple-vector fixnum) t)) `(svref ,simple-vector ,index)) ((trans-specs :c-type (((array obj) sint32) obj)) (make-c-subscript-expr simple-vector index))) (def-c-translation set-svref (simple-vector index value) ((lisp-specs :ftype ((simple-vector fixnum t) t)) `(setf (svref ,simple-vector ,index) ,value)) ((trans-specs :c-type (((array obj) sint32 obj) obj)) (make-c-infix-expr (make-c-subscript-expr simple-vector index) "=" value))) (tl:defsetf tl:svref set-svref) (def-c-translation tl:schar (string index) Note that within TL , schar can be applied to strings with fill - pointers . ((lisp-specs :ftype ((string fixnum) character)) `(char ,string ,index)) ((trans-specs :c-type (((array unsigned-char) sint32) unsigned-char)) (make-c-subscript-expr string index))) (def-tl-macro tl:char (string index) `(tl:schar ,string ,index)) (def-c-translation set-schar (string index value) Note that within TL , schar can be applied to strings with fill - pointers . ((lisp-specs :ftype ((string fixnum character) character)) `(setf (char ,string ,index) ,value)) ((trans-specs :c-type (((array unsigned-char) sint32 unsigned-char) unsigned-char)) (make-c-infix-expr (make-c-subscript-expr string index) "=" value))) (tl:defsetf tl:schar set-schar) integer values it does . For reference , a negative value means was less than string2 , a zero means they are equal strings , and positive if string1 is greater than string2 . (tl:declaim (tl:functional string-compare)) (def-c-translation string-compare (string1 string2) ((lisp-specs :ftype ((string string) fixnum)) (let ((str1 (gensym)) (str2 (gensym))) `(let ((,str1 ,string1) (,str2 ,string2)) (cond ((string< ,str1 ,str2) -1) ((string= ,str1 ,str2) 0) (t 1))))) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char)) sint32)) (make-c-function-call-expr (make-c-name-expr "strcmp") (list (make-c-cast-expr '(pointer char) string1) (make-c-cast-expr '(pointer char) string2))))) enough room in the first string to hold the values being copied , or else (def-tl-macro tl:replace-strings (to-string from-string &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let* ((,to ,to-string) (,from ,from-string) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length-trans ,from)))) (tl:declare (string ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-strings-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(tl:- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-strings-1 (to from start1 start2 count) ((lisp-specs :ftype ((string string fixnum fixnum fixnum) string)) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char) sint32 sint32 sint32) (pointer unsigned-char))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) count)))) (def-tl-macro tl:replace-simple-vectors (to-simple-vector from-simple-vector &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let* ((,to ,to-simple-vector) (,from ,from-simple-vector) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length-trans ,from)))) (tl:declare (simple-vector ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-simple-vectors-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-simple-vectors-1 (to from start1 start2 count) ((lisp-specs :ftype ((simple-vector simple-vector fixnum fixnum fixnum) simple-vector)) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer obj) (pointer obj) sint32 sint32 sint32) (pointer obj))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) (make-c-infix-expr (make-c-sizeof-expr (c-type-string 'obj)) "*" count))))) arrays of ( unsigned - byte 16 ) . Note that there is purposefully no : END1 argument . There must be enough room in the first array to hold the values (def-tl-macro tl:replace-uint16-arrays (to-array from-array &key (start1 0) (start2 0) end2) (let ((to (gensym)) (from (gensym)) (s1 (if (constantp start1) start1 (gensym))) (s2 (if (constantp start2) start2 (gensym))) (e2 (gensym))) `(tl:let ((,to ,to-array) (,from ,from-array) ,@(if (symbolp s1) `((,s1 ,start1))) ,@(if (symbolp s2) `((,s2 ,start2))) (,e2 ,(or end2 `(length ,from)))) (tl:declare (type (array (unsigned-byte 16)) ,to ,from) (fixnum ,@(if (symbolp s1) `(,s1)) ,@(if (symbolp s2) `(,s2)) ,e2)) (replace-uint16-arrays-1 ,to ,from ,s1 ,s2 ,(if (eql s2 0) e2 `(tl:- ,e2 ,s2))) ,@(unless (eql s1 0) `(,to))))) (def-c-translation replace-uint16-arrays-1 (to from start1 start2 count) ((lisp-specs :ftype (((array (unsigned-byte 16)) (array (unsigned-byte 16)) fixnum fixnum fixnum) (array (unsigned-byte 16)))) `(replace ,to ,from :start1 ,start1 :start2 ,start2 :end2 (the fixnum (+ ,start2 ,count)))) ((trans-specs :c-type (((pointer uint16) (pointer uint16) sint32 sint32 sint32) (pointer uint16))) (make-c-function-call-expr (make-c-name-expr "memcpy") (list (make-c-cast-expr '(pointer void) (make-c-add-expr to "+" start1)) (make-c-cast-expr '(pointer void) (make-c-add-expr from "+" start2)) (make-c-infix-expr count "*" 2))))) (def-tl-macro tl:fill-string (string character &key (start nil) (end nil)) (if (and (null start) (null end)) (if (symbolp string) `(tl:progn (fill-string-1 ,string ,character 0 (length-trans (tl:the string ,string))) ,string) (let ((string-var (gensym))) `(tl:let ((,string-var ,string)) (tl:declare (string ,string-var)) (fill-string-1 ,string-var ,character 0 (length-trans ,string-var)) ,string-var))) (let ((string-var (gensym)) (char-var (gensym)) (start-var (gensym)) (end-var (gensym))) `(tl:let* ((,string-var ,string) (,char-var ,character) (,start-var ,(or start 0)) (,end-var ,(or end `(length-trans (tl:the string ,string-var))))) (tl:declare (string ,string-var) (character ,char-var) (fixnum ,start-var ,end-var)) (fill-string-1 ,string-var ,char-var ,start-var (- ,end-var ,start-var)) ,string-var)))) (def-c-translation fill-string-1 (string char start count) ((lisp-specs :ftype ((string character fixnum fixnum) void)) `(fill ,string ,char :start ,start :end (+ ,start ,count))) ((trans-specs :c-type (((pointer unsigned-char) unsigned-char sint32 sint32) void)) (make-c-function-call-expr (make-c-name-expr "memset") (list (make-c-cast-expr '(pointer void) (make-c-infix-expr string "+" start)) char count)))) (tl:declaim (tl:functional search-string-1 position-in-string-1)) (def-c-translation search-string-1 (pattern searched start1 start2) ((lisp-specs :ftype ((string string fixnum fixnum) t)) `(search ,pattern ,searched :start1 ,start1 :start2 ,start2)) ((trans-specs :c-type (((pointer unsigned-char) (pointer unsigned-char) sint32 sint32) obj)) (let ((result-var (reusable-c-variable-identifier 'strstr-result c-func '(pointer char) (l-expr-env function-call-l-expr)))) (make-c-conditional-expr (make-c-infix-expr (make-c-infix-expr (make-c-name-expr result-var) "=" (make-c-function-call-expr (make-c-name-expr "strstr") (list (make-c-infix-expr (make-c-cast-expr '(pointer char) searched) "+" start1) (make-c-infix-expr (make-c-cast-expr '(pointer char) pattern) "+" start2)))) "==" "NULL") (make-c-cast-expr 'obj (make-c-name-expr "NULL")) (coerce-c-expr-result-to-type (make-c-infix-expr (make-c-cast-expr 'uint32 (make-c-name-expr result-var)) "-" (make-c-cast-expr 'uint32 searched)) 'uint32 'obj (l-expr-env function-call-l-expr)))))) (def-c-translation position-in-string-1 (target-char searched start) ((lisp-specs :ftype ((character string fixnum) t)) `(position ,target-char ,searched :start ,start)) ((trans-specs :c-type ((unsigned-char (pointer unsigned-char) sint32) obj)) (let ((result-var (reusable-c-variable-identifier 'strchr-result c-func '(pointer char) (l-expr-env function-call-l-expr)))) (make-c-conditional-expr (make-c-infix-expr (make-c-infix-expr (make-c-name-expr result-var) "=" (make-c-function-call-expr (make-c-name-expr "strchr") (list (make-c-cast-expr '(pointer char) (make-c-add-expr searched "+" start)) (make-c-cast-expr 'int target-char)))) "==" "NULL") (make-c-cast-expr 'obj (make-c-name-expr "NULL")) (coerce-c-expr-result-to-type (make-c-infix-expr (make-c-cast-expr 'uint32 (make-c-name-expr result-var)) "-" (make-c-cast-expr 'uint32 searched)) 'uint32 'obj (l-expr-env function-call-l-expr)))))) (defun l-expr-wants-unsigned-char-type-p (l-expr) (and (not (l-expr-constant-p l-expr)) (satisfies-c-required-type-p (uncoerced-l-expr-c-return-type l-expr) 'unsigned-char))) (tl:declaim (tl:functional tl:char-code tl:code-char)) (def-c-translation tl:char-code (char) ((lisp-specs :ftype ((character) fixnum)) `(char-code ,char)) ((trans-specs :c-type ((unsigned-char) sint32)) (make-c-cast-expr 'sint32 char))) (def-c-translation tl:code-char (integer) ((lisp-specs :ftype ((fixnum) character)) `(code-char ,integer)) ((trans-specs :c-type ((sint32) unsigned-char)) (make-c-cast-expr 'unsigned-char integer))) (defmacro def-char-comparitors (lisp-and-c-op-pairs) (cons 'progn (loop for (lisp-op c-op) in lisp-and-c-op-pairs for lisp-sym = (intern (symbol-name lisp-op) *lisp-package*) for tl-sym = (intern (format nil "TWO-ARG-~a" (symbol-name lisp-sym))) append `((tl:declaim (tl:functional ,tl-sym)) (def-c-translation ,tl-sym (char1 char2) ((lisp-specs :ftype ((character character) t)) `(,',lisp-sym ,char1 ,char2)) ((trans-specs :test (or (l-expr-wants-unsigned-char-type-p char1-l-expr) (l-expr-wants-unsigned-char-type-p char2-l-expr)) :c-type ((unsigned-char unsigned-char) boolean)) (make-c-infix-expr char1 ,c-op char2)) ((trans-specs :c-type ((obj obj) boolean)) (make-c-infix-expr char1 ,c-op char2))))))) (def-char-comparitors ((char= "==") (char/= "!=") (char< "<") (char<= "<=") (char> ">") (char>= ">="))) (def-c-translation make-simple-vector (length) ((lisp-specs :ftype ((fixnum) simple-vector)) `(make-array ,length)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_simple_vector") (list length (make-c-literal-expr (region-number-for-type-and-area 'simple-vector (declared-area-name (l-expr-env function-call-l-expr) 'simple-vector))) (make-c-literal-expr (c-type-tag 'sv)))))) (def-c-translation make-string-1 (length) ((lisp-specs :ftype ((fixnum) string)) `(make-string-array ,length :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_string") (list length (make-c-literal-expr (region-number-for-type-and-area 'string (declared-area-name (l-expr-env function-call-l-expr) 'string))) (make-c-literal-expr (c-type-tag 'str)))))) (def-tl-macro tl:make-string (length &key (initial-element #\null) (dont-initialize nil)) (if dont-initialize `(make-string-1 ,length) (let ((new-string (gensym))) `(tl:let ((,new-string (make-string-1 ,length))) (tl:declare (string ,new-string)) (tl:fill-string ,new-string ,initial-element) ,new-string)))) (def-c-translation make-uint8-array (length) ((lisp-specs :ftype ((fixnum) (array (unsigned-byte 8)))) `(make-array ,length :element-type '(unsigned-byte 8) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_uint8_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (unsigned-byte 8)) (declared-area-name (l-expr-env function-call-l-expr) '(array (unsigned-byte 8))))) (make-c-literal-expr (c-type-tag 'sa-uint8)))))) (def-c-translation make-sint16-array (length) ((lisp-specs :ftype ((fixnum) (array (signed-byte 16)))) `(make-array ,length :element-type '(signed-byte 16) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_sint16_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (signed-byte 16)) (declared-area-name (l-expr-env function-call-l-expr) '(array (signed-byte 16))))) (make-c-literal-expr (c-type-tag 'sa-sint16)))))) (def-c-translation make-uint16-array (length) ((lisp-specs :ftype ((fixnum) (array (unsigned-byte 16)))) `(make-array ,length :element-type '(unsigned-byte 16) :fill-pointer t)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_uint16_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array (unsigned-byte 16)) (declared-area-name (l-expr-env function-call-l-expr) '(array (unsigned-byte 16))))) (make-c-literal-expr (c-type-tag 'sa-uint16)))))) (def-c-translation make-double-array (length) ((lisp-specs :ftype ((fixnum) (array double-float))) `(make-array ,length :element-type 'double-float)) ((trans-specs :c-type ((sint32) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_double_array") (list length (make-c-literal-expr (region-number-for-type-and-area '(array double-float) (declared-area-name (l-expr-env function-call-l-expr) '(array double-float)))) (make-c-literal-expr (c-type-tag 'sa-double)))))) (def-tl-macro tl:make-array (&environment env dimensions &key (element-type t) (initial-element nil element-supplied?) initial-contents fill-pointer) (let* ((expanded-element-type (tl:macroexpand-all element-type env)) (upgraded-type (if (constantp expanded-element-type) (upgraded-tl-array-element-type (eval expanded-element-type)) (error "TL:make-array :element-type arguments must be constants, was ~s" element-type))) (array-var (gensym)) (index-var (gensym)) (iteration-length-var (gensym)) (initial-var (gensym)) (constant-length? (and (constantp dimensions) (let ((dim (eval dimensions))) (or (and (fixnump dim) dim) (and (consp dim) (null (cdr dim)) (fixnump (car dim)) (car dim)) (error "Bad make-array dimensions: ~s" dimensions))))) (fixnum-dims? (tl-subtypep (expression-result-type dimensions env) 'fixnum))) (when initial-contents (fat-and-slow-warning env "INITIAL-CONTENTS argument to MAKE-ARRAY" initial-contents)) (when (and (memqp upgraded-type '(t tl:double-float)) fill-pointer) (error "Make-array with upgraded-array-element-type ~S can't have a fill-pointer." upgraded-type)) (multiple-value-bind (maker-function array-type) (array-maker-function-and-type-for-element-type upgraded-type) (let ((length-form (cond (constant-length? constant-length?) (fixnum-dims? dimensions) (t `(tl::check-make-array-dimensions ,dimensions))))) (cond (element-supplied? (if (eq array-type 'tl:string) `(tl:make-string ,length-form :initial-element ,initial-element) `(tl:let* ((,iteration-length-var ,length-form) (,array-var (,maker-function ,iteration-length-var)) (,initial-var ,initial-element)) (tl:declare (tl:fixnum ,iteration-length-var) (tl:type ,array-type ,array-var) (tl:type ,upgraded-type ,initial-var)) (tl:dotimes (,index-var ,iteration-length-var) (tl:declare (tl:fixnum ,index-var)) (tl:setf (tl:aref ,array-var ,index-var) ,initial-var)) ,array-var))) (initial-contents `(tl:let* ((,iteration-length-var ,length-form) (,array-var (,maker-function ,iteration-length-var)) (,initial-var ,initial-contents)) (tl:declare (tl:fixnum ,iteration-length-var) (tl:type ,array-type ,array-var)) (tl:dotimes (,index-var ,iteration-length-var) (tl:declare (tl:fixnum ,index-var)) (tl:setf (tl:aref ,array-var ,index-var) (tl:the ,upgraded-type (tl:car (tl:the tl:cons ,initial-var)))) (tl:setq ,initial-var (tl:cdr (tl:the tl:cons ,initial-var)))) ,array-var)) (t `(,maker-function ,length-form))))))) (defun array-maker-function-and-type-for-element-type (upgraded-type) (cond ((eq upgraded-type 'tl:character) (values 'make-string-1 'tl:string)) ((equal upgraded-type '(tl:unsigned-byte 8)) (values 'make-uint8-array '(tl:array (tl:unsigned-byte 8)))) ((equal upgraded-type '(tl:signed-byte 16)) (values 'make-sint16-array '(tl:array (tl:signed-byte 16)))) ((equal upgraded-type '(tl:unsigned-byte 16)) (values 'make-uint16-array '(tl:array (tl:unsigned-byte 16)))) ((eq upgraded-type 'tl:double-float) (values 'make-double-array '(tl:array tl:double-float))) ((eq upgraded-type t) (values 'make-simple-vector 'tl:simple-vector)) (t (error "Unrecognized upgraded-array-element-type ~s" upgraded-type)))) The type ` tl : managed - float ' has been added to TL to provide low level #+c-managed-floats (def-c-translation tl:make-managed-float (new-value) ((lisp-specs :ftype ((double-float) managed-float)) (let ((new-array (gensym)) (new-obj (gensym))) `(let* ((,new-array (make-array 1 :element-type 'double-float)) (,new-obj (cons ,new-array 'managed-float))) (setf (aref (the (array double-float) ,new-array) 0) ,new-value) ,new-obj))) ((trans-specs :c-type ((double) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_mdouble") (list new-value (make-c-literal-expr (region-number-for-type-and-area 'managed-float (declared-area-name (l-expr-env function-call-l-expr) 'managed-float))) (make-c-literal-expr (c-type-tag 'mdouble)))))) #+c-managed-floats (tl:declaim (tl:side-effect-free tl:managed-float-value)) #+c-managed-floats (def-c-translation tl:managed-float-value (managed-float) ((lisp-specs :ftype ((managed-float) double-float)) `(aref (the (array double-float) (car ,managed-float)) 0)) ((trans-specs :c-type ((obj) double)) (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "value"))) #+c-managed-floats (tl:defsetf tl:managed-float-value set-managed-float-value) #+c-managed-floats (def-c-translation set-managed-float-value (managed-float new-value) ((lisp-specs :ftype ((managed-float double-float) double-float)) (let ((mfloat (gensym))) `(let ((,mfloat ,managed-float)) (setf (cdr ,mfloat) 'managed-float) (setf (aref (the (array double-float) (car ,mfloat)) 0) ,new-value)))) ((trans-specs :c-type ((obj double) double)) (make-c-infix-expr (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "value") "=" new-value))) #-c-managed-floats (def-tl-macro set-managed-float-value (managed-float new-value) `(tl:setf (tl:aref (tl:the (tl:array tl:double-float) (tl:car (tl:the tl:cons ,managed-float))) 0) (tl:the tl:double-float ,new-value))) #+c-managed-floats (tl:declaim (tl:side-effect-free tl:managed-float-next-object)) #+c-managed-floats (def-c-translation tl:managed-float-next-object (managed-float) ((lisp-specs :ftype ((managed-float) t)) `(cdr ,managed-float)) ((trans-specs :c-type ((obj) obj)) (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "next_object"))) #+c-managed-floats (tl:defsetf tl:managed-float-next-object set-managed-float-next-object) #+c-managed-floats (def-c-translation set-managed-float-next-object (managed-float new-value) ((lisp-specs :ftype ((managed-float t) t)) `(setf (cdr ,managed-float) ,new-value)) ((trans-specs :c-type ((obj double) double)) (make-c-infix-expr (make-c-direct-selection-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer mdouble) managed-float) "body") "next_object") "=" new-value))) #+c-managed-floats (tl:declaim (tl:functional tl:managed-float-p)) #+c-managed-floats (def-c-translation tl:managed-float-p (object) ((lisp-specs :ftype ((t) t)) (let ((thing (gensym))) `(let ((,thing ,object)) (and (consp ,thing) (typep (car ,thing) '(array double-float)) (eq (cdr ,thing) 'managed-float))))) ((trans-specs :c-type ((obj) boolean)) (if (c-name-expr-p object) (translate-type-check-predicate object 'managed-float 't) (let ((temp (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr)))) (emit-expr-to-compound-statement (make-c-infix-expr (make-c-name-expr temp) "=" object) c-compound-statement) (translate-type-check-predicate (make-c-name-expr temp) 'managed-float t))))) Within TL only two kinds of Common Lisp streams are implemented . They are implement the * terminal - io * stream to " stdout " and " stdin " . (def-c-translation tl:make-string-output-stream () ((lisp-specs :ftype (() tl-string-stream)) `(make-tl-string-stream)) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_string_strm") (list (make-c-literal-expr (region-number-for-type-and-area 'tl-string-stream (declared-area-name (l-expr-env function-call-l-expr) 'tl-string-stream))) (make-c-literal-expr (c-type-tag 'string-strm)))))) (def-tl-macro tl:make-string-input-stream (string) `(tl:let ((in-stream (tl:make-string-output-stream)) (in-string ,string)) (tl:setf (string-stream-input-string in-stream) in-string) (tl:setf (string-stream-input-index in-stream) 0) (tl:setf (string-stream-input-index-bounds in-stream) (length-trans in-string)) in-stream)) (tl:declaim (tl:side-effect-free string-stream-strings)) (def-c-translation string-stream-strings (string-stream) ((lisp-trans :ftype ((tl-string-stream) list)) `(tl-string-stream-strings ,string-stream)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "strings"))) (def-c-translation set-string-stream-strings (string-stream list) ((lisp-trans :ftype ((tl-string-stream list) list)) `(setf (tl-string-stream-strings ,string-stream) ,list)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "strings") "=" list))) (tl:defsetf string-stream-strings set-string-stream-strings) (tl:declaim (tl:side-effect-free string-stream-input-string)) (def-c-translation string-stream-input-string (string-stream) ((lisp-trans :ftype ((tl-string-stream) string)) `(tl-string-stream-input-string ,string-stream)) ((trans-specs :c-type ((obj) (array unsigned-char))) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_string"))) (def-c-translation set-string-stream-input-string (string-stream string) ((lisp-trans :ftype ((tl-string-stream string) string)) `(setf (tl-string-stream-input-string ,string-stream) ,string)) ((trans-specs :c-type ((obj (array unsigned-char)) (array unsigned-char))) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_string") "=" string))) (tl:defsetf string-stream-input-string set-string-stream-input-string) (tl:declaim (tl:side-effect-free string-stream-input-index)) (def-c-translation string-stream-input-index (string-stream) ((lisp-trans :ftype ((tl-string-stream) fixnum)) `(tl-string-stream-input-index ,string-stream)) ((trans-specs :c-type ((obj) sint32)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index"))) (def-c-translation set-string-stream-input-index (string-stream fixnum) ((lisp-trans :ftype ((tl-string-stream fixnum) fixnum)) `(setf (tl-string-stream-input-index ,string-stream) ,fixnum)) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index") "=" fixnum))) (tl:defsetf string-stream-input-index set-string-stream-input-index) (tl:declaim (tl:side-effect-free string-stream-input-index-bounds)) (def-c-translation string-stream-input-index-bounds (string-stream) ((lisp-trans :ftype ((tl-string-stream) fixnum)) `(tl-string-stream-input-index-bounds ,string-stream)) ((trans-specs :c-type ((obj) sint32)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index_bounds"))) (def-c-translation set-string-stream-input-index-bounds (string-stream fixnum) ((lisp-trans :ftype ((tl-string-stream fixnum) fixnum)) `(setf (tl-string-stream-input-index-bounds ,string-stream) ,fixnum)) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer string-strm) string-stream) "input_index_bounds") "=" fixnum))) (tl:defsetf string-stream-input-index-bounds set-string-stream-input-index-bounds) (def-c-translation make-terminal-io-file-stream () ((lisp-specs :ftype (() file-stream)) '*terminal-io*) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_file_strm") (list (make-c-name-expr "stdin") (make-c-name-expr "stdout") (make-c-name-expr "NULL") (make-c-name-expr "NULL") (make-c-literal-expr (region-number-for-type-and-area 'file-stream (declared-area-name (l-expr-env function-call-l-expr) 'file-stream))) (make-c-literal-expr (c-type-tag 'file-strm)))))) (def-c-translation make-error-output-file-stream () ((lisp-specs :ftype (() file-stream)) '*terminal-io*) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_file_strm") (list (make-c-name-expr "NULL") (make-c-name-expr "stderr") (make-c-name-expr "NULL") (make-c-name-expr "NULL") (make-c-literal-expr (region-number-for-type-and-area 'file-stream (declared-area-name (l-expr-env function-call-l-expr) 'file-stream))) (make-c-literal-expr (c-type-tag 'file-strm)))))) Conses Note that TL : CONS is declared side - effect free since allocators modify no (tl:declaim (tl:side-effect-free tl:cons)) (def-c-translation tl:cons (car cdr) ((lisp-specs :ftype ((t t) cons)) `(cons ,car ,cdr)) ((trans-specs :c-type ((obj obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_cons") (list car cdr (make-c-literal-expr (region-number-for-type-and-area 'cons (declared-area-name (l-expr-env function-call-l-expr) 'cons))))))) (tl:declaim (tl:side-effect-free make-list-1)) (def-c-translation make-list-1 (length init-elements-p initial-elt) Note that the result type is T since a zero elt list returns NIL . ((lisp-specs :ftype ((fixnum fixnum t) t)) `(make-list ,length :initial-element (and (not (zerop ,init-elements-p)) ,initial-elt))) ((trans-specs :c-type ((sint32 sint32 obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_list") (list length init-elements-p initial-elt (make-c-literal-expr (region-number-for-type-and-area 'cons (declared-area-name (l-expr-env function-call-l-expr) 'cons))))))) argument . It is more efficient than calling setf on the first , then second , (def-tl-macro set-list-contents (list &rest new-contents) (cond ((null new-contents) list) ((null (cdr new-contents)) (if (symbolp list) `(tl:progn (tl:setf (tl:car ,list) ,(car new-contents)) ,list) (let ((list-evaled (gensym))) `(tl:let ((,list-evaled ,list)) (tl:setf (tl:car ,list-evaled) ,(car new-contents)) ,list-evaled)))) (t (let* ((eval-needed? (not (symbolp list))) (new-list (if eval-needed? (gensym) list)) (current-cons (gensym))) `(tl:let* (,@(if eval-needed? `((,new-list ,list))) (,current-cons ,new-list)) (tl:setf (tl:car ,current-cons) ,(car new-contents)) ,@(loop with lines = nil for element in (cdr new-contents) do (push `(tl:setq ,current-cons (tl:cdr-of-cons ,current-cons)) lines) (push `(tl:setf (tl:car ,current-cons) ,element) lines) finally (return (nreverse lines))) ,new-list))))) (def-tl-macro set-list-contents* (list &rest new-contents) (cond ((null (cdr new-contents)) (error "SET-LIST-CONTENTS* must be called with at least 2 new-value ~ arguments.")) (t (let* ((eval-needed? (not (symbolp list))) (new-list (if eval-needed? (gensym) list)) (current-cons (gensym))) `(tl:let* (,@(if eval-needed? `((,new-list ,list))) (,current-cons ,new-list)) (tl:setf (tl:car ,current-cons) ,(car new-contents)) ,@(loop with lines = nil for element-cons on (cdr new-contents) for element = (car element-cons) do (cond ((cons-cdr element-cons) (push `(tl:setq ,current-cons (tl:cdr-of-cons ,current-cons)) lines) (push `(tl:setf (tl:car ,current-cons) ,element) lines)) (t (push `(tl:setf (tl:cdr ,current-cons) ,element) lines))) finally (return (nreverse lines))) ,new-list))))) (tl:declaim (tl:functional car-trans cdr-trans)) (def-c-translation car-trans (list) ((lisp-specs :ftype ((list) t)) `(car ,list)) ((trans-specs :lisp-type ((cons) t) :c-type ((obj) obj)) (make-c-function-call-expr (make-c-name-expr "CAR") (list list))) ((trans-specs :lisp-type ((list) t) :c-type ((obj) obj)) (let ((var? nil) (expr list)) (unless (c-name-expr-p expr) (setq var? (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr))) (setq expr (make-c-name-expr var?)) (emit-expr-to-compound-statement (make-c-infix-expr expr "=" list) c-compound-statement)) (make-c-conditional-expr (make-c-infix-expr expr "!=" "NULL") (make-c-function-call-expr (make-c-name-expr "CAR") (list expr)) (make-c-cast-expr 'obj (make-c-name-expr "NULL")))))) (def-c-translation set-car (cons value) ((lisp-specs :ftype ((cons t) t)) `(setf (car ,cons) ,value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-function-call-expr (make-c-name-expr "CAR") (list cons)) "=" value))) (tl:defsetf tl:car set-car) (def-tl-macro tl:rplaca (cons new-car) (if (symbolp cons) `(tl:progn (tl:setf (tl:car ,cons) ,new-car) ,cons) (let ((cons-var (gensym))) `(tl:let ((,cons-var ,cons)) (tl:setf (tl:car ,cons-var) ,new-car) ,cons-var)))) (def-c-translation cdr-trans (list) ((lisp-specs :ftype ((list) t)) `(cdr ,list)) ((trans-specs :lisp-type ((cons) t) :c-type ((obj) obj)) (make-c-function-call-expr (make-c-name-expr "CDR") (list list))) ((trans-specs :lisp-type ((list) t) :c-type ((obj) obj)) (let ((var? nil) (expr list)) (unless (c-name-expr-p expr) (setq var? (reusable-c-variable-identifier 'temp c-func 'obj (l-expr-env function-call-l-expr))) (setq expr (make-c-name-expr var?)) (emit-expr-to-compound-statement (make-c-infix-expr expr "=" list) c-compound-statement)) (make-c-conditional-expr (make-c-infix-expr expr "!=" "NULL") (make-c-function-call-expr (make-c-name-expr "CDR") (list expr)) (make-c-cast-expr 'obj (make-c-name-expr "NULL")))))) (def-c-translation set-cdr (cons value) ((lisp-specs :ftype ((cons t) t)) `(setf (cdr ,cons) ,value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-function-call-expr (make-c-name-expr "CDR") (list cons)) "=" value))) (tl:defsetf tl:cdr set-cdr) (def-tl-macro tl:rplacd (cons new-car) (if (symbolp cons) `(tl:progn (tl:setf (tl:cdr ,cons) ,new-car) ,cons) (let ((cons-var (gensym))) `(tl:let ((,cons-var ,cons)) (tl:setf (tl:cdr ,cons-var) ,new-car) ,cons-var)))) (def-tl-macro tl:car-of-cons (tl:cons) `(tl:car (tl:the tl:cons ,tl:cons))) (def-tl-macro tl:cdr-of-cons (tl:cons) `(tl:cdr (tl:the tl:cons ,tl:cons))) The macro ` def - car - cdr - suite ' will be called from within TL , where the so that we can use Lisp , since the CxR suite must be defined before tl : loop . (defmacro def-car-cdr-suite (from-level to-level) (cons 'tl:progn (loop for levels from from-level to to-level append (loop for op-index from 0 below (expt 2 levels) for selector-list = (loop for char-index from 0 below levels collect (if (logbitp char-index op-index) #\D #\A)) for car-cdr-list = (loop for char-index from 0 below levels collect (if (logbitp char-index op-index) 'tl:cdr 'tl:car)) for op-name = (intern (concatenate 'string '(#\C) selector-list '(#\R)) *tl-package*) for op-of-conses = (intern (format nil "~a-OF-CONSES" op-name) *tl-package*) for setter-name = (intern (format nil "SET-~a" op-name) *tli-package*) for outer-op = (intern (format nil "C~aR" (car selector-list)) *tl-package*) for inner-op = (intern (concatenate 'string '(#\C) (cdr selector-list) '(#\R)) *tl-package*) for inner-op-of-conses = (intern (format nil "~a-OF-CONS~a" inner-op (if (cddr selector-list) "ES" "")) *tl-package*) append `((tl:declaim (tl:functional ,op-name) ,@(if (<= levels 3) `((tl:inline ,op-name)) nil)) (tl:defun ,op-name (tl:list) (tl:declare (tl:type tl:list tl:list) (tl:return-type t)) ,@(loop for op-cons on (reverse car-cdr-list) for op = (car op-cons) collect (if (null (cons-cdr op-cons)) `(tl:if tl:list (,op (tl:the tl:cons tl:list)) nil) `(tl:if tl:list (tl:setq tl:list (,op (tl:the tl:cons tl:list))) (tl:return-from ,op-name nil))))) (tl:defmacro ,op-of-conses (tl:list) `(,',outer-op (tl:the tl:cons (,',inner-op-of-conses ,tl:list)))) (tl:defsetf ,op-name ,setter-name) (tl:defmacro ,setter-name (list value) `(tl:setf (,',outer-op (,',inner-op-of-conses ,list)) ,value))))))) (def-tl-macro tl:push (&environment env item list-place) (if (and (symbolp list-place) (not (eq (tl:variable-information list-place env) :symbol-macro))) `(tl:setf ,list-place (tl:cons ,item ,list-place)) (multiple-value-bind (temps vals stores store-form access-form) (tl:get-setf-expansion list-place env) (let ((item-var (gensym))) `(tl:let* ,(cons (list item-var item) (loop for var in (append temps stores) for val in (append vals `((tl:cons ,item-var ,access-form))) collect (list var val))) ,store-form))))) (def-tl-macro tl:pop (&environment env list-place) (if (and (symbolp list-place) (not (eq (tl:variable-information list-place env) :symbol-macro))) `(tl:prog1 (tl:car ,list-place) (tl:setq ,list-place (tl:cdr ,list-place))) (multiple-value-bind (temps vals stores store-form access-form) (tl:get-setf-expansion list-place env) `(tl:let* ,(loop for var in (append temps stores) for val in (append vals `((tl:cdr ,access-form))) collect (list var val)) (tl:prog1 (tl:car ,access-form) ,store-form))))) happen in the TL libraries for packages . (def-c-translation make-empty-symbol () ((lisp-specs :ftype (() symbol)) `(derror "There is no development time expansion for make-empty-symbol.")) ((trans-specs :c-type (() obj)) (make-c-function-call-expr (make-c-name-expr "alloc_symbol") (list (make-c-literal-expr (region-number-for-type-and-area 'symbol (declared-area-name (l-expr-env function-call-l-expr) 'symbol))) (make-c-literal-expr (c-type-tag 'sym)))))) (def-c-translation set-symbol-type-tag (symbol) ((lisp-specs :ftype ((symbol) fixnum)) `(derror "No development translation for set-symbol-type-tag of ~s." ,symbol)) ((trans-specs :c-type ((obj) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "type") "=" (make-c-literal-expr (c-type-tag 'sym))))) (tl:declaim (tl:side-effect-free symbol-local-value)) (def-c-translation symbol-local-value (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "local_value"))) (tl:defsetf symbol-local-value set-symbol-local-value) (def-c-translation set-symbol-local-value (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Cant set-symbol-local-value of ~s to ~s in development." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "local_value") "=" flag))) (tl:declaim (tl:side-effect-free symbol-external)) (def-c-translation symbol-external (symbol) ((lisp-specs :ftype ((symbol) t)) (let ((sym (gensym))) `(let ((,sym ,symbol)) (multiple-value-bind (new-sym internal) (find-symbol (symbol-name ,sym) (symbol-package ,sym)) (declare (ignore new-sym)) (eq internal :external))))) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "external"))) (tl:defsetf symbol-external set-symbol-external) (def-c-translation set-symbol-external (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-external of ~s to ~s in development." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "external") "=" flag))) (tl:declaim (tl:side-effect-free symbol-balance)) (def-c-translation symbol-balance (symbol) ((lisp-specs :ftype ((symbol) fixnum)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "balance")))) (tl:defsetf symbol-balance set-symbol-balance) (def-c-translation set-symbol-balance (symbol fixnum) ((lisp-specs :ftype ((symbol fixnum) fixnum)) (declare (ignore symbol)) fixnum) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "balance") "=" fixnum))) (tl:declaim (tl:side-effect-free symbol-imported)) (def-c-translation symbol-imported (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) boolean)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "imported"))) (tl:defsetf symbol-imported set-symbol-imported) (def-c-translation set-symbol-imported (symbol flag) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-imported of ~s to ~s." ,symbol ,flag)) ((trans-specs :c-type ((obj boolean) boolean)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "imported") "=" flag))) (tl:declaim (tl:side-effect-free symbol-name-hash)) (def-c-translation symbol-name-hash (symbol) ((lisp-specs :ftype ((symbol) fixnum)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "name_hash")))) (tl:defsetf symbol-name-hash set-symbol-name-hash) (def-c-translation set-symbol-name-hash (symbol fixnum) ((lisp-specs :ftype ((symbol fixnum) fixnum)) (declare (ignore symbol)) fixnum) ((trans-specs :c-type ((obj sint32) sint32)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "name_hash") "=" fixnum))) (def-tl-macro tl:symbol-name (symbol) `(tl:the tl:string ,(if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (non-null-symbol-name ,symbol) "NIL") (let ((sym (gensym))) `(tl:let ((,sym ,symbol)) (tl:symbol-name ,sym)))))) (tl:declaim (tl:functional non-null-symbol-name)) (def-c-translation non-null-symbol-name (symbol) ((lisp-specs :ftype ((symbol) string)) `(symbol-name ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_name"))) (def-c-translation set-symbol-name (symbol string) ((lisp-specs :ftype ((t t) t)) `(derror "Can't actually set the symbol name in development: ~s ~s" ,symbol ,string)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_name") "=" string))) (def-tl-macro tl:symbol-value (symbol) (if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (tl:if (symbol-local-value ,symbol) (symbol-value-pointer ,symbol) (symbol-non-local-value ,symbol)) nil) (let ((var (gensym))) `(tl:let ((,var ,symbol)) (tl:symbol-value ,var))))) (tl:defsetf tl:symbol-value tl:set) (def-tl-macro tl:set (symbol new-value) (let ((sym (gensym)) (val (gensym))) `(tl:let ((,sym ,symbol) (,val ,new-value)) (tl:if ,sym (tl:if (symbol-local-value ,sym) (set-symbol-value-pointer ,sym ,val) (set-symbol-non-local-value ,sym ,val)) (tl:error "Can't set the symbol-value of NIL.")) ,val))) (tl:declaim (tl:side-effect-free symbol-value-pointer)) (def-c-translation symbol-value-pointer (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-value ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))) (tl:defsetf symbol-value-pointer set-symbol-value-pointer) (def-c-translation set-symbol-value-pointer (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-value ,symbol) ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value") "=" new-value))) (tl:declaim (tl:side-effect-free symbol-non-local-value)) (def-c-translation symbol-non-local-value (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-value ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-unary-expr #\* (make-c-cast-expr '(pointer obj) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))))) (def-c-translation set-symbol-non-local-value (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-value ,symbol) ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-unary-expr #\* (make-c-cast-expr '(pointer obj) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_value"))) "=" new-value))) (def-tl-macro tl:symbol-plist (symbol) (if (or (symbolp symbol) (constantp symbol)) `(tl:if ,symbol (non-null-symbol-plist ,symbol) symbol-plist-of-nil) (let ((var (gensym))) `(tl:let ((,var ,symbol)) (tl:symbol-plist ,var))))) (tl:declaim (tl:side-effect-free non-null-symbol-plist)) (def-c-translation non-null-symbol-plist (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-plist ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_plist"))) (tl:defsetf tl:symbol-plist set-symbol-plist) (def-tl-macro set-symbol-plist (symbol new-plist) (let ((sym (gensym)) (new (gensym))) `(tl:let ((,sym ,symbol) (,new ,new-plist)) (tl:if ,sym (set-non-null-symbol-plist ,sym ,new) (tl:setq symbol-plist-of-nil ,new))))) (def-c-translation set-non-null-symbol-plist (symbol new-plist) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-plist ,symbol) ,new-plist)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_plist") "=" new-plist))) (tl:declaim (tl:side-effect-free tl:symbol-package)) (def-c-translation tl:symbol-package (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-package ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_package"))) (def-c-translation set-symbol-package (symbol package-or-nil) ((lisp-specs :ftype ((symbol t) t)) `(derror "There is no development implementation of set-symbol-package: ~ args = ~s, ~s" ,symbol ,package-or-nil)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_package") "=" package-or-nil))) (tl:declaim (tl:side-effect-free tl:symbol-function)) (def-c-translation tl:symbol-function (symbol) ((lisp-specs :ftype ((symbol) t)) `(symbol-function ,symbol)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_function"))) (def-c-translation set-symbol-function (symbol function) ((lisp-specs :ftype ((symbol t) t)) `(setf (symbol-function ,symbol) ,function)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "symbol_function") "=" function))) (tl:defsetf tl:symbol-function set-symbol-function) (tl:declaim (tl:side-effect-free symbol-left-branch)) symbol - function cell of the symbol is to a compiled - function . Note that TL does not allow function names of the ( setf < symbol > ) style , and so this (def-tl-macro tl:fboundp (symbol) (if (eval-feature :translator) `(tl:not (tl:eq (tl:symbol-function ,symbol) (the-unbound-value))) `(ab-lisp::fboundp ,symbol))) (def-c-translation symbol-left-branch (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "left_branch"))) (tl:defsetf symbol-left-branch set-symbol-left-branch) (def-c-translation set-symbol-left-branch (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-left-branch of ~s to ~s in development." ,symbol ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "left_branch") "=" new-value))) (tl:declaim (tl:side-effect-free symbol-right-branch)) (def-c-translation symbol-right-branch (symbol) ((lisp-specs :ftype ((symbol) t)) (declare (ignore symbol)) 'nonnil-variable-of-unknowable-value-and-type) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "right_branch"))) (tl:defsetf symbol-right-branch set-symbol-right-branch) (def-c-translation set-symbol-right-branch (symbol new-value) ((lisp-specs :ftype ((symbol t) t)) `(derror "Can't set-symbol-right-branch of ~s to ~s in development." ,symbol ,new-value)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer sym) symbol) "right_branch") "=" new-value))) (tl:declaim (tl:side-effect-free not-unbound-value-p)) (def-c-translation not-unbound-value-p (value) ((lisp-specs :ftype ((t) t)) `(derror "Not-unbound-value-p has no development implementation: ~s" ,value)) ((trans-specs :c-type ((obj) boolean)) (make-c-infix-expr value "!=" (make-c-cast-expr 'obj (make-c-unary-expr #\& (make-c-name-expr "Unbound")))))) (tl:declaim (tl:side-effect-free the-unbound-value)) (def-c-translation the-unbound-value () ((lisp-specs :ftype (() t)) `(derror "The-unbound-value cannot be returned in development Lisp.")) ((trans-specs :c-type (() obj)) (c-unbound-value-expr))) In CMU Lisp , if you give a fill - pointered string to make - symbol , the compiler can croak on that later on . Since TL always allocates (defun make-symbol-safely (string) (when (not (simple-string-p string)) (let ((new-string (make-string (length string)))) (replace new-string string) (setq string new-string))) (make-symbol string)) (tl:declaim (tl:side-effect-free compiled-function-arg-count compiled-function-optional-arguments compiled-function-default-arguments compiled-function-closure-environment compiled-function-name)) (def-c-translation compiled-function-arg-count (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-arg-count ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "arg_count")))) (def-c-translation compiled-function-optional-arguments (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-optional-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "optional_arguments")))) (def-c-translation compiled-function-sets-values-count (compiled-function) ((lisp-specs :ftype ((compiled-function) fixnum)) `(derror "No Lisp env implementation of (compiled-function-optional-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "sets_values_count")))) (defvar variable-of-unknown-value nil) (def-c-translation compiled-function-default-arguments (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) `(derror "No Lisp env implementation of (compiled-function-default-arguments ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "default_arguments"))) (def-c-translation compiled-function-closure-environment (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) `(derror "No Lisp env implementation of (compiled-function-closure-environment ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "closure_environment"))) (def-c-translation set-compiled-function-closure-environment (compiled-function closure-env) ((lisp-specs :ftype ((compiled-function t) t)) `(derror "No Lisp env implementation of (set-compiled-function-closure-environment ~s ~s)" ,compiled-function ,closure-env)) ((trans-specs :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "closure_environment") "=" closure-env))) (tl:defsetf compiled-function-closure-environment set-compiled-function-closure-environment) (def-c-translation set-thread-closure-env (new-closure-env) ((lisp-specs :ftype ((t) t)) new-closure-env) ((trans-specs :c-type ((obj) obj)) (make-c-infix-expr (make-c-name-expr "Closure_env") "=" new-closure-env))) (def-c-translation compiled-function-name (compiled-function) ((lisp-specs :ftype ((compiled-function) t)) #+lucid `(lucid::function-name ,compiled-function) #+cmu `(kernel:%function-name ,compiled-function) #-(or lucid cmu) `(derror "No Lisp env implementation of (compiled-function-name ~s)" ,compiled-function)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer func) compiled-function) "name"))) (def-tl-macro tl:make-package (name &key (use ''("TL"))) (if (eval-feature :translator) `(tl::make-package-1 ,name ,use) `(lisp:make-package ,name :use ,use))) (def-tl-macro tl:find-package (string-or-symbol-or-package) (if (eval-feature :translator) `(tl::find-package-1 ,string-or-symbol-or-package) Note that the Lucid implementation of find - package has an error , in -jallard , 5/1/97 `(find-package-safely ,string-or-symbol-or-package))) (defun find-package-safely (arg) (if (typep arg 'package) arg (lisp:find-package arg))) (def-c-translation make-new-package (name use-list) ((lisp-specs :ftype ((string t) package)) `(make-package ,name :use ,use-list)) ((trans-specs :c-type ((obj obj) obj)) (make-c-function-call-expr (make-c-name-expr "alloc_package") (list name use-list (make-c-literal-expr (region-number-for-type-and-area 'package (declared-area-name (l-expr-env function-call-l-expr) 'package))) (make-c-literal-expr (c-type-tag 'pkg)))))) (tl:declaim (tl:functional tl:package-name)) (def-c-translation tl:package-name (package) ((lisp-specs :ftype ((package) string)) `(package-name ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "name"))) (tl:declaim (tl:side-effect-free package-use-list-internal)) (def-c-translation package-use-list-internal (package) ((lisp-specs :ftype ((package) t)) `(package-use-list ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "used_packages"))) (tl:declaim (tl:side-effect-free package-root-symbol)) (def-c-translation package-root-symbol (package) ((lisp-specs :ftype ((package) t)) `(derror "Package-root-symbol has no development implementation: ~s" ,package)) ((trans-specs :c-type ((obj) obj)) (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "root_symbol"))) (tl:defsetf package-root-symbol set-package-root-symbol) (def-c-translation set-package-root-symbol (package symbol) ((lisp-specs :ftype ((package t) t)) `(derror "Set-package-root-symbol has no development implementation: ~s to ~s" ,package ,symbol)) ((c-type :c-type ((obj obj) obj)) (make-c-infix-expr (make-c-indirect-selection-expr (make-c-cast-expr '(pointer pkg) package) "root_symbol") "=" symbol))) Typep (def-tl-macro tl:typep (&environment env object type) (let ((expanded-type (tl:macroexpand type env))) (unless (tl:constantp expanded-type) (error "TL:typep can only handle constant types, not ~s" expanded-type)) (setq type (expand-type (eval expanded-type))) (if (and (symbolp object) (not (eq (tl:variable-information object env) :symbol-macro))) (cond ((consp type) (let ((first (cons-car type))) (case first ((and or not) `(,(cdr (assq first '((and . tl:and) (or . tl:or) (not . tl:not)))) ,@(loop for subtype in (cons-cdr type) collect `(tl:typep ,object (tl:quote ,subtype))))) ((satisfies tl:satisfies) `(,(cons-second type) ,object)) ((integer) `(tl:and (inlined-typep ,object 'tl:fixnum) ,@(cond ((eq (cons-second type) '*) nil) ((atom (cons-second type)) `((tl:>= (tl:the tl:fixnum ,object) ,(cons-second type)))) (t `((tl:> (tl:the tl:fixnum ,object) ,(car (cons-second type)))))) ,@(cond ((eq (cons-third type) '*) nil) ((atom (cons-third type)) `((tl:<= (tl:the tl:fixnum ,object) ,(cons-third type)))) (t `((tl:< (tl:the tl:fixnum ,object) ,(car (cons-third type)))))))) (t `(inlined-typep ,object (tl:quote ,type)))))) ((and (class-type-p type) structure-type-tags-assigned) (let* ((tag-var (gensym)) (info (structure-info type)) (min-type-tag (struct-type-tag info)) (max-type-tag (struct-maximum-subtype-tag info))) (declare (fixnum min-type-tag max-type-tag)) (if (= min-type-tag max-type-tag) `(tl:= (type-tag ,object) ,min-type-tag) `(tl:let ((,tag-var (type-tag ,object))) (tl:declare (tl:fixnum ,tag-var)) (tl:and (tl:<= ,min-type-tag ,tag-var) (tl:<= ,tag-var ,max-type-tag)))))) (t `(inlined-typep ,object (tl:quote ,type)))) (let ((object-var (gensym))) `(tl:let ((,object-var ,object)) (tl:typep ,object-var (tl:quote ,type))))))) (def-c-translation type-tag (object) ((lisp-specs :ftype ((t) fixnum)) `(car (type-tags-for-lisp-type (type-of ,object)))) ((trans-specs :c-type ((obj) sint32)) (let ((tag-var (reusable-c-variable-identifier 'temp c-func 'sint32 (l-expr-env function-call-l-expr)))) (make-c-function-call-expr (make-c-name-expr "TYPE_TAG") (list object (make-c-name-expr tag-var)))))) (def-tl-macro tl:typecase (keyform &rest clauses) (if (eval-feature :translator) (if (symbolp keyform) `(fixnum-case (type-tag ,keyform) ,@(loop with tags-so-far = nil for (type . forms) in clauses for type-tags? = (unless (eq type t) (type-tags-for-lisp-type type)) for unused-tags = (loop for tag in type-tags? unless (member tag tags-so-far) collect (progn (push tag tags-so-far) tag)) when (eq type t) collect `(t ,@forms) when (and (not (eq type t)) unused-tags) collect `(,unused-tags ,@forms))) (let ((key-var (gensym))) `(tl:let ((,key-var ,keyform)) (tl:typecase ,key-var ,@clauses)))) (let ((key-var (gensym))) `(tl:let ((,key-var ,keyform)) (tl:cond ,@(loop for (type . forms) in clauses collect (if (memqp type '(tl:t tl:otherwise)) `(t ,@forms) `((tl:typep ,key-var ',type) ,@forms)))))))) (tl:declaim (tl:functional tl:not)) (def-c-translation tl:not (object) ((lisp-specs :ftype ((t) t)) `(not ,object)) ((trans-specs :c-type ((boolean) boolean)) (cond ((and (c-unary-expr-p object) (char= (c-unary-expr-op-char object) #\!)) (c-unary-expr-arg-expr object)) ((c-equality-expr-p object) (let ((op-string (c-equality-expr-op-string object))) (make-c-equality-expr (c-equality-expr-left-arg object) (cond ((string= op-string "==") "!=") ((string= op-string "!=") "==") (t (translation-error "Can't translate NOT of ~s, bad string ~s" object op-string))) (c-equality-expr-right-arg object)))) (t (make-c-unary-expr #\! object))))) (def-c-translation eq-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(eq ,object1 ,object2)) ((trans-specs :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2))) (tl:define-compiler-macro tl:eql (object1 object2) `(eql-trans ,object1 ,object2)) (tl:declaim (tl:functional eql-trans)) (def-c-translation eql-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(eql ,object1 ,object2)) ((trans-specs :lisp-type (((or symbol fixnum character) t) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t (or symbol fixnum character)) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t t) t) :c-type ((obj obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "eql" '(obj obj)) (make-c-function-call-expr (make-c-name-expr "eql") (list object1 object2)))) (tl:define-compiler-macro tl:equal (object1 object2) `(equal-trans ,object1 ,object2)) (tl:declaim (tl:functional equal-trans)) (def-c-translation equal-trans (object1 object2) ((lisp-specs :ftype ((t t) t)) `(equal ,object1 ,object2)) ((trans-specs :lisp-type (((or symbol fixnum character) t) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t (or symbol fixnum character)) t) :c-type ((obj obj) boolean)) (make-c-equality-expr object1 "==" object2)) ((trans-specs :lisp-type ((t t) t) :c-type ((obj obj) obj)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'obj "equal" '(obj obj)) (make-c-function-call-expr (make-c-name-expr "equal") (list object1 object2)))) (defun process-cond-clauses (clauses) (let ((clause (cons-car clauses)) (rest-clauses (cons-cdr clauses))) (unless (consp clause) (error "Malformed cond clause ~s" clause)) (let ((test (cons-car clause)) (forms (cons-cdr clause))) (cond ((eq test t) (if forms `(tl:progn ,@forms) t)) (forms `(tl:if ,test (tl:progn ,@forms) ,(when rest-clauses (process-cond-clauses rest-clauses)))) (t (let ((test-value (gensym))) `(tl:let ((,test-value ,test)) (tl:if ,test-value ,test-value ,(when rest-clauses (process-cond-clauses rest-clauses)))))))))) (def-tl-macro tl:cond (&rest clauses) (if clauses (process-cond-clauses clauses) nil)) (def-tl-macro tl:when (test &body body) `(tl:if ,test (tl:progn ,@body))) (def-tl-macro tl:unless (test &body body) `(tl:if (tl:not ,test) (tl:progn ,@body))) (def-tl-macro tl:case (&environment env keyform &rest case-clauses) (cond ((and (tl-subtypep (expression-result-type keyform env) 'fixnum) (loop for (keys) in case-clauses always (or (fixnump keys) (memqp keys '(t tl:otherwise)) (and (consp keys) (loop for key in keys always (fixnump key)))))) `(fixnum-case ,keyform ,@case-clauses)) ((and (tl-subtypep (expression-result-type keyform env) 'character) (loop for (keys) in case-clauses always (or (characterp keys) (memqp keys '(t tl:otherwise)) (and (consp keys) (loop for key in keys always (characterp key)))))) `(fixnum-case (tl:char-code ,keyform) ,@(loop for (keys . forms) in case-clauses collect `(,(cond ((characterp keys) (list (char-code keys))) ((memqp keys '(t tl:otherwise)) keys) (t (loop for key in keys collect (char-code key)))) ,@forms)))) (t (let ((key-val (gensym))) `(tl:let ((,key-val ,keyform)) (tl:cond ,@(loop for (keylist . forms) in case-clauses when keylist collect (cond ((memqp keylist '(tl:t tl:otherwise)) `(tl:t ,@forms)) ((atom keylist) `((tl:eql ,key-val ',keylist) ,@forms)) ((null (cdr keylist)) `((tl:eql ,key-val ',(car keylist)) ,@forms)) (t `((tl:or ,@(loop for key in keylist collect `(tl:eql ,key-val ',key))) ,@forms)))))))))) (def-tl-macro tl:ecase (&rest args) `(tl:case ,@args (t (tl:error "Fell off end of ECASE - no matching clause")))) (def-tl-macro tl:psetq (&rest vars-and-values) (cond ((null vars-and-values) nil) ((null (cons-cddr vars-and-values)) `(tl:progn (tl:setq ,(cons-car vars-and-values) ,(cons-second vars-and-values)) nil)) (t (let ((settings nil)) `(tl:let ,(loop for (var value) on vars-and-values by #'cddr for temp-var = (gensym) collect (list temp-var value) do (push `(tl:setq ,var ,temp-var) settings)) ,@(nreverse settings) nil))))) (def-tl-macro tl:multiple-value-setq (variables form) (let ((bind-vars (loop repeat (length variables) collect (gensym)))) `(tl:multiple-value-bind ,bind-vars ,form ,@(when (memq nil (cdr variables)) `((tl:declare (tl:ignore ,@(loop for first = t then nil for set in variables for bind in bind-vars when (and (null set) (not first)) collect bind))))) ,@(loop for set in variables for bind in bind-vars when set collect `(tl:setq ,set ,bind)) ,(car bind-vars)))) Pointers result will be a negative value . Also note that informatoin will be lost of which are implemented as sint32 values , in which case it will retain all its (def-c-translation pointer-as-fixnum (object) ((lisp-specs :ftype ((t) fixnum)) #+lucid `(sys:%pointer ,object) #-lucid `(progn ,object -1)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 object))) 29 - bit fixnum that can be used as a good hashing number for Lisp objects . value is the pointer shifted right by 3 bits . Since we allocate items on 4 byte boundaries , not 8 , this could lead to two objects whose addresses are within 4 bytes of each to return the same value from this operation . However , since all of our Lisp objects are at least 8 bytes wide , I believe (def-c-translation pointer-as-positive-fixnum (object) ((lisp-specs :ftype ((t) fixnum)) #+lucid `(sys:%pointer ,object) #-lucid `(sxhash ,object)) ((trans-specs :c-type ((obj) sint32)) (make-c-cast-expr 'sint32 (make-c-infix-expr (make-c-cast-expr 'uint32 object) ">>" (make-c-literal-expr 3))))) (def-c-translation get-platform-code () ((lisp-specs :ftype (() fixnum)) '(if nonnil-variable-of-unknowable-value-and-type the code for Sun4 nonnil-variable-of-unknowable-value-and-type)) ((trans-specs :c-type (() sint32)) (register-needed-function-extern (c-func-c-file c-func) '("extern") 'sint32 "get_platform_code" nil) (make-c-function-call-expr (make-c-name-expr "get_platform_code") nil))) (def-c-translation malloc-block-into-region (region-number byte-count silent) ((lisp-specs :ftype ((fixnum fixnum fixnum) void)) `(derror "No Lisp type expansion for (malloc_block_into_region ~a ~a)" ,region-number ,byte-count ,silent)) ((trans-specs :c-type ((sint32 sint32 sint32) void)) (make-c-function-call-expr (make-c-name-expr "malloc_block_into_region") (list region-number byte-count silent)))) (def-c-translation internal-region-bytes-size (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-size ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_size") (list region-number)))) (def-c-translation internal-region-bytes-used (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-used ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_used") (list region-number)))) (def-c-translation internal-region-bytes-available (region-number) ((lisp-specs :ftype ((fixnum) fixnum)) `(derror "No Lisp type expansion for (region-bytes-available ~a)" ,region-number)) ((trans-specs :c-type ((sint32) sint32)) (make-c-function-call-expr (make-c-name-expr "region_number_bytes_available") (list region-number))))
6806e9c477bc89cfdf0d7f8d246e5bcab7eb874946b1566e960152eaa1049889
mark-watson/haskell_tutorial_cookbook_examples
Guards.hs
module Main where import Data.Maybe import System.Random -- uses random library (see Pure.cabal file) spaceship n | n < 0 = -1 | n == 0 = 0 | otherwise = 1 randomMaybeValue n | n `mod` 2 == 0 = Just n | otherwise = Nothing main = do print $ spaceship (-100) print $ spaceship 0 print $ spaceship 17 print $ randomMaybeValue 1 print $ randomMaybeValue 2
null
https://raw.githubusercontent.com/mark-watson/haskell_tutorial_cookbook_examples/0f46465b67d245fa3853b4e320d79b7d7234e061/Pure/Guards.hs
haskell
uses random library (see Pure.cabal file)
module Main where import Data.Maybe spaceship n | n < 0 = -1 | n == 0 = 0 | otherwise = 1 randomMaybeValue n | n `mod` 2 == 0 = Just n | otherwise = Nothing main = do print $ spaceship (-100) print $ spaceship 0 print $ spaceship 17 print $ randomMaybeValue 1 print $ randomMaybeValue 2
b34eb8a5044a7423dd97742b844b3894cb9ce2c0ad9ed2078e43c370acacc6f3
ldgrp/uptop
UI.hs
{-# LANGUAGE OverloadedStrings #-} module UI where import Brick.Types import Lens.Micro import Types import UI.HelpView import UI.MainView drawUI :: State -> [Widget Name] drawUI st = case st ^. (screen . focus . view) of MainView lz _m -> drawMain st lz HelpView -> drawHelp st
null
https://raw.githubusercontent.com/ldgrp/uptop/53001b39793df4be48c9c3aed9454be0fc178434/up-top/src/UI.hs
haskell
# LANGUAGE OverloadedStrings #
module UI where import Brick.Types import Lens.Micro import Types import UI.HelpView import UI.MainView drawUI :: State -> [Widget Name] drawUI st = case st ^. (screen . focus . view) of MainView lz _m -> drawMain st lz HelpView -> drawHelp st
30da2c8961c9fdc8758581b935091940f8b0e415c2597c6d3d8a5de8e963e634
dancrossnyc/multics
lisp_gfn_.lisp
;;; ************************************************************** ;;; * * * Copyright , ( C ) Massachusetts Institute of Technology , 1982 * ;;; * * ;;; ************************************************************** ;;; ************************************************************** * * * * * * * * * * * S - expression formatter ( grindef ) * * * * * * * * ;;; ************************************************************** * * ( c ) Copyright 1974 Massachusetts Institute of Technology * * ;;; ****** this is a read-only file! (all writes reserved) ******* ;;; ************************************************************** This version of Grind works in both ITS and Multics Maclisp copied from ( ) . gfn - fns for pretty - printing functions and S - expressions in core . when compiled , uses about 2300.instructions , 950 . list cells , 320 . fixnum cells , and 160 . symbols . remgrind applied therein will reclaim about 300 . list cells , the array space of ;; grindreadtble and gtab/|, and very little else. (declare (array* (notype (gtab/| 128.))) (noargs t) (special merge readtable grindreadtable remsemi grindpredict grindproperties grindef predict grindfn grindmacro programspace topwidth /;/ ; user - paging arg linel pagewidth gap comspace fill nomerge comnt / ; ? ^d macro unbnd - vrbl form prog? n m l h grind-standard-quote sgploses) (*expr form topwidth programspace pagewidth comspace nomerge remsemi prin50com rem/; rem/;/;) (*fexpr trace slashify unslashify grindfn grindmacro unreadmacro readmacro grindef) (*lexpr merge predict user-paging fill testl) (mapex t) (genprefix /|gr) (or (get 'maknum 'subr) (defun macro maknum (x) (cons '(lambda (x) (abs (sxhash x))) (cdr x)))) ;temporary for Multics (fixnum nn mm (prog-predict notype fixnum fixnum) (block-predict notype fixnum fixnum) (setq-predict notype fixnum fixnum) (panmax notype fixnum fixnum) (maxpan notype fixnum) (gflatsize))) (defun macex macro (x) (list 'defun (cadr x) 'macro (caddr x) (eval (cadddr x)))) (defun ifoio macro (x) (cond ((not (status feature newio)) (cadr x)) ('(comment ifoio not taken)))) (defun ifnio macro (x) (cond ((status feature newio) (cadr x)) ('(comment ifnio not taken)))) (macex newlineseq (x) (cond ((status feature Multics) ''(list (ascii 12))) (t ''(list (ascii 15)(ascii 12))))) (macex version (x) (subst (maknam (nconc (newlineseq) (explodec '/;loading/ grindef/ ) (explodec (cond ((status feature newio) (caddr (names infile))) ((cadr (status uread))))) (newlineseq))) 'version ''(iog nil (princ 'version) (ascii 0)))) (ifnio (defun newlinel macro (x) (subst (cadr x) 'nn '(setq linel nn)))) (ifoio (defun newlinel (nn) (setq chrct (+ chrct (- nn linel))) (setq linel nn))) (ifoio (defun grchrct macro (x) 'chrct)) (ifnio (defun macro set-linel (x) '(setq linel (linel (and outfiles (car outfiles)))))) (ifoio (defun macro set-linel (x) '(comment linel))) (version) ;;*user-paging (prog nil ;some initializations (and (not (boundp 'grind-use-original-readtable)) (setq grind-use-original-readtable t)) (and (or (not (boundp 'grindreadtable)) (null grindreadtable)) ((lambda (readtable) (setsyntax 12. 'single nil) ;^l made noticeable. (sstatus terpri t) ;the grindreadtable is tailored for (setsyntax '/; ;grind. no cr 'splicing 'semi-comment)) ;are inserted by lisp when (setq grindreadtable (*array nil 'readtable grind-use-original-readtable)))) ;print exceeds linel. (and (not (boundp 'grind-standard-quote)) ;standard readmacroinveser for quote (setq sgploses (setq grind-standard-quote t))) (setq remsemi nil m 0. grindlinct 8. grindef nil global-lincnt 59.) (setq grindproperties '(expr fexpr value macro datum cexpr)) (and (status sstatus feature) (sstatus feature grindef)) (array gtab/| t 128.)) ;;debugging break for grind. (declare (read) (read)) ;gbreak restricted to interpretive ;version. (defun gbreak fexpr (x) (and gbreak ;break transparent to chrct (prog (chrct* ^r) (setq chrct* (grchrct)) (apply 'break (cond ((null x) '(grind t)) ((list x t)))) (terpri) a (cond ((eq chrct* (grchrct))) ((princ '/ ) (go a))) (return t)))) (setq gbreak t) rem function - note : to be complete , remgrind should remprop all grindfn , grindmacro and ;;properties from any atom on the obarray. * ( expr macro value grindpredict ) comment - form (defun remsubr (x) (remprop x 'subr)) (defun remfsubr (x) (remprop x 'fsubr)) (defun remlsubr (x) (remprop x 'lsubr)) (defun remgrind fexpr nil (lispgrind) (cond ((status sstatus nofeature) (sstatus nofeature grind) (sstatus nofeature grindef))) (cond ((null (get 'conniver 'array)) (remsubr 'grindexmac) (remsubr 'grindatmac) (remsubr 'grindcolmac) (remsubr 'grindcommac) (remsubr 'grindseparator) (remsubr 'grindnxtchr))) (remfsubr 'grind) (remfsubr 'grind0) (remfsubr 'grindef) (remsubr 'turpri) (remlsubr 'fill) (remlsubr 'user-paging) (remlsubr 'merge) (remlsubr 'testl) (remlsubr 'predict) (remfsubr 'slashify) (remfsubr 'unslashify) (remfsubr 'unformat) (remfsubr 'grindmacro) (remfsubr 'grindfn) (remfsubr 'readmacro) (remfsubr 'unreadmacro) (remfsubr 'readmacroinverse) (remsubr 'slashify1) (remsubr 'unslashify1) (remsubr 'programspace) (remsubr 'grindmacrocheck) (remsubr '?grindmacro) (remsubr 'comment-form) (remsubr 'pagewidth) (remsubr 'comspace) (remsubr 'lispgrind) (remsubr 'cnvrgrind) (remsubr 'page) (remsubr 'topwidth) (remsubr 'rem/;) (ifnio (remsubr 'newlinel)) (ifnio (remsubr 'grchrct)) (remsubr 'rem/;/;) (remsubr 'tj6) (remsubr 'prin50com) (remsubr 'prinallcmnt) (remsubr 'semi-comment) (remsubr 'putgrind) (remsubr 'lambda-form) (remsubr 'prog-form) (remsubr 'if-form) (remsubr 'def-form) (remsubr 'coment-form) (remsubr 'block-form) (remsubr 'mem-form) (remsubr 'setq-form) (remsubr 'setq-predict) (remsubr 'remsem1) (remsubr 'remsemi) (remsubr 'popl) (remsubr 'semi?) (remsubr 'semisemi?) (remsubr 'indent) (remsubr 'indent-to) (remsubr 'pprin) (remsubr 'form) (remsubr 'sprint) (remsubr 'grind-unbnd-vrbl) (remsubr 'sprinter) (remsubr 'sprint1) (remsubr 'grindargs) (remsubr 'done?) (remsubr 'gblock) (remsubr 'gprin1) (remsubr 'maxpan) (remsubr 'panmax) (remsubr 'prog-predict) (remsubr 'block-predict) (remsubr 'gflatsize) (remsubr 'flatdata) (remsubr 'grindslew) (remsubr 'remlsubr) (remfsubr 'remgrind) (remsubr 'remfsubr) (remsubr 'remsubr) ((lambda (nn) (do mm 0 (1+ mm) (= mm nn) (mapc '(lambda (x) (cond ((getl x '(grindfn grindpredict grindmacro)) (remprop x 'grindfn) (remprop x 'grindpredict) (remprop x 'grindmacro)))) ((lambda (x) (cond ((and x (atom x)) (ncons x)) (x))) (obarray mm)) ))) (cadr (arraydims 'obarray))) (makunbound 'merge) (makunbound 'grindpredict ) (makunbound 'predict) (makunbound 'grindfn) (makunbound 'grindmacro) (makunbound 'programspace) (makunbound 'topwidth) (makunbound '/;) (makunbound '/;/;) (makunbound 'user-paging) (makunbound 'pagewidth) (makunbound 'comspace) (makunbound 'prog?) (makunbound 'comnt) (makunbound '/;/;?) (makunbound 'cnvrgrindflag) (makunbound 'remsemi) (makunbound 'grindlinct) (makunbound 'global-lincnt) (makunbound 'grindproperties) (makunbound 'grindef) (makunbound 'grindreadtable) (makunbound 'grind-standard-quote) (makunbound 'grind-use-original-readtable) (*rearray 'gtab/|) (gctwa)) (defun grindef fexpr (atoms) ;(grindef <atoms>) grinds the properties (prog (traced fn props) ;of the atoms listed on (set-linel) " grindproperties " . ( (or cnvrgrindflag (cnvrgrind)))) (cond (atoms (setq grindef atoms)) ;(additional properties) <atoms>) grinds ((setq atoms grindef))) ;the additional properties as well. (setq props grindproperties) a (cond ((null atoms) (return (ascii 0.)))) (setq fn (car atoms) atoms (cdr atoms)) (cond ((atom fn)) ((setq props (append fn props)) (go a))) (cond ((setq traced (and (cond ((status sstatus feature) (status feature trace)) ((get 'trace 'fexpr))) (memq fn (trace)))) ;flag for fn being traced (terpri) (terpri) (princ '/;traced))) (do ((plist (cdr fn) (cddr plist)) (ind 'value (car plist)) (prop (and (boundp fn) (symeval fn)) (cadr plist)) (valueless (not (boundp fn)) t)) ;needed in case there are value properties (nil) ignore first fn property if traced (setq traced nil) (go b)) ((not (memq ind props)) (go b)) ;grindef only desired properties. ((eq ind 'value) (cond ((not valueless) (terpri) (terpri) (sprint (list 'setq fn (list 'quote prop)) linel 0.))) (go b))) (terpri) (terpri) ;terpri's placed here to avoid (cond ((eq ind 'theorem) ;terpri'ing when no properties. (sprint (cons (car prop) (cons fn (cdr prop))) linel 0.)) ((and (memq ind '(expr fexpr macro)) ;lambda -> defun (eq (car prop) 'lambda)) (sprint (cons 'defun (cons fn (cond ((eq ind 'expr) (cdr prop)) ((cons ind (cdr prop)))))) linel 0.)) ((eq ind 'cexpr) (sprint (cons 'cdefun (cons fn prop)) linel 0.)) ((sprint (list 'defprop fn prop ind) linel 0.))) b (or plist (return nil))) ;exit from do when no more properties (go a) ;look for more atoms to do. )) ;;;assigning special formats ( unformat fn1 fn2 ... ) or ( unformat (or (atom (car x)) (setq x (car x))) ;(fn1 fn2 ...)) (mapc '(lambda (x) (remprop x 'grindfn) (remprop x 'grindmacro) (remprop x 'grindpredict)) x)) eg ( grindmacro quote / ' ) (putgrind (car y) (cdr y) 'grindmacro)) eg ( grindfn ( prog thprog ) prog - form ) (putgrind (car y) (cdr y) 'grindfn)) (defun putgrind expr (fn prop ind) ;like putprop (cond ((atom fn) (setq prop (cond ((atom (car prop)) (and (get (car prop) 'grindpredict) (putprop fn (get (car prop) 'grindpredict) 'grindpredict)) (car prop)) (t (and (eq (caar prop) 'readmacroinverse) (putprop fn (get 'readmacroinverse 'grindpredict) 'grindpredict)) (cons 'lambda (cons nil prop))))) (putprop fn prop ind)) ((mapc '(lambda (x) (putgrind x prop ind)) fn)))) ;;;read macros (defun readmacro fexpr (y) ;eg (readmacro quote /' [optional]) (putgrind (car y) ;where optional means macro cons not (list (cons 'readmacroinverse ;list (cons (cadr y) (cddr y)))) 'grindmacro)) (defun unreadmacro fexpr (y) (remprop y 'grindmacro)) (defun ?grindmacro (x) (prog (y) (cond ((and cnvrgrindflag (setq y (get x 'grindmacro))) (return (list (cddr (caddr y))))) (t (return nil))))) (defun grindmacrocheck (x l) (cond ((and (equal x '((t))) (cdr l))) ((and (equal x '(nil)) (= (length l) 2.))) ((and (equal x '((cnvr-optional))) (cdr l))))) ( fn - print l > . (prog (sprarg) (cond ((grindmacrocheck (list (cdr x)) l) ;macro-char = atom or list of ascii (cond ((atom (car x)) (princ (car x))) ;values. macro must have arg to execute ((mapc 'tyo (car x)))) ;inverse (setq sprarg (cond ((null (cdr x)) (cadr l)) ((eq (cadr x) t) (cdr l)) ((= (length (cdr l)) 1.) (cond ((null (cadr l)) (tyo 32.) (return t)) (t (cadr l)))) (t (cdr l)))) (cond ((sprint1 sprarg (grchrct) m) (prin1 sprarg))) (return t)) (t (return nil))))) ;;predefined formats (defun lambda-form nil (form 'line) ;format for lambda's (and (< (grchrct) (gflatsize (testl))) ;prohibits form3 if args do not fit on (setq form 'form2)) ;line. (form 'block)) (defun prog-form nil format for thprog 's and prog 's (setq prog? t) (setq form (cond ((and predict (< (grchrct) (gflatsize (testl)))) ;prohibits form3 if args do not fit on 'form2) ;line. (arg))) (form 'block)) (defun if-form nil (setq prog? t) (form 'line) (cond ((atom (testl)) (form 'line))) (setq form (cond ((and predict (< (grchrct) (gflatsize (testl)))) 'form2) (arg))) (form 'list)) (defun def-form nil (prog nil (cond ((eq (car l) 'cdefun) (setq prog? t))) (form 'line) (form 'line) go (cond ((memq (testl) '(expr fexpr macro thnoassert cexpr)) (form 'line) (go go))) (setq form (cond ((and predict (< (grchrct) (gflatsize (testl)))) ;prohibits form3 if args do not fit on 'form2) ;line. (arg))) (return (form 'block)))) (defun comment-form nil (gblock (- (grchrct) 1. (gflatsize (car l))))) ;grinds l with args outputed as list. (defun block-form nil (gblock (grchrct))) (defun mem-form nil (prog (p gm) quoted second arg ground as block (remsemi) (catch (and (setq p (panmax (car l) (grchrct) 0.)) (cond ((< (panmax (car l) n 0.) p)) ((setq n (grchrct)))))) (cond ((sprint1 (car l) n 0.) (prin1 (car l)))) a (cond ((null (cdr l)) (setq l (error 'mem-form l 'fail-act)) (go a))) (popl) go (indent-to n) (setq m (1+ m)) (cond ((eq (caar l) 'quote) (princ '/') (cond ((pprin (cadar l) 'block)) ((prin1 (cadar l))))) ((setq gm (sprint1 (car l) n m)) (cond ((and cnvrgrindflag (grindmacrocheck gm l)) (princ '/./ ) (sprint1 l (- n 2.) m) (setq l nil) (return nil)) (t (prin1 (car l)))))) (popl) (cond (l (go go)) ((return nil))))) (defun setq-form nil (cond ((catch (prog (mm) (setq mm (maxpan (cdr l) arg)) ;standard form (setq n arg) ;committed to at least standard form (defprop setq (setq-predict l n m) grindpredict) ;prediction in special form computed to (and (< mm ;compare to p. (panmax l (prog2 nil (1+ n) (setq n arg)) m)) ;setq form (return t)) (form 'line) d (or l (return nil)) (indent-to n) (form 'line) (form 'code) (remsemi) (go d))) (defprop setq nil grindpredict) ;setq-predict causes throw when variable (form 'line) ;name is very long. therefore, it is (setq form n)))) ;not used all the time but only inside ;setq-form. (defun setq-predict (l n m) ;returns number of lines to print args (prog (mm nn) ;as name-value pairs. n = space for name <space> value . 2 = (setq mm 0.) ;space for ( and <space preceding a (and (null (setq l (cdr l))) (return mm)) ;variable>. (and (semi? (car l)) (go a)) nn = space for value . 2 = space for ) b (cond ((null (cdr l)) ;and <space preceding value>. (setq l (error 'setq-predict l 'wrng-no-args)) (go b))) (setq l (cdr l)) (and (semi? (car l)) (go b)) (setq mm (+ mm (panmax (car l) nn 0.))) (go a))) ;;;format control (defun predict args (setq predict (cond ((= args 0.)) ((arg 1.))))) ;(predict) <=> (predict t) => ;super-careful sprint considering all ;formats. (predict nil) => less careful ;but quicker. the following format fns are used only in grinding files . however , they may appear in a grind ( init ) file which is loaded by gfn . hence , they are defined in gfn to avoid undf error . ( eg ( slashify $ ) . preserve slashes ;preceding user read macros. (defun unslashify fexpr (chars) (mapc 'unslashify1 chars)) (defun slashify1 (char) ;make char '-like readmacro. ((lambda (readtable) (or (null (getchar char 2.)) ;will be null only if char is single (setq char (error 'slashify char 'wrng-type-arg))) (setsyntax char 'macro (subst char 'char '(lambda nil (list 'char (read))))) (apply 'readmacro (list char char))) grindreadtable)) ( declare ( noargs nil ) ) ; args prop for user - level tj6 fns . (defun unslashify1 (char) ((lambda (readtable) (or (null (getchar char 2.)) (setq char (error 'unslashify char 'wrng-type-arg))) (setsyntax char 'macro nil) (apply 'unreadmacro (list char))) grindreadtable)) (defun programspace (x) (setq programspace (newlinel x)) (setq comspace (- pagewidth gap programspace))) (defun pagewidth (w x y z) (setq pagewidth w) (setq gap y) (setq programspace x) (setq comspace z)) (defun comspace (x) (setq comspace x) (setq programspace (- pagewidth gap comspace))) (defun page nil (tyo 12.) (setq grindlinct global-lincnt)) (defun fill args (setq fill (cond ((= args 0.)) ((arg 1.))))) ;(fill) <=> (fill t) => spaces gobbled ;in ; comments. (fill nil) => spaces ;not gobbled. triple semi comments are ;never filled but are retyped exactly inuser 's original form . (defun merge args (setq merge (cond ((= args 0.)) ((arg 1.))))) ;(merge) <=> (merge t) => adjoining ; ;and ;; comments are merged. (merge nil) ;=> adjoining comments not merged. ;;;;... are never merged. (defun user-paging args ;(user-paging) <=> (user-paging t) (setq user-paging (cond ((= args 0.)) ((arg 1.))))) ;grind does not insert any formfeeds, ;but preserves paging of user's file. ;(user-paging nil) => grind inserts formfeed every 59 lines . attempts to ;avoid s-expr pretty-printed over page ;boundary. ignores users paging. paging ;of user's file. (defun topwidth (x) (setq topwidth x)) ( declare ( noargs t ) ) ; args prop for user - level tj6 fns . ;;user defined formats (defun remsemi nil (prog (retval) loop (cond ((remsem1) (setq retval t)) ((return retval))) (go loop))) (defun remsem1 nil ;remsemi switch t for grinding files, ) ( rem/;/ ;) t ) ( ( rem/;/ ;) ) ) ) ) ; nil for grindef . speeds up grindef . ;also, prevents possible illegal memory reference by rem/ ; caar on pnames . (defun popl nil (setq l (cdr l)) (remsemi) l) (defun semisemi? (k) (cond ((null remsemi) nil) ;check for any ;;'s ((eq k /;/;)) ((atom k) nil) ((or (semisemi? (car k)) (semisemi? (cdr k)))))) ;at any depth (defun semi? (k) (and remsemi (or (eq (car k) /;) (eq (car k) /;/;)))) (defun indent (nn) ;indents additonal nn spaces. (cond ((minusp (setq nn (- (grchrct) nn))) (error 'indent/ beyond/ linel? nn 'fail-act) (terpri)) ((indent-to nn)))) replaced by compiler by tab ( 8 its , 10 . ; Multics ) (defun indent-to (nn) ;chrct set to nn ((lambda (nct tab) (declare (fixnum nct tab)) (cond ((or (< nct 0.) (> nn nct)) ;chrct may become negative from (turpri) ;prin50com. (setq nct linel))) (cond ((< nn nct) ;some indentation is necessary (setq tab (+ nct (- (stat-tab)) position as a result of first tab . tabs do not move 8 , but to nearest multiple of 8 (setq nct tab) (cond ((< nn nct) (grindslew (// (setq nct (- nct nn)) (stat-tab)) 9.) (grindslew (\ nct (stat-tab)) 32.)))))))) (grchrct) 0.)) (defun grindslew (nn x) (do mm nn (1- mm) (zerop mm) (tyo x))) (defun pprin (l tp) (cond ((and cnvrgrindflag (atom l) (?grindmacro l)) nil) ((atom l) (prin1 l) t) ;l is ground as line if tp = 'line, as a ((eq tp 'line) (cond ((gprin1 l n)(prin1 l))) t ) ;block if tp = 'block or as a function ((eq tp 'block) ;followed by a list (or (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro))) (progn (princ '/() ;of arguments if l = 'list, or normally (gblock (grchrct)) ;if tp = 'code. (princ '/))))) ((eq tp 'list) (or (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro))) (progn (princ '/() (gblock (- (grchrct) 1. (gflatsize (car l)))) (princ '/))))) ((eq tp 'code) (sprint1 l (grchrct) m) t))) (defun turpri nil (and remsemi comnt (prin50com)) ;cr with line of outstanding single semi (terpri) ;comment printed, if any. grindlinct = (setq grindlinct (cond ((= grindlinct 0.) global-lincnt) ;lines remaining on page. ((1- grindlinct))))) (ifnio (defun grchrct nil (- linel (charpos (and outfiles (car outfiles)))))) (defun testl args (prog (k nargs) (setq k l nargs (cond ((= 0. args) 0.) ((arg 1.)))) a (cond ((null k) (return nil)) ((semi? (car k)) (setq k (cdr k)) (go a)) ((= 0. nargs) (return (cond ((= 2. args) k) (t (car k))))) ((setq nargs (1- nargs)) (setq k (cdr k)) (go a))))) (defun form (x) ;pprin the car of l, then pops l. (cond ((remsemi) (form x)) ;no-op if l is already nil. process (l (cond ((pprin (car l) x) ;initial semi-colon comment, if any, (and (cdr l) (tyo 32.)) ;then try again. pretty-print c(car l) (setq l (cdr l))) ((and cnvrgrindflag (grindmacrocheck (?grindmacro (car l)) l)) (princ '/./ ) (gprin1 l (- n 2.)) (setq l nil form nil)) (t (prin1 (car l)) (and (cdr l) (tyo 32.)) (setq l (cdr l))))))) ;in desired format. if l is not yet nil, ;output a space. return popped l. ;;local functions (defun sprinter (l) ;pretty print over whole width (prog nil (set-linel) (turpri) (turpri) (sprint l linel 0.) (turpri) (return '*))) (defun sprint (l n m) (fillarray 'gtab/| '(nil)) (sprint1 l n m)) ;;;sprint formats = ( s1 form2 = ( s1 s2 form3 = ( s1 s2 ( sprint1 last ) ) ;;; s2 s3) ;;; s3) (defun sprint1 (l n m) ;expression l to be sprinted in space n (prog (form arg fn args p prog? grindfn form3? gm) ;with m unbalanced "/)" hanging. p is number lines to sprint1 as form2 (setq /;/;? nil) (indent-to n) (and (atom l) (cond (cnvrgrindflag) ((setq gm (?grindmacro l)) (return gm)) (t (prin1 l) (return nil)))) (cond ((and grind-standard-quote ;This is an explicit check for QUOTE. (eq (car l) 'quote) ;The alternative is to use the standard grindmacro (cdr l) ;To use your own personal readmacro for quote, (null (cddr l))) ;setq grind-standard-quote to nil. (princ '/') (and (setq gm (sprint1 (cadr l) (grchrct) m)) cnvrgrindflag (cond ((grindmacrocheck gm (cdr l)) (princ '/./ ) (sprint1 (cdr l) (- (grchrct) 2) m)) (t (prin1 (car l))))) (return nil))) (and (atom (car l)) (setq fn (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro)) (return nil)) (cond ((semisemi? l)) ;if a ;; comnt, force multi-line ((< (+ m -1. (gflatsize l)) (grchrct)) (return (gprin1 l n)))) (princ '/() (setq n (grchrct)) (setq arg (- n (gflatsize (car l)) 1.)) (and (atom (setq args (cond ((setq grindfn (get fn 'grindfn)) (apply grindfn nil) (and (numberp form) (setq n form) (go b)) (and (null l) (princ '/)) (return nil)) l) ((cdr l))))) (go b)) (catch ;catch exited if space insufficient. (and (setq p (maxpan args arg)) ;p = # of lines to sprint l in standard (cond (predict (not (< (maxpan args n) p))) ;format. exit if miser more efficient (fn)) ;than standard in no-predict mode, use (setq n arg) ;miser format on all non-fn-lists. (cond ;committed to standard format. (grindfn (or (eq form 'form2) (> (maxpan args (grchrct)) p) (setq n (grchrct)))) ((prog nil (or predict (go a)) ;skip form3 is predict=nil. (catch (setq l can not be fit in chrct is it more ) ) ; efficient to grind l form3 or form2 (< (maxpan (last l) (- (grchrct) (- (gflatsize l) (gflatsize (last l))))) p)))) a (cond ((setq gm (gprin1 (car l) n)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- n 2.)) (setq l nil) (go b1)) (t (prin1 (car l)))))) (tyo 32.) (and (cdr (setq l (cdr l))) form3? (go a)) b1 (setq n (grchrct))))))) b (grindargs l n m))) elements of l are ground one under the (prog (gm sprarg1 sprarg2) ;next a (and (done? nn) (return nil)) ;prints closing paren if done. (setq sprarg1 (cond ((and cnvrgrindflag (eq (car l) '/"aux/")) (+ nn 6.)) ((and prog? (car l) (or (atom (car l)) (and cnvrgrindflag (eq (caar l) ':)))) (+ nn 5.)) ;exception of tags which are unindented 5 (setq sprarg2 (cond ((null (cdr l)) (1+ mm)) ((atom (cdr l)) (+ 4. mm (gflatsize (cdr l)))) (0.))) (cond ((setq gm (sprint1 (car l) sprarg1 sprarg2)) (cond ((grindmacrocheck gm l) (princ '/./ ) (sprint1 l (- sprarg1 2.) sprarg2) (setq l nil) (go a)) (t (prin1 (car l)))))) (setq l (cdr l)) (go a))) (defun done? (nn) (cond ((atom l) (and /;/;? (indent-to nn)) ;if previous line a ;; comment, then do (cond (l (princ '/ /./ ) (prin1 l))) ;not print closing paren on same line as (princ '/)) ;comment. t))) ;prints closing "/)" if done (defun gblock (n) ;l printed as text with indent n. (prog (gm) (and (remsemi) (or l (return nil))) a (cond ((setq gm (gprin1 (car l) n)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- n 2.)) (return (setq l nil))) (t (prin1 (car l)))))) (or (popl) (return nil)) (cond ((< (gflatsize (car l)) (- (grchrct) 2. m)) (tyo 32.) (go a)) ((and (not (atom (car l))) ;non-atomic elements occuring in block (< (- n m) (gflatsize (car l)))) ;too large for the line are sprinted. (cond ((setq gm (sprint1 (car l) n m)) ;this occurs in the variable list of a (cond ((grindmacrocheck gm l) ;thprog. (princ '/./ ) (sprint1 l (- n 2.) m) (return (setq l nil))) (t (prin1 (car l)))))) (or (popl) (return nil)))) (indent-to n) ;new line (go a))) prin1 with grindmacro feature . (cond ((and cnvrgrindflag (atom l) (?grindmacro l))) ((atom l) (prin1 l) nil) ((prog (gm) (remsemi) (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro)) (return nil)) (princ '/() a (cond ((setq gm (gprin1 (car l) nn)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- nn 2.)) (setq l nil) (go a1)) (t (prin1 (car l)))))) (popl) a1 (and (done? nn) (return nil)) (tyo 32.) (go a))))) ;;prediction functions (defun maxpan (l n) estimates number of lines to sprint1 (setq g 0.) ;list of s expression one under the next a (setq g ;in space n (+ g (panmax (car l) n (cond ((null (setq l (cdr l))) (1+ m)) ((atom l) (+ m 4. (gflatsize l))) (0.))))) (and (atom l) (return g)) (go a))) (defun panmax (l n m) estimates number of lines to sprint1 an ((or (< n 3.) (atom l)) (throw 40.)) ;s expression in space n. less costly ((or (not (atom (car l))) (atom (cdr l))) ;than sprint (maxpan l (sub1 n))) as it always chooses form2 . if ((maxpan (cdr l) (- n 2. (gflatsize (car l))))))) ;insufficient space, throws. (defun prog-predict (l n m) ((lambda (nn) (+ (block-predict (cadr l) nn 1.) (maxpan (cddr l) nn))) (- n 2. (gflatsize (car l))))) (defprop lambda-form (prog-predict l n m) grindpredict) (defprop prog-form (prog-predict l n m) grindpredict) (defun block-predict (l n indent) ;indent=spaces indented to margin of block . throw if remaining space . ((1+ (// (- (gflatsize l) indent) n))))) ;number of lines approx by dividing size ;of l by block width. (defprop comment-form (block-predict l n (+ (gflatsize (car l)) 2.)) grindpredict) (defprop block-form (block-predict l n 1.) grindpredict) (defprop readmacroinverse (panmax (cadr l) (1- n) m) grindpredict) (defun gflatsize (data) ((lambda (nn bucket) (setq bucket (gtab/| nn)) (cdr (cond ((and bucket (assq data bucket))) (t (car (store (gtab/| nn) (cons (setq data (cons data (flatsize data))) bucket))))))) (\ (maknum data) 127.) nil)) conniver macros (setq cnvrgrindflag nil) (defun cnvrgrind nil ((lambda (readtable) (setsyntax ': 'macro 'grindcolmac) (setsyntax '@ 'macro 'grindatmac) (setsyntax '/, 'macro 'grindcommac) (setsyntax '! 'macro 'grindexmac) (readmacro : :) (readmacro /, /,) (readmacro @ @ t) (readmacro !$ (33. 36.) t) (readmacro !/" (33. 34.) t) (readmacro !@ (33. 64.) t) (readmacro !? (33. 63.) cnvr-optional) (readmacro !/, (33. 44.) cnvr-optional) (readmacro !< (33. 60.) cnvr-optional) (readmacro !> (33. 62.) cnvr-optional) ( 33 . 59 . ) cnvr - optional ) (readmacro !/' (33. 39.) cnvr-optional) (setq cnvrgrindflag t sgploses grind-standard-quote grind-standard-quote nil) 'conniver-macros-learned) grindreadtable)) (defun lispgrind nil ((lambda (readtable) (setsyntax ': 'macro nil) (setsyntax '@ 'macro nil) (setsyntax '/, 'macro nil) (setsyntax '! 'macro nil) (mapc 'unreadmacro '(: /, @ !$ !/" !@ !? !/' !/, !< !> !/;)) (setq cnvrgrindflag nil grind-standard-quote sgploses) 'conniver-macros-forgotten) grindreadtable)) ;;default formats ;"quote" is explicitly checked, and the inverse ;macro function ignored if this flag is non-nil. ;To have your own macro for quote take effect, ;set grind-standard-quote to nil. (readmacro quote /') ;Still ned to define the standard macro (grindfn (grindfn grindmacro) (form 'line) (form 'block)) (grindfn lambda lambda-form) (grindfn (if-added if-needed if-removed) if-form) (grindfn (defun cdefun) def-form) (grindfn prog prog-form) (grindfn (comment remob **array *fexpr *expr *lexpr special unspecial) comment-form) (grindfn (member memq map maplist mapcar mapcon mapcan mapc assq assoc sassq sassoc getl) mem-form) (grindfn setq setq-form) (grindfn csetq setq-form) (predict nil) ;;;the following default formats are relevant only to grinding files. however , they appear here since the format fns are not defined in gfile and gfn is not loaded until after gfile . ;;default formats (pagewidth 120. 70. 1. 49.) (topwidth 110.) (merge t) (fill t) (user-paging nil) ;;;read the user's start_up.grind [Multics] or grind (init) [ITS] file. (cond ((status feature its) (prog (form ^w h l) ;loader for grind (init) file (setq h (list nil) l (crunit)) (apply 'crunit (list 'dsk (status udir))) (cond ((cond ((get 'uprobe 'fsubr) (cond ((uprobe grind /(init/)) (uread grind /(init/)) t) (t (go dn1)))) ((errset (uread grind /(init/)) nil))) (terpri) (princ '/;loading/ grind/ /(init/)/ dsk/ ) (princ (cadr (crunit))) (setq ^q t)) (t (go done))) init (cond ((and ^q (not (eq h (setq form (read h))))) (eval form) (go init))) done (apply 'crunit l) dn1 (gctwa) (return '*)) ) (t (errset (load (list (status udir) ;loader for start_up.grind file 'start_up 'grind)) nil)))
null
https://raw.githubusercontent.com/dancrossnyc/multics/dc291689edf955c660e57236da694630e2217151/library_dir_dir/system_library_unbundled/source/bound_lisp_library_.s.archive/lisp_gfn_.lisp
lisp
************************************************************** * * * * ************************************************************** ************************************************************** ************************************************************** ****** this is a read-only file! (all writes reserved) ******* ************************************************************** grindreadtble and gtab/|, and very little else. / ; user - paging ? ^d macro unbnd - vrbl form rem/;/;) temporary for Multics loading/ grindef/ ) *user-paging some initializations ^l made noticeable. the grindreadtable is tailored for ;grind. no cr are inserted by lisp when print exceeds linel. standard readmacroinveser for quote debugging break for grind. gbreak restricted to interpretive version. break transparent to chrct properties from any atom on the obarray. ) /;) ) /;) /;?) (grindef <atoms>) grinds the properties of the atoms listed on (additional properties) <atoms>) grinds the additional properties as well. flag for fn being traced traced))) needed in case there are value properties grindef only desired properties. terpri's placed here to avoid terpri'ing when no properties. lambda -> defun exit from do when no more properties look for more atoms to do. assigning special formats (fn1 fn2 ...)) like putprop read macros eg (readmacro quote /' [optional]) where optional means macro cons not list macro-char = atom or list of ascii values. macro must have arg to execute inverse predefined formats format for lambda's prohibits form3 if args do not fit on line. prohibits form3 if args do not fit on line. prohibits form3 if args do not fit on line. grinds l with args outputed as list. standard form committed to at least standard form prediction in special form computed to compare to p. setq form setq-predict causes throw when variable name is very long. therefore, it is not used all the time but only inside setq-form. returns number of lines to print args as name-value pairs. space for ( and <space preceding variable>. and <space preceding value>. format control (predict) <=> (predict t) => super-careful sprint considering all formats. (predict nil) => less careful but quicker. preceding user read macros. make char '-like readmacro. will be null only if char is single args prop for user - level tj6 fns . (fill) <=> (fill t) => spaces gobbled in ; comments. (fill nil) => spaces not gobbled. triple semi comments are never filled but are retyped exactly (merge) <=> (merge t) => adjoining ; and ;; comments are merged. (merge nil) => adjoining comments not merged. ... are never merged. (user-paging) <=> (user-paging t) grind does not insert any formfeeds, but preserves paging of user's file. (user-paging nil) => grind inserts avoid s-expr pretty-printed over page boundary. ignores users paging. paging of user's file. args prop for user - level tj6 fns . user defined formats remsemi switch t for grinding files, / ;) t ) ( ( rem/;/ ;) ) ) ) ) ; nil for grindef . speeds up grindef . also, prevents possible illegal memory caar on pnames . check for any ;;'s /;)) at any depth ) (eq (car k) /;/;)))) indents additonal nn spaces. Multics ) chrct set to nn chrct may become negative from prin50com. some indentation is necessary l is ground as line if tp = 'line, as a block if tp = 'block or as a function followed by a list of arguments if l = 'list, or normally if tp = 'code. cr with line of outstanding single semi comment printed, if any. grindlinct = lines remaining on page. pprin the car of l, then pops l. no-op if l is already nil. process initial semi-colon comment, if any, then try again. pretty-print c(car l) in desired format. if l is not yet nil, output a space. return popped l. local functions pretty print over whole width sprint formats s2 s3) s3) expression l to be sprinted in space n with m unbalanced "/)" hanging. p is /;? nil) This is an explicit check for QUOTE. The alternative is to use the standard grindmacro To use your own personal readmacro for quote, setq grind-standard-quote to nil. if a ;; comnt, force multi-line catch exited if space insufficient. p = # of lines to sprint l in standard format. exit if miser more efficient than standard in no-predict mode, use miser format on all non-fn-lists. committed to standard format. skip form3 is predict=nil. efficient to grind l form3 or form2 next prints closing paren if done. exception of tags which are unindented /;? (indent-to nn)) ;if previous line a ;; comment, then do not print closing paren on same line as comment. prints closing "/)" if done l printed as text with indent n. non-atomic elements occuring in block too large for the line are sprinted. this occurs in the variable list of a thprog. new line prediction functions list of s expression one under the next in space n s expression in space n. less costly than sprint insufficient space, throws. indent=spaces indented to margin of number of lines approx by dividing size of l by block width. )) default formats "quote" is explicitly checked, and the inverse macro function ignored if this flag is non-nil. To have your own macro for quote take effect, set grind-standard-quote to nil. Still ned to define the standard macro the following default formats are relevant only to grinding files. default formats read the user's start_up.grind [Multics] or grind (init) [ITS] file. loader for grind (init) file loading/ grind/ /(init/)/ dsk/ ) loader for start_up.grind file
* Copyright , ( C ) Massachusetts Institute of Technology , 1982 * * * * * * * * * * * * S - expression formatter ( grindef ) * * * * * * * * * * ( c ) Copyright 1974 Massachusetts Institute of Technology * * This version of Grind works in both ITS and Multics Maclisp copied from ( ) . gfn - fns for pretty - printing functions and S - expressions in core . when compiled , uses about 2300.instructions , 950 . list cells , 320 . fixnum cells , and 160 . symbols . remgrind applied therein will reclaim about 300 . list cells , the array space of (declare (array* (notype (gtab/| 128.))) (noargs t) (special merge readtable grindreadtable remsemi grindpredict grindproperties grindef predict grindfn grindmacro programspace topwidth arg linel pagewidth gap comspace fill nomerge comnt prog? n m l h grind-standard-quote sgploses) (*expr form topwidth programspace pagewidth comspace (*fexpr trace slashify unslashify grindfn grindmacro unreadmacro readmacro grindef) (*lexpr merge predict user-paging fill testl) (mapex t) (genprefix /|gr) (fixnum nn mm (prog-predict notype fixnum fixnum) (block-predict notype fixnum fixnum) (setq-predict notype fixnum fixnum) (panmax notype fixnum fixnum) (maxpan notype fixnum) (gflatsize))) (defun macex macro (x) (list 'defun (cadr x) 'macro (caddr x) (eval (cadddr x)))) (defun ifoio macro (x) (cond ((not (status feature newio)) (cadr x)) ('(comment ifoio not taken)))) (defun ifnio macro (x) (cond ((status feature newio) (cadr x)) ('(comment ifnio not taken)))) (macex newlineseq (x) (cond ((status feature Multics) ''(list (ascii 12))) (t ''(list (ascii 15)(ascii 12))))) (macex version (x) (subst (maknam (nconc (newlineseq) (explodec (cond ((status feature newio) (caddr (names infile))) ((cadr (status uread))))) (newlineseq))) 'version ''(iog nil (princ 'version) (ascii 0)))) (ifnio (defun newlinel macro (x) (subst (cadr x) 'nn '(setq linel nn)))) (ifoio (defun newlinel (nn) (setq chrct (+ chrct (- nn linel))) (setq linel nn))) (ifoio (defun grchrct macro (x) 'chrct)) (ifnio (defun macro set-linel (x) '(setq linel (linel (and outfiles (car outfiles)))))) (ifoio (defun macro set-linel (x) '(comment linel))) (version) (and (not (boundp 'grind-use-original-readtable)) (setq grind-use-original-readtable t)) (and (or (not (boundp 'grindreadtable)) (null grindreadtable)) 'splicing (setq grindreadtable (setq sgploses (setq grind-standard-quote t))) (setq remsemi nil m 0. grindlinct 8. grindef nil global-lincnt 59.) (setq grindproperties '(expr fexpr value macro datum cexpr)) (and (status sstatus feature) (sstatus feature grindef)) (array gtab/| t 128.)) (defun gbreak fexpr (x) (prog (chrct* ^r) (setq chrct* (grchrct)) (apply 'break (cond ((null x) '(grind t)) ((list x t)))) (terpri) a (cond ((eq chrct* (grchrct))) ((princ '/ ) (go a))) (return t)))) (setq gbreak t) rem function - note : to be complete , remgrind should remprop all grindfn , grindmacro and * ( expr macro value grindpredict ) comment - form (defun remsubr (x) (remprop x 'subr)) (defun remfsubr (x) (remprop x 'fsubr)) (defun remlsubr (x) (remprop x 'lsubr)) (defun remgrind fexpr nil (lispgrind) (cond ((status sstatus nofeature) (sstatus nofeature grind) (sstatus nofeature grindef))) (cond ((null (get 'conniver 'array)) (remsubr 'grindexmac) (remsubr 'grindatmac) (remsubr 'grindcolmac) (remsubr 'grindcommac) (remsubr 'grindseparator) (remsubr 'grindnxtchr))) (remfsubr 'grind) (remfsubr 'grind0) (remfsubr 'grindef) (remsubr 'turpri) (remlsubr 'fill) (remlsubr 'user-paging) (remlsubr 'merge) (remlsubr 'testl) (remlsubr 'predict) (remfsubr 'slashify) (remfsubr 'unslashify) (remfsubr 'unformat) (remfsubr 'grindmacro) (remfsubr 'grindfn) (remfsubr 'readmacro) (remfsubr 'unreadmacro) (remfsubr 'readmacroinverse) (remsubr 'slashify1) (remsubr 'unslashify1) (remsubr 'programspace) (remsubr 'grindmacrocheck) (remsubr '?grindmacro) (remsubr 'comment-form) (remsubr 'pagewidth) (remsubr 'comspace) (remsubr 'lispgrind) (remsubr 'cnvrgrind) (remsubr 'page) (remsubr 'topwidth) (ifnio (remsubr 'newlinel)) (ifnio (remsubr 'grchrct)) (remsubr 'tj6) (remsubr 'prin50com) (remsubr 'prinallcmnt) (remsubr 'semi-comment) (remsubr 'putgrind) (remsubr 'lambda-form) (remsubr 'prog-form) (remsubr 'if-form) (remsubr 'def-form) (remsubr 'coment-form) (remsubr 'block-form) (remsubr 'mem-form) (remsubr 'setq-form) (remsubr 'setq-predict) (remsubr 'remsem1) (remsubr 'remsemi) (remsubr 'popl) (remsubr 'semi?) (remsubr 'semisemi?) (remsubr 'indent) (remsubr 'indent-to) (remsubr 'pprin) (remsubr 'form) (remsubr 'sprint) (remsubr 'grind-unbnd-vrbl) (remsubr 'sprinter) (remsubr 'sprint1) (remsubr 'grindargs) (remsubr 'done?) (remsubr 'gblock) (remsubr 'gprin1) (remsubr 'maxpan) (remsubr 'panmax) (remsubr 'prog-predict) (remsubr 'block-predict) (remsubr 'gflatsize) (remsubr 'flatdata) (remsubr 'grindslew) (remsubr 'remlsubr) (remfsubr 'remgrind) (remsubr 'remfsubr) (remsubr 'remsubr) ((lambda (nn) (do mm 0 (1+ mm) (= mm nn) (mapc '(lambda (x) (cond ((getl x '(grindfn grindpredict grindmacro)) (remprop x 'grindfn) (remprop x 'grindpredict) (remprop x 'grindmacro)))) ((lambda (x) (cond ((and x (atom x)) (ncons x)) (x))) (obarray mm)) ))) (cadr (arraydims 'obarray))) (makunbound 'merge) (makunbound 'grindpredict ) (makunbound 'predict) (makunbound 'grindfn) (makunbound 'grindmacro) (makunbound 'programspace) (makunbound 'topwidth) (makunbound 'user-paging) (makunbound 'pagewidth) (makunbound 'comspace) (makunbound 'prog?) (makunbound 'comnt) (makunbound 'cnvrgrindflag) (makunbound 'remsemi) (makunbound 'grindlinct) (makunbound 'global-lincnt) (makunbound 'grindproperties) (makunbound 'grindef) (makunbound 'grindreadtable) (makunbound 'grind-standard-quote) (makunbound 'grind-use-original-readtable) (*rearray 'gtab/|) (gctwa)) (set-linel) " grindproperties " . ( (or cnvrgrindflag (cnvrgrind)))) (setq props grindproperties) a (cond ((null atoms) (return (ascii 0.)))) (setq fn (car atoms) atoms (cdr atoms)) (cond ((atom fn)) ((setq props (append fn props)) (go a))) (cond ((setq traced (and (cond ((status sstatus feature) (status feature trace)) ((get 'trace 'fexpr))) (terpri) (terpri) (do ((plist (cdr fn) (cddr plist)) (ind 'value (car plist)) (prop (and (boundp fn) (symeval fn)) (cadr plist)) (nil) ignore first fn property if traced (setq traced nil) (go b)) ((eq ind 'value) (cond ((not valueless) (terpri) (terpri) (sprint (list 'setq fn (list 'quote prop)) linel 0.))) (go b))) (terpri) (sprint (cons (car prop) (cons fn (cdr prop))) linel 0.)) (eq (car prop) 'lambda)) (sprint (cons 'defun (cons fn (cond ((eq ind 'expr) (cdr prop)) ((cons ind (cdr prop)))))) linel 0.)) ((eq ind 'cexpr) (sprint (cons 'cdefun (cons fn prop)) linel 0.)) ((sprint (list 'defprop fn prop ind) linel 0.))) )) ( unformat fn1 fn2 ... ) or ( unformat (mapc '(lambda (x) (remprop x 'grindfn) (remprop x 'grindmacro) (remprop x 'grindpredict)) x)) eg ( grindmacro quote / ' ) (putgrind (car y) (cdr y) 'grindmacro)) eg ( grindfn ( prog thprog ) prog - form ) (putgrind (car y) (cdr y) 'grindfn)) (cond ((atom fn) (setq prop (cond ((atom (car prop)) (and (get (car prop) 'grindpredict) (putprop fn (get (car prop) 'grindpredict) 'grindpredict)) (car prop)) (t (and (eq (caar prop) 'readmacroinverse) (putprop fn (get 'readmacroinverse 'grindpredict) 'grindpredict)) (cons 'lambda (cons nil prop))))) (putprop fn prop ind)) ((mapc '(lambda (x) (putgrind x prop ind)) fn)))) (cons (cadr y) (cddr y)))) 'grindmacro)) (defun unreadmacro fexpr (y) (remprop y 'grindmacro)) (defun ?grindmacro (x) (prog (y) (cond ((and cnvrgrindflag (setq y (get x 'grindmacro))) (return (list (cddr (caddr y))))) (t (return nil))))) (defun grindmacrocheck (x l) (cond ((and (equal x '((t))) (cdr l))) ((and (equal x '(nil)) (= (length l) 2.))) ((and (equal x '((cnvr-optional))) (cdr l))))) ( fn - print l > . (prog (sprarg) (setq sprarg (cond ((null (cdr x)) (cadr l)) ((eq (cadr x) t) (cdr l)) ((= (length (cdr l)) 1.) (cond ((null (cadr l)) (tyo 32.) (return t)) (t (cadr l)))) (t (cdr l)))) (cond ((sprint1 sprarg (grchrct) m) (prin1 sprarg))) (return t)) (t (return nil))))) (defun lambda-form nil (form 'block)) (defun prog-form nil format for thprog 's and prog 's (setq prog? t) (arg))) (form 'block)) (defun if-form nil (setq prog? t) (form 'line) (cond ((atom (testl)) (form 'line))) (setq form (cond ((and predict (< (grchrct) (gflatsize (testl)))) 'form2) (arg))) (form 'list)) (defun def-form nil (prog nil (cond ((eq (car l) 'cdefun) (setq prog? t))) (form 'line) (form 'line) go (cond ((memq (testl) '(expr fexpr macro thnoassert cexpr)) (form 'line) (go go))) (setq form (arg))) (return (form 'block)))) (defun block-form nil (gblock (grchrct))) (defun mem-form nil (prog (p gm) quoted second arg ground as block (remsemi) (catch (and (setq p (panmax (car l) (grchrct) 0.)) (cond ((< (panmax (car l) n 0.) p)) ((setq n (grchrct)))))) (cond ((sprint1 (car l) n 0.) (prin1 (car l)))) a (cond ((null (cdr l)) (setq l (error 'mem-form l 'fail-act)) (go a))) (popl) go (indent-to n) (setq m (1+ m)) (cond ((eq (caar l) 'quote) (princ '/') (cond ((pprin (cadar l) 'block)) ((prin1 (cadar l))))) ((setq gm (sprint1 (car l) n m)) (cond ((and cnvrgrindflag (grindmacrocheck gm l)) (princ '/./ ) (sprint1 l (- n 2.) m) (setq l nil) (return nil)) (t (prin1 (car l)))))) (popl) (cond (l (go go)) ((return nil))))) (defun setq-form nil (cond ((catch (prog (mm) (defprop setq (setq-predict l n m) (panmax l (prog2 nil (1+ n) (setq n arg)) (return t)) (form 'line) d (or l (return nil)) (indent-to n) (form 'line) (form 'code) (remsemi) (go d))) n = space for name <space> value . 2 = (and (semi? (car l)) (go a)) nn = space for value . 2 = space for ) (setq l (error 'setq-predict l 'wrng-no-args)) (go b))) (setq l (cdr l)) (and (semi? (car l)) (go b)) (setq mm (+ mm (panmax (car l) nn 0.))) (go a))) the following format fns are used only in grinding files . however , they may appear in a grind ( init ) file which is loaded by gfn . hence , they are defined in gfn to avoid undf error . ( eg ( slashify $ ) . preserve slashes (defun unslashify fexpr (chars) (mapc 'unslashify1 chars)) ((lambda (readtable) (or (setq char (error 'slashify char 'wrng-type-arg))) (setsyntax char 'macro (subst char 'char '(lambda nil (list 'char (read))))) (apply 'readmacro (list char char))) grindreadtable)) (defun unslashify1 (char) ((lambda (readtable) (or (null (getchar char 2.)) (setq char (error 'unslashify char 'wrng-type-arg))) (setsyntax char 'macro nil) (apply 'unreadmacro (list char))) grindreadtable)) (defun programspace (x) (setq programspace (newlinel x)) (setq comspace (- pagewidth gap programspace))) (defun pagewidth (w x y z) (setq pagewidth w) (setq gap y) (setq programspace x) (setq comspace z)) (defun comspace (x) (setq comspace x) (setq programspace (- pagewidth gap comspace))) (defun page nil (tyo 12.) (setq grindlinct global-lincnt)) inuser 's original form . formfeed every 59 lines . attempts to (defun topwidth (x) (setq topwidth x)) (defun remsemi nil (prog (retval) loop (cond ((remsem1) (setq retval t)) ((return retval))) (go loop))) (defun popl nil (setq l (cdr l)) (remsemi) l) (defun semisemi? (k) ((atom k) nil) (cond ((minusp (setq nn (- (grchrct) nn))) (error 'indent/ beyond/ linel? nn 'fail-act) (terpri)) ((indent-to nn)))) ((lambda (nct tab) (declare (fixnum nct tab)) (setq nct linel))) (setq tab (+ nct (- (stat-tab)) position as a result of first tab . tabs do not move 8 , but to nearest multiple of 8 (setq nct tab) (cond ((< nn nct) (grindslew (// (setq nct (- nct nn)) (stat-tab)) 9.) (grindslew (\ nct (stat-tab)) 32.)))))))) (grchrct) 0.)) (defun grindslew (nn x) (do mm nn (1- mm) (zerop mm) (tyo x))) (defun pprin (l tp) (cond ((and cnvrgrindflag (atom l) (?grindmacro l)) nil) ((eq tp 'line) (or (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro))) (princ '/))))) ((eq tp 'list) (or (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro))) (progn (princ '/() (gblock (- (grchrct) 1. (gflatsize (car l)))) (princ '/))))) ((eq tp 'code) (sprint1 l (grchrct) m) t))) (defun turpri nil ((1- grindlinct))))) (ifnio (defun grchrct nil (- linel (charpos (and outfiles (car outfiles)))))) (defun testl args (prog (k nargs) (setq k l nargs (cond ((= 0. args) 0.) ((arg 1.)))) a (cond ((null k) (return nil)) ((semi? (car k)) (setq k (cdr k)) (go a)) ((= 0. nargs) (return (cond ((= 2. args) k) (t (car k))))) ((setq nargs (1- nargs)) (setq k (cdr k)) (go a))))) (setq l (cdr l))) ((and cnvrgrindflag (grindmacrocheck (?grindmacro (car l)) l)) (princ '/./ ) (gprin1 l (- n 2.)) (setq l nil form nil)) (t (prin1 (car l)) (and (cdr l) (tyo 32.)) (prog nil (set-linel) (turpri) (turpri) (sprint l linel 0.) (turpri) (return '*))) (defun sprint (l n m) (fillarray 'gtab/| '(nil)) (sprint1 l n m)) = ( s1 form2 = ( s1 s2 form3 = ( s1 s2 ( sprint1 last ) ) number lines to sprint1 as form2 (indent-to n) (and (atom l) (cond (cnvrgrindflag) ((setq gm (?grindmacro l)) (return gm)) (t (prin1 l) (return nil)))) (princ '/') (and (setq gm (sprint1 (cadr l) (grchrct) m)) cnvrgrindflag (cond ((grindmacrocheck gm (cdr l)) (princ '/./ ) (sprint1 (cdr l) (- (grchrct) 2) m)) (t (prin1 (car l))))) (return nil))) (and (atom (car l)) (setq fn (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro)) (return nil)) ((< (+ m -1. (gflatsize l)) (grchrct)) (return (gprin1 l n)))) (princ '/() (setq n (grchrct)) (setq arg (- n (gflatsize (car l)) 1.)) (and (atom (setq args (cond ((setq grindfn (get fn 'grindfn)) (apply grindfn nil) (and (numberp form) (setq n form) (go b)) (and (null l) (princ '/)) (return nil)) l) ((cdr l))))) (go b)) (and (grindfn (or (eq form 'form2) (> (maxpan args (grchrct)) p) (setq n (grchrct)))) ((prog nil (catch (setq l can not be fit in chrct is it more (< (maxpan (last l) (- (grchrct) (- (gflatsize l) (gflatsize (last l))))) p)))) a (cond ((setq gm (gprin1 (car l) n)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- n 2.)) (setq l nil) (go b1)) (t (prin1 (car l)))))) (tyo 32.) (and (cdr (setq l (cdr l))) form3? (go a)) b1 (setq n (grchrct))))))) b (grindargs l n m))) elements of l are ground one under the (setq sprarg1 (cond ((and cnvrgrindflag (eq (car l) '/"aux/")) (+ nn 6.)) ((and prog? (car l) (or (atom (car l)) (and cnvrgrindflag (eq (caar l) ':)))) 5 (setq sprarg2 (cond ((null (cdr l)) (1+ mm)) ((atom (cdr l)) (+ 4. mm (gflatsize (cdr l)))) (0.))) (cond ((setq gm (sprint1 (car l) sprarg1 sprarg2)) (cond ((grindmacrocheck gm l) (princ '/./ ) (sprint1 l (- sprarg1 2.) sprarg2) (setq l nil) (go a)) (t (prin1 (car l)))))) (setq l (cdr l)) (go a))) (defun done? (nn) (cond ((atom l) (prog (gm) (and (remsemi) (or l (return nil))) a (cond ((setq gm (gprin1 (car l) n)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- n 2.)) (return (setq l nil))) (t (prin1 (car l)))))) (or (popl) (return nil)) (cond ((< (gflatsize (car l)) (- (grchrct) 2. m)) (tyo 32.) (go a)) (princ '/./ ) (sprint1 l (- n 2.) m) (return (setq l nil))) (t (prin1 (car l)))))) (or (popl) (return nil)))) (go a))) prin1 with grindmacro feature . (cond ((and cnvrgrindflag (atom l) (?grindmacro l))) ((atom l) (prin1 l) nil) ((prog (gm) (remsemi) (and (atom (car l)) ((lambda (x) (and x (apply x nil))) (get (car l) 'grindmacro)) (return nil)) (princ '/() a (cond ((setq gm (gprin1 (car l) nn)) (cond ((grindmacrocheck gm l) (princ '/./ ) (gprin1 l (- nn 2.)) (setq l nil) (go a1)) (t (prin1 (car l)))))) (popl) a1 (and (done? nn) (return nil)) (tyo 32.) (go a))))) (defun maxpan (l n) estimates number of lines to sprint1 (+ g (panmax (car l) n (cond ((null (setq l (cdr l))) (1+ m)) ((atom l) (+ m 4. (gflatsize l))) (0.))))) (and (atom l) (return g)) (go a))) (defun panmax (l n m) estimates number of lines to sprint1 an (maxpan l (sub1 n))) as it always chooses form2 . if (defun prog-predict (l n m) ((lambda (nn) (+ (block-predict (cadr l) nn 1.) (maxpan (cddr l) nn))) (- n 2. (gflatsize (car l))))) (defprop lambda-form (prog-predict l n m) grindpredict) (defprop prog-form (prog-predict l n m) grindpredict) block . throw if remaining space . (defprop comment-form (block-predict l n (+ (gflatsize (car l)) 2.)) grindpredict) (defprop block-form (block-predict l n 1.) grindpredict) (defprop readmacroinverse (panmax (cadr l) (1- n) m) grindpredict) (defun gflatsize (data) ((lambda (nn bucket) (setq bucket (gtab/| nn)) (cdr (cond ((and bucket (assq data bucket))) (t (car (store (gtab/| nn) (cons (setq data (cons data (flatsize data))) bucket))))))) (\ (maknum data) 127.) nil)) conniver macros (setq cnvrgrindflag nil) (defun cnvrgrind nil ((lambda (readtable) (setsyntax ': 'macro 'grindcolmac) (setsyntax '@ 'macro 'grindatmac) (setsyntax '/, 'macro 'grindcommac) (setsyntax '! 'macro 'grindexmac) (readmacro : :) (readmacro /, /,) (readmacro @ @ t) (readmacro !$ (33. 36.) t) (readmacro !/" (33. 34.) t) (readmacro !@ (33. 64.) t) (readmacro !? (33. 63.) cnvr-optional) (readmacro !/, (33. 44.) cnvr-optional) (readmacro !< (33. 60.) cnvr-optional) (readmacro !> (33. 62.) cnvr-optional) ( 33 . 59 . ) cnvr - optional ) (readmacro !/' (33. 39.) cnvr-optional) (setq cnvrgrindflag t sgploses grind-standard-quote grind-standard-quote nil) 'conniver-macros-learned) grindreadtable)) (defun lispgrind nil ((lambda (readtable) (setsyntax ': 'macro nil) (setsyntax '@ 'macro nil) (setsyntax '/, 'macro nil) (setsyntax '! 'macro nil) (mapc 'unreadmacro (setq cnvrgrindflag nil grind-standard-quote sgploses) 'conniver-macros-forgotten) grindreadtable)) (grindfn (grindfn grindmacro) (form 'line) (form 'block)) (grindfn lambda lambda-form) (grindfn (if-added if-needed if-removed) if-form) (grindfn (defun cdefun) def-form) (grindfn prog prog-form) (grindfn (comment remob **array *fexpr *expr *lexpr special unspecial) comment-form) (grindfn (member memq map maplist mapcar mapcon mapcan mapc assq assoc sassq sassoc getl) mem-form) (grindfn setq setq-form) (grindfn csetq setq-form) (predict nil) however , they appear here since the format fns are not defined in gfile and gfn is not loaded until after gfile . (pagewidth 120. 70. 1. 49.) (topwidth 110.) (merge t) (fill t) (user-paging nil) (cond ((status feature its) (setq h (list nil) l (crunit)) (apply 'crunit (list 'dsk (status udir))) (cond ((cond ((get 'uprobe 'fsubr) (cond ((uprobe grind /(init/)) (uread grind /(init/)) t) (t (go dn1)))) ((errset (uread grind /(init/)) nil))) (terpri) (princ (cadr (crunit))) (setq ^q t)) (t (go done))) init (cond ((and ^q (not (eq h (setq form (read h))))) (eval form) (go init))) done (apply 'crunit l) dn1 (gctwa) (return '*)) ) 'start_up 'grind)) nil)))
0015403ecaaf709584e306cbd1d8614777566c0984f8fbc40064d2169a84782b
docker-in-aws/docker-in-aws
version.clj
(ns swarmpit.version (:require [swarmpit.config :as cfg] [clojure.java.io :as io] [clojure.walk :refer [keywordize-keys]]) (:import (java.util Properties))) (def pom-properties (doto (Properties.) (.load (-> "META-INF/maven/swarmpit/swarmpit/pom.properties" (io/resource) (io/reader))))) (defn info [] {:name "swarmpit" :version (get pom-properties "version") :revision (get pom-properties "revision") :docker {:api (read-string (cfg/config :docker-api)) :engine (cfg/config :docker-engine)}})
null
https://raw.githubusercontent.com/docker-in-aws/docker-in-aws/bfc7e82ac82ea158bfb03445da6aec167b1a14a3/ch16/swarmpit/src/clj/swarmpit/version.clj
clojure
(ns swarmpit.version (:require [swarmpit.config :as cfg] [clojure.java.io :as io] [clojure.walk :refer [keywordize-keys]]) (:import (java.util Properties))) (def pom-properties (doto (Properties.) (.load (-> "META-INF/maven/swarmpit/swarmpit/pom.properties" (io/resource) (io/reader))))) (defn info [] {:name "swarmpit" :version (get pom-properties "version") :revision (get pom-properties "revision") :docker {:api (read-string (cfg/config :docker-api)) :engine (cfg/config :docker-engine)}})
976708be58b3feb79db32bb18bf3abb6b897084f9d68df71fe52a96825208f49
mpdairy/posh
update.cljc
(ns posh.lib.update (:require [posh.lib.util :as util] [posh.lib.datom-matcher :as dm] [posh.lib.pull-analyze :as pa] [posh.lib.q-analyze :as qa] [posh.lib.db :as db])) (defn update-pull [{:keys [dcfg retrieve] :as posh-tree} storage-key] ;;(println "updated pull: " storage-key) (let [[_ poshdb pull-pattern eid] storage-key] (let [analysis (pa/pull-analyze dcfg (cons :patterns retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eid)] (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-pull}) :patterns)))) (defn update-filter-pull [{:keys [dcfg retrieve] :as posh-tree} storage-key] ;;(println "updated filter-pull: " storage-key) (let [[_ poshdb pull-pattern eid] storage-key] (let [analysis (pa/pull-analyze dcfg (concat [:patterns :ref-patterns] retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eid)] (dissoc (merge analysis {:pass-patterns (first (vals (:patterns analysis))) :reload-patterns (:ref-patterns analysis) :reload-fn posh.lib.update/update-filter-pull}) :patterns :ref-patterns)))) (defn update-pull-many [{:keys [dcfg retrieve] :as posh-tree} storage-key] ;;(println "updated pull-many: " storage-key) (let [[_ poshdb pull-pattern eids] storage-key] (let [analysis (pa/pull-many-analyze dcfg (cons :patterns retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eids)] (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-pull-many}) :patterns)))) (declare update-q) (defn update-q-with-dbvarmap [{:keys [dcfg retrieve] :as posh-tree} storage-key] "Returns {:dbvarmap .. :analysis ..}" (let [[_ query args] storage-key retrieve (concat [:results :simple-patterns] (remove #{:patterns} retrieve)) qm (merge {:in '[$]} (qa/query-to-map query)) dbvarmap (qa/make-dbarg-map (:in qm) args) ;; no longer using poshdbs ( vals dbvarmap ) poshdbmap (->> dbvarmap (map (fn [[db-sym poshdb]] {db-sym (db/poshdb->analyze-db posh-tree poshdb)})) (apply merge)) fixed-args (->> (zipmap (:in qm) args) (map (fn [[sym arg]] (or (get poshdbmap sym) arg)))) analysis (qa/q-analyze dcfg retrieve query fixed-args)] {:dbvarmap dbvarmap :analysis (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-q}) :patterns)})) (defn update-q [posh-tree storage-key] ;;(println "updated q: " storage-key) (:analysis (update-q-with-dbvarmap posh-tree storage-key))) (defn reduce-entities [r] (reduce (fn [acc xs] (reduce (fn [acc x] (conj acc x)) acc xs)) #{} r)) (declare update-filter-q) (defn filter-q-transform-analysis [analysis] (dissoc (merge analysis {:pass-patterns [[(reduce-entities (:results analysis))]] :reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-filter-q}) :results :patterns)) (defn update-filter-q [posh-tree storage-key] ;;(println "update-filter-q" storage-key) (filter-q-transform-analysis (:analysis (update-q-with-dbvarmap posh-tree storage-key)))) (defn update-posh-item [posh-tree storage-key] (case (first storage-key) :pull (update-pull posh-tree storage-key) :q (:analysis (update-q posh-tree storage-key)) :filter-pull (update-filter-pull posh-tree storage-key)))
null
https://raw.githubusercontent.com/mpdairy/posh/2347c8505f795ab252dbab2fcdf27eca65a75b58/src/posh/lib/update.cljc
clojure
(println "updated pull: " storage-key) (println "updated filter-pull: " storage-key) (println "updated pull-many: " storage-key) no longer using (println "updated q: " storage-key) (println "update-filter-q" storage-key)
(ns posh.lib.update (:require [posh.lib.util :as util] [posh.lib.datom-matcher :as dm] [posh.lib.pull-analyze :as pa] [posh.lib.q-analyze :as qa] [posh.lib.db :as db])) (defn update-pull [{:keys [dcfg retrieve] :as posh-tree} storage-key] (let [[_ poshdb pull-pattern eid] storage-key] (let [analysis (pa/pull-analyze dcfg (cons :patterns retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eid)] (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-pull}) :patterns)))) (defn update-filter-pull [{:keys [dcfg retrieve] :as posh-tree} storage-key] (let [[_ poshdb pull-pattern eid] storage-key] (let [analysis (pa/pull-analyze dcfg (concat [:patterns :ref-patterns] retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eid)] (dissoc (merge analysis {:pass-patterns (first (vals (:patterns analysis))) :reload-patterns (:ref-patterns analysis) :reload-fn posh.lib.update/update-filter-pull}) :patterns :ref-patterns)))) (defn update-pull-many [{:keys [dcfg retrieve] :as posh-tree} storage-key] (let [[_ poshdb pull-pattern eids] storage-key] (let [analysis (pa/pull-many-analyze dcfg (cons :patterns retrieve) (db/poshdb->analyze-db posh-tree poshdb) pull-pattern eids)] (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-pull-many}) :patterns)))) (declare update-q) (defn update-q-with-dbvarmap [{:keys [dcfg retrieve] :as posh-tree} storage-key] "Returns {:dbvarmap .. :analysis ..}" (let [[_ query args] storage-key retrieve (concat [:results :simple-patterns] (remove #{:patterns} retrieve)) qm (merge {:in '[$]} (qa/query-to-map query)) dbvarmap (qa/make-dbarg-map (:in qm) args) poshdbs ( vals dbvarmap ) poshdbmap (->> dbvarmap (map (fn [[db-sym poshdb]] {db-sym (db/poshdb->analyze-db posh-tree poshdb)})) (apply merge)) fixed-args (->> (zipmap (:in qm) args) (map (fn [[sym arg]] (or (get poshdbmap sym) arg)))) analysis (qa/q-analyze dcfg retrieve query fixed-args)] {:dbvarmap dbvarmap :analysis (dissoc (merge analysis {:reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-q}) :patterns)})) (defn update-q [posh-tree storage-key] (:analysis (update-q-with-dbvarmap posh-tree storage-key))) (defn reduce-entities [r] (reduce (fn [acc xs] (reduce (fn [acc x] (conj acc x)) acc xs)) #{} r)) (declare update-filter-q) (defn filter-q-transform-analysis [analysis] (dissoc (merge analysis {:pass-patterns [[(reduce-entities (:results analysis))]] :reload-patterns (:patterns analysis) :reload-fn posh.lib.update/update-filter-q}) :results :patterns)) (defn update-filter-q [posh-tree storage-key] (filter-q-transform-analysis (:analysis (update-q-with-dbvarmap posh-tree storage-key)))) (defn update-posh-item [posh-tree storage-key] (case (first storage-key) :pull (update-pull posh-tree storage-key) :q (:analysis (update-q posh-tree storage-key)) :filter-pull (update-filter-pull posh-tree storage-key)))
9abd247cec20b7895f28b1393474b7084ff0e3d1ed99d487512ec04099bc8197
microsoft/SLAyer
NSList.ml
Copyright ( c ) Microsoft Corporation . All rights reserved . open NSLib module List = struct include List let cons x xs = x :: xs let tryfind pred lst = try Some(find pred lst) with Not_found -> None let rec no_duplicates = function | [] -> true | x::xs -> if (List.mem x xs) then false else (no_duplicates xs) let rec iteri_aux fn i = function | [] -> () | x::xs -> fn i x; iteri_aux fn (i+1) xs let iteri fn xs = iteri_aux fn 0 xs let fold fn l a = fold_left (fun a x -> fn x a) a l let foldi fn s z = snd (fold (fun x (i,z) -> (i+1, fn i x z)) s (0, z)) let fold2 fn xs ys a = fold_left2 (fun a x y -> fn x y a) a xs ys let fold3 fn = let rec fold3_fn xs ys zs a = match xs, ys, zs with | [], [], [] -> a | x::xs, y::ys, z::zs -> fold3_fn xs ys zs (fn x y z a) | _ -> invalid_arg "List.fold3: expected equal-length lists" in fold3_fn let mapi fn xs = rev (snd (fold (fun x (i,z) -> (i+1, fn i x :: z)) xs (0,[]))) let map3 fn = let rec map3 xs ys zs = match xs, ys, zs with | [], [], [] -> [] | x::xs, y::ys, z::zs -> fn x y z :: map3 xs ys zs | _ -> invalid_arg "List.map3: expected equal-length lists" in map3 let map_append fn xs ys = fold (fun x ys -> fn x :: ys) xs ys let map_to_array fn xs = match xs with | [] -> [||] | hd::tl as xs -> let a = Array.make (List.length xs) (fn hd) in let rec set i = function | [] -> a | hd::tl -> Array.set a i (fn hd); set (i+1) tl in set 1 tl let map_fold fn (xs,z) = fold_right (fun x (ys,z) -> let y, z = fn (x,z) in (y::ys, z) ) xs ([],z) let reduce fn = function | [] -> invalid_arg "List.reduce" | x::xs -> fold fn xs x let rec kfold fn xs k a = match xs with | [] -> k a | x::xs -> fn x (kfold fn xs k) a let rec kfold2 fn xs ys k a = match xs, ys with | [], [] -> k a | x::xs, y::ys -> fn x y (kfold2 fn xs ys k) a | _ -> invalid_arg "List.kfold2: expected equal-length lists" let rec kfold3 fn xs ys zs k a = match xs, ys, zs with | [], [], [] -> k a | x::xs, y::ys, z::zs -> fn x y z (kfold3 fn xs ys zs k) a | _ -> invalid_arg "List.kfold3: expected equal-length lists" let rec fold_pairs fn xs a = match xs with | [] -> a | x::xs -> fold (fn x) xs (fold_pairs fn xs a) let rec kfold_pairs fn k xs a = match xs with | [] -> k a | x::xs -> kfold (fn x) xs (kfold_pairs fn k xs) a let rec fold_product fn xs ys a = match xs with | [] -> a | x::xs -> fold (fn x) ys (fold_product fn xs ys a) let rec kfold_product xs ys fn k a = match xs with | [] -> k a | x::xs -> kfold (fn x) ys (kfold_product xs ys fn k) a let rec prefixes = function | [] -> [[]] | x :: xs -> [] :: map (fun l -> x :: l) (prefixes xs) let rec infixes = function | [] -> [[]] | x :: xs -> fold (fun l z -> (x :: l) :: z) (prefixes xs) (infixes xs) let rec powerlist = function | [] -> [[]] | x :: xs -> let pow_xs = powerlist xs in fold (fun l z -> (x :: l) :: z) pow_xs pow_xs let combs fn xs ys = let rec loop1 zs xs = function | [] -> [[]] | y :: ys -> let rec loop2 zs a = function | [] -> a | x :: xs -> loop2 (x :: zs) (fold (fun comb a -> (fn x y comb) :: a) (loop1 zs xs ys) a) xs in loop2 [] (loop2 [] [] zs) xs in loop1 [] xs ys let rec permutations fn xs = let rec loop zs xs ps = match xs with | [] -> ps | x :: xs -> loop (x :: zs) xs (List.fold_left (fn x) ps (permutations fn (zs @ xs))) in if xs = [] then [[]] else loop [] xs [] let fin_funs xs ys = List.map (List.combine xs) (permutations (fun x ps p -> (x :: p) :: ps) ys) let map_partial fn xs = List.fold_right (fun x maybe_ys -> match maybe_ys with | None -> None | Some ys -> match fn x with | None -> None | Some y -> Some (y::ys) ) xs (Some []) let classify fn xs = let rec classify_one x = function | xs :: xss when fn x (List.hd xs) -> (x :: xs) :: xss | xs :: xss -> xs :: (classify_one x xss) | [] -> [[x]] in fold classify_one xs [] let divide fn ys = let rec divide_ xss ys = match xss, ys with | xs :: xss, y :: ys when fn y (List.hd xs) -> divide_ ((y :: xs) :: xss) ys | xss, y :: ys -> divide_ ([y] :: xss) ys | xss, [] -> List.rev_map List.rev xss in divide_ [] ys let rec range i j = if i <= j then i::(range (i+1) j) else [] let rec replicate n x = if n <= 0 then [] else x :: replicate (n-1) x let inter xs ys = List.filter (fun x -> List.mem x ys) xs let union xs ys = fold (fun x us -> if List.mem x us then us else x::us) xs ys let diff xs rs = find_all (fun x -> not (List.mem x rs)) xs let rec take_ p ys xs = match xs with | x :: xs -> if p x then (x, rev_append ys xs) else take_ p (x :: ys) xs | [] -> raise Not_found let take p xs = take_ p [] xs let exists_unique p xs = let module M = struct exception Found end in try fold (fun x found -> if found then not (p x) || raise M.Found else p x ) xs false with M.Found -> false let rec equal fn xs ys = if xs == ys then true else match xs,ys with | [], [] -> true | [], _::_ | _::_, [] -> false | x::xs, y::ys -> fn x y && equal fn xs ys let rec compare fn xs ys = if xs == ys then 0 else match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 fn (compare fn) (x,xs) (y,ys) let rec compare_lex fn xs ys = if xs == ys then 0 else match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 (compare_lex fn) fn (xs,x) (ys,y) let compare_sorted cmp xs ys = if xs == ys then 0 else let rec loop xs ys = match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 cmp loop (x,xs) (y,ys) in loop (fast_sort cmp xs) (fast_sort cmp ys) let fmt sep fn ff xs = let rec aux ff = function | [] -> () | [x] -> (try fn ff x with Nothing_to_fmt -> ()) | x::xs -> try Format.fprintf ff "%a%( fmt %)%a" fn x sep aux xs with Nothing_to_fmt -> aux ff xs in aux ff xs let fmtt sep ff xs = let rec aux ff = function | [] -> () | [x] -> (try x ff with Nothing_to_fmt -> ()) | x::xs -> try Format.fprintf ff "%t%( fmt %)%a" x sep aux xs with Nothing_to_fmt -> aux ff xs in aux ff xs module Set (Elt: sig type t end) = struct type elt = Elt.t type t = elt list let empty = [] let is_empty s = s = [] let add e s = e :: s let singleton e = [e] let iter = iter let map = map let fold = fold let map_fold = map_fold let kfold fn s z = kfold s fn z let for_all = for_all let exists = exists let exists_unique = exists_unique let filter = filter let cardinal = length let of_list s = s let to_list s = s let choose = function x::_ -> x | [] -> raise Not_found let union = rev_append let diff = diff end module SetOrd (Elt: OrderedType) = struct include Set(Elt) let equal x y = equal Elt.equal x y let compare x y = compare Elt.compare x y let rec remove x = function | [] -> [] | y::ys when Elt.equal x y -> ys | y::ys -> y :: remove x ys let diff_inter_diff xs ys = let xs = fast_sort Elt.compare xs and ys = fast_sort Elt.compare ys in let rec did xxs yys = match xxs, yys with | [], ys -> ([], [], ys) | xs, [] -> (xs, [], []) | x::xs, y::ys -> let o = Elt.compare x y in if o = 0 then let xs_ys, i, ys_xs = did xs ys in (xs_ys, x::i, ys_xs) else if o < 0 then let xs_yys, i, yys_xs = did xs yys in (x::xs_yys, i, yys_xs) else let xxs_ys, i, ys_xxs = did xxs ys in (xxs_ys, i, y::ys_xxs) in did xs ys end end
null
https://raw.githubusercontent.com/microsoft/SLAyer/6f46f6999c18f415bc368b43b5ba3eb54f0b1c04/src/Library/NSList.ml
ocaml
Copyright ( c ) Microsoft Corporation . All rights reserved . open NSLib module List = struct include List let cons x xs = x :: xs let tryfind pred lst = try Some(find pred lst) with Not_found -> None let rec no_duplicates = function | [] -> true | x::xs -> if (List.mem x xs) then false else (no_duplicates xs) let rec iteri_aux fn i = function | [] -> () | x::xs -> fn i x; iteri_aux fn (i+1) xs let iteri fn xs = iteri_aux fn 0 xs let fold fn l a = fold_left (fun a x -> fn x a) a l let foldi fn s z = snd (fold (fun x (i,z) -> (i+1, fn i x z)) s (0, z)) let fold2 fn xs ys a = fold_left2 (fun a x y -> fn x y a) a xs ys let fold3 fn = let rec fold3_fn xs ys zs a = match xs, ys, zs with | [], [], [] -> a | x::xs, y::ys, z::zs -> fold3_fn xs ys zs (fn x y z a) | _ -> invalid_arg "List.fold3: expected equal-length lists" in fold3_fn let mapi fn xs = rev (snd (fold (fun x (i,z) -> (i+1, fn i x :: z)) xs (0,[]))) let map3 fn = let rec map3 xs ys zs = match xs, ys, zs with | [], [], [] -> [] | x::xs, y::ys, z::zs -> fn x y z :: map3 xs ys zs | _ -> invalid_arg "List.map3: expected equal-length lists" in map3 let map_append fn xs ys = fold (fun x ys -> fn x :: ys) xs ys let map_to_array fn xs = match xs with | [] -> [||] | hd::tl as xs -> let a = Array.make (List.length xs) (fn hd) in let rec set i = function | [] -> a | hd::tl -> Array.set a i (fn hd); set (i+1) tl in set 1 tl let map_fold fn (xs,z) = fold_right (fun x (ys,z) -> let y, z = fn (x,z) in (y::ys, z) ) xs ([],z) let reduce fn = function | [] -> invalid_arg "List.reduce" | x::xs -> fold fn xs x let rec kfold fn xs k a = match xs with | [] -> k a | x::xs -> fn x (kfold fn xs k) a let rec kfold2 fn xs ys k a = match xs, ys with | [], [] -> k a | x::xs, y::ys -> fn x y (kfold2 fn xs ys k) a | _ -> invalid_arg "List.kfold2: expected equal-length lists" let rec kfold3 fn xs ys zs k a = match xs, ys, zs with | [], [], [] -> k a | x::xs, y::ys, z::zs -> fn x y z (kfold3 fn xs ys zs k) a | _ -> invalid_arg "List.kfold3: expected equal-length lists" let rec fold_pairs fn xs a = match xs with | [] -> a | x::xs -> fold (fn x) xs (fold_pairs fn xs a) let rec kfold_pairs fn k xs a = match xs with | [] -> k a | x::xs -> kfold (fn x) xs (kfold_pairs fn k xs) a let rec fold_product fn xs ys a = match xs with | [] -> a | x::xs -> fold (fn x) ys (fold_product fn xs ys a) let rec kfold_product xs ys fn k a = match xs with | [] -> k a | x::xs -> kfold (fn x) ys (kfold_product xs ys fn k) a let rec prefixes = function | [] -> [[]] | x :: xs -> [] :: map (fun l -> x :: l) (prefixes xs) let rec infixes = function | [] -> [[]] | x :: xs -> fold (fun l z -> (x :: l) :: z) (prefixes xs) (infixes xs) let rec powerlist = function | [] -> [[]] | x :: xs -> let pow_xs = powerlist xs in fold (fun l z -> (x :: l) :: z) pow_xs pow_xs let combs fn xs ys = let rec loop1 zs xs = function | [] -> [[]] | y :: ys -> let rec loop2 zs a = function | [] -> a | x :: xs -> loop2 (x :: zs) (fold (fun comb a -> (fn x y comb) :: a) (loop1 zs xs ys) a) xs in loop2 [] (loop2 [] [] zs) xs in loop1 [] xs ys let rec permutations fn xs = let rec loop zs xs ps = match xs with | [] -> ps | x :: xs -> loop (x :: zs) xs (List.fold_left (fn x) ps (permutations fn (zs @ xs))) in if xs = [] then [[]] else loop [] xs [] let fin_funs xs ys = List.map (List.combine xs) (permutations (fun x ps p -> (x :: p) :: ps) ys) let map_partial fn xs = List.fold_right (fun x maybe_ys -> match maybe_ys with | None -> None | Some ys -> match fn x with | None -> None | Some y -> Some (y::ys) ) xs (Some []) let classify fn xs = let rec classify_one x = function | xs :: xss when fn x (List.hd xs) -> (x :: xs) :: xss | xs :: xss -> xs :: (classify_one x xss) | [] -> [[x]] in fold classify_one xs [] let divide fn ys = let rec divide_ xss ys = match xss, ys with | xs :: xss, y :: ys when fn y (List.hd xs) -> divide_ ((y :: xs) :: xss) ys | xss, y :: ys -> divide_ ([y] :: xss) ys | xss, [] -> List.rev_map List.rev xss in divide_ [] ys let rec range i j = if i <= j then i::(range (i+1) j) else [] let rec replicate n x = if n <= 0 then [] else x :: replicate (n-1) x let inter xs ys = List.filter (fun x -> List.mem x ys) xs let union xs ys = fold (fun x us -> if List.mem x us then us else x::us) xs ys let diff xs rs = find_all (fun x -> not (List.mem x rs)) xs let rec take_ p ys xs = match xs with | x :: xs -> if p x then (x, rev_append ys xs) else take_ p (x :: ys) xs | [] -> raise Not_found let take p xs = take_ p [] xs let exists_unique p xs = let module M = struct exception Found end in try fold (fun x found -> if found then not (p x) || raise M.Found else p x ) xs false with M.Found -> false let rec equal fn xs ys = if xs == ys then true else match xs,ys with | [], [] -> true | [], _::_ | _::_, [] -> false | x::xs, y::ys -> fn x y && equal fn xs ys let rec compare fn xs ys = if xs == ys then 0 else match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 fn (compare fn) (x,xs) (y,ys) let rec compare_lex fn xs ys = if xs == ys then 0 else match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 (compare_lex fn) fn (xs,x) (ys,y) let compare_sorted cmp xs ys = if xs == ys then 0 else let rec loop xs ys = match xs,ys with | [], _::_ -> -1 | [], [] -> 0 | _::_, [] -> 1 | x::xs, y::ys -> compare_tup2 cmp loop (x,xs) (y,ys) in loop (fast_sort cmp xs) (fast_sort cmp ys) let fmt sep fn ff xs = let rec aux ff = function | [] -> () | [x] -> (try fn ff x with Nothing_to_fmt -> ()) | x::xs -> try Format.fprintf ff "%a%( fmt %)%a" fn x sep aux xs with Nothing_to_fmt -> aux ff xs in aux ff xs let fmtt sep ff xs = let rec aux ff = function | [] -> () | [x] -> (try x ff with Nothing_to_fmt -> ()) | x::xs -> try Format.fprintf ff "%t%( fmt %)%a" x sep aux xs with Nothing_to_fmt -> aux ff xs in aux ff xs module Set (Elt: sig type t end) = struct type elt = Elt.t type t = elt list let empty = [] let is_empty s = s = [] let add e s = e :: s let singleton e = [e] let iter = iter let map = map let fold = fold let map_fold = map_fold let kfold fn s z = kfold s fn z let for_all = for_all let exists = exists let exists_unique = exists_unique let filter = filter let cardinal = length let of_list s = s let to_list s = s let choose = function x::_ -> x | [] -> raise Not_found let union = rev_append let diff = diff end module SetOrd (Elt: OrderedType) = struct include Set(Elt) let equal x y = equal Elt.equal x y let compare x y = compare Elt.compare x y let rec remove x = function | [] -> [] | y::ys when Elt.equal x y -> ys | y::ys -> y :: remove x ys let diff_inter_diff xs ys = let xs = fast_sort Elt.compare xs and ys = fast_sort Elt.compare ys in let rec did xxs yys = match xxs, yys with | [], ys -> ([], [], ys) | xs, [] -> (xs, [], []) | x::xs, y::ys -> let o = Elt.compare x y in if o = 0 then let xs_ys, i, ys_xs = did xs ys in (xs_ys, x::i, ys_xs) else if o < 0 then let xs_yys, i, yys_xs = did xs yys in (x::xs_yys, i, yys_xs) else let xxs_ys, i, ys_xxs = did xxs ys in (xxs_ys, i, y::ys_xxs) in did xs ys end end
99b056bba0a3e1c5c773c47b266754d3dcc3ca91eb6c9b2590ff2f092a84c701
hashobject/boot-s3
s3.clj
(ns hashobject.boot-s3.s3 (:require [aws.sdk.s3 :as s3])) (defn get-file-details-for "Get the file details for the file in s3. Returns nil if there is no file at the given key." [cred bucket-name key] (try (let [response (s3/get-object-metadata cred bucket-name key)] (assoc response :key key)) (catch com.amazonaws.services.s3.model.AmazonS3Exception e (when-not (= 404 (.getStatusCode e)) (throw e))))) (defn- response->file-details [response] {:path (:key response) :md5 (:etag response)} ) (defn analyse-s3-bucket [cred bucket-name file-paths] (let [s3-lookup (partial get-file-details-for cred bucket-name) bucket-sync-state {:bucket-name bucket-name :remote-file-details []}] (if-not (s3/bucket-exists? cred bucket-name) (assoc bucket-sync-state :errors [(str "No bucket " bucket-name)]) (->> file-paths (map s3-lookup) (map response->file-details) (remove nil?) (set))))) (defn put-file [cred bucket-name key file metadata permissions] (let [grants (map #(apply s3/grant %) permissions)] (apply s3/put-object cred bucket-name key file metadata grants)))
null
https://raw.githubusercontent.com/hashobject/boot-s3/7f9dd89947703070d40e0b95cfa173d3812a7db3/src/hashobject/boot_s3/s3.clj
clojure
(ns hashobject.boot-s3.s3 (:require [aws.sdk.s3 :as s3])) (defn get-file-details-for "Get the file details for the file in s3. Returns nil if there is no file at the given key." [cred bucket-name key] (try (let [response (s3/get-object-metadata cred bucket-name key)] (assoc response :key key)) (catch com.amazonaws.services.s3.model.AmazonS3Exception e (when-not (= 404 (.getStatusCode e)) (throw e))))) (defn- response->file-details [response] {:path (:key response) :md5 (:etag response)} ) (defn analyse-s3-bucket [cred bucket-name file-paths] (let [s3-lookup (partial get-file-details-for cred bucket-name) bucket-sync-state {:bucket-name bucket-name :remote-file-details []}] (if-not (s3/bucket-exists? cred bucket-name) (assoc bucket-sync-state :errors [(str "No bucket " bucket-name)]) (->> file-paths (map s3-lookup) (map response->file-details) (remove nil?) (set))))) (defn put-file [cred bucket-name key file metadata permissions] (let [grants (map #(apply s3/grant %) permissions)] (apply s3/put-object cred bucket-name key file metadata grants)))
b4d59bbb97bc73ee3f1bd0a336a579cefc8baeb124563c8533f2e0ba93dafbba
jfaure/Irie-lang
Externs.hs
Externs : resolve names from external files ( solvescopes handles λ , mutuals , locals et .. ) -- * things in scope, but defined later * primitives : ( note . prim bindings are CoreSyn ) -- * imported modules -- * extern functions (esp. C) -- * imported label/field names should overwrite locals (they are supposed to be the same) -- * The 0 module (compiler primitives) is used to mark tuple fields: (n : Iname) -> 0.n module Externs (GlobalResolver(..) , ModDeps, ModDependencies(..), addModuleToResolver , addModName , primResolver , primBinds , Import(..) , Externs(..) , readParseExtern , readQParseExtern , readLabel , readPrimExtern , resolveImports , typeOfLit , addDependency) where import Builtins ( primBinds , primMap , typeOfLit , primLabelHNames , primLabelMap )--, primFieldHNames, primFieldMap ) import CoreSyn import ShowCore() import MixfixSyn ( mfw2qmfw, MFWord, QMFWord ) import qualified ParseSyntax as P ( NameMap ) import qualified BitSetMap as BSM ( singleton ) import qualified Data.IntMap as IM ( IntMap, filterWithKey, singleton, toList, union ) import qualified Data.Map.Strict as M ( Map, (!?), member, size, insert, singleton, traverseWithKey, unionWith, unionsWith, update ) import qualified Data.Vector.Mutable as MV ( length, unsafeGrow, unsafeNew, write ) import qualified Data.Vector as V TODO should treat global resolver like a normal module : Also handle mutual modules -- Except: -- file IName map : IName -> HName -- imports (= dependencies) -- newlineList -- Global ops: -- Search : binding , type -- List : module | lens -- Dependency tree Avoid linearity caused by threading GlobalResolver ----------------- -- Import Tree -- ----------------- Imports are typechecked binds + parsed nameMap data Import = Import { importNames :: P.NameMap , importBinds :: V.Vector (HName , Bind) } -- only direct dependencies are saved; main tracks the work stack to detect cycles type ModDeps = BitSet data ModDependencies = ModDependencies { deps :: Integer , dependents :: Integer } deriving Show data GlobalResolver = GlobalResolver { modCount :: Int module HName - > Iname HName - > ModuleIName - > IName , lnames :: M.Map HName QName -- TODO rm , modNamesV :: V.Vector HName Module - > IName - > ( HName , ) , labelHNames :: V.Vector (V.Vector HName) , dependencies :: V.Vector ModDependencies HName - > ( MFIName - > ModuleIName ) , globalMixfixWords :: M.Map HName (IM.IntMap [QMFWord]) } deriving Show -- basic resolver used to initialise a cache the private 0 module " .compilerPrimitives " contains : -- * cpu-instructions binds * tuple fields : .. ] -- * extra labels (esp. for demutualisation and other optimisations) primResolver :: GlobalResolver = let primModName = "(builtinPrimitives)" in GlobalResolver 1 (M.singleton primModName 0) (IM.singleton 0 <$> primMap) primLabelMap -- primFieldMap (V.singleton primModName) (V.singleton primBinds) -- primitive bindings (V.singleton primLabelHNames) (V.singleton (ModDependencies 0 0)) mempty ------------- Externs -- ------------- how to substitute P.VExtern during mixfix resolution data Externs = Externs { extNames :: V.Vector ExternVar , extBinds :: V.Vector (V.Vector (HName , Expr)) -- all loaded bindings (same as in global resolver) , importLabels :: V.Vector QName , eModNamesV :: V.Vector HName } deriving Show readPrimExtern e i = snd (extBinds e V.! 0 V.! i) , readLabel exts l = if l < 0 then mkQName 0 (-1 - l) else exts.importLabels V.! l f = if f < 0 then mkQName 0 ( -1 - f ) else exts.importFields V. ! f exported functions to resolve ParseSyn . VExterns readQParseExtern :: BitSet -> Int -> Externs -> Int -> IName -> CoreSyn.ExternVar readQParseExtern openMods thisModIName (exts :: Externs) modNm iNm = if | modNm == thisModIName -> ForwardRef iNm -- solveScopes can handle this | openMods `testBit` modNm -> Imported $ case snd ((exts.extBinds V.! modNm) V.! iNm) of e@(Core f t) -> case f of -- inline trivial things Lit{} -> e Instr{} -> e var indirection ( TODO continue maybe inlining ? ) _ -> Core (Var $ VQBind (mkQName modNm iNm)) t PoisonExpr -> PoisonExpr x -> x -- types and sets | otherwise -> NotOpened (exts.eModNamesV V.! modNm) (fst (exts.extBinds V.! modNm V.! iNm)) readParseExtern openMods thisModIName exts i = case exts.extNames V.! i of Importable modNm iNm -> readQParseExtern openMods thisModIName exts modNm iNm x -> x First resolve names for a module , then that module can be added to the resolver We need to resolve INames accross module boundaries . Externs are a vector of CoreExprs , generated as : builtins + + concat imports ; which is indexed by the permuation described in the extNames vector . * primitives must always be present in GlobalResolver resolveImports :: GlobalResolver -> IName -> M.Map HName IName -> (M.Map HName IName) -> M.Map HName [MFWord] -> M.Map HName IName -> Maybe OldCachedModule -> (GlobalResolver , Externs) resolveImports (GlobalResolver modCount modNames curResolver l modNamesV prevBinds lh deps curMFWords) -- localNames = all things let-bound (to help rm stale names) -- iNames = all Names in scope modIName localNames labelMap mixfixHNames iNames maybeOld = let oldIName = oldModuleIName <$> maybeOld HName - > Modules with that resolver = let temporarily mark field / label names ( use 2 bits from the iname , not the module name which tracks their origin ) instead resolveName could use 3 maps , but would be slow since frequently entire maps would come back negative labels = IM.singleton modIName . (`setBit` labelBit) <$> labelMap -- Deleted names from the old module won't be overwritten so must be explicitly removed rmStaleNames nameMap = let collect = V.foldl (\stale nm -> if M.member nm localNames then stale else nm : stale) [] staleNames = fromMaybe [] ((collect . oldBindNames) <$> maybeOld) :: [HName] in case oldIName of Just oldMod -> foldr (\staleName m -> M.update (Just . IM.filterWithKey (\k _v -> k /= oldMod)) staleName m) nameMap staleNames Nothing -> nameMap in rmStaleNames $ M.unionsWith IM.union [((\iNms -> IM.singleton modIName iNms) <$> localNames) , curResolver , labels] mfResolver = M.unionWith IM.union curMFWords $ M.unionsWith IM.union $ zipWith (\modNm map -> IM.singleton modNm <$> map) [modIName..] [map (mfw2qmfw modIName) <$> mixfixHNames] resolveName :: HName -> ExternVar resolveName hNm = let binds = IM.toList <$> (resolver M.!? hNm) mfWords = IM.toList <$> (mfResolver M.!? hNm) flattenMFMap = concatMap snd in case (binds , mfWords) of (Just [] , _) -> NotInScope hNm -- this name was deleted from (all) modules (Just [(0 , iNm)] , Nothing) -> Imported $ snd ((prevBinds V.! 0) V.! iNm) -- inline builtins (Just [(modNm , iNm)] , Nothing) -- label applications look like normal bindings `n = Nil` | True <- testBit iNm labelBit -> let q = mkQName modNm (clearBit iNm labelBit) in Imported (Core (Label q []) (TyGround [THTyCon $ THSumTy (BSM.singleton (qName2Key q) (TyGround [THTyCon $ THTuple mempty]))])) | True <- testBit iNm fieldBit -> NotInScope hNm | True -> Importable modNm iNm (b , Just mfWords) | Nothing <- b -> MixfixyVar $ Mixfixy Nothing (flattenMFMap mfWords) | Just [(m,i)] <- b -> MixfixyVar $ Mixfixy (Just (mkQName m i)) (flattenMFMap mfWords) (Nothing , Nothing) -> NotInScope hNm (Just many , _) -> AmbiguousBinding hNm many convert noScopeNames map to a vector ( Map HName IName - > Vector HName ) names :: Map HName Int -> V.Vector ExternVar names noScopeNames = V.create $ do v <- MV.unsafeNew (M.size noScopeNames) v <$ (\nm idx -> MV.write v idx $ resolveName nm) `M.traverseWithKey` noScopeNames -- labels may be imported from elsewhere, else they are new and assigned to this module mkTable :: Map HName QName -> Map HName Int -> V.Vector QName mkTable map localMap = V.create $ do v <- MV.unsafeNew (M.size localMap) let getQName hNm localName = case map M.!? hNm of -- if field imported, use that QName Just q | modName q /= modIName -> q -- iff not from the module we're recompiling _ -> mkQName modIName localName -- new field introduced in this (modIName) module v <$ (\hNm localName -> MV.write v localName (getQName hNm localName)) `M.traverseWithKey` localMap in ( GlobalResolver modCount modNames resolver l modNamesV prevBinds lh deps mfResolver , Externs { extNames = names iNames , extBinds = prevBinds , importLabels = mkTable l labelMap , eModNamesV = modNamesV }) -- Often we deal with incomplete vectors (with holes for modules in the pipeline eg. when processing dependencies) -- Unfortunately writing/caching them to disk requires full initialisation (error "" would trigger when writing) -- the trashValue serves as an obviously wrong 'uninitialised' element which should never be read eg. "(Uninitialized)" updateVecIdx :: a -> V.Vector a -> Int -> a -> V.Vector a updateVecIdx trashValue v' i new = runST $ do v <- V.unsafeThaw v' let l = MV.length v g <- if l > i then pure v else do g <- MV.unsafeGrow v i g <$ [l .. l+i-1] `forM` \i -> MV.write g i trashValue -- initialise with recognizable trash to help debug bad reads MV.write g i new V.unsafeFreeze g addModName modIName modHName g = g { modCount = modCount g + 1 , modNameMap = M.insert modHName modIName (modNameMap g) , modNamesV = updateVecIdx "(Uninitialized)" (modNamesV g) modIName modHName } addDependency _imported _moduleIName r = r -- { dependencies = let ModDependencies dependents = if V.length ( dependencies r ) > moduleIName then dependencies r V. ! else ModDependencies emptyBitSet emptyBitSet in updateVecIdx ( ModDependencies 0 0 ) ( dependencies r ) moduleIName ( ModDependencies ( ` setBit ` imported ) dependents ) -- } addModuleToResolver :: Externs.GlobalResolver -> Int -> V.Vector (HName, CoreSyn.Expr) -> V.Vector HName -> Map HName Int -> p -> Externs.GlobalResolver addModuleToResolver (GlobalResolver modCount modNames nameMaps l modNamesV binds lh deps mfResolver) modIName newBinds lHNames labelNames _modDeps = let binds' = updateVecIdx (V.singleton ("(Uninitialized)" , PoisonExpr)) binds modIName newBinds lh' = updateVecIdx (V.singleton "(Uninitialized)") lh modIName lHNames ' = updateVecIdx ( ModDependencies 0 0 ) modIName modDeps l' = alignWith (\case { This new -> mkQName modIName new ; That old -> old ; These _new old -> old }) labelNames l in GlobalResolver modCount modNames nameMaps l' modNamesV binds' lh' deps mfResolver
null
https://raw.githubusercontent.com/jfaure/Irie-lang/186640a095d14560ff102ef613648e558e5b3f1e/compiler/3_Core/Externs.hs
haskell
* things in scope, but defined later * imported modules * extern functions (esp. C) * imported label/field names should overwrite locals (they are supposed to be the same) * The 0 module (compiler primitives) is used to mark tuple fields: (n : Iname) -> 0.n , primFieldHNames, primFieldMap ) Except: file IName map : IName -> HName imports (= dependencies) newlineList Global ops: Search : binding , type List : module | lens Dependency tree --------------- Import Tree -- --------------- only direct dependencies are saved; main tracks the work stack to detect cycles TODO rm basic resolver used to initialise a cache * cpu-instructions binds * extra labels (esp. for demutualisation and other optimisations) primFieldMap primitive bindings ----------- ----------- all loaded bindings (same as in global resolver) solveScopes can handle this inline trivial things types and sets localNames = all things let-bound (to help rm stale names) iNames = all Names in scope Deleted names from the old module won't be overwritten so must be explicitly removed this name was deleted from (all) modules inline builtins label applications look like normal bindings `n = Nil` labels may be imported from elsewhere, else they are new and assigned to this module if field imported, use that QName iff not from the module we're recompiling new field introduced in this (modIName) module Often we deal with incomplete vectors (with holes for modules in the pipeline eg. when processing dependencies) Unfortunately writing/caching them to disk requires full initialisation (error "" would trigger when writing) the trashValue serves as an obviously wrong 'uninitialised' element which should never be read eg. "(Uninitialized)" initialise with recognizable trash to help debug bad reads { dependencies = let }
Externs : resolve names from external files ( solvescopes handles λ , mutuals , locals et .. ) * primitives : ( note . prim bindings are CoreSyn ) module Externs (GlobalResolver(..) , ModDeps, ModDependencies(..), addModuleToResolver , addModName , primResolver , primBinds , Import(..) , Externs(..) , readParseExtern , readQParseExtern , readLabel , readPrimExtern , resolveImports , typeOfLit , addDependency) where import CoreSyn import ShowCore() import MixfixSyn ( mfw2qmfw, MFWord, QMFWord ) import qualified ParseSyntax as P ( NameMap ) import qualified BitSetMap as BSM ( singleton ) import qualified Data.IntMap as IM ( IntMap, filterWithKey, singleton, toList, union ) import qualified Data.Map.Strict as M ( Map, (!?), member, size, insert, singleton, traverseWithKey, unionWith, unionsWith, update ) import qualified Data.Vector.Mutable as MV ( length, unsafeGrow, unsafeNew, write ) import qualified Data.Vector as V TODO should treat global resolver like a normal module : Also handle mutual modules Avoid linearity caused by threading GlobalResolver Imports are typechecked binds + parsed nameMap data Import = Import { importNames :: P.NameMap , importBinds :: V.Vector (HName , Bind) } type ModDeps = BitSet data ModDependencies = ModDependencies { deps :: Integer , dependents :: Integer } deriving Show data GlobalResolver = GlobalResolver { modCount :: Int module HName - > Iname HName - > ModuleIName - > IName , modNamesV :: V.Vector HName Module - > IName - > ( HName , ) , labelHNames :: V.Vector (V.Vector HName) , dependencies :: V.Vector ModDependencies HName - > ( MFIName - > ModuleIName ) , globalMixfixWords :: M.Map HName (IM.IntMap [QMFWord]) } deriving Show the private 0 module " .compilerPrimitives " contains : * tuple fields : .. ] primResolver :: GlobalResolver = let primModName = "(builtinPrimitives)" in GlobalResolver 1 (M.singleton primModName 0) (IM.singleton 0 <$> primMap) (V.singleton primModName) (V.singleton primLabelHNames) (V.singleton (ModDependencies 0 0)) mempty how to substitute P.VExtern during mixfix resolution data Externs = Externs { extNames :: V.Vector ExternVar , importLabels :: V.Vector QName , eModNamesV :: V.Vector HName } deriving Show readPrimExtern e i = snd (extBinds e V.! 0 V.! i) , readLabel exts l = if l < 0 then mkQName 0 (-1 - l) else exts.importLabels V.! l f = if f < 0 then mkQName 0 ( -1 - f ) else exts.importFields V. ! f exported functions to resolve ParseSyn . VExterns readQParseExtern :: BitSet -> Int -> Externs -> Int -> IName -> CoreSyn.ExternVar readQParseExtern openMods thisModIName (exts :: Externs) modNm iNm = if | openMods `testBit` modNm -> Imported $ case snd ((exts.extBinds V.! modNm) V.! iNm) of Lit{} -> e Instr{} -> e var indirection ( TODO continue maybe inlining ? ) _ -> Core (Var $ VQBind (mkQName modNm iNm)) t PoisonExpr -> PoisonExpr | otherwise -> NotOpened (exts.eModNamesV V.! modNm) (fst (exts.extBinds V.! modNm V.! iNm)) readParseExtern openMods thisModIName exts i = case exts.extNames V.! i of Importable modNm iNm -> readQParseExtern openMods thisModIName exts modNm iNm x -> x First resolve names for a module , then that module can be added to the resolver We need to resolve INames accross module boundaries . Externs are a vector of CoreExprs , generated as : builtins + + concat imports ; which is indexed by the permuation described in the extNames vector . * primitives must always be present in GlobalResolver resolveImports :: GlobalResolver -> IName -> M.Map HName IName -> (M.Map HName IName) -> M.Map HName [MFWord] -> M.Map HName IName -> Maybe OldCachedModule -> (GlobalResolver , Externs) resolveImports (GlobalResolver modCount modNames curResolver l modNamesV prevBinds lh deps curMFWords) modIName localNames labelMap mixfixHNames iNames maybeOld = let oldIName = oldModuleIName <$> maybeOld HName - > Modules with that resolver = let temporarily mark field / label names ( use 2 bits from the iname , not the module name which tracks their origin ) instead resolveName could use 3 maps , but would be slow since frequently entire maps would come back negative labels = IM.singleton modIName . (`setBit` labelBit) <$> labelMap rmStaleNames nameMap = let collect = V.foldl (\stale nm -> if M.member nm localNames then stale else nm : stale) [] staleNames = fromMaybe [] ((collect . oldBindNames) <$> maybeOld) :: [HName] in case oldIName of Just oldMod -> foldr (\staleName m -> M.update (Just . IM.filterWithKey (\k _v -> k /= oldMod)) staleName m) nameMap staleNames Nothing -> nameMap in rmStaleNames $ M.unionsWith IM.union [((\iNms -> IM.singleton modIName iNms) <$> localNames) , curResolver , labels] mfResolver = M.unionWith IM.union curMFWords $ M.unionsWith IM.union $ zipWith (\modNm map -> IM.singleton modNm <$> map) [modIName..] [map (mfw2qmfw modIName) <$> mixfixHNames] resolveName :: HName -> ExternVar resolveName hNm = let binds = IM.toList <$> (resolver M.!? hNm) mfWords = IM.toList <$> (mfResolver M.!? hNm) flattenMFMap = concatMap snd in case (binds , mfWords) of (Just [(modNm , iNm)] , Nothing) | True <- testBit iNm labelBit -> let q = mkQName modNm (clearBit iNm labelBit) in Imported (Core (Label q []) (TyGround [THTyCon $ THSumTy (BSM.singleton (qName2Key q) (TyGround [THTyCon $ THTuple mempty]))])) | True <- testBit iNm fieldBit -> NotInScope hNm | True -> Importable modNm iNm (b , Just mfWords) | Nothing <- b -> MixfixyVar $ Mixfixy Nothing (flattenMFMap mfWords) | Just [(m,i)] <- b -> MixfixyVar $ Mixfixy (Just (mkQName m i)) (flattenMFMap mfWords) (Nothing , Nothing) -> NotInScope hNm (Just many , _) -> AmbiguousBinding hNm many convert noScopeNames map to a vector ( Map HName IName - > Vector HName ) names :: Map HName Int -> V.Vector ExternVar names noScopeNames = V.create $ do v <- MV.unsafeNew (M.size noScopeNames) v <$ (\nm idx -> MV.write v idx $ resolveName nm) `M.traverseWithKey` noScopeNames mkTable :: Map HName QName -> Map HName Int -> V.Vector QName mkTable map localMap = V.create $ do v <- MV.unsafeNew (M.size localMap) v <$ (\hNm localName -> MV.write v localName (getQName hNm localName)) `M.traverseWithKey` localMap in ( GlobalResolver modCount modNames resolver l modNamesV prevBinds lh deps mfResolver , Externs { extNames = names iNames , extBinds = prevBinds , importLabels = mkTable l labelMap , eModNamesV = modNamesV }) updateVecIdx :: a -> V.Vector a -> Int -> a -> V.Vector a updateVecIdx trashValue v' i new = runST $ do v <- V.unsafeThaw v' let l = MV.length v g <- if l > i then pure v else do g <- MV.unsafeGrow v i MV.write g i new V.unsafeFreeze g addModName modIName modHName g = g { modCount = modCount g + 1 , modNameMap = M.insert modHName modIName (modNameMap g) , modNamesV = updateVecIdx "(Uninitialized)" (modNamesV g) modIName modHName } addDependency _imported _moduleIName r = r ModDependencies dependents = if V.length ( dependencies r ) > moduleIName then dependencies r V. ! else ModDependencies emptyBitSet emptyBitSet in updateVecIdx ( ModDependencies 0 0 ) ( dependencies r ) moduleIName ( ModDependencies ( ` setBit ` imported ) dependents ) addModuleToResolver :: Externs.GlobalResolver -> Int -> V.Vector (HName, CoreSyn.Expr) -> V.Vector HName -> Map HName Int -> p -> Externs.GlobalResolver addModuleToResolver (GlobalResolver modCount modNames nameMaps l modNamesV binds lh deps mfResolver) modIName newBinds lHNames labelNames _modDeps = let binds' = updateVecIdx (V.singleton ("(Uninitialized)" , PoisonExpr)) binds modIName newBinds lh' = updateVecIdx (V.singleton "(Uninitialized)") lh modIName lHNames ' = updateVecIdx ( ModDependencies 0 0 ) modIName modDeps l' = alignWith (\case { This new -> mkQName modIName new ; That old -> old ; These _new old -> old }) labelNames l in GlobalResolver modCount modNames nameMaps l' modNamesV binds' lh' deps mfResolver
2a05d0c04180cc034fec54514c3f4fd99b0dd8b0e63f14f2207ddee12a77411c
cxxxr/valtan
ansi-tests.lisp
Copyright ( C ) 2004 < > ;; ALL RIGHTS RESERVED. ;; $ I d : ansi - tests.lisp , v 1.3 2004/09/28 01:53:23 yuji Exp $ ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions ;; are met: ;; ;; * Redistributions of source code must retain the above copyright ;; notice, this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in ;; the documentation and/or other materials provided with the ;; distribution. ;; ;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ;; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ;; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; Commentary: Support routines for ANSI testsuite . ;; ;; When testing loop.lisp, do the following. ;; (load "loop.lisp") ;; (load "tests/ansi-tests.lisp") ;; (in-package "CL-TEST") ;; (shadowing-import '(sacla-loop:loop sacla-loop:loop-finish)) (defpackage "CL-TEST" (:use "COMMON-LISP")) (in-package "CL-TEST") (defmacro deftest (name form &rest values) `(equal (multiple-value-list ,form) ',values)) from ansi-aux.lsp of GCL 's ANSI - TESTS Author : Created : Sat Mar 28 17:10:18 1998 ;;;; License: GPL (defmacro classify-error* (form) "Evaluate form in safe mode, returning its value if there is no error. If an error does occur, return a symbol classify the error, or allow the condition to go uncaught if it cannot be classified." `(locally (declare (optimize (safety 3))) (handler-case ,form (undefined-function () 'undefined-function) (program-error () 'program-error) (package-error () 'package-error) (type-error () 'type-error) (control-error () 'control-error) (stream-error () 'stream-error) (reader-error () 'reader-error) (file-error () 'file-error) (control-error () 'control-error) (cell-error () 'cell-error) (error () 'error) ))) (defun classify-error** (form) (handler-bind ((warning #'(lambda (c) (declare (ignore c)) (muffle-warning)))) (classify-error* (eval form)))) (defmacro classify-error (form) `(classify-error** ',form)) (defun notnot (x) (not (not x))) (defun eqlt (x y) "Like EQL, but guaranteed to return T for true." (apply #'values (mapcar #'notnot (multiple-value-list (eql x y))))) (defun equalt (x y) "Like EQUAL, but guaranteed to return T for true." (apply #'values (mapcar #'notnot (multiple-value-list (equal x y))))) (defun symbol< (x &rest args) (apply #'string< (symbol-name x) (mapcar #'symbol-name args)))
null
https://raw.githubusercontent.com/cxxxr/valtan/ec3164d42b86869357dc185b747c5dfba25c0a3c/tests/sacla-tests/ansi-tests.lisp
lisp
ALL RIGHTS RESERVED. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Commentary: When testing loop.lisp, do the following. (load "loop.lisp") (load "tests/ansi-tests.lisp") (in-package "CL-TEST") (shadowing-import '(sacla-loop:loop sacla-loop:loop-finish)) License: GPL
Copyright ( C ) 2004 < > $ I d : ansi - tests.lisp , v 1.3 2004/09/28 01:53:23 yuji Exp $ " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT Support routines for ANSI testsuite . (defpackage "CL-TEST" (:use "COMMON-LISP")) (in-package "CL-TEST") (defmacro deftest (name form &rest values) `(equal (multiple-value-list ,form) ',values)) from ansi-aux.lsp of GCL 's ANSI - TESTS Author : Created : Sat Mar 28 17:10:18 1998 (defmacro classify-error* (form) "Evaluate form in safe mode, returning its value if there is no error. If an error does occur, return a symbol classify the error, or allow the condition to go uncaught if it cannot be classified." `(locally (declare (optimize (safety 3))) (handler-case ,form (undefined-function () 'undefined-function) (program-error () 'program-error) (package-error () 'package-error) (type-error () 'type-error) (control-error () 'control-error) (stream-error () 'stream-error) (reader-error () 'reader-error) (file-error () 'file-error) (control-error () 'control-error) (cell-error () 'cell-error) (error () 'error) ))) (defun classify-error** (form) (handler-bind ((warning #'(lambda (c) (declare (ignore c)) (muffle-warning)))) (classify-error* (eval form)))) (defmacro classify-error (form) `(classify-error** ',form)) (defun notnot (x) (not (not x))) (defun eqlt (x y) "Like EQL, but guaranteed to return T for true." (apply #'values (mapcar #'notnot (multiple-value-list (eql x y))))) (defun equalt (x y) "Like EQUAL, but guaranteed to return T for true." (apply #'values (mapcar #'notnot (multiple-value-list (equal x y))))) (defun symbol< (x &rest args) (apply #'string< (symbol-name x) (mapcar #'symbol-name args)))
b768953ba1060b8d828220c8a15016dfef338941b3bb2d25731da84b0d6afcdc
hoytech/antiweb
cffi-scl.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; cffi-scl.lisp --- CFFI-SYS implementation for the Scieneer Common Lisp. ;;; Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2006 , Scieneer Pty Ltd. ;;; ;;; Permission is hereby granted, free of charge, to any person ;;; obtaining a copy of this software and associated documentation files ( the " Software " ) , to deal in the Software without ;;; restriction, including without limitation the rights to use, copy, ;;; modify, merge, publish, distribute, sublicense, and/or sell copies of the Software , and to permit persons to whom the Software is ;;; furnished to do so, subject to the following conditions: ;;; ;;; The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software . ;;; THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT ;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, ;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ;;; DEALINGS IN THE SOFTWARE. ;;; ;;; For posterity, a few optimizations we might use in the future: #-(and) (defun lisp-string-to-foreign (string ptr size) (c-call::deport-string-to-system-area string ptr size :iso-8859-1)) #-(and) (defun foreign-string-to-lisp (ptr &optional (size most-positive-fixnum) (null-terminated-p t)) (unless (null-pointer-p ptr) (if null-terminated-p (c-call::naturalize-c-string ptr :iso-8859-1) (c-call::naturalize-c-string ptr :iso-8859-1 size)))) # Administrivia (defpackage #:cffi-sys (:use #:common-lisp #:alien #:c-call #:cffi-utils) (:export #:canonicalize-symbol-name-case #:pointerp #:pointer-eq #:null-pointer #:null-pointer-p #:inc-pointer #:make-pointer #:pointer-address #:%foreign-alloc #:foreign-free #:with-foreign-pointer #:%foreign-funcall #:%foreign-funcall-pointer #:%foreign-type-alignment #:%foreign-type-size #:%load-foreign-library #:%close-foreign-library #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:foreign-symbol-pointer #:%defcallback #:%callback #:finalize #:cancel-finalization)) (in-package #:cffi-sys) ;;;# Features (eval-when (:compile-toplevel :load-toplevel :execute) (mapc (lambda (feature) (pushnew feature *features*)) '(;; OS/CPU features. #+unix cffi-features:unix #+x86 cffi-features:x86 #+amd64 cffi-features:x86-64 #+(and ppc (not ppc64)) cffi-features:ppc32 ))) ;;; Symbol case. (defun canonicalize-symbol-name-case (name) (declare (string name)) (if (eq ext:*case-mode* :upper) (string-upcase name) (string-downcase name))) ;;;# Basic Pointer Operations (declaim (inline pointerp)) (defun pointerp (ptr) "Return true if 'ptr is a foreign pointer." (sys:system-area-pointer-p ptr)) (declaim (inline pointer-eq)) (defun pointer-eq (ptr1 ptr2) "Return true if 'ptr1 and 'ptr2 point to the same address." (sys:sap= ptr1 ptr2)) (declaim (inline null-pointer)) (defun null-pointer () "Construct and return a null pointer." (sys:int-sap 0)) (declaim (inline null-pointer-p)) (defun null-pointer-p (ptr) "Return true if 'ptr is a null pointer." (zerop (sys:sap-int ptr))) (declaim (inline inc-pointer)) (defun inc-pointer (ptr offset) "Return a pointer pointing 'offset bytes past 'ptr." (sys:sap+ ptr offset)) (declaim (inline make-pointer)) (defun make-pointer (address) "Return a pointer pointing to 'address." (sys:int-sap address)) (declaim (inline pointer-address)) (defun pointer-address (ptr) "Return the address pointed to by 'ptr." (sys:sap-int ptr)) (defmacro with-foreign-pointer ((var size &optional size-var) &body body) "Bind 'var to 'size bytes of foreign memory during 'body. The pointer in 'var is invalid beyond the dynamic extent of 'body, and may be stack-allocated if supported by the implementation. If 'size-var is supplied, it will be bound to 'size during 'body." (unless size-var (setf size-var (gensym (symbol-name '#:size)))) ;; If the size is constant we can stack-allocate. (cond ((constantp size) (let ((alien-var (gensym (symbol-name '#:alien)))) `(with-alien ((,alien-var (array (unsigned 8) ,(eval size)))) (let ((,size-var ,size) (,var (alien-sap ,alien-var))) (declare (ignorable ,size-var)) ,@body)))) (t `(let ((,size-var ,size)) (alien:with-bytes (,var ,size-var) ,@body))))) ;;;# Allocation ;;; ;;; Functions and macros for allocating foreign memory on the stack and on the heap . The main CFFI package defines macros that wrap ' foreign - alloc and ;;; 'foreign-free in 'unwind-protect for the common usage when the memory has ;;; dynamic extent. (defun %foreign-alloc (size) "Allocate 'size bytes on the heap and return a pointer." (declare (type (unsigned-byte #-64bit 32 #+64bit 64) size)) (alien-funcall (extern-alien "malloc" (function system-area-pointer unsigned)) size)) (defun foreign-free (ptr) "Free a 'ptr allocated by 'foreign-alloc." (declare (type system-area-pointer ptr)) (alien-funcall (extern-alien "free" (function (values) system-area-pointer)) ptr)) ;;;# Shareable Vectors (defun make-shareable-byte-vector (size) "Create a Lisp vector of 'size bytes that can passed to 'with-pointer-to-vector-data." (make-array size :element-type '(unsigned-byte 8))) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind 'ptr-var to a foreign pointer to the data in 'vector." (let ((vector-var (gensym (symbol-name '#:vector)))) `(let ((,vector-var ,vector)) (ext:with-pinned-object (,vector-var) (let ((,ptr-var (sys:vector-sap ,vector-var))) ,@body))))) ;;;# Dereferencing Define the % MEM - REF and % MEM - SET functions , as well as compiler ;;; macros that optimize the case where the type keyword is constant ;;; at compile-time. (defmacro define-mem-accessors (&body pairs) `(progn (defun %mem-ref (ptr type &optional (offset 0)) (ecase type ,@(loop for (keyword fn) in pairs collect `(,keyword (,fn ptr offset))))) (defun %mem-set (value ptr type &optional (offset 0)) (ecase type ,@(loop for (keyword fn) in pairs collect `(,keyword (setf (,fn ptr offset) value))))) (define-compiler-macro %mem-ref (&whole form ptr type &optional (offset 0)) (if (constantp type) (ecase (eval type) ,@(loop for (keyword fn) in pairs collect `(,keyword `(,',fn ,ptr ,offset)))) form)) (define-compiler-macro %mem-set (&whole form value ptr type &optional (offset 0)) (if (constantp type) (once-only (value) (ecase (eval type) ,@(loop for (keyword fn) in pairs collect `(,keyword `(setf (,',fn ,ptr ,offset) ,value))))) form)))) (define-mem-accessors (:char sys:signed-sap-ref-8) (:unsigned-char sys:sap-ref-8) (:short sys:signed-sap-ref-16) (:unsigned-short sys:sap-ref-16) (:int sys:signed-sap-ref-32) (:unsigned-int sys:sap-ref-32) (:long #-64bit sys:signed-sap-ref-32 #+64bit sys:signed-sap-ref-64) (:unsigned-long #-64bit sys:sap-ref-32 #+64bit sys:sap-ref-64) (:long-long sys:signed-sap-ref-64) (:unsigned-long-long sys:sap-ref-64) (:float sys:sap-ref-single) (:double sys:sap-ref-double) #+long-float (:long-double sys:sap-ref-long) (:pointer sys:sap-ref-sap)) ;;;# Calling Foreign Functions (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to an ALIEN type." (ecase type-keyword (:char 'char) (:unsigned-char 'unsigned-char) (:short 'short) (:unsigned-short 'unsigned-short) (:int 'int) (:unsigned-int 'unsigned-int) (:long 'long) (:unsigned-long 'unsigned-long) (:long-long '(signed 64)) (:unsigned-long-long '(unsigned 64)) (:float 'single-float) (:double 'double-float) #+long-float (:long-double 'long-float) (:pointer 'system-area-pointer) (:void 'void))) (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (values (truncate (alien-internals:alien-type-bits (alien-internals:parse-alien-type (convert-foreign-type type-keyword))) 8))) (defun %foreign-type-alignment (type-keyword) "Return the alignment in bytes of a foreign type." (values (truncate (alien-internals:alien-type-alignment (alien-internals:parse-alien-type (convert-foreign-type type-keyword))) 8))) (defun foreign-funcall-type-and-args (args) "Return an 'alien function type for 'args." (let ((return-type nil)) (loop for (type arg) on args by #'cddr if arg collect (convert-foreign-type type) into types and collect arg into fargs else do (setf return-type (convert-foreign-type type)) finally (return (values types fargs return-type))))) (defmacro %%foreign-funcall (name types fargs rettype) "Internal guts of '%foreign-funcall." `(alien-funcall (extern-alien ,name (function ,rettype ,@types)) ,@fargs)) (defmacro %foreign-funcall (name &rest args) "Perform a foreign function call, document it more later." (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(%%foreign-funcall ,name ,types ,fargs ,rettype))) (defmacro %foreign-funcall-pointer (ptr &rest args) "Funcall a pointer to a foreign function." (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) (with-unique-names (function) `(with-alien ((,function (* (function ,rettype ,@types)) ,ptr)) (alien-funcall ,function ,@fargs))))) ;;; Callbacks (defmacro %defcallback (name rettype arg-names arg-types &body body) `(alien:defcallback ,name (,(convert-foreign-type rettype) ,@(mapcar (lambda (sym type) (list sym (convert-foreign-type type))) arg-names arg-types)) ,@body)) (declaim (inline %callback)) (defun %callback (name) (alien:callback-sap name)) # Loading and Closing Foreign Libraries (defun %load-foreign-library (name) "Load the foreign library 'name." (ext:load-dynamic-object name)) (defun %close-foreign-library (name) "Closes the foreign library 'name." (ext:close-dynamic-object name)) ;;;# Foreign Globals (defun foreign-symbol-pointer (name) "Returns a pointer to a foreign symbol 'name." (let ((sap (sys:foreign-symbol-address name))) (if (zerop (sys:sap-int sap)) nil sap))) ;;;# Finalizers ;;; TODO : confirm that SCL 's finalizer API is the same as CMUCL 's . -- LO 2006/04/24 (defun finalize (object function) "Pushes a new FUNCTION to the OBJECT's list of finalizers. FUNCTION should take no arguments. Returns OBJECT. For portability reasons, FUNCTION should not attempt to look at OBJECT by closing over it because, in some lisps, OBJECT will already have been garbage collected and is therefore not accessible when FUNCTION is invoked." (ext:finalize object function)) (defun cancel-finalization (object) "Cancels all of OBJECT's finalizers, if any." (ext:cancel-finalization object))
null
https://raw.githubusercontent.com/hoytech/antiweb/53c38f78ea01f04f6d1a1ecdca5c012e7a9ae4bb/bundled/cffi/cffi-scl.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- cffi-scl.lisp --- CFFI-SYS implementation for the Scieneer Common Lisp. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For posterity, a few optimizations we might use in the future: # Features OS/CPU features. Symbol case. # Basic Pointer Operations If the size is constant we can stack-allocate. # Allocation Functions and macros for allocating foreign memory on the stack and on the 'foreign-free in 'unwind-protect for the common usage when the memory has dynamic extent. # Shareable Vectors # Dereferencing macros that optimize the case where the type keyword is constant at compile-time. # Calling Foreign Functions Callbacks # Foreign Globals # Finalizers
Copyright ( C ) 2005 - 2006 , < > Copyright ( C ) 2006 , Scieneer Pty Ltd. files ( the " Software " ) , to deal in the Software without of the Software , and to permit persons to whom the Software is included in all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , #-(and) (defun lisp-string-to-foreign (string ptr size) (c-call::deport-string-to-system-area string ptr size :iso-8859-1)) #-(and) (defun foreign-string-to-lisp (ptr &optional (size most-positive-fixnum) (null-terminated-p t)) (unless (null-pointer-p ptr) (if null-terminated-p (c-call::naturalize-c-string ptr :iso-8859-1) (c-call::naturalize-c-string ptr :iso-8859-1 size)))) # Administrivia (defpackage #:cffi-sys (:use #:common-lisp #:alien #:c-call #:cffi-utils) (:export #:canonicalize-symbol-name-case #:pointerp #:pointer-eq #:null-pointer #:null-pointer-p #:inc-pointer #:make-pointer #:pointer-address #:%foreign-alloc #:foreign-free #:with-foreign-pointer #:%foreign-funcall #:%foreign-funcall-pointer #:%foreign-type-alignment #:%foreign-type-size #:%load-foreign-library #:%close-foreign-library #:%mem-ref #:%mem-set #:make-shareable-byte-vector #:with-pointer-to-vector-data #:foreign-symbol-pointer #:%defcallback #:%callback #:finalize #:cancel-finalization)) (in-package #:cffi-sys) (eval-when (:compile-toplevel :load-toplevel :execute) (mapc (lambda (feature) (pushnew feature *features*)) #+unix cffi-features:unix #+x86 cffi-features:x86 #+amd64 cffi-features:x86-64 #+(and ppc (not ppc64)) cffi-features:ppc32 ))) (defun canonicalize-symbol-name-case (name) (declare (string name)) (if (eq ext:*case-mode* :upper) (string-upcase name) (string-downcase name))) (declaim (inline pointerp)) (defun pointerp (ptr) "Return true if 'ptr is a foreign pointer." (sys:system-area-pointer-p ptr)) (declaim (inline pointer-eq)) (defun pointer-eq (ptr1 ptr2) "Return true if 'ptr1 and 'ptr2 point to the same address." (sys:sap= ptr1 ptr2)) (declaim (inline null-pointer)) (defun null-pointer () "Construct and return a null pointer." (sys:int-sap 0)) (declaim (inline null-pointer-p)) (defun null-pointer-p (ptr) "Return true if 'ptr is a null pointer." (zerop (sys:sap-int ptr))) (declaim (inline inc-pointer)) (defun inc-pointer (ptr offset) "Return a pointer pointing 'offset bytes past 'ptr." (sys:sap+ ptr offset)) (declaim (inline make-pointer)) (defun make-pointer (address) "Return a pointer pointing to 'address." (sys:int-sap address)) (declaim (inline pointer-address)) (defun pointer-address (ptr) "Return the address pointed to by 'ptr." (sys:sap-int ptr)) (defmacro with-foreign-pointer ((var size &optional size-var) &body body) "Bind 'var to 'size bytes of foreign memory during 'body. The pointer in 'var is invalid beyond the dynamic extent of 'body, and may be stack-allocated if supported by the implementation. If 'size-var is supplied, it will be bound to 'size during 'body." (unless size-var (setf size-var (gensym (symbol-name '#:size)))) (cond ((constantp size) (let ((alien-var (gensym (symbol-name '#:alien)))) `(with-alien ((,alien-var (array (unsigned 8) ,(eval size)))) (let ((,size-var ,size) (,var (alien-sap ,alien-var))) (declare (ignorable ,size-var)) ,@body)))) (t `(let ((,size-var ,size)) (alien:with-bytes (,var ,size-var) ,@body))))) heap . The main CFFI package defines macros that wrap ' foreign - alloc and (defun %foreign-alloc (size) "Allocate 'size bytes on the heap and return a pointer." (declare (type (unsigned-byte #-64bit 32 #+64bit 64) size)) (alien-funcall (extern-alien "malloc" (function system-area-pointer unsigned)) size)) (defun foreign-free (ptr) "Free a 'ptr allocated by 'foreign-alloc." (declare (type system-area-pointer ptr)) (alien-funcall (extern-alien "free" (function (values) system-area-pointer)) ptr)) (defun make-shareable-byte-vector (size) "Create a Lisp vector of 'size bytes that can passed to 'with-pointer-to-vector-data." (make-array size :element-type '(unsigned-byte 8))) (defmacro with-pointer-to-vector-data ((ptr-var vector) &body body) "Bind 'ptr-var to a foreign pointer to the data in 'vector." (let ((vector-var (gensym (symbol-name '#:vector)))) `(let ((,vector-var ,vector)) (ext:with-pinned-object (,vector-var) (let ((,ptr-var (sys:vector-sap ,vector-var))) ,@body))))) Define the % MEM - REF and % MEM - SET functions , as well as compiler (defmacro define-mem-accessors (&body pairs) `(progn (defun %mem-ref (ptr type &optional (offset 0)) (ecase type ,@(loop for (keyword fn) in pairs collect `(,keyword (,fn ptr offset))))) (defun %mem-set (value ptr type &optional (offset 0)) (ecase type ,@(loop for (keyword fn) in pairs collect `(,keyword (setf (,fn ptr offset) value))))) (define-compiler-macro %mem-ref (&whole form ptr type &optional (offset 0)) (if (constantp type) (ecase (eval type) ,@(loop for (keyword fn) in pairs collect `(,keyword `(,',fn ,ptr ,offset)))) form)) (define-compiler-macro %mem-set (&whole form value ptr type &optional (offset 0)) (if (constantp type) (once-only (value) (ecase (eval type) ,@(loop for (keyword fn) in pairs collect `(,keyword `(setf (,',fn ,ptr ,offset) ,value))))) form)))) (define-mem-accessors (:char sys:signed-sap-ref-8) (:unsigned-char sys:sap-ref-8) (:short sys:signed-sap-ref-16) (:unsigned-short sys:sap-ref-16) (:int sys:signed-sap-ref-32) (:unsigned-int sys:sap-ref-32) (:long #-64bit sys:signed-sap-ref-32 #+64bit sys:signed-sap-ref-64) (:unsigned-long #-64bit sys:sap-ref-32 #+64bit sys:sap-ref-64) (:long-long sys:signed-sap-ref-64) (:unsigned-long-long sys:sap-ref-64) (:float sys:sap-ref-single) (:double sys:sap-ref-double) #+long-float (:long-double sys:sap-ref-long) (:pointer sys:sap-ref-sap)) (defun convert-foreign-type (type-keyword) "Convert a CFFI type keyword to an ALIEN type." (ecase type-keyword (:char 'char) (:unsigned-char 'unsigned-char) (:short 'short) (:unsigned-short 'unsigned-short) (:int 'int) (:unsigned-int 'unsigned-int) (:long 'long) (:unsigned-long 'unsigned-long) (:long-long '(signed 64)) (:unsigned-long-long '(unsigned 64)) (:float 'single-float) (:double 'double-float) #+long-float (:long-double 'long-float) (:pointer 'system-area-pointer) (:void 'void))) (defun %foreign-type-size (type-keyword) "Return the size in bytes of a foreign type." (values (truncate (alien-internals:alien-type-bits (alien-internals:parse-alien-type (convert-foreign-type type-keyword))) 8))) (defun %foreign-type-alignment (type-keyword) "Return the alignment in bytes of a foreign type." (values (truncate (alien-internals:alien-type-alignment (alien-internals:parse-alien-type (convert-foreign-type type-keyword))) 8))) (defun foreign-funcall-type-and-args (args) "Return an 'alien function type for 'args." (let ((return-type nil)) (loop for (type arg) on args by #'cddr if arg collect (convert-foreign-type type) into types and collect arg into fargs else do (setf return-type (convert-foreign-type type)) finally (return (values types fargs return-type))))) (defmacro %%foreign-funcall (name types fargs rettype) "Internal guts of '%foreign-funcall." `(alien-funcall (extern-alien ,name (function ,rettype ,@types)) ,@fargs)) (defmacro %foreign-funcall (name &rest args) "Perform a foreign function call, document it more later." (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) `(%%foreign-funcall ,name ,types ,fargs ,rettype))) (defmacro %foreign-funcall-pointer (ptr &rest args) "Funcall a pointer to a foreign function." (multiple-value-bind (types fargs rettype) (foreign-funcall-type-and-args args) (with-unique-names (function) `(with-alien ((,function (* (function ,rettype ,@types)) ,ptr)) (alien-funcall ,function ,@fargs))))) (defmacro %defcallback (name rettype arg-names arg-types &body body) `(alien:defcallback ,name (,(convert-foreign-type rettype) ,@(mapcar (lambda (sym type) (list sym (convert-foreign-type type))) arg-names arg-types)) ,@body)) (declaim (inline %callback)) (defun %callback (name) (alien:callback-sap name)) # Loading and Closing Foreign Libraries (defun %load-foreign-library (name) "Load the foreign library 'name." (ext:load-dynamic-object name)) (defun %close-foreign-library (name) "Closes the foreign library 'name." (ext:close-dynamic-object name)) (defun foreign-symbol-pointer (name) "Returns a pointer to a foreign symbol 'name." (let ((sap (sys:foreign-symbol-address name))) (if (zerop (sys:sap-int sap)) nil sap))) TODO : confirm that SCL 's finalizer API is the same as CMUCL 's . -- LO 2006/04/24 (defun finalize (object function) "Pushes a new FUNCTION to the OBJECT's list of finalizers. FUNCTION should take no arguments. Returns OBJECT. For portability reasons, FUNCTION should not attempt to look at OBJECT by closing over it because, in some lisps, OBJECT will already have been garbage collected and is therefore not accessible when FUNCTION is invoked." (ext:finalize object function)) (defun cancel-finalization (object) "Cancels all of OBJECT's finalizers, if any." (ext:cancel-finalization object))
3087707589674610506a262c76f9cd84ba4035893f6f630596cc2cd8ba694d64
serras/t-regex
FPDag2015.hs
# LANGUAGE DeriveGeneric # # LANGUAGE ViewPatterns # # LANGUAGE PostfixOperators # # LANGUAGE QuasiQuotes # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE FlexibleInstances # module Data.Regex.Example.FPDag2015 where import Control.Applicative import Data.Regex.Generics import Data.Regex.TH import GHC.Generics import Test.QuickCheck data List_ a l = Cons_ a l | Nil_ deriving (Show, Generic1) type List a = Fix (List_ a) pattern Cons x xs = Fix (Cons_ x xs) pattern Nil = Fix Nil_ instance Arbitrary a => Arbitrary (List a) where arbitrary = frequency [ (1, return Nil) , (3, Cons <$> arbitrary <*> arbitrary) ] oneTwoOrOneThree :: Regex c (List_ Int) oneTwoOrOneThree = inj $ Cons_ 1 (inj (Cons_ 2 $ inj Nil_) <||> inj (Cons_ 3 $ inj Nil_)) oneTwoThree :: List Char -> Bool oneTwoThree [rx| iter (\k -> inj (Cons_ 'a' (inj $ Cons_ 'b' (inj $ Cons_ 'c' k))) <||> _last <<- inj Nil_) |] = True oneTwoThree _ = False data Tree_ t = Node_ Int t t | Leaf_ Int deriving (Show, Generic1) type Tree = Fix Tree_ pattern Node x l r = Fix (Node_ x l r) pattern Leaf x = Fix (Leaf_ x) matchAny :: Regex c Tree_ matchAny = any_ topTwo :: Regex c Tree_ topTwo = inj (Node_ 2 any_ any_) shape1 :: Regex c Tree_ shape1 = inj $ Node_ 2 (inj $ Node_ 3 any_ any_) (inj $ Node_ 4 any_ any_) shape2 :: Regex c Tree_ shape2 = inj $ Node_ __ (inj $ Node_ 3 any_ any_) (inj $ Node_ 4 any_ any_) allTwos :: Regex c Tree_ allTwos = iter (\k -> inj (Node_ 2 k k) <||> inj (Leaf_ 2)) allTwosPostfix :: Regex c Tree_ allTwosPostfix = ((\k -> inj (Node_ 2 k k) <||> inj (Leaf_ 2))^*) allLeaves :: Tree -> [Int] allLeaves [rx| iter (\k -> inj (Node_ __ k k) <||> leaves <<- inj (Leaf_ __)) |] = map (\(Leaf i) -> i) leaves -- Note this is a Fix-ed element data Expr_ e = Plus_ e e | Times_ e e | Var_ Int deriving (Show, Generic1) type Expr = Fix Expr_ iPlus a b = inj (Plus_ a b) iTimes a b = inj (Times_ a b) iVar v = inj (Var_ v) simplify :: Expr -> Expr simplify [rx| iPlus (iVar 0) (x <<- any_) <||> iPlus (x <<- any_) (iVar 0) <||> iTimes (iVar 1) (x <<- any_) <||> iTimes (x <<- any_) (iVar 1) |] = simplify (head x) simplify x = x
null
https://raw.githubusercontent.com/serras/t-regex/8890f99b849baaf55b7e9ae9fbdb6d818b992ba3/src/Data/Regex/Example/FPDag2015.hs
haskell
# LANGUAGE TypeSynonymInstances # Note this is a Fix-ed element
# LANGUAGE DeriveGeneric # # LANGUAGE ViewPatterns # # LANGUAGE PostfixOperators # # LANGUAGE QuasiQuotes # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # # LANGUAGE FlexibleInstances # module Data.Regex.Example.FPDag2015 where import Control.Applicative import Data.Regex.Generics import Data.Regex.TH import GHC.Generics import Test.QuickCheck data List_ a l = Cons_ a l | Nil_ deriving (Show, Generic1) type List a = Fix (List_ a) pattern Cons x xs = Fix (Cons_ x xs) pattern Nil = Fix Nil_ instance Arbitrary a => Arbitrary (List a) where arbitrary = frequency [ (1, return Nil) , (3, Cons <$> arbitrary <*> arbitrary) ] oneTwoOrOneThree :: Regex c (List_ Int) oneTwoOrOneThree = inj $ Cons_ 1 (inj (Cons_ 2 $ inj Nil_) <||> inj (Cons_ 3 $ inj Nil_)) oneTwoThree :: List Char -> Bool oneTwoThree [rx| iter (\k -> inj (Cons_ 'a' (inj $ Cons_ 'b' (inj $ Cons_ 'c' k))) <||> _last <<- inj Nil_) |] = True oneTwoThree _ = False data Tree_ t = Node_ Int t t | Leaf_ Int deriving (Show, Generic1) type Tree = Fix Tree_ pattern Node x l r = Fix (Node_ x l r) pattern Leaf x = Fix (Leaf_ x) matchAny :: Regex c Tree_ matchAny = any_ topTwo :: Regex c Tree_ topTwo = inj (Node_ 2 any_ any_) shape1 :: Regex c Tree_ shape1 = inj $ Node_ 2 (inj $ Node_ 3 any_ any_) (inj $ Node_ 4 any_ any_) shape2 :: Regex c Tree_ shape2 = inj $ Node_ __ (inj $ Node_ 3 any_ any_) (inj $ Node_ 4 any_ any_) allTwos :: Regex c Tree_ allTwos = iter (\k -> inj (Node_ 2 k k) <||> inj (Leaf_ 2)) allTwosPostfix :: Regex c Tree_ allTwosPostfix = ((\k -> inj (Node_ 2 k k) <||> inj (Leaf_ 2))^*) allLeaves :: Tree -> [Int] allLeaves [rx| iter (\k -> inj (Node_ __ k k) <||> leaves <<- inj (Leaf_ __)) |] = data Expr_ e = Plus_ e e | Times_ e e | Var_ Int deriving (Show, Generic1) type Expr = Fix Expr_ iPlus a b = inj (Plus_ a b) iTimes a b = inj (Times_ a b) iVar v = inj (Var_ v) simplify :: Expr -> Expr simplify [rx| iPlus (iVar 0) (x <<- any_) <||> iPlus (x <<- any_) (iVar 0) <||> iTimes (iVar 1) (x <<- any_) <||> iTimes (x <<- any_) (iVar 1) |] = simplify (head x) simplify x = x
26d6bb8fb3153953f5641bb2cb38c94957980b5dfb712cefc5dba0cdaf816d5d
synduce/Synduce
max_point_sum.ml
* @synduce -NBc -n 30 --no - lifting type list = | Elt of int * int | Cons of int * int * list type clist = | Single of int * int | Concat of clist * clist let rec repr = function | Single (a, b) -> Elt (a, b) | Concat (x, y) -> dec y x and dec l1 = function | Single (a, b) -> Cons (a, b, repr l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec csorted l = sorted (repr l) and sorted = function | Elt (x, y) -> true | Cons (x, y, l) -> aux (x + y) l and aux a = function | Elt (x, y) -> a <= x + y | Cons (x, y, l) -> a <= x + y && aux (x + y) l ;; let rec spec = function | Elt (a, b) -> a + b | Cons (a, b, tl) -> max (a + b) (spec tl) ;; let rec target = function | Single (a, b) -> [%synt s0] a b | Concat (l, r) -> [%synt s1] (target r) [@@requires csorted] ;; assert (target = repr @@ spec)
null
https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/sortedlist/max_point_sum.ml
ocaml
* @synduce -NBc -n 30 --no - lifting type list = | Elt of int * int | Cons of int * int * list type clist = | Single of int * int | Concat of clist * clist let rec repr = function | Single (a, b) -> Elt (a, b) | Concat (x, y) -> dec y x and dec l1 = function | Single (a, b) -> Cons (a, b, repr l1) | Concat (x, y) -> dec (Concat (y, l1)) x ;; let rec csorted l = sorted (repr l) and sorted = function | Elt (x, y) -> true | Cons (x, y, l) -> aux (x + y) l and aux a = function | Elt (x, y) -> a <= x + y | Cons (x, y, l) -> a <= x + y && aux (x + y) l ;; let rec spec = function | Elt (a, b) -> a + b | Cons (a, b, tl) -> max (a + b) (spec tl) ;; let rec target = function | Single (a, b) -> [%synt s0] a b | Concat (l, r) -> [%synt s1] (target r) [@@requires csorted] ;; assert (target = repr @@ spec)
b94e91ab81c165c926cdd2b12ad91ef0c6e673f5c5f60aaef50d2810d5be1199
UnixJunkie/dokeysto
test_lz4.ml
open Printf let n = 1_000_000 (* RWDBZ *) let test_rwdbz () = let module Rwdbz = Dokeysto_lz4.Db_lz4.RWZ in let start = Unix.gettimeofday () in let rwz = Rwdbz.create "rwdb_lz4" in for i = 1 to n do let s = string_of_int i in Rwdbz.add rwz s s done; let stop = Unix.gettimeofday () in printf "RWZ records creation rate: %.2f/s\n%!" (float n /. (stop -. start)); Rwdbz.sync rwz; let start' = Unix.gettimeofday () in for i = 1 to n do let s = string_of_int i in assert(s = Rwdbz.find rwz s); done; let stop' = Unix.gettimeofday () in printf "RWZ records find rate: %.2f/s\n%!" (float n /. (stop' -. start')); let _ = Sys.command "ls -lh rwdb_lz4 rwdb_lz4.idx" in Rwdbz.close rwz let test_rwdbz_gen () = let module Rwdbz_gen = Dokeysto_lz4.Db_lz4_gen.RWZ (Dokeysto.Gen_gen) in let start = Unix.gettimeofday () in let rwz = Rwdbz_gen.create "rwdb_lz4_gen" in for i = 1 to n do Rwdbz_gen.add rwz i i done; let stop = Unix.gettimeofday () in printf "RWZ_gen records creation rate: %.2f/s\n%!" (float n /. (stop -. start)); Rwdbz_gen.sync rwz; let start' = Unix.gettimeofday () in for i = 1 to n do assert(i = Rwdbz_gen.find rwz i); done; let stop' = Unix.gettimeofday () in printf "RWZ_gen records find rate: %.2f/s\n%!" (float n /. (stop' -. start')); let _ = Sys.command "ls -lh rwdb_lz4_gen rwdb_lz4_gen.idx" in Rwdbz_gen.close rwz RODBZ let test_rodbz () = let module Rodbz = Dokeysto_lz4.Db_lz4.ROZ in let roz = Rodbz.open_existing "rwdb_lz4" in let start''' = Unix.gettimeofday () in for i = 1 to n do let s = string_of_int i in assert(s = Rodbz.find roz s); done; let stop''' = Unix.gettimeofday () in printf "ROZ records find rate: %.2f/s\n%!" (float n /. (stop''' -. start''')) let test_rodbz_gen () = let module Rodbz_gen = Dokeysto_lz4.Db_lz4_gen.ROZ (Dokeysto.Gen_gen) in let roz = Rodbz_gen.open_existing "rwdb_lz4_gen" in let start''' = Unix.gettimeofday () in for i = 1 to n do assert(i = Rodbz_gen.find roz i); done; let stop''' = Unix.gettimeofday () in printf "ROZ_gen records find rate: %.2f/s\n%!" (float n /. (stop''' -. start''')) let () = test_rwdbz (); test_rwdbz_gen (); test_rodbz (); test_rodbz_gen ()
null
https://raw.githubusercontent.com/UnixJunkie/dokeysto/48b0486769d127f60d523cce89db001179ced92b/src/test_lz4.ml
ocaml
RWDBZ
open Printf let n = 1_000_000 let test_rwdbz () = let module Rwdbz = Dokeysto_lz4.Db_lz4.RWZ in let start = Unix.gettimeofday () in let rwz = Rwdbz.create "rwdb_lz4" in for i = 1 to n do let s = string_of_int i in Rwdbz.add rwz s s done; let stop = Unix.gettimeofday () in printf "RWZ records creation rate: %.2f/s\n%!" (float n /. (stop -. start)); Rwdbz.sync rwz; let start' = Unix.gettimeofday () in for i = 1 to n do let s = string_of_int i in assert(s = Rwdbz.find rwz s); done; let stop' = Unix.gettimeofday () in printf "RWZ records find rate: %.2f/s\n%!" (float n /. (stop' -. start')); let _ = Sys.command "ls -lh rwdb_lz4 rwdb_lz4.idx" in Rwdbz.close rwz let test_rwdbz_gen () = let module Rwdbz_gen = Dokeysto_lz4.Db_lz4_gen.RWZ (Dokeysto.Gen_gen) in let start = Unix.gettimeofday () in let rwz = Rwdbz_gen.create "rwdb_lz4_gen" in for i = 1 to n do Rwdbz_gen.add rwz i i done; let stop = Unix.gettimeofday () in printf "RWZ_gen records creation rate: %.2f/s\n%!" (float n /. (stop -. start)); Rwdbz_gen.sync rwz; let start' = Unix.gettimeofday () in for i = 1 to n do assert(i = Rwdbz_gen.find rwz i); done; let stop' = Unix.gettimeofday () in printf "RWZ_gen records find rate: %.2f/s\n%!" (float n /. (stop' -. start')); let _ = Sys.command "ls -lh rwdb_lz4_gen rwdb_lz4_gen.idx" in Rwdbz_gen.close rwz RODBZ let test_rodbz () = let module Rodbz = Dokeysto_lz4.Db_lz4.ROZ in let roz = Rodbz.open_existing "rwdb_lz4" in let start''' = Unix.gettimeofday () in for i = 1 to n do let s = string_of_int i in assert(s = Rodbz.find roz s); done; let stop''' = Unix.gettimeofday () in printf "ROZ records find rate: %.2f/s\n%!" (float n /. (stop''' -. start''')) let test_rodbz_gen () = let module Rodbz_gen = Dokeysto_lz4.Db_lz4_gen.ROZ (Dokeysto.Gen_gen) in let roz = Rodbz_gen.open_existing "rwdb_lz4_gen" in let start''' = Unix.gettimeofday () in for i = 1 to n do assert(i = Rodbz_gen.find roz i); done; let stop''' = Unix.gettimeofday () in printf "ROZ_gen records find rate: %.2f/s\n%!" (float n /. (stop''' -. start''')) let () = test_rwdbz (); test_rwdbz_gen (); test_rodbz (); test_rodbz_gen ()
b15e735ac86b7d4384dbcffa0f104692f6ecd340f0cae26a81f6c043cbfa5f0f
BrownCS1260/class-compiler
compile.ml
open S_exp open Asm open Util open Ast_lam open Constant_folding let num_shift = 2 let num_mask = 0b11 let num_tag = 0b00 let bool_shift = 7 let bool_mask = 0b1111111 let bool_tag = 0b0011111 let heap_mask = 0b111 let pair_tag = 0b010 let fn_tag = 0b110 let operand_of_bool (b : bool) : operand = Imm (((if b then 1 else 0) lsl bool_shift) lor bool_tag) let operand_of_num (x : int) : operand = Imm ((x lsl num_shift) lor num_tag) let zf_to_bool : directive list = [ Mov (Reg Rax, Imm 0); Setz (Reg Rax); Shl (Reg Rax, Imm bool_shift); Or (Reg Rax, Imm bool_tag); ] let lf_to_bool : directive list = [ Mov (Reg Rax, Imm 0); Setl (Reg Rax); Shl (Reg Rax, Imm bool_shift); Or (Reg Rax, Imm bool_tag); ] modifies R8 let ensure_num (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm num_mask); Cmp (Reg R8, Imm num_tag); Jnz "error"; ] modifies R8 let ensure_pair (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm heap_mask); Cmp (Reg R8, Imm pair_tag); Jnz "error"; ] modifies R8 let ensure_fn (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm heap_mask); Cmp (Reg R8, Imm fn_tag); Jnz "error"; ] let stack_address stack_index = MemOffset (Reg Rsp, Imm stack_index) let align_stack_index (stack_index : int) : int = if stack_index mod 16 = -8 then stack_index else stack_index - 8 let rec compile_exp (defns : defn list) (tab : int symtab) (stack_index : int) (exp : expr) (is_tail : bool) : directive list = match exp with | Call (f, args) when is_tail -> let compiled_args = args |> List.mapi (fun i arg -> compile_exp defns tab (stack_index - (8 * i)) arg false @ [ Mov (stack_address (stack_index - (8 * i)), Reg Rax) ]) |> List.concat in let moved_args = args |> List.mapi (fun i _ -> [ Mov (Reg R8, stack_address (stack_index - (8 * i))); Mov (stack_address ((i + 1) * -8), Reg R8); ]) |> List.concat in compiled_args @ compile_exp defns tab (stack_index - (8 * (List.length args + 2))) f false @ ensure_fn (Reg Rax) @ moved_args @ [ Mov (stack_address ((List.length args + 1) * -8), Reg Rax); Sub (Reg Rax, Imm fn_tag); Mov (Reg Rax, MemOffset (Reg Rax, Imm 0)); ] @ [ ComputedJmp (Reg Rax) ] | Call (f, args) -> let stack_base = align_stack_index (stack_index + 8) in let compiled_args = args |> List.mapi (fun i arg -> compile_exp defns tab (stack_base - (8 * (i + 2))) arg false @ [ Mov (stack_address (stack_base - (8 * (i + 2))), Reg Rax) ]) |> List.concat in compiled_args @ compile_exp defns tab (stack_base - (8 * (List.length args + 2))) f false @ ensure_fn (Reg Rax) @ [ Mov (stack_address (stack_base - (8 * (List.length args + 2))), Reg Rax); Sub (Reg Rax, Imm fn_tag); Mov (Reg Rax, MemOffset (Reg Rax, Imm 0)); ] @ [ Add (Reg Rsp, Imm stack_base); ComputedCall (Reg Rax); Sub (Reg Rsp, Imm stack_base); ] | Var var when Symtab.mem var tab -> [ Mov (Reg Rax, stack_address (Symtab.find var tab)) ] | Var var when is_defn defns var -> [ LeaLabel (Reg Rax, defn_label var); Mov (MemOffset (Reg Rdi, Imm 0), Reg Rax); Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm fn_tag); Add (Reg Rdi, Imm 8); ] | Closure f -> let defn = get_defn defns f in let fvs = fv defns (List.map (fun d -> d.name) defns @ defn.args) defn.body in let fv_movs = List.mapi (fun i var -> [ Mov (Reg Rax, stack_address (Symtab.find var tab)); Mov (MemOffset (Reg Rdi, Imm (8 * (i + 1))), Reg Rax); ]) fvs in if List.exists (fun v -> not (Symtab.mem v tab)) fvs then raise (BadExpression exp) else [ LeaLabel (Reg Rax, defn_label f); Mov (MemOffset (Reg Rdi, Imm 0), Reg Rax); ] @ List.concat fv_movs @ [ Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm fn_tag); Add (Reg Rdi, Imm (8 * (List.length fvs + 1))); ] | Var _ -> raise (BadExpression exp) | Num n -> [ Mov (Reg Rax, operand_of_num n) ] | True -> [ Mov (Reg Rax, operand_of_bool true) ] | False -> [ Mov (Reg Rax, operand_of_bool false) ] | Prim1 (Not, arg) -> compile_exp defns tab stack_index arg false @ [ Cmp (Reg Rax, operand_of_bool false) ] @ zf_to_bool | Prim1 (ZeroP, arg) -> compile_exp defns tab stack_index arg false @ [ Cmp (Reg Rax, operand_of_num 0) ] @ zf_to_bool | Prim1 (NumP, arg) -> compile_exp defns tab stack_index arg false @ [ And (Reg Rax, Imm num_mask); Cmp (Reg Rax, Imm num_tag) ] @ zf_to_bool | Prim1 (Add1, arg) -> compile_exp defns tab stack_index arg false @ ensure_num (Reg Rax) @ [ Add (Reg Rax, operand_of_num 1) ] | Prim1 (Sub1, arg) -> compile_exp defns tab stack_index arg false @ ensure_num (Reg Rax) @ [ Sub (Reg Rax, operand_of_num 1) ] | If (test_exp, then_exp, else_exp) -> let else_label = Util.gensym "else" in let continue_label = Util.gensym "continue" in compile_exp defns tab stack_index test_exp false @ [ Cmp (Reg Rax, operand_of_bool false); Jz else_label ] @ compile_exp defns tab stack_index then_exp is_tail @ [ Jmp continue_label ] @ [ Label else_label ] @ compile_exp defns tab stack_index else_exp is_tail @ [ Label continue_label ] | Prim2 (Plus, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Add (Reg Rax, Reg R8) ] | Prim2 (Minus, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, Reg Rax); Mov (Reg Rax, stack_address stack_index); Sub (Reg Rax, Reg R8); ] | Prim2 (Lt, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Cmp (Reg R8, Reg Rax) ] @ lf_to_bool | Prim2 (Eq, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Cmp (Reg R8, Reg Rax) ] @ zf_to_bool | Let (var, e, body) -> compile_exp defns tab stack_index e false @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns (Symtab.add var stack_index tab) (stack_index - 8) body is_tail | Prim2 (Pair, e1, e2) -> compile_exp defns tab stack_index e1 false @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ [ Mov (Reg R8, stack_address stack_index); Mov (MemOffset (Reg Rdi, Imm 0), Reg R8); Mov (MemOffset (Reg Rdi, Imm 8), Reg Rax); Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm pair_tag); Add (Reg Rdi, Imm 16); ] | Prim1 (Left, e) -> compile_exp defns tab stack_index e false @ ensure_pair (Reg Rax) @ [ Mov (Reg Rax, MemOffset (Reg Rax, Imm (-pair_tag))) ] | Prim1 (Right, e) -> compile_exp defns tab stack_index e false @ ensure_pair (Reg Rax) @ [ Mov (Reg Rax, MemOffset (Reg Rax, Imm (-pair_tag + 8))) ] | Prim0 ReadNum -> [ Mov (stack_address stack_index, Reg Rdi); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "read_num"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); ] | Prim1 (Print, e) -> compile_exp defns tab stack_index e false @ [ Mov (stack_address stack_index, Reg Rdi); Mov (Reg Rdi, Reg Rax); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "print_value"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); Mov (Reg Rax, operand_of_bool true); ] | Prim0 Newline -> [ Mov (stack_address stack_index, Reg Rdi); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "print_newline"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); Mov (Reg Rax, operand_of_bool true); ] | Do exps -> List.mapi (fun i exp -> compile_exp defns tab stack_index exp (if i = List.length exps - 1 then is_tail else false)) exps |> List.concat let compile_defn (defns : defn list) (defn : defn) : directive list = let fvs = fv defns (List.map (fun d -> d.name) defns @ defn.args) defn.body in let ftab = defn.args @ fvs |> List.mapi (fun i arg -> (arg, -8 * (i + 1))) |> Symtab.of_list in let fvs_to_stack = [ Mov (Reg Rax, stack_address (-8 * (List.length defn.args + 1))); Sub (Reg Rax, Imm fn_tag); Add (Reg Rax, Imm 8); ] @ List.concat (List.mapi (fun i _ -> [ Mov (Reg R8, MemOffset (Reg Rax, Imm (i * 8))); Mov (stack_address (-8 * (List.length defn.args + 1 + i)), Reg R8); ]) fvs) in [ Align 8; Label (defn_label defn.name) ] @ fvs_to_stack @ compile_exp defns ftab (-8 * (Symtab.cardinal ftab + 1)) defn.body true @ [ Ret ] let compile (program : s_exp list) : string = let prog = program_of_s_exps program |> fold_program in [ Global "entry"; Extern "error"; Extern "read_num"; Extern "print_value"; Extern "print_newline"; ] @ [ Label "entry" ] @ compile_exp prog.defns Symtab.empty (-8) prog.body true @ [ Ret ] @ List.concat_map (compile_defn prog.defns) prog.defns |> List.map string_of_directive |> String.concat "\n" let compile_to_file (program : string) : unit = let file = open_out "program.s" in output_string file (compile (parse_many program)); close_out file let compile_and_run (program : string) : unit = compile_to_file program; ignore (Unix.system "nasm program.s -f elf64 -o program.o"); ignore (Unix.system "gcc -no-pie program.o runtime.o -o program"); ignore (Unix.system "./program") let compile_and_run_io (program : string) (input : string) : string = compile_to_file program; ignore (Unix.system "nasm program.s -f elf64 -o program.o"); ignore (Unix.system "gcc -no-pie program.o runtime.o -o program"); let inp, outp = Unix.open_process "./program" in output_string outp input; close_out outp; let r = input_all inp in close_in inp; r let compile_and_run_err (program : string) (input : string) : string = try compile_and_run_io program input with BadExpression _ -> "ERROR" let difftest (examples : (string * string) list) = let results = List.map (fun (ex, i) -> (compile_and_run_err ex i, Interp.interp_err ex i)) examples in List.for_all (fun (r1, r2) -> r1 = r2) results let test () = difftest [ ("(print (read-num))", "1") ]
null
https://raw.githubusercontent.com/BrownCS1260/class-compiler/31450320bfb3fd7da0e6473e29d001248ee087cf/lib/compile.ml
ocaml
open S_exp open Asm open Util open Ast_lam open Constant_folding let num_shift = 2 let num_mask = 0b11 let num_tag = 0b00 let bool_shift = 7 let bool_mask = 0b1111111 let bool_tag = 0b0011111 let heap_mask = 0b111 let pair_tag = 0b010 let fn_tag = 0b110 let operand_of_bool (b : bool) : operand = Imm (((if b then 1 else 0) lsl bool_shift) lor bool_tag) let operand_of_num (x : int) : operand = Imm ((x lsl num_shift) lor num_tag) let zf_to_bool : directive list = [ Mov (Reg Rax, Imm 0); Setz (Reg Rax); Shl (Reg Rax, Imm bool_shift); Or (Reg Rax, Imm bool_tag); ] let lf_to_bool : directive list = [ Mov (Reg Rax, Imm 0); Setl (Reg Rax); Shl (Reg Rax, Imm bool_shift); Or (Reg Rax, Imm bool_tag); ] modifies R8 let ensure_num (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm num_mask); Cmp (Reg R8, Imm num_tag); Jnz "error"; ] modifies R8 let ensure_pair (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm heap_mask); Cmp (Reg R8, Imm pair_tag); Jnz "error"; ] modifies R8 let ensure_fn (op : operand) : directive list = [ Mov (Reg R8, op); And (Reg R8, Imm heap_mask); Cmp (Reg R8, Imm fn_tag); Jnz "error"; ] let stack_address stack_index = MemOffset (Reg Rsp, Imm stack_index) let align_stack_index (stack_index : int) : int = if stack_index mod 16 = -8 then stack_index else stack_index - 8 let rec compile_exp (defns : defn list) (tab : int symtab) (stack_index : int) (exp : expr) (is_tail : bool) : directive list = match exp with | Call (f, args) when is_tail -> let compiled_args = args |> List.mapi (fun i arg -> compile_exp defns tab (stack_index - (8 * i)) arg false @ [ Mov (stack_address (stack_index - (8 * i)), Reg Rax) ]) |> List.concat in let moved_args = args |> List.mapi (fun i _ -> [ Mov (Reg R8, stack_address (stack_index - (8 * i))); Mov (stack_address ((i + 1) * -8), Reg R8); ]) |> List.concat in compiled_args @ compile_exp defns tab (stack_index - (8 * (List.length args + 2))) f false @ ensure_fn (Reg Rax) @ moved_args @ [ Mov (stack_address ((List.length args + 1) * -8), Reg Rax); Sub (Reg Rax, Imm fn_tag); Mov (Reg Rax, MemOffset (Reg Rax, Imm 0)); ] @ [ ComputedJmp (Reg Rax) ] | Call (f, args) -> let stack_base = align_stack_index (stack_index + 8) in let compiled_args = args |> List.mapi (fun i arg -> compile_exp defns tab (stack_base - (8 * (i + 2))) arg false @ [ Mov (stack_address (stack_base - (8 * (i + 2))), Reg Rax) ]) |> List.concat in compiled_args @ compile_exp defns tab (stack_base - (8 * (List.length args + 2))) f false @ ensure_fn (Reg Rax) @ [ Mov (stack_address (stack_base - (8 * (List.length args + 2))), Reg Rax); Sub (Reg Rax, Imm fn_tag); Mov (Reg Rax, MemOffset (Reg Rax, Imm 0)); ] @ [ Add (Reg Rsp, Imm stack_base); ComputedCall (Reg Rax); Sub (Reg Rsp, Imm stack_base); ] | Var var when Symtab.mem var tab -> [ Mov (Reg Rax, stack_address (Symtab.find var tab)) ] | Var var when is_defn defns var -> [ LeaLabel (Reg Rax, defn_label var); Mov (MemOffset (Reg Rdi, Imm 0), Reg Rax); Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm fn_tag); Add (Reg Rdi, Imm 8); ] | Closure f -> let defn = get_defn defns f in let fvs = fv defns (List.map (fun d -> d.name) defns @ defn.args) defn.body in let fv_movs = List.mapi (fun i var -> [ Mov (Reg Rax, stack_address (Symtab.find var tab)); Mov (MemOffset (Reg Rdi, Imm (8 * (i + 1))), Reg Rax); ]) fvs in if List.exists (fun v -> not (Symtab.mem v tab)) fvs then raise (BadExpression exp) else [ LeaLabel (Reg Rax, defn_label f); Mov (MemOffset (Reg Rdi, Imm 0), Reg Rax); ] @ List.concat fv_movs @ [ Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm fn_tag); Add (Reg Rdi, Imm (8 * (List.length fvs + 1))); ] | Var _ -> raise (BadExpression exp) | Num n -> [ Mov (Reg Rax, operand_of_num n) ] | True -> [ Mov (Reg Rax, operand_of_bool true) ] | False -> [ Mov (Reg Rax, operand_of_bool false) ] | Prim1 (Not, arg) -> compile_exp defns tab stack_index arg false @ [ Cmp (Reg Rax, operand_of_bool false) ] @ zf_to_bool | Prim1 (ZeroP, arg) -> compile_exp defns tab stack_index arg false @ [ Cmp (Reg Rax, operand_of_num 0) ] @ zf_to_bool | Prim1 (NumP, arg) -> compile_exp defns tab stack_index arg false @ [ And (Reg Rax, Imm num_mask); Cmp (Reg Rax, Imm num_tag) ] @ zf_to_bool | Prim1 (Add1, arg) -> compile_exp defns tab stack_index arg false @ ensure_num (Reg Rax) @ [ Add (Reg Rax, operand_of_num 1) ] | Prim1 (Sub1, arg) -> compile_exp defns tab stack_index arg false @ ensure_num (Reg Rax) @ [ Sub (Reg Rax, operand_of_num 1) ] | If (test_exp, then_exp, else_exp) -> let else_label = Util.gensym "else" in let continue_label = Util.gensym "continue" in compile_exp defns tab stack_index test_exp false @ [ Cmp (Reg Rax, operand_of_bool false); Jz else_label ] @ compile_exp defns tab stack_index then_exp is_tail @ [ Jmp continue_label ] @ [ Label else_label ] @ compile_exp defns tab stack_index else_exp is_tail @ [ Label continue_label ] | Prim2 (Plus, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Add (Reg Rax, Reg R8) ] | Prim2 (Minus, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, Reg Rax); Mov (Reg Rax, stack_address stack_index); Sub (Reg Rax, Reg R8); ] | Prim2 (Lt, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Cmp (Reg R8, Reg Rax) ] @ lf_to_bool | Prim2 (Eq, e1, e2) -> compile_exp defns tab stack_index e1 false @ ensure_num (Reg Rax) @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ ensure_num (Reg Rax) @ [ Mov (Reg R8, stack_address stack_index) ] @ [ Cmp (Reg R8, Reg Rax) ] @ zf_to_bool | Let (var, e, body) -> compile_exp defns tab stack_index e false @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns (Symtab.add var stack_index tab) (stack_index - 8) body is_tail | Prim2 (Pair, e1, e2) -> compile_exp defns tab stack_index e1 false @ [ Mov (stack_address stack_index, Reg Rax) ] @ compile_exp defns tab (stack_index - 8) e2 false @ [ Mov (Reg R8, stack_address stack_index); Mov (MemOffset (Reg Rdi, Imm 0), Reg R8); Mov (MemOffset (Reg Rdi, Imm 8), Reg Rax); Mov (Reg Rax, Reg Rdi); Or (Reg Rax, Imm pair_tag); Add (Reg Rdi, Imm 16); ] | Prim1 (Left, e) -> compile_exp defns tab stack_index e false @ ensure_pair (Reg Rax) @ [ Mov (Reg Rax, MemOffset (Reg Rax, Imm (-pair_tag))) ] | Prim1 (Right, e) -> compile_exp defns tab stack_index e false @ ensure_pair (Reg Rax) @ [ Mov (Reg Rax, MemOffset (Reg Rax, Imm (-pair_tag + 8))) ] | Prim0 ReadNum -> [ Mov (stack_address stack_index, Reg Rdi); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "read_num"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); ] | Prim1 (Print, e) -> compile_exp defns tab stack_index e false @ [ Mov (stack_address stack_index, Reg Rdi); Mov (Reg Rdi, Reg Rax); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "print_value"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); Mov (Reg Rax, operand_of_bool true); ] | Prim0 Newline -> [ Mov (stack_address stack_index, Reg Rdi); Add (Reg Rsp, Imm (align_stack_index stack_index)); Call "print_newline"; Sub (Reg Rsp, Imm (align_stack_index stack_index)); Mov (Reg Rdi, stack_address stack_index); Mov (Reg Rax, operand_of_bool true); ] | Do exps -> List.mapi (fun i exp -> compile_exp defns tab stack_index exp (if i = List.length exps - 1 then is_tail else false)) exps |> List.concat let compile_defn (defns : defn list) (defn : defn) : directive list = let fvs = fv defns (List.map (fun d -> d.name) defns @ defn.args) defn.body in let ftab = defn.args @ fvs |> List.mapi (fun i arg -> (arg, -8 * (i + 1))) |> Symtab.of_list in let fvs_to_stack = [ Mov (Reg Rax, stack_address (-8 * (List.length defn.args + 1))); Sub (Reg Rax, Imm fn_tag); Add (Reg Rax, Imm 8); ] @ List.concat (List.mapi (fun i _ -> [ Mov (Reg R8, MemOffset (Reg Rax, Imm (i * 8))); Mov (stack_address (-8 * (List.length defn.args + 1 + i)), Reg R8); ]) fvs) in [ Align 8; Label (defn_label defn.name) ] @ fvs_to_stack @ compile_exp defns ftab (-8 * (Symtab.cardinal ftab + 1)) defn.body true @ [ Ret ] let compile (program : s_exp list) : string = let prog = program_of_s_exps program |> fold_program in [ Global "entry"; Extern "error"; Extern "read_num"; Extern "print_value"; Extern "print_newline"; ] @ [ Label "entry" ] @ compile_exp prog.defns Symtab.empty (-8) prog.body true @ [ Ret ] @ List.concat_map (compile_defn prog.defns) prog.defns |> List.map string_of_directive |> String.concat "\n" let compile_to_file (program : string) : unit = let file = open_out "program.s" in output_string file (compile (parse_many program)); close_out file let compile_and_run (program : string) : unit = compile_to_file program; ignore (Unix.system "nasm program.s -f elf64 -o program.o"); ignore (Unix.system "gcc -no-pie program.o runtime.o -o program"); ignore (Unix.system "./program") let compile_and_run_io (program : string) (input : string) : string = compile_to_file program; ignore (Unix.system "nasm program.s -f elf64 -o program.o"); ignore (Unix.system "gcc -no-pie program.o runtime.o -o program"); let inp, outp = Unix.open_process "./program" in output_string outp input; close_out outp; let r = input_all inp in close_in inp; r let compile_and_run_err (program : string) (input : string) : string = try compile_and_run_io program input with BadExpression _ -> "ERROR" let difftest (examples : (string * string) list) = let results = List.map (fun (ex, i) -> (compile_and_run_err ex i, Interp.interp_err ex i)) examples in List.for_all (fun (r1, r2) -> r1 = r2) results let test () = difftest [ ("(print (read-num))", "1") ]
dd21bf615236047c287908ff2cdc246ccedc7a86fff3bf8da92d5e1cd4ccb496
lambdaisland/uri
uri_test.cljc
(ns lambdaisland.uri-test (:require [clojure.test :as t :refer [are deftest is testing]] [lambdaisland.uri :as uri] [lambdaisland.uri.normalize :as norm] [lambdaisland.uri.platform :as platform] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :as tc] [clojure.string :as str]) #?(:clj (:import lambdaisland.uri.URI))) (deftest parsing (testing "happy path" (are [x y] (= y (uri/parse x)) "::8080/path?query=value#fragment" (uri/URI. "http" "user" "password" "example.com" "8080" "/path" "query=value" "fragment") "/happy/path" (uri/URI. nil nil nil nil nil "/happy/path" nil nil) "relative/path" (uri/URI. nil nil nil nil nil "relative/path" nil nil) "" (uri/URI. "http" nil nil "example.com" nil nil nil nil) ))) (deftest joining (are [x y] (= (uri/parse y) (apply uri/join (map uri/parse x))) ["" ""] "" ["" "/a/path"] "" ["" "/a/path"] "" ["" "a/relative/path"] "" ["/" "a/relative/path"] "" ["/foo/bar/" "a/relative/path"] "/foo/bar/a/relative/path" ["" "a/relative/path"] "" ["/" "../../x/y"] "") (testing "-rel-test.html" (are [x y] (= y (str (uri/join (uri/parse ";p?q") (uri/parse x)))) "g" "" "./g" "" "g/" "/" "/g" "" "//g" "" "?y" ";p?y" "g?y" "" "#s" ";p?q#s" "g#s" "#s" "g?y#s" "#s" ";x" "/;x" "g;x" ";x" "g;x?y#s" ";x?y#s" "" ";p?q" "." "/" "./" "/" ".." "/" "../" "/" "../g" "" "../.." "/" "../../" "/" "../../g" "" "../../../g" "" "../../../../g" "" "/./g" "" "/g" "" "g." "." ".g" "" "g.." ".." "..g" "" "./../g" "" "./g/" "/" "g/h" "" "h" "" "g;x=1/./y" ";x=1/y" "g;x=1/../y" "" "g?y/./x" "" "g?y/../x" "" "g#s/./x" "#s/./x" "g#s/../x" "#s/../x" "http:g" "http:g")) (testing "coerces its arguments" (is (= (uri/join "" "/a/b/c") (uri/parse ""))) #?(:clj (is (= (uri/join (java.net.URI. "") "/a/b/c") (uri/parse "")))))) (deftest lambdaisland-uri-URI (let [example "::8080/path?query=value#fragment" parsed (uri/uri example)] (testing "it allows keyword based access" (is (= (:scheme parsed) "http")) (is (= (:user parsed) "usr")) (is (= (:password parsed) "pwd")) (is (= (:host parsed) "example.com")) (is (= (:port parsed) "8080")) (is (= (:path parsed) "/path")) (is (= (:query parsed) "query=value")) (is (= (:fragment parsed) "fragment"))) #?(:bb nil :default (testing "it allows map-style access" (is (= (parsed :scheme) "http")) (is (= (parsed :user) "usr")) (is (= (parsed :password) "pwd")) (is (= (parsed :host) "example.com")) (is (= (parsed :port) "8080")) (is (= (parsed :path) "/path")) (is (= (parsed :query) "query=value")) (is (= (parsed :fragment) "fragment")))) (testing "it converts correctly to string" (is (= (str parsed) example))))) (deftest lambdaisland-uri-relative? (are [x] (uri/relative? (uri/parse x)) "//example.com" "/some/path" "?only=a-query" "#only-a-fragment" "//example.com:8080/foo/bar?baz#baq") (are [x] (uri/absolute? (uri/parse x)) "" ":8080/foo/bar?baz#baq")) (deftest query-map-test (is (= {:foo "bar", :aaa "bbb"} (uri/query-map ""))) (is (= {"foo" "bar", "aaa" "bbb"} (uri/query-map "" {:keywordize? false}))) (is (= {:id ["1" "2"]} (uri/query-map "?id=1&id=2"))) (is (= {:id "2"} (uri/query-map "?id=1&id=2" {:multikeys :never}))) (is (= {:foo ["bar"], :id ["2"]} (uri/query-map "?foo=bar&id=2" {:multikeys :always}))) (is (= {:foo " +&xxx=123"} (uri/query-map "?foo=%20%2B%26xxx%3D123")))) (deftest assoc-query-test (is (= (uri/uri "") (uri/assoc-query "" :foo "baq" :hello "world"))) (is (= (uri/uri "") (uri/assoc-query* "" {:foo "baq" :hello "world"}))) (is (= (uri/uri "?id=1&id=2") (uri/assoc-query* "" (uri/query-map "?id=1&id=2")))) (is (= (uri/uri "?id=1") (uri/assoc-query "?id=1&name=jack" :name nil))) (is (= (uri/uri "?foo=+%2B%26%3D") (uri/assoc-query "" :foo " +&="))) (is (= "a=a+b&b=b+c" (-> "/foo" (uri/assoc-query* {:a "a b"}) (uri/assoc-query* {:b "b c"}) :query))) (is (= {:a "a b"} (-> "/foo" (uri/assoc-query* {:a "a b"}) uri/query-map)))) (deftest uri-predicate-test (is (true? (uri/uri? (uri/uri "/foo"))))) (def query-map-gen (gen/map (gen/such-that #(not= ":/" (str %)) gen/keyword) gen/string)) (tc/defspec query-string-round-trips 100 (prop/for-all [q query-map-gen] (let [res (-> q uri/map->query-string uri/query-string->map)] (or (and (empty? q) (empty? res)) ;; (= nil {}) (= q res)))))
null
https://raw.githubusercontent.com/lambdaisland/uri/c3aab11508faf0301dc666216119e93e602334e3/test/lambdaisland/uri_test.cljc
clojure
(= nil {})
(ns lambdaisland.uri-test (:require [clojure.test :as t :refer [are deftest is testing]] [lambdaisland.uri :as uri] [lambdaisland.uri.normalize :as norm] [lambdaisland.uri.platform :as platform] [clojure.test.check.generators :as gen] [clojure.test.check.properties :as prop] [clojure.test.check.clojure-test :as tc] [clojure.string :as str]) #?(:clj (:import lambdaisland.uri.URI))) (deftest parsing (testing "happy path" (are [x y] (= y (uri/parse x)) "::8080/path?query=value#fragment" (uri/URI. "http" "user" "password" "example.com" "8080" "/path" "query=value" "fragment") "/happy/path" (uri/URI. nil nil nil nil nil "/happy/path" nil nil) "relative/path" (uri/URI. nil nil nil nil nil "relative/path" nil nil) "" (uri/URI. "http" nil nil "example.com" nil nil nil nil) ))) (deftest joining (are [x y] (= (uri/parse y) (apply uri/join (map uri/parse x))) ["" ""] "" ["" "/a/path"] "" ["" "/a/path"] "" ["" "a/relative/path"] "" ["/" "a/relative/path"] "" ["/foo/bar/" "a/relative/path"] "/foo/bar/a/relative/path" ["" "a/relative/path"] "" ["/" "../../x/y"] "") (testing "-rel-test.html" (are [x y] (= y (str (uri/join (uri/parse ";p?q") (uri/parse x)))) "g" "" "./g" "" "g/" "/" "/g" "" "//g" "" "?y" ";p?y" "g?y" "" "#s" ";p?q#s" "g#s" "#s" "g?y#s" "#s" ";x" "/;x" "g;x" ";x" "g;x?y#s" ";x?y#s" "" ";p?q" "." "/" "./" "/" ".." "/" "../" "/" "../g" "" "../.." "/" "../../" "/" "../../g" "" "../../../g" "" "../../../../g" "" "/./g" "" "/g" "" "g." "." ".g" "" "g.." ".." "..g" "" "./../g" "" "./g/" "/" "g/h" "" "h" "" "g;x=1/./y" ";x=1/y" "g;x=1/../y" "" "g?y/./x" "" "g?y/../x" "" "g#s/./x" "#s/./x" "g#s/../x" "#s/../x" "http:g" "http:g")) (testing "coerces its arguments" (is (= (uri/join "" "/a/b/c") (uri/parse ""))) #?(:clj (is (= (uri/join (java.net.URI. "") "/a/b/c") (uri/parse "")))))) (deftest lambdaisland-uri-URI (let [example "::8080/path?query=value#fragment" parsed (uri/uri example)] (testing "it allows keyword based access" (is (= (:scheme parsed) "http")) (is (= (:user parsed) "usr")) (is (= (:password parsed) "pwd")) (is (= (:host parsed) "example.com")) (is (= (:port parsed) "8080")) (is (= (:path parsed) "/path")) (is (= (:query parsed) "query=value")) (is (= (:fragment parsed) "fragment"))) #?(:bb nil :default (testing "it allows map-style access" (is (= (parsed :scheme) "http")) (is (= (parsed :user) "usr")) (is (= (parsed :password) "pwd")) (is (= (parsed :host) "example.com")) (is (= (parsed :port) "8080")) (is (= (parsed :path) "/path")) (is (= (parsed :query) "query=value")) (is (= (parsed :fragment) "fragment")))) (testing "it converts correctly to string" (is (= (str parsed) example))))) (deftest lambdaisland-uri-relative? (are [x] (uri/relative? (uri/parse x)) "//example.com" "/some/path" "?only=a-query" "#only-a-fragment" "//example.com:8080/foo/bar?baz#baq") (are [x] (uri/absolute? (uri/parse x)) "" ":8080/foo/bar?baz#baq")) (deftest query-map-test (is (= {:foo "bar", :aaa "bbb"} (uri/query-map ""))) (is (= {"foo" "bar", "aaa" "bbb"} (uri/query-map "" {:keywordize? false}))) (is (= {:id ["1" "2"]} (uri/query-map "?id=1&id=2"))) (is (= {:id "2"} (uri/query-map "?id=1&id=2" {:multikeys :never}))) (is (= {:foo ["bar"], :id ["2"]} (uri/query-map "?foo=bar&id=2" {:multikeys :always}))) (is (= {:foo " +&xxx=123"} (uri/query-map "?foo=%20%2B%26xxx%3D123")))) (deftest assoc-query-test (is (= (uri/uri "") (uri/assoc-query "" :foo "baq" :hello "world"))) (is (= (uri/uri "") (uri/assoc-query* "" {:foo "baq" :hello "world"}))) (is (= (uri/uri "?id=1&id=2") (uri/assoc-query* "" (uri/query-map "?id=1&id=2")))) (is (= (uri/uri "?id=1") (uri/assoc-query "?id=1&name=jack" :name nil))) (is (= (uri/uri "?foo=+%2B%26%3D") (uri/assoc-query "" :foo " +&="))) (is (= "a=a+b&b=b+c" (-> "/foo" (uri/assoc-query* {:a "a b"}) (uri/assoc-query* {:b "b c"}) :query))) (is (= {:a "a b"} (-> "/foo" (uri/assoc-query* {:a "a b"}) uri/query-map)))) (deftest uri-predicate-test (is (true? (uri/uri? (uri/uri "/foo"))))) (def query-map-gen (gen/map (gen/such-that #(not= ":/" (str %)) gen/keyword) gen/string)) (tc/defspec query-string-round-trips 100 (prop/for-all [q query-map-gen] (let [res (-> q uri/map->query-string uri/query-string->map)] (= q res)))))
4fd109c6c256b38c269bfc02e5de2db0cc79584c60a678368ee235b2cb4af863
min-nguyen/prob-fx
Lift.hs
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE ScopedTypeVariables # {- | For lifting arbitrary monadic computations into an algebraic effect setting. -} module Effects.Lift ( Lift(..) , lift , handleLift) where import Prog ( call, Member(prj), Prog(..) ) import Data.Function (fix) -- | Lift a monadic computation @m a@ into the effect @Lift m@ newtype Lift m a = Lift (m a) -- | Wrapper function for calling @Lift@ lift :: (Member (Lift m) es) => m a -> Prog es a lift = call . Lift -- | Handle @Lift m@ as the last effect handleLift :: forall m w. Monad m => Prog '[Lift m] w -> m w handleLift (Val x) = return x handleLift (Op u q) = case prj u of Just (Lift m) -> m >>= handleLift . q Nothing -> error "Impossible: Nothing cannot occur"
null
https://raw.githubusercontent.com/min-nguyen/prob-fx/870a341f344638887ac63f6e6f7e3a352a03ef62/src/Effects/Lift.hs
haskell
# LANGUAGE GADTs # | For lifting arbitrary monadic computations into an algebraic effect setting. | Lift a monadic computation @m a@ into the effect @Lift m@ | Wrapper function for calling @Lift@ | Handle @Lift m@ as the last effect
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # module Effects.Lift ( Lift(..) , lift , handleLift) where import Prog ( call, Member(prj), Prog(..) ) import Data.Function (fix) newtype Lift m a = Lift (m a) lift :: (Member (Lift m) es) => m a -> Prog es a lift = call . Lift handleLift :: forall m w. Monad m => Prog '[Lift m] w -> m w handleLift (Val x) = return x handleLift (Op u q) = case prj u of Just (Lift m) -> m >>= handleLift . q Nothing -> error "Impossible: Nothing cannot occur"
f8c99da0a92483ef9b0092d9b403ff410ff609097edf8cafb165c2ca24086a58
footprintanalytics/footprint-web
google.clj
(ns metabase.api.google "/api/google endpoints" (:require [compojure.core :refer [PUT]] [metabase.api.common :as api] [metabase.api.common.validation :as validation] [metabase.integrations.google :as google] [metabase.models.setting :as setting] [schema.core :as s] [toucan.db :as db])) (api/defendpoint PUT "/settings" "Update Google Sign-In related settings. You must be a superuser or have `setting` permission to do this." [:as {{:keys [google-auth-client-id google-auth-enabled google-auth-auto-create-accounts-domain]} :body}] {google-auth-client-id (s/maybe s/Str) google-auth-enabled (s/maybe s/Bool) google-auth-auto-create-accounts-domain (s/maybe s/Str)} (validation/check-has-application-permission :setting) Set google - auth - enabled in a separate step because it requires the client ID to be set first (db/transaction (setting/set-many! {:google-auth-client-id google-auth-client-id :google-auth-auto-create-accounts-domain google-auth-auto-create-accounts-domain}) (google/google-auth-enabled! google-auth-enabled))) (api/define-routes)
null
https://raw.githubusercontent.com/footprintanalytics/footprint-web/d3090d943dd9fcea493c236f79e7ef8a36ae17fc/src/metabase/api/google.clj
clojure
(ns metabase.api.google "/api/google endpoints" (:require [compojure.core :refer [PUT]] [metabase.api.common :as api] [metabase.api.common.validation :as validation] [metabase.integrations.google :as google] [metabase.models.setting :as setting] [schema.core :as s] [toucan.db :as db])) (api/defendpoint PUT "/settings" "Update Google Sign-In related settings. You must be a superuser or have `setting` permission to do this." [:as {{:keys [google-auth-client-id google-auth-enabled google-auth-auto-create-accounts-domain]} :body}] {google-auth-client-id (s/maybe s/Str) google-auth-enabled (s/maybe s/Bool) google-auth-auto-create-accounts-domain (s/maybe s/Str)} (validation/check-has-application-permission :setting) Set google - auth - enabled in a separate step because it requires the client ID to be set first (db/transaction (setting/set-many! {:google-auth-client-id google-auth-client-id :google-auth-auto-create-accounts-domain google-auth-auto-create-accounts-domain}) (google/google-auth-enabled! google-auth-enabled))) (api/define-routes)
fce0c0b0d8587b276d2496565112b9176d649115cabfb27b736d6f3214103da5
ndmitchell/supero
Example6.hs
module Example6 where import Prelude hiding (head,fail,reverse,foldl) data Expr = Add Expr Expr | Mul Expr Expr | Val Int eval :: Expr -> Int eval (Add x y) = eval x + eval y eval (Mul x y) = eval x - eval y eval (Val x) = x main x y z = eval (Add (Mul (Val x) (Val y)) (Val z))
null
https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/example/Example6.hs
haskell
module Example6 where import Prelude hiding (head,fail,reverse,foldl) data Expr = Add Expr Expr | Mul Expr Expr | Val Int eval :: Expr -> Int eval (Add x y) = eval x + eval y eval (Mul x y) = eval x - eval y eval (Val x) = x main x y z = eval (Add (Mul (Val x) (Val y)) (Val z))
bc5009e5773011fbe4af9223c32cf389a4acd098224210ac87ba252cacc543cc
ocurrent/opam-health-check
server_configfile.ml
type t = { yamlfile : Fpath.t; mutable name : string option; mutable port : int option; mutable public_url : string option; mutable admin_port : int option; mutable auto_run_interval : int option; mutable processes : int option; mutable enable_dune_cache : bool option; mutable enable_logs_compression : bool option; mutable default_repository : Intf.Github.t option; mutable extra_repositories : Intf.Repository.t list option; mutable with_test : bool option; mutable with_lower_bound : bool option; mutable list_command : string option; mutable extra_command : string option; mutable platform_os : string option; mutable platform_arch : string option; mutable platform_pool : string option; mutable platform_distribution : string option; mutable platform_image : string option; mutable ocaml_switches : Intf.Switch.t list option; mutable slack_webhooks : Uri.t list option; mutable job_timeout : float option; } let create_conf yamlfile = { yamlfile; name = None; port = None; public_url = None; admin_port = None; auto_run_interval = None; processes = None; enable_dune_cache = None; enable_logs_compression = None; default_repository = None; extra_repositories = None; with_test = None; with_lower_bound = None; list_command = None; extra_command = None; platform_os = None; platform_arch = None; platform_pool = None; platform_distribution = None; platform_image = None; ocaml_switches = None; slack_webhooks = None; job_timeout = None; } let set_field ~field set = function | Some _ -> failwith (Printf.sprintf "Config parser: '%s' is defined twice" field) | None -> set () let get_comp_str = function | `String s -> Intf.Compiler.from_string s | _ -> failwith "string expected" let get_comp = function | `O [name, `String switch] -> Intf.Switch.create ~name ~switch | _ -> failwith "key and value expected" let get_repo = function | `O [name, `O ["github", `String github]] | `O [name, `String github] -> Intf.Repository.create ~name ~github ~for_switches:None | `O [name, `O [("github", `String github); ("for-switches", `A for_switches)]] -> let for_switches = List.map get_comp_str for_switches in Intf.Repository.create ~name ~github ~for_switches:(Some for_switches) | _ -> failwith "key and value expected" let get_uri = function | `String s -> Uri.of_string s | _ -> failwith "string expected" let check_is_docker_compatible name = if not (String.for_all Oca_lib.char_is_docker_compatible name) then failwith "name field has to contain only alphanumerical characters and '.'" let set_config conf = function | _, `Null -> () | "name" as field, `String name -> check_is_docker_compatible name; set_field ~field (fun () -> conf.name <- Some name) conf.name | "port" as field, `Float port -> set_field ~field (fun () -> conf.port <- Some (int_of_float port)) conf.port | "public-url" as field, `String public_url -> set_field ~field (fun () -> conf.public_url <- Some public_url) conf.public_url | "admin-port" as field, `Float admin_port -> set_field ~field (fun () -> conf.admin_port <- Some (int_of_float admin_port)) conf.admin_port | "auto-run-interval" as field, `Float auto_run_interval -> set_field ~field (fun () -> conf.auto_run_interval <- Some (int_of_float auto_run_interval)) conf.auto_run_interval | "enable-dune-cache" as field, `Bool dune_cache -> set_field ~field (fun () -> conf.enable_dune_cache <- Some dune_cache) conf.enable_dune_cache | "enable-logs-compression" as field, `Bool logs_compression -> set_field ~field (fun () -> conf.enable_logs_compression <- Some logs_compression) conf.enable_logs_compression | "default-repository" as field, `String github -> let repo = Intf.Github.create github in set_field ~field (fun () -> conf.default_repository <- Some repo) conf.default_repository | "extra-repositories" as field, `A repositories -> let repositories = List.map get_repo repositories in set_field ~field (fun () -> conf.extra_repositories <- Some repositories) conf.extra_repositories | "with-test" as field, `Bool with_test -> set_field ~field (fun () -> conf.with_test <- Some with_test) conf.with_test | "with-lower-bound" as field, `Bool with_lower_bound -> set_field ~field (fun () -> conf.with_lower_bound <- Some with_lower_bound) conf.with_lower_bound | "processes" as field, `Float processes -> set_field ~field (fun () -> conf.processes <- Some (int_of_float processes)) conf.processes | "list-command" as field, `String list_command -> set_field ~field (fun () -> conf.list_command <- Some list_command) conf.list_command | "extra-command" as field, `String extra_command -> set_field ~field (fun () -> conf.extra_command <- Some extra_command) conf.extra_command | "platform", `O platform -> List.iter (function | _, `Null -> () | "os" as field, `String os -> set_field ~field (fun () -> conf.platform_os <- Some os) conf.platform_os | "arch" as field, `String arch -> set_field ~field (fun () -> conf.platform_arch <- Some arch) conf.platform_arch | "custom-pool" as field, `String pool -> set_field ~field (fun () -> conf.platform_pool <- Some pool) conf.platform_pool | "distribution" as field, `String distribution -> set_field ~field (fun () -> conf.platform_distribution <- Some distribution) conf.platform_distribution | "image" as field, `String image -> set_field ~field (fun () -> conf.platform_image <- Some image) conf.platform_image | field, _ -> failwith (Printf.sprintf "Config parser: '%s' field not recognized" field) ) platform | "ocaml-switches" as field, `A switches -> let switches = List.map get_comp switches in set_field ~field (fun () -> conf.ocaml_switches <- Some switches) conf.ocaml_switches | "slack-webhooks" as field, `A webhooks -> let webhooks = List.map get_uri webhooks in set_field ~field (fun () -> conf.slack_webhooks <- Some webhooks) conf.slack_webhooks | "job-timeout" as field, `Float job_timeout -> set_field ~field (fun () -> conf.job_timeout <- Some job_timeout) conf.job_timeout | field, _ -> failwith (Printf.sprintf "Config parser: '%s' field not recognized" field) let yaml_of_extra_repositories l = let aux repo = match Intf.Repository.for_switches repo with | None -> `String (Intf.Github.to_string (Intf.Repository.github repo)) | Some for_switches -> `O [ ("github", `String (Intf.Github.to_string (Intf.Repository.github repo))); ("for-switches", `A (List.map (fun s -> `String (Intf.Compiler.to_string s)) for_switches)); ] in `A (List.map (fun repo -> `O [Intf.Repository.name repo, aux repo]) l) let yaml_of_ocaml_switches l = `A (List.map (fun s -> `O [Intf.(Compiler.to_string (Switch.name s)), `String (Intf.Switch.switch s)]) l) let yaml_of_slack_webhooks l = `A (List.map (fun s -> `String (Uri.to_string s)) l) let yaml_of_str_opt = function | None -> `Null | Some x -> `String x let yaml_of_conf conf = `O [ "name", `String (Option.get_exn_or "conf.name" conf.name); "port", `Float (float_of_int (Option.get_exn_or "conf.port" conf.port)); "public-url", `String (Option.get_exn_or "conf.public_url" conf.public_url); "admin-port", `Float (float_of_int (Option.get_exn_or "conf.admin_port" conf.admin_port)); "auto-run-interval", `Float (float_of_int (Option.get_exn_or "conf.auto_run_interval" conf.auto_run_interval)); "processes", `Float (float_of_int (Option.get_exn_or "conf.processes" conf.processes)); "enable-dune-cache", `Bool (Option.get_exn_or "conf.enable_dune_cache" conf.enable_dune_cache); "enable-logs-compression", `Bool (Option.get_exn_or "conf.enable_logs_compression" conf.enable_logs_compression); "default-repository", `String (Intf.Github.to_string (Option.get_exn_or "conf.default_repository" conf.default_repository)); "extra-repositories", Option.map_or ~default:`Null yaml_of_extra_repositories conf.extra_repositories; "with-test", `Bool (Option.get_exn_or "conf.with_test" conf.with_test); "with-lower-bound", `Bool (Option.get_exn_or "conf.with_lower_bound" conf.with_lower_bound); "list-command", `String (Option.get_exn_or "conf.list_command" conf.list_command); "extra-command", Option.map_or ~default:`Null (fun s -> `String s) conf.extra_command; "platform", `O [ "os", `String (Option.get_exn_or "conf.platform_os" conf.platform_os); "arch", `String (Option.get_exn_or "conf.platform_arch" conf.platform_arch); "custom-pool", yaml_of_str_opt conf.platform_pool; "distribution", `String (Option.get_exn_or "conf.platform_distribution" conf.platform_distribution); "image", `String (Option.get_exn_or "conf.platform_image" conf.platform_image); ]; "ocaml-switches", Option.map_or ~default:`Null yaml_of_ocaml_switches conf.ocaml_switches; "slack-webhooks", Option.map_or ~default:`Null yaml_of_slack_webhooks conf.slack_webhooks; "job-timeout", `Float (Option.get_exn_or "conf.job-timeout" conf.job_timeout); ] let set_defaults conf = if Option.is_none conf.name then conf.name <- Some Oca_lib.default_server_name; if Option.is_none conf.port then conf.port <- Some (int_of_string Oca_lib.default_html_port); if Option.is_none conf.public_url then conf.public_url <- Some Oca_lib.default_public_url; if Option.is_none conf.admin_port then conf.admin_port <- Some (int_of_string Oca_lib.default_admin_port); if Option.is_none conf.auto_run_interval then conf.auto_run_interval <- Some Oca_lib.default_auto_run_interval; if Option.is_none conf.processes then conf.processes <- Some Oca_lib.default_processes; if Option.is_none conf.enable_dune_cache then conf.enable_dune_cache <- Some false; (* NOTE: Too unstable to enable by default *) if Option.is_none conf.enable_logs_compression then conf.enable_logs_compression <- Some true; (* NOTE: Requires too much disk space for regular users *) if Option.is_none conf.default_repository then conf.default_repository <- Some (Intf.Github.create "ocaml/opam-repository"); if Option.is_none conf.extra_repositories then conf.extra_repositories <- Some []; if Option.is_none conf.with_test then TODO : Enable by default in the future ( takes 1.5x the time ) if Option.is_none conf.with_lower_bound then conf.with_lower_bound <- Some false; (* TODO: Enable by default in the future (takes 2x the time) *) if Option.is_none conf.list_command then conf.list_command <- Some Oca_lib.default_list_command; if Option.is_none conf.platform_os then conf.platform_os <- Some "linux"; if Option.is_none conf.platform_arch then conf.platform_arch <- Some "x86_64"; if Option.is_none conf.platform_distribution then conf.platform_distribution <- Some "debian-unstable"; if Option.is_none conf.platform_image then conf.platform_image <- Some "ocaml/opam:debian-unstable@sha256:a13c01aab19715953d47831effb2beb0ac90dc98c13b216893db2550799e3b9f"; if Option.is_none conf.slack_webhooks then conf.slack_webhooks <- Some []; if Option.is_none conf.job_timeout then NOTE : 2 hours by default . TODO : Maybe move to 1 hour when the cluster is more stable let yaml = Yaml.to_string_exn (yaml_of_conf conf) in IO.with_out (Fpath.to_string conf.yamlfile) (fun out -> output_string out yaml) let set_auto_run_interval conf i = conf.auto_run_interval <- Some i; set_defaults conf; Lwt.return_unit let set_processes conf i = conf.processes <- Some i; set_defaults conf; Lwt.return_unit let set_ocaml_switches conf switches = conf.ocaml_switches <- Some switches; set_defaults conf; Lwt.return_unit let set_default_ocaml_switches conf f = if Option.is_none conf.ocaml_switches then let%lwt x = f () in set_ocaml_switches conf x else Lwt.return_unit let set_list_command conf cmd = conf.list_command <- Some cmd; set_defaults conf; Lwt.return_unit let set_extra_command conf cmd = conf.extra_command <- cmd; set_defaults conf; Lwt.return_unit let set_slack_webhooks conf webhooks = conf.slack_webhooks <- Some webhooks; set_defaults conf; Lwt.return_unit let set_platform_image conf image = conf.platform_image <- Some image; set_defaults conf; Lwt.return_unit let create yamlfile yaml = let conf = create_conf yamlfile in List.iter (set_config conf) yaml; set_defaults conf; conf let from_workdir workdir = let yamlfile = Server_workdirs.configfile workdir in let yaml = IO.with_in ~flags:[Open_creat] (Fpath.to_string yamlfile) (IO.read_all ?size:None) in match Yaml.of_string_exn yaml with | `O yaml -> create yamlfile yaml | `String "" | `Null -> create yamlfile [] | _ -> failwith "Config parser: unrecognized config file" let name {name; _} = Option.get_exn_or "name" name let port {port; _} = Option.get_exn_or "name" port let public_url {public_url; _} = Option.get_exn_or "public_url" public_url let admin_port {admin_port; _} = Option.get_exn_or "admin_port" admin_port let auto_run_interval {auto_run_interval; _} = Option.get_exn_or "auto_run_interval" auto_run_interval let processes {processes; _} = Option.get_exn_or "processes" processes let enable_dune_cache {enable_dune_cache; _} = Option.get_exn_or "enable_dune_cache" enable_dune_cache let enable_logs_compression {enable_logs_compression; _} = Option.get_exn_or "enable_logs_compression" enable_logs_compression let default_repository {default_repository; _} = Option.get_exn_or "default_repository" default_repository let extra_repositories {extra_repositories; _} = Option.get_exn_or "extra_repositories" extra_repositories let with_test {with_test; _} = Option.get_exn_or "with_test" with_test let with_lower_bound {with_lower_bound; _} = Option.get_exn_or "with_lower_bound" with_lower_bound let list_command {list_command; _} = Option.get_exn_or "list_command" list_command let extra_command {extra_command; _} = extra_command let platform_os {platform_os; _} = Option.get_exn_or "platform_os" platform_os let platform_arch {platform_arch; _} = Option.get_exn_or "platform_arch" platform_arch let platform_pool ({platform_pool; _} as conf) = match platform_pool with | None -> platform_os conf^"-"^platform_arch conf | Some pool -> pool let platform_distribution {platform_distribution; _} = Option.get_exn_or "platform_distribution" platform_distribution let platform_image {platform_image; _} = Option.get_exn_or "platform_image" platform_image let ocaml_switches {ocaml_switches; _} = ocaml_switches let slack_webhooks {slack_webhooks; _} = Option.get_exn_or "slack_webhooks" slack_webhooks let job_timeout {job_timeout; _} = Option.get_exn_or "job_timeout" job_timeout
null
https://raw.githubusercontent.com/ocurrent/opam-health-check/07dbcb82f1c6101823994b2f61b5f058025f6863/lib/server_configfile.ml
ocaml
NOTE: Too unstable to enable by default NOTE: Requires too much disk space for regular users TODO: Enable by default in the future (takes 2x the time)
type t = { yamlfile : Fpath.t; mutable name : string option; mutable port : int option; mutable public_url : string option; mutable admin_port : int option; mutable auto_run_interval : int option; mutable processes : int option; mutable enable_dune_cache : bool option; mutable enable_logs_compression : bool option; mutable default_repository : Intf.Github.t option; mutable extra_repositories : Intf.Repository.t list option; mutable with_test : bool option; mutable with_lower_bound : bool option; mutable list_command : string option; mutable extra_command : string option; mutable platform_os : string option; mutable platform_arch : string option; mutable platform_pool : string option; mutable platform_distribution : string option; mutable platform_image : string option; mutable ocaml_switches : Intf.Switch.t list option; mutable slack_webhooks : Uri.t list option; mutable job_timeout : float option; } let create_conf yamlfile = { yamlfile; name = None; port = None; public_url = None; admin_port = None; auto_run_interval = None; processes = None; enable_dune_cache = None; enable_logs_compression = None; default_repository = None; extra_repositories = None; with_test = None; with_lower_bound = None; list_command = None; extra_command = None; platform_os = None; platform_arch = None; platform_pool = None; platform_distribution = None; platform_image = None; ocaml_switches = None; slack_webhooks = None; job_timeout = None; } let set_field ~field set = function | Some _ -> failwith (Printf.sprintf "Config parser: '%s' is defined twice" field) | None -> set () let get_comp_str = function | `String s -> Intf.Compiler.from_string s | _ -> failwith "string expected" let get_comp = function | `O [name, `String switch] -> Intf.Switch.create ~name ~switch | _ -> failwith "key and value expected" let get_repo = function | `O [name, `O ["github", `String github]] | `O [name, `String github] -> Intf.Repository.create ~name ~github ~for_switches:None | `O [name, `O [("github", `String github); ("for-switches", `A for_switches)]] -> let for_switches = List.map get_comp_str for_switches in Intf.Repository.create ~name ~github ~for_switches:(Some for_switches) | _ -> failwith "key and value expected" let get_uri = function | `String s -> Uri.of_string s | _ -> failwith "string expected" let check_is_docker_compatible name = if not (String.for_all Oca_lib.char_is_docker_compatible name) then failwith "name field has to contain only alphanumerical characters and '.'" let set_config conf = function | _, `Null -> () | "name" as field, `String name -> check_is_docker_compatible name; set_field ~field (fun () -> conf.name <- Some name) conf.name | "port" as field, `Float port -> set_field ~field (fun () -> conf.port <- Some (int_of_float port)) conf.port | "public-url" as field, `String public_url -> set_field ~field (fun () -> conf.public_url <- Some public_url) conf.public_url | "admin-port" as field, `Float admin_port -> set_field ~field (fun () -> conf.admin_port <- Some (int_of_float admin_port)) conf.admin_port | "auto-run-interval" as field, `Float auto_run_interval -> set_field ~field (fun () -> conf.auto_run_interval <- Some (int_of_float auto_run_interval)) conf.auto_run_interval | "enable-dune-cache" as field, `Bool dune_cache -> set_field ~field (fun () -> conf.enable_dune_cache <- Some dune_cache) conf.enable_dune_cache | "enable-logs-compression" as field, `Bool logs_compression -> set_field ~field (fun () -> conf.enable_logs_compression <- Some logs_compression) conf.enable_logs_compression | "default-repository" as field, `String github -> let repo = Intf.Github.create github in set_field ~field (fun () -> conf.default_repository <- Some repo) conf.default_repository | "extra-repositories" as field, `A repositories -> let repositories = List.map get_repo repositories in set_field ~field (fun () -> conf.extra_repositories <- Some repositories) conf.extra_repositories | "with-test" as field, `Bool with_test -> set_field ~field (fun () -> conf.with_test <- Some with_test) conf.with_test | "with-lower-bound" as field, `Bool with_lower_bound -> set_field ~field (fun () -> conf.with_lower_bound <- Some with_lower_bound) conf.with_lower_bound | "processes" as field, `Float processes -> set_field ~field (fun () -> conf.processes <- Some (int_of_float processes)) conf.processes | "list-command" as field, `String list_command -> set_field ~field (fun () -> conf.list_command <- Some list_command) conf.list_command | "extra-command" as field, `String extra_command -> set_field ~field (fun () -> conf.extra_command <- Some extra_command) conf.extra_command | "platform", `O platform -> List.iter (function | _, `Null -> () | "os" as field, `String os -> set_field ~field (fun () -> conf.platform_os <- Some os) conf.platform_os | "arch" as field, `String arch -> set_field ~field (fun () -> conf.platform_arch <- Some arch) conf.platform_arch | "custom-pool" as field, `String pool -> set_field ~field (fun () -> conf.platform_pool <- Some pool) conf.platform_pool | "distribution" as field, `String distribution -> set_field ~field (fun () -> conf.platform_distribution <- Some distribution) conf.platform_distribution | "image" as field, `String image -> set_field ~field (fun () -> conf.platform_image <- Some image) conf.platform_image | field, _ -> failwith (Printf.sprintf "Config parser: '%s' field not recognized" field) ) platform | "ocaml-switches" as field, `A switches -> let switches = List.map get_comp switches in set_field ~field (fun () -> conf.ocaml_switches <- Some switches) conf.ocaml_switches | "slack-webhooks" as field, `A webhooks -> let webhooks = List.map get_uri webhooks in set_field ~field (fun () -> conf.slack_webhooks <- Some webhooks) conf.slack_webhooks | "job-timeout" as field, `Float job_timeout -> set_field ~field (fun () -> conf.job_timeout <- Some job_timeout) conf.job_timeout | field, _ -> failwith (Printf.sprintf "Config parser: '%s' field not recognized" field) let yaml_of_extra_repositories l = let aux repo = match Intf.Repository.for_switches repo with | None -> `String (Intf.Github.to_string (Intf.Repository.github repo)) | Some for_switches -> `O [ ("github", `String (Intf.Github.to_string (Intf.Repository.github repo))); ("for-switches", `A (List.map (fun s -> `String (Intf.Compiler.to_string s)) for_switches)); ] in `A (List.map (fun repo -> `O [Intf.Repository.name repo, aux repo]) l) let yaml_of_ocaml_switches l = `A (List.map (fun s -> `O [Intf.(Compiler.to_string (Switch.name s)), `String (Intf.Switch.switch s)]) l) let yaml_of_slack_webhooks l = `A (List.map (fun s -> `String (Uri.to_string s)) l) let yaml_of_str_opt = function | None -> `Null | Some x -> `String x let yaml_of_conf conf = `O [ "name", `String (Option.get_exn_or "conf.name" conf.name); "port", `Float (float_of_int (Option.get_exn_or "conf.port" conf.port)); "public-url", `String (Option.get_exn_or "conf.public_url" conf.public_url); "admin-port", `Float (float_of_int (Option.get_exn_or "conf.admin_port" conf.admin_port)); "auto-run-interval", `Float (float_of_int (Option.get_exn_or "conf.auto_run_interval" conf.auto_run_interval)); "processes", `Float (float_of_int (Option.get_exn_or "conf.processes" conf.processes)); "enable-dune-cache", `Bool (Option.get_exn_or "conf.enable_dune_cache" conf.enable_dune_cache); "enable-logs-compression", `Bool (Option.get_exn_or "conf.enable_logs_compression" conf.enable_logs_compression); "default-repository", `String (Intf.Github.to_string (Option.get_exn_or "conf.default_repository" conf.default_repository)); "extra-repositories", Option.map_or ~default:`Null yaml_of_extra_repositories conf.extra_repositories; "with-test", `Bool (Option.get_exn_or "conf.with_test" conf.with_test); "with-lower-bound", `Bool (Option.get_exn_or "conf.with_lower_bound" conf.with_lower_bound); "list-command", `String (Option.get_exn_or "conf.list_command" conf.list_command); "extra-command", Option.map_or ~default:`Null (fun s -> `String s) conf.extra_command; "platform", `O [ "os", `String (Option.get_exn_or "conf.platform_os" conf.platform_os); "arch", `String (Option.get_exn_or "conf.platform_arch" conf.platform_arch); "custom-pool", yaml_of_str_opt conf.platform_pool; "distribution", `String (Option.get_exn_or "conf.platform_distribution" conf.platform_distribution); "image", `String (Option.get_exn_or "conf.platform_image" conf.platform_image); ]; "ocaml-switches", Option.map_or ~default:`Null yaml_of_ocaml_switches conf.ocaml_switches; "slack-webhooks", Option.map_or ~default:`Null yaml_of_slack_webhooks conf.slack_webhooks; "job-timeout", `Float (Option.get_exn_or "conf.job-timeout" conf.job_timeout); ] let set_defaults conf = if Option.is_none conf.name then conf.name <- Some Oca_lib.default_server_name; if Option.is_none conf.port then conf.port <- Some (int_of_string Oca_lib.default_html_port); if Option.is_none conf.public_url then conf.public_url <- Some Oca_lib.default_public_url; if Option.is_none conf.admin_port then conf.admin_port <- Some (int_of_string Oca_lib.default_admin_port); if Option.is_none conf.auto_run_interval then conf.auto_run_interval <- Some Oca_lib.default_auto_run_interval; if Option.is_none conf.processes then conf.processes <- Some Oca_lib.default_processes; if Option.is_none conf.enable_dune_cache then if Option.is_none conf.enable_logs_compression then if Option.is_none conf.default_repository then conf.default_repository <- Some (Intf.Github.create "ocaml/opam-repository"); if Option.is_none conf.extra_repositories then conf.extra_repositories <- Some []; if Option.is_none conf.with_test then TODO : Enable by default in the future ( takes 1.5x the time ) if Option.is_none conf.with_lower_bound then if Option.is_none conf.list_command then conf.list_command <- Some Oca_lib.default_list_command; if Option.is_none conf.platform_os then conf.platform_os <- Some "linux"; if Option.is_none conf.platform_arch then conf.platform_arch <- Some "x86_64"; if Option.is_none conf.platform_distribution then conf.platform_distribution <- Some "debian-unstable"; if Option.is_none conf.platform_image then conf.platform_image <- Some "ocaml/opam:debian-unstable@sha256:a13c01aab19715953d47831effb2beb0ac90dc98c13b216893db2550799e3b9f"; if Option.is_none conf.slack_webhooks then conf.slack_webhooks <- Some []; if Option.is_none conf.job_timeout then NOTE : 2 hours by default . TODO : Maybe move to 1 hour when the cluster is more stable let yaml = Yaml.to_string_exn (yaml_of_conf conf) in IO.with_out (Fpath.to_string conf.yamlfile) (fun out -> output_string out yaml) let set_auto_run_interval conf i = conf.auto_run_interval <- Some i; set_defaults conf; Lwt.return_unit let set_processes conf i = conf.processes <- Some i; set_defaults conf; Lwt.return_unit let set_ocaml_switches conf switches = conf.ocaml_switches <- Some switches; set_defaults conf; Lwt.return_unit let set_default_ocaml_switches conf f = if Option.is_none conf.ocaml_switches then let%lwt x = f () in set_ocaml_switches conf x else Lwt.return_unit let set_list_command conf cmd = conf.list_command <- Some cmd; set_defaults conf; Lwt.return_unit let set_extra_command conf cmd = conf.extra_command <- cmd; set_defaults conf; Lwt.return_unit let set_slack_webhooks conf webhooks = conf.slack_webhooks <- Some webhooks; set_defaults conf; Lwt.return_unit let set_platform_image conf image = conf.platform_image <- Some image; set_defaults conf; Lwt.return_unit let create yamlfile yaml = let conf = create_conf yamlfile in List.iter (set_config conf) yaml; set_defaults conf; conf let from_workdir workdir = let yamlfile = Server_workdirs.configfile workdir in let yaml = IO.with_in ~flags:[Open_creat] (Fpath.to_string yamlfile) (IO.read_all ?size:None) in match Yaml.of_string_exn yaml with | `O yaml -> create yamlfile yaml | `String "" | `Null -> create yamlfile [] | _ -> failwith "Config parser: unrecognized config file" let name {name; _} = Option.get_exn_or "name" name let port {port; _} = Option.get_exn_or "name" port let public_url {public_url; _} = Option.get_exn_or "public_url" public_url let admin_port {admin_port; _} = Option.get_exn_or "admin_port" admin_port let auto_run_interval {auto_run_interval; _} = Option.get_exn_or "auto_run_interval" auto_run_interval let processes {processes; _} = Option.get_exn_or "processes" processes let enable_dune_cache {enable_dune_cache; _} = Option.get_exn_or "enable_dune_cache" enable_dune_cache let enable_logs_compression {enable_logs_compression; _} = Option.get_exn_or "enable_logs_compression" enable_logs_compression let default_repository {default_repository; _} = Option.get_exn_or "default_repository" default_repository let extra_repositories {extra_repositories; _} = Option.get_exn_or "extra_repositories" extra_repositories let with_test {with_test; _} = Option.get_exn_or "with_test" with_test let with_lower_bound {with_lower_bound; _} = Option.get_exn_or "with_lower_bound" with_lower_bound let list_command {list_command; _} = Option.get_exn_or "list_command" list_command let extra_command {extra_command; _} = extra_command let platform_os {platform_os; _} = Option.get_exn_or "platform_os" platform_os let platform_arch {platform_arch; _} = Option.get_exn_or "platform_arch" platform_arch let platform_pool ({platform_pool; _} as conf) = match platform_pool with | None -> platform_os conf^"-"^platform_arch conf | Some pool -> pool let platform_distribution {platform_distribution; _} = Option.get_exn_or "platform_distribution" platform_distribution let platform_image {platform_image; _} = Option.get_exn_or "platform_image" platform_image let ocaml_switches {ocaml_switches; _} = ocaml_switches let slack_webhooks {slack_webhooks; _} = Option.get_exn_or "slack_webhooks" slack_webhooks let job_timeout {job_timeout; _} = Option.get_exn_or "job_timeout" job_timeout
d4c5d75842bbeb5acbccae7bf2e6a7a6027a89e230b3073fdfe4bd7361218c84
kblake/erlang-chat-demo
action_event.erl
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (action_event). -include_lib ("wf.hrl"). -compile(export_all). render_action(#event { postback=Postback, actions=Actions, anchor=Anchor, trigger=Trigger, target=Target, validation_group=ValidationGroup, type=Type, keycode=KeyCode, delay=Delay, delegate=Delegate, extra_param=ExtraParam }) -> ValidationGroup1 = wf:coalesce([ValidationGroup, Trigger]), AnchorScript = wf_render_actions:generate_anchor_script(Anchor, Target), PostbackScript = wf_event:generate_postback_script(Postback, Anchor, ValidationGroup1, Delegate, ExtraParam), SystemPostbackScript = wf_event:generate_system_postback_script(Postback, Anchor, ValidationGroup1, Delegate), WireAction = #wire { trigger=Trigger, target=Target, actions=Actions }, Script = case Type of %% SYSTEM EVENTS %%% % Trigger a system postback immediately... system when Delay == 0 -> [ AnchorScript, SystemPostbackScript, WireAction ]; % Trigger a system postback after some delay... system -> TempID = wf:temp_id(), [ AnchorScript, wf:f("document.~s = function() {", [TempID]), SystemPostbackScript, WireAction, "};", wf:f("setTimeout(\"document.~s(); document.~s=null;\", ~p);", [TempID, TempID, Delay]) ]; %% USER EVENTS %%% Handle keypress , , or keyup when a keycode is defined ... _ when (Type==keypress orelse Type==keydown orelse Type==keyup) andalso (KeyCode /= undefined) -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, Type]), wf:f("if (Nitrogen.$is_key_code(event, ~p)) { ", [KeyCode]), AnchorScript, PostbackScript, WireAction, "return false; }});" ]; % Convenience method for Enter Key... enterkey -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, keydown]), wf:f("if (Nitrogen.$is_key_code(event, ~p)) { ", [13]), AnchorScript, PostbackScript, WireAction, "return false; }});" ]; % Run the event after a specified amount of time timer -> TempID = wf:temp_id(), [ wf:f("document.~s = function() {", [TempID]), AnchorScript, PostbackScript, WireAction, "};", wf:f("setTimeout(\"document.~s(); document.~s=null;\", ~p);", [TempID, TempID, Delay]) ]; default -> [ AnchorScript, PostbackScript, WireAction ]; Run some other Javascript event ( click , mouseover , mouseout , etc . ) _ -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, Type]), AnchorScript, PostbackScript, WireAction, "});" ] end, Script.
null
https://raw.githubusercontent.com/kblake/erlang-chat-demo/6fd2fce12f2e059e25a24c9a84169b088710edaf/apps/nitrogen/src/actions/action_event.erl
erlang
SYSTEM EVENTS %%% Trigger a system postback immediately... Trigger a system postback after some delay... USER EVENTS %%% Convenience method for Enter Key... Run the event after a specified amount of time
Nitrogen Web Framework for Erlang Copyright ( c ) 2008 - 2010 See MIT - LICENSE for licensing information . -module (action_event). -include_lib ("wf.hrl"). -compile(export_all). render_action(#event { postback=Postback, actions=Actions, anchor=Anchor, trigger=Trigger, target=Target, validation_group=ValidationGroup, type=Type, keycode=KeyCode, delay=Delay, delegate=Delegate, extra_param=ExtraParam }) -> ValidationGroup1 = wf:coalesce([ValidationGroup, Trigger]), AnchorScript = wf_render_actions:generate_anchor_script(Anchor, Target), PostbackScript = wf_event:generate_postback_script(Postback, Anchor, ValidationGroup1, Delegate, ExtraParam), SystemPostbackScript = wf_event:generate_system_postback_script(Postback, Anchor, ValidationGroup1, Delegate), WireAction = #wire { trigger=Trigger, target=Target, actions=Actions }, Script = case Type of system when Delay == 0 -> [ AnchorScript, SystemPostbackScript, WireAction ]; system -> TempID = wf:temp_id(), [ AnchorScript, wf:f("document.~s = function() {", [TempID]), SystemPostbackScript, WireAction, "};", wf:f("setTimeout(\"document.~s(); document.~s=null;\", ~p);", [TempID, TempID, Delay]) ]; Handle keypress , , or keyup when a keycode is defined ... _ when (Type==keypress orelse Type==keydown orelse Type==keyup) andalso (KeyCode /= undefined) -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, Type]), wf:f("if (Nitrogen.$is_key_code(event, ~p)) { ", [KeyCode]), AnchorScript, PostbackScript, WireAction, "return false; }});" ]; enterkey -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, keydown]), wf:f("if (Nitrogen.$is_key_code(event, ~p)) { ", [13]), AnchorScript, PostbackScript, WireAction, "return false; }});" ]; timer -> TempID = wf:temp_id(), [ wf:f("document.~s = function() {", [TempID]), AnchorScript, PostbackScript, WireAction, "};", wf:f("setTimeout(\"document.~s(); document.~s=null;\", ~p);", [TempID, TempID, Delay]) ]; default -> [ AnchorScript, PostbackScript, WireAction ]; Run some other Javascript event ( click , mouseover , mouseout , etc . ) _ -> [ wf:f("Nitrogen.$observe_event('~s', '~s', '~s', function anonymous(event) {", [Anchor, Trigger, Type]), AnchorScript, PostbackScript, WireAction, "});" ] end, Script.
33a9c51e00e199d3008450e4c7e201350ac038b5081d8acca8b256b0e764f771
rm-hull/wireframes
lighting.clj
(ns wireframes.renderer.lighting (:require [inkspot.color :refer [coerce scale]] [wireframes.transform :refer [normal point]])) (def default-position (point 10000 -10000 -1000000)) (defn- brightness [i c] (coerce (scale c i))) (defn compute-lighting [lighting-position] (let [lx (double (get lighting-position 0)) ly (double (get lighting-position 1)) lz (double (get lighting-position 2)) v (Math/sqrt (+ (* lx lx) (* ly ly) (* lz lz)))] (fn [normal] (let [nx (double (get normal 0)) ny (double (get normal 1)) nz (double (get normal 2)) dp (+ (* nx lx) (* ny ly) (* nz lz))] (Math/abs ;when-not (neg? dp) (/ dp (* v (Math/sqrt (+ (* nx nx) (* ny ny) (* nz nz)))))))))) (defn positional-lighting-decorator [lighting-position color-fn] (let [lighting-fn (compute-lighting lighting-position)] (fn [points-3d transformed-points polygon] (let [intensity (->> (:vertices polygon) (map transformed-points) (apply normal) (lighting-fn))] (brightness intensity (color-fn points-3d transformed-points polygon))))))
null
https://raw.githubusercontent.com/rm-hull/wireframes/7df78cc6e2040cd0de026795f2e63ad129e4fee5/src/clj/wireframes/renderer/lighting.clj
clojure
when-not (neg? dp)
(ns wireframes.renderer.lighting (:require [inkspot.color :refer [coerce scale]] [wireframes.transform :refer [normal point]])) (def default-position (point 10000 -10000 -1000000)) (defn- brightness [i c] (coerce (scale c i))) (defn compute-lighting [lighting-position] (let [lx (double (get lighting-position 0)) ly (double (get lighting-position 1)) lz (double (get lighting-position 2)) v (Math/sqrt (+ (* lx lx) (* ly ly) (* lz lz)))] (fn [normal] (let [nx (double (get normal 0)) ny (double (get normal 1)) nz (double (get normal 2)) dp (+ (* nx lx) (* ny ly) (* nz lz))] (/ dp (* v (Math/sqrt (+ (* nx nx) (* ny ny) (* nz nz)))))))))) (defn positional-lighting-decorator [lighting-position color-fn] (let [lighting-fn (compute-lighting lighting-position)] (fn [points-3d transformed-points polygon] (let [intensity (->> (:vertices polygon) (map transformed-points) (apply normal) (lighting-fn))] (brightness intensity (color-fn points-3d transformed-points polygon))))))
7cad17fa13d96411280ba1783aff3bc12b1772719489f7503cbf89c57dc4fcb3
haskell-opengl/GLUT
TexBind.hs
TexBind.hs ( adapted from texbind.c which is ( c ) Silicon Graphics , Inc ) Copyright ( c ) 2002 - 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE This program demonstrates using textureBinding by creating and managing two textures . TexBind.hs (adapted from texbind.c which is (c) Silicon Graphics, Inc) Copyright (c) Sven Panne 2002-2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE This program demonstrates using textureBinding by creating and managing two textures. -} import Control.Monad ( when ) import Data.Bits ( (.&.) ) import Foreign ( withArray ) import System.Exit ( exitFailure, exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT -- Create checkerboard image checkImageSize :: TextureSize2D checkImageSize = TextureSize2D 64 64 withCheckImage :: TextureSize2D -> GLsizei -> (GLubyte -> (Color4 GLubyte)) -> (PixelData (Color4 GLubyte) -> IO ()) -> IO () withCheckImage (TextureSize2D w h) n f act = withArray [ f c | i <- [ 0 .. w - 1 ], j <- [ 0 .. h - 1 ], let c | (i .&. n) == (j .&. n) = 0 | otherwise = 255 ] $ act . PixelData RGBA UnsignedByte myInit :: IO (TextureObject, TextureObject) myInit = do clearColor $= Color4 0 0 0 0 shadeModel $= Flat depthFunc $= Just Less rowAlignment Unpack $= 1 [texName0, texName1] <- genObjectNames 2 textureBinding Texture2D $= Just texName0 textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) withCheckImage checkImageSize 0x08 (\c -> Color4 c c c 255) $ texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0 textureBinding Texture2D $= Just texName1 textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureFunction $= Decal withCheckImage checkImageSize 0x10 (\c -> Color4 c 0 0 255) $ texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0 texture Texture2D $= Enabled return (texName0, texName1) display :: (TextureObject, TextureObject) -> DisplayCallback display (texName0, texName1) = do clear [ ColorBuffer, DepthBuffer ] -- resolve overloading, not needed in "real" programs let texCoord2f = texCoord :: TexCoord2 GLfloat -> IO () vertex3f = vertex :: Vertex3 GLfloat -> IO () textureBinding Texture2D $= Just texName0 renderPrimitive Quads $ do texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 (-2.0) (-1.0) 0.0 ) texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 (-2.0) 1.0 0.0 ) texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 0.0 1.0 0.0 ) texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 0.0 (-1.0) 0.0 ) textureBinding Texture2D $= Just texName1 renderPrimitive Quads $ do texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 1.0 (-1.0) 0.0 ) texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 1.0 1.0 0.0 ) texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 2.41421 1.0 (-1.41421)) texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 2.41421 (-1.0) (-1.41421)) flush reshape :: ReshapeCallback reshape size@(Size w h) = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity perspective 60 (fromIntegral w / fromIntegral h) 1 30 matrixMode $= Modelview 0 loadIdentity translate (Vector3 0 0 (-3.6 :: GLfloat)) keyboard :: KeyboardMouseCallback keyboard (Char '\27') Down _ _ = exitWith ExitSuccess keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ] initialWindowSize $= Size 250 250 initialWindowPosition $= Position 100 100 _ <- createWindow progName -- we have to do this *after* createWindow, otherwise we have no OpenGL context version <- get (majorMinor glVersion) when (version == (1,0)) $ do putStrLn "This program demonstrates a feature which is not in OpenGL Version 1.0." putStrLn "If your implementation of OpenGL Version 1.0 has the right extensions," putStrLn "you may be able to modify this program to make it run." exitFailure texNames <- myInit reshapeCallback $= Just reshape displayCallback $= display texNames keyboardMouseCallback $= Just keyboard mainLoop
null
https://raw.githubusercontent.com/haskell-opengl/GLUT/36207fa51e4c1ea1e5512aeaa373198a4a56cad0/examples/RedBook4/TexBind.hs
haskell
Create checkerboard image resolve overloading, not needed in "real" programs we have to do this *after* createWindow, otherwise we have no OpenGL context
TexBind.hs ( adapted from texbind.c which is ( c ) Silicon Graphics , Inc ) Copyright ( c ) 2002 - 2018 < > This file is part of HOpenGL and distributed under a BSD - style license See the file libraries / GLUT / LICENSE This program demonstrates using textureBinding by creating and managing two textures . TexBind.hs (adapted from texbind.c which is (c) Silicon Graphics, Inc) Copyright (c) Sven Panne 2002-2018 <> This file is part of HOpenGL and distributed under a BSD-style license See the file libraries/GLUT/LICENSE This program demonstrates using textureBinding by creating and managing two textures. -} import Control.Monad ( when ) import Data.Bits ( (.&.) ) import Foreign ( withArray ) import System.Exit ( exitFailure, exitWith, ExitCode(ExitSuccess) ) import Graphics.UI.GLUT checkImageSize :: TextureSize2D checkImageSize = TextureSize2D 64 64 withCheckImage :: TextureSize2D -> GLsizei -> (GLubyte -> (Color4 GLubyte)) -> (PixelData (Color4 GLubyte) -> IO ()) -> IO () withCheckImage (TextureSize2D w h) n f act = withArray [ f c | i <- [ 0 .. w - 1 ], j <- [ 0 .. h - 1 ], let c | (i .&. n) == (j .&. n) = 0 | otherwise = 255 ] $ act . PixelData RGBA UnsignedByte myInit :: IO (TextureObject, TextureObject) myInit = do clearColor $= Color4 0 0 0 0 shadeModel $= Flat depthFunc $= Just Less rowAlignment Unpack $= 1 [texName0, texName1] <- genObjectNames 2 textureBinding Texture2D $= Just texName0 textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) withCheckImage checkImageSize 0x08 (\c -> Color4 c c c 255) $ texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0 textureBinding Texture2D $= Just texName1 textureWrapMode Texture2D S $= (Repeated, Clamp) textureWrapMode Texture2D T $= (Repeated, Clamp) textureFilter Texture2D $= ((Nearest, Nothing), Nearest) textureFunction $= Decal withCheckImage checkImageSize 0x10 (\c -> Color4 c 0 0 255) $ texImage2D Texture2D NoProxy 0 RGBA' checkImageSize 0 texture Texture2D $= Enabled return (texName0, texName1) display :: (TextureObject, TextureObject) -> DisplayCallback display (texName0, texName1) = do clear [ ColorBuffer, DepthBuffer ] let texCoord2f = texCoord :: TexCoord2 GLfloat -> IO () vertex3f = vertex :: Vertex3 GLfloat -> IO () textureBinding Texture2D $= Just texName0 renderPrimitive Quads $ do texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 (-2.0) (-1.0) 0.0 ) texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 (-2.0) 1.0 0.0 ) texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 0.0 1.0 0.0 ) texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 0.0 (-1.0) 0.0 ) textureBinding Texture2D $= Just texName1 renderPrimitive Quads $ do texCoord2f (TexCoord2 0 0); vertex3f (Vertex3 1.0 (-1.0) 0.0 ) texCoord2f (TexCoord2 0 1); vertex3f (Vertex3 1.0 1.0 0.0 ) texCoord2f (TexCoord2 1 1); vertex3f (Vertex3 2.41421 1.0 (-1.41421)) texCoord2f (TexCoord2 1 0); vertex3f (Vertex3 2.41421 (-1.0) (-1.41421)) flush reshape :: ReshapeCallback reshape size@(Size w h) = do viewport $= (Position 0 0, size) matrixMode $= Projection loadIdentity perspective 60 (fromIntegral w / fromIntegral h) 1 30 matrixMode $= Modelview 0 loadIdentity translate (Vector3 0 0 (-3.6 :: GLfloat)) keyboard :: KeyboardMouseCallback keyboard (Char '\27') Down _ _ = exitWith ExitSuccess keyboard _ _ _ _ = return () main :: IO () main = do (progName, _args) <- getArgsAndInitialize initialDisplayMode $= [ SingleBuffered, RGBMode, WithDepthBuffer ] initialWindowSize $= Size 250 250 initialWindowPosition $= Position 100 100 _ <- createWindow progName version <- get (majorMinor glVersion) when (version == (1,0)) $ do putStrLn "This program demonstrates a feature which is not in OpenGL Version 1.0." putStrLn "If your implementation of OpenGL Version 1.0 has the right extensions," putStrLn "you may be able to modify this program to make it run." exitFailure texNames <- myInit reshapeCallback $= Just reshape displayCallback $= display texNames keyboardMouseCallback $= Just keyboard mainLoop
6dca360f32231b5a5a9b83bd59ab4b9d62d95b2fe7b3ddcdfb611bc5db8a6d0f
Incubaid/arakoon
tlogcollection_test.ml
Copyright ( 2010 - 2014 ) INCUBAID BVBA 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 . Copyright (2010-2014) INCUBAID BVBA 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. *) open OUnit open Extra open Lwt open Update open Tlogcollection open Tlogcommon let section = Logger.Section.main let setup factory test_name () = let dn = Printf.sprintf "/tmp/%s" test_name in let tlf_dir = Printf.sprintf "%s_tlx" dn in Logger.info_f_ "setup %s" dn >>= fun () -> let make_dir dir = File_system.mkdir dir 0o755 >>= fun () -> Logger.info_f_ "created %s" dir in let prepare_dir dir = File_system.exists dir >>= (function | true -> begin Logger.info_f_ "%s exists cleaning" dir >>= fun () -> let cmd = Lwt_process.shell (Printf.sprintf "rm -rf %s" dir) in Lwt_process.exec cmd >>= fun status -> begin match status with | Unix.WEXITED rc when rc = 0 -> make_dir dir | Unix.WEXITED rc -> Llio.lwt_failfmt "rm -rf '%s' gave rc %i" dir rc | Unix.WSIGNALED _ | Unix.WSTOPPED _ -> Llio.lwt_failfmt "rm -rf '%s' failed" dir end end | false -> make_dir dir ) in prepare_dir dn >>= fun () -> prepare_dir tlf_dir >>= fun () -> Lwt.return (dn, tlf_dir, factory) let teardown (dn, tlf_dir, _factory) = Logger.info_f_ "teardown %s,%s" dn tlf_dir let _make_set_v k v= Value.create_client_value [Update.Set (k,v)] false let _log_repeat tlc (value:Value.t) n = let rec loop i = if i = (Sn.of_int n) then Lwt.return () else begin tlc # log_value i value >>= fun _wr_result -> loop (Sn.succ i) end in loop Sn.start let test_rollover (dn, tlf_dir, factory) = Logger.info_f_ "test_rollover %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 5 in factory dn "node_name" >>= fun (c:tlog_collection) -> let value = _make_set_v "x" "y" in _log_repeat c value 101 >>= fun () -> c # close () >>= fun ()-> Lwt.return () let test_rollover_1002 (dn, tlf_dir, factory) = Logger.info_f_ "test_rollover_1002 %s, %s" dn tlf_dir >>= fun () -> let n = 5 in let () = Tlogcommon.tlogEntriesPerFile := n in factory dn "node_name" >>= fun (c:tlog_collection) -> let value = _make_set_v "x" "y" in let n_updates = 1002 * n + 3 in _log_repeat c value n_updates >>= fun () -> c # close () >>= fun () -> factory dn "node_name" >>= fun tlc_two -> let vo = tlc_two # get_last_value (Sn.of_int (n_updates-1)) in let vos = Log_extra.option2s (Value.value2s ~values:false) vo in Logger.info_f_ "last_value = %s" vos >>= fun () -> tlc_two # close() >>= fun () -> Lwt.return () let test_get_value_bug (dn, _tlf_dir, factory) = Logger.info_ "test_get_value_bug" >>= fun () -> factory dn "node_name" >>= fun (c0:tlog_collection) -> let v0 = Value.create_master_value ~lease_start:0. "XXXX" in c0 # log_value 0L v0 >>= fun _wr_result -> c0 # close () >>= fun () -> factory dn "node_name" >>= fun c1 -> (* c1 # validate () >>= fun _ -> *) match c1 # get_last_value 0L with | None -> Llio.lwt_failfmt "get_last_update 0 yields None" | Some v -> let () = OUnit.assert_equal v v0 in Lwt.return () let test_regexp (_dn, _tlf_dir, _factory) = Logger.info_ "test_get_regexp_bug" >>= fun () -> let open Compression in let tests = ["001.tlog", true; "000" ^ Tlc2.extension Snappy, true; "000" ^ Tlc2.extension Snappy ^ ".part", false; "000" ^ Tlc2.extension Bz2, true; "000" ^ Tlc2.extension Bz2 ^ ".part", false; ] in let test (fn,e) = let r = Str.string_match Tlc2.file_regexp fn 0 in OUnit.assert_equal r e in List.iter test tests; Lwt.return () let test_restart (dn, _tlf_dir, factory) = factory dn "node_name" >>= fun (tlc_one:tlog_collection) -> let value = _make_set_v "x" "y" in _log_repeat tlc_one value 100 >>= fun () -> tlc_one # close () >>= fun () -> factory dn "node_name" >>= fun tlc_two -> let _ = tlc_two # get_last_value (Sn.of_int 99) in tlc_two # close () >>= fun () -> Lwt.return () let test_iterate (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "xxx" "y" in _log_repeat tlc value 323 >>= fun () -> let sum = ref 0 in tlc # iterate (Sn.of_int 125) (Sn.of_int 304) (fun entry -> let i = Entry.i_of entry in sum := !sum + (Int64.to_int i); Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> Lwt.return ()) >>= fun () -> tlc # close () >>= fun () -> Logger.debug_f_ "sum =%i " !sum >>= fun () -> OUnit.assert_equal ~printer:string_of_int !sum 38306; Lwt.return () let test_iterate2 (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate2 %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "test_iterate0" "xxx" in _log_repeat tlc value 3 >>= fun () -> let result = ref [] in tlc # iterate (Sn.of_int 0) (Sn.of_int 1) (fun entry -> let i = Entry.i_of entry in result := i :: ! result; Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> Lwt.return ()) >>= fun () -> OUnit.assert_equal ~printer:string_of_int 1 (List.length !result); tlc # close () >>= fun () -> Lwt.return () let test_iterate3 (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate3 %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "test_iterate3" "xxx" in _log_repeat tlc value 120 >>= fun () -> let result = ref [] in tlc # iterate (Sn.of_int 99) (Sn.of_int 101) (fun entry -> let i = Entry.i_of entry in Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> let () = result := i :: !result in Lwt.return () ) >>= fun () -> OUnit.assert_equal (List.mem (Sn.of_int 99) !result) true; tlc # close () >>= fun () -> Lwt.return () let test_validate_normal (dn, tlf_dir, factory) = Logger.info_f_ "test_validate_normal %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile:= 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "XXX" "X" in _log_repeat tlc value 123 >>= fun () -> tlc # close () >>= fun () -> Logger.debug_f_ "reopening %s" dn >>= fun () -> factory dn "node_name" >>= fun (tlc_two:tlog_collection) -> tlc_two # validate_last_tlog () >>= fun result -> let _validity, eo, _ = result in let wsn = Sn.of_int 122 in let wanted = (Some wsn) in let io = match eo with None -> None | Some e -> Some (Entry.i_of e) in let tos x= Log_extra.option2s Sn.string_of x in Logger.info_f_ "wanted:%s, got:%s" (tos wanted) (tos io) >>= fun() -> OUnit.assert_equal io wanted ; Lwt.return () let test_validate_corrupt_1 (dn, tlf_dir, factory) = let () = Tlogcommon.tlogEntriesPerFile:= 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "Incompetent" "Politicians" in _log_repeat tlc value 42 >>= fun () -> tlc # close () >>= fun () -> let fn = Tlc2.get_full_path dn tlf_dir "000.tlog" in Lwt_unix.openfile fn [Unix.O_RDWR] 0o640 >>= fun fd -> Lwt_unix.lseek fd 666 Unix.SEEK_SET >>= fun _ -> Lwt_unix.write fd "\x00\x00\x00\x00\x00\x00" 0 6 >>= fun _ -> Lwt_unix.close fd >>= fun () -> Logger.info_f_ "corrupted 6 bytes" >>= fun () -> Lwt.catch (fun () -> factory dn "node_name" >>= fun (tlc_two:tlog_collection) -> tlc_two # validate_last_tlog () >>= fun _ -> tlc_two # close () >>= fun () -> OUnit.assert_bool "this tlog should not be valid" false; Lwt.return () ) (function | TLogCheckSumError _pos | TLogUnexpectedEndOfFile _pos -> Lwt.return () | exn -> let () = ignore exn in let msg = Printf.sprintf "it threw the wrong exception %s" "?" in OUnit.assert_bool msg false; Lwt.return () ) >>= fun () -> Lwt.return () let wrap factory test (name:string) = lwt_bracket (setup factory name) test teardown let create_test_tlc dn = Mem_tlogcollection.make_mem_tlog_collection dn None None ~fsync:false ~fsync_tlog_dir:false let wrap_memory name = wrap create_test_tlc name let suite_mem = "mem_tlogcollection" >::: [ "rollover" >:: wrap_memory test_rollover "rollover"; " get_value_bug " > : : ; ( * assumption that different tlog_collections with the same name have the same state (* assumption that different tlog_collections with the same name have the same state *) *) ]
null
https://raw.githubusercontent.com/Incubaid/arakoon/43a8d0b26e4876ef91d9657149f105c7e57e0cb0/src/tlog/tlogcollection_test.ml
ocaml
c1 # validate () >>= fun _ -> assumption that different tlog_collections with the same name have the same state
Copyright ( 2010 - 2014 ) INCUBAID BVBA 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 . Copyright (2010-2014) INCUBAID BVBA 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. *) open OUnit open Extra open Lwt open Update open Tlogcollection open Tlogcommon let section = Logger.Section.main let setup factory test_name () = let dn = Printf.sprintf "/tmp/%s" test_name in let tlf_dir = Printf.sprintf "%s_tlx" dn in Logger.info_f_ "setup %s" dn >>= fun () -> let make_dir dir = File_system.mkdir dir 0o755 >>= fun () -> Logger.info_f_ "created %s" dir in let prepare_dir dir = File_system.exists dir >>= (function | true -> begin Logger.info_f_ "%s exists cleaning" dir >>= fun () -> let cmd = Lwt_process.shell (Printf.sprintf "rm -rf %s" dir) in Lwt_process.exec cmd >>= fun status -> begin match status with | Unix.WEXITED rc when rc = 0 -> make_dir dir | Unix.WEXITED rc -> Llio.lwt_failfmt "rm -rf '%s' gave rc %i" dir rc | Unix.WSIGNALED _ | Unix.WSTOPPED _ -> Llio.lwt_failfmt "rm -rf '%s' failed" dir end end | false -> make_dir dir ) in prepare_dir dn >>= fun () -> prepare_dir tlf_dir >>= fun () -> Lwt.return (dn, tlf_dir, factory) let teardown (dn, tlf_dir, _factory) = Logger.info_f_ "teardown %s,%s" dn tlf_dir let _make_set_v k v= Value.create_client_value [Update.Set (k,v)] false let _log_repeat tlc (value:Value.t) n = let rec loop i = if i = (Sn.of_int n) then Lwt.return () else begin tlc # log_value i value >>= fun _wr_result -> loop (Sn.succ i) end in loop Sn.start let test_rollover (dn, tlf_dir, factory) = Logger.info_f_ "test_rollover %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 5 in factory dn "node_name" >>= fun (c:tlog_collection) -> let value = _make_set_v "x" "y" in _log_repeat c value 101 >>= fun () -> c # close () >>= fun ()-> Lwt.return () let test_rollover_1002 (dn, tlf_dir, factory) = Logger.info_f_ "test_rollover_1002 %s, %s" dn tlf_dir >>= fun () -> let n = 5 in let () = Tlogcommon.tlogEntriesPerFile := n in factory dn "node_name" >>= fun (c:tlog_collection) -> let value = _make_set_v "x" "y" in let n_updates = 1002 * n + 3 in _log_repeat c value n_updates >>= fun () -> c # close () >>= fun () -> factory dn "node_name" >>= fun tlc_two -> let vo = tlc_two # get_last_value (Sn.of_int (n_updates-1)) in let vos = Log_extra.option2s (Value.value2s ~values:false) vo in Logger.info_f_ "last_value = %s" vos >>= fun () -> tlc_two # close() >>= fun () -> Lwt.return () let test_get_value_bug (dn, _tlf_dir, factory) = Logger.info_ "test_get_value_bug" >>= fun () -> factory dn "node_name" >>= fun (c0:tlog_collection) -> let v0 = Value.create_master_value ~lease_start:0. "XXXX" in c0 # log_value 0L v0 >>= fun _wr_result -> c0 # close () >>= fun () -> factory dn "node_name" >>= fun c1 -> match c1 # get_last_value 0L with | None -> Llio.lwt_failfmt "get_last_update 0 yields None" | Some v -> let () = OUnit.assert_equal v v0 in Lwt.return () let test_regexp (_dn, _tlf_dir, _factory) = Logger.info_ "test_get_regexp_bug" >>= fun () -> let open Compression in let tests = ["001.tlog", true; "000" ^ Tlc2.extension Snappy, true; "000" ^ Tlc2.extension Snappy ^ ".part", false; "000" ^ Tlc2.extension Bz2, true; "000" ^ Tlc2.extension Bz2 ^ ".part", false; ] in let test (fn,e) = let r = Str.string_match Tlc2.file_regexp fn 0 in OUnit.assert_equal r e in List.iter test tests; Lwt.return () let test_restart (dn, _tlf_dir, factory) = factory dn "node_name" >>= fun (tlc_one:tlog_collection) -> let value = _make_set_v "x" "y" in _log_repeat tlc_one value 100 >>= fun () -> tlc_one # close () >>= fun () -> factory dn "node_name" >>= fun tlc_two -> let _ = tlc_two # get_last_value (Sn.of_int 99) in tlc_two # close () >>= fun () -> Lwt.return () let test_iterate (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "xxx" "y" in _log_repeat tlc value 323 >>= fun () -> let sum = ref 0 in tlc # iterate (Sn.of_int 125) (Sn.of_int 304) (fun entry -> let i = Entry.i_of entry in sum := !sum + (Int64.to_int i); Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> Lwt.return ()) >>= fun () -> tlc # close () >>= fun () -> Logger.debug_f_ "sum =%i " !sum >>= fun () -> OUnit.assert_equal ~printer:string_of_int !sum 38306; Lwt.return () let test_iterate2 (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate2 %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "test_iterate0" "xxx" in _log_repeat tlc value 3 >>= fun () -> let result = ref [] in tlc # iterate (Sn.of_int 0) (Sn.of_int 1) (fun entry -> let i = Entry.i_of entry in result := i :: ! result; Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> Lwt.return ()) >>= fun () -> OUnit.assert_equal ~printer:string_of_int 1 (List.length !result); tlc # close () >>= fun () -> Lwt.return () let test_iterate3 (dn, tlf_dir, factory) = Logger.info_f_ "test_iterate3 %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile := 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "test_iterate3" "xxx" in _log_repeat tlc value 120 >>= fun () -> let result = ref [] in tlc # iterate (Sn.of_int 99) (Sn.of_int 101) (fun entry -> let i = Entry.i_of entry in Logger.debug_f_ "i=%s" (Sn.string_of i) >>= fun () -> let () = result := i :: !result in Lwt.return () ) >>= fun () -> OUnit.assert_equal (List.mem (Sn.of_int 99) !result) true; tlc # close () >>= fun () -> Lwt.return () let test_validate_normal (dn, tlf_dir, factory) = Logger.info_f_ "test_validate_normal %s, %s" dn tlf_dir >>= fun () -> let () = Tlogcommon.tlogEntriesPerFile:= 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "XXX" "X" in _log_repeat tlc value 123 >>= fun () -> tlc # close () >>= fun () -> Logger.debug_f_ "reopening %s" dn >>= fun () -> factory dn "node_name" >>= fun (tlc_two:tlog_collection) -> tlc_two # validate_last_tlog () >>= fun result -> let _validity, eo, _ = result in let wsn = Sn.of_int 122 in let wanted = (Some wsn) in let io = match eo with None -> None | Some e -> Some (Entry.i_of e) in let tos x= Log_extra.option2s Sn.string_of x in Logger.info_f_ "wanted:%s, got:%s" (tos wanted) (tos io) >>= fun() -> OUnit.assert_equal io wanted ; Lwt.return () let test_validate_corrupt_1 (dn, tlf_dir, factory) = let () = Tlogcommon.tlogEntriesPerFile:= 100 in factory dn "node_name" >>= fun (tlc:tlog_collection) -> let value = _make_set_v "Incompetent" "Politicians" in _log_repeat tlc value 42 >>= fun () -> tlc # close () >>= fun () -> let fn = Tlc2.get_full_path dn tlf_dir "000.tlog" in Lwt_unix.openfile fn [Unix.O_RDWR] 0o640 >>= fun fd -> Lwt_unix.lseek fd 666 Unix.SEEK_SET >>= fun _ -> Lwt_unix.write fd "\x00\x00\x00\x00\x00\x00" 0 6 >>= fun _ -> Lwt_unix.close fd >>= fun () -> Logger.info_f_ "corrupted 6 bytes" >>= fun () -> Lwt.catch (fun () -> factory dn "node_name" >>= fun (tlc_two:tlog_collection) -> tlc_two # validate_last_tlog () >>= fun _ -> tlc_two # close () >>= fun () -> OUnit.assert_bool "this tlog should not be valid" false; Lwt.return () ) (function | TLogCheckSumError _pos | TLogUnexpectedEndOfFile _pos -> Lwt.return () | exn -> let () = ignore exn in let msg = Printf.sprintf "it threw the wrong exception %s" "?" in OUnit.assert_bool msg false; Lwt.return () ) >>= fun () -> Lwt.return () let wrap factory test (name:string) = lwt_bracket (setup factory name) test teardown let create_test_tlc dn = Mem_tlogcollection.make_mem_tlog_collection dn None None ~fsync:false ~fsync_tlog_dir:false let wrap_memory name = wrap create_test_tlc name let suite_mem = "mem_tlogcollection" >::: [ "rollover" >:: wrap_memory test_rollover "rollover"; " get_value_bug " > : : ; ( * assumption that different tlog_collections with the same name have the same state *) ]
e2c181728526ecd1e0ee27cdb8f7027276418c3d167152dfb5471a7dd5b31eab
ddssff/cabal-debian
Git.hs
-- | Git related functions that belong in some other package. # LANGUAGE ScopedTypeVariables # module System.Git ( gitResetHard , gitResetSubdir , gitUnclean , gitIsClean , withCleanRepo ) where import Control.Exception (catch, SomeException, throw) import System.Directory (getCurrentDirectory) import System.Exit (ExitCode(ExitSuccess, ExitFailure)) import System.IO (hPutStrLn, stderr) import System.Process (readProcessWithExitCode, readProcess) -- | Do a hard reset of all the files of the repository containing the -- working directory. gitResetHard :: IO () gitResetHard = do (code, _out, _err) <- readProcessWithExitCode "git" ["reset", "--hard"] "" case code of ExitSuccess -> pure () ExitFailure _n -> error "gitResetHard" -- | Do a hard reset of all the files of a subdirectory within a git -- repository. (Does this every throw an exception?) gitResetSubdir :: FilePath -> IO () gitResetSubdir dir = do (readProcess "git" ["checkout", "--", dir] "" >> readProcess "git" ["clean", "-f", dir] "" >> pure ()) `catch` \(e :: SomeException) -> hPutStrLn stderr ("gitResetSubdir " ++ show dir ++ " failed: " ++ show e) >> throw e -- | Determine whether the repository containing the working directory -- is in a modified state, if so return the messages. gitUnclean :: IO (Maybe String) gitUnclean = do here <- getCurrentDirectory hPutStrLn stderr ("here: " ++ show here) (code, out, _err) <- readProcessWithExitCode "git" ["status", "--porcelain"] "" case code of ExitFailure _ -> error "gitCheckClean failure" ExitSuccess | all unmodified (lines out) -> pure Nothing ExitSuccess -> pure $ Just out where unmodified (a : b : _) = elem a "?! " && elem b "?! " unmodified _ = False gitIsClean :: IO Bool gitIsClean = maybe True (const False) <$> gitUnclean withCleanRepo :: IO a -> IO a withCleanRepo action = do gitUnclean >>= maybe action (\s -> error $ "withCleanRepo: please commit or revert changes:\n" ++ s)
null
https://raw.githubusercontent.com/ddssff/cabal-debian/763270aed987f870762e660f243451e9a34e1325/src/System/Git.hs
haskell
| Git related functions that belong in some other package. | Do a hard reset of all the files of the repository containing the working directory. | Do a hard reset of all the files of a subdirectory within a git repository. (Does this every throw an exception?) | Determine whether the repository containing the working directory is in a modified state, if so return the messages.
# LANGUAGE ScopedTypeVariables # module System.Git ( gitResetHard , gitResetSubdir , gitUnclean , gitIsClean , withCleanRepo ) where import Control.Exception (catch, SomeException, throw) import System.Directory (getCurrentDirectory) import System.Exit (ExitCode(ExitSuccess, ExitFailure)) import System.IO (hPutStrLn, stderr) import System.Process (readProcessWithExitCode, readProcess) gitResetHard :: IO () gitResetHard = do (code, _out, _err) <- readProcessWithExitCode "git" ["reset", "--hard"] "" case code of ExitSuccess -> pure () ExitFailure _n -> error "gitResetHard" gitResetSubdir :: FilePath -> IO () gitResetSubdir dir = do (readProcess "git" ["checkout", "--", dir] "" >> readProcess "git" ["clean", "-f", dir] "" >> pure ()) `catch` \(e :: SomeException) -> hPutStrLn stderr ("gitResetSubdir " ++ show dir ++ " failed: " ++ show e) >> throw e gitUnclean :: IO (Maybe String) gitUnclean = do here <- getCurrentDirectory hPutStrLn stderr ("here: " ++ show here) (code, out, _err) <- readProcessWithExitCode "git" ["status", "--porcelain"] "" case code of ExitFailure _ -> error "gitCheckClean failure" ExitSuccess | all unmodified (lines out) -> pure Nothing ExitSuccess -> pure $ Just out where unmodified (a : b : _) = elem a "?! " && elem b "?! " unmodified _ = False gitIsClean :: IO Bool gitIsClean = maybe True (const False) <$> gitUnclean withCleanRepo :: IO a -> IO a withCleanRepo action = do gitUnclean >>= maybe action (\s -> error $ "withCleanRepo: please commit or revert changes:\n" ++ s)
b8a8dd697378ccf29f283bdfb20542304644788e862385c221c2f2b6dfe18e33
FlowerWrong/mblog
mp3_manager.erl
%% --- Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . %% Copyrights apply to this code. It may not be used to create training material, %% courses, books, articles, and the like. Contact us if you are in doubt. %% We make no guarantees that this code is fit for any purpose. %% Visit for more book information. %%--- -module(mp3_manager). -import(lists, [map/2, reverse/1]). -compile(export_all). start1() -> Files = lib_files_find:files("/Volumes/joe/piano_concertos", "*.mp3", true), V = map(fun handle/1, Files), lib_misc:dump("mp3data", V). start2() -> Files = lib_files_find:files("/windows/backup/music/artists", "*.mp3", true), V = map(fun handle/1, Files), lib_misc:dump("mp3data", V). handle(File) -> (catch read_id3_tag(File)). read_id3_tag(File) -> case file:open(File, [read,binary,raw]) of {ok, S} -> Size = filelib:file_size(File), Result = (catch analyse1(S, Size)), file:close(S), {File, Result}; Error -> {File, Error} end. analyse1(S, Size) -> {ok, B1} = file:pread(S, 0, 10), case parse_start_tag(B1) of {"ID3v2.3.0", {_Unsync, Extended, _Experimental, Len}} -> {ok, Data} = file:pread(S, 10, Len), case Extended of 1 -> {Extended, Data1} = split_binary(Data, 10), parse_frames(Data1); 0 -> parse_frames(Data) end; no -> %% see if we can find a tag at the end {ok, B2} = file:pread(S, Size-128, 128), parse_v1_tag(B2) end. parse_start_tag(<<$I,$D,$3,3,0,Unsync:1,Extended:1,Experimental:1,_:5,K:32>>) -> Tag = "ID3v2.3.0", Size = syncsafe2int(K), {Tag, {Unsync, Extended, Experimental, Size}}; parse_start_tag(_) -> no. parse_frames(B) -> F = gather_frames(B), G = map(fun parse_frame/1, F), H = [{I,J}||{I,J}<-G], {ok, H}. parse_frame({"TIT2", _, Txt}) -> {title, parse_txt(Txt)}; parse_frame({"TPE1", _, Txt}) -> {performer, parse_txt(Txt)}; parse_frame({"TALB", _, Txt}) -> {album, parse_txt(Txt)}; parse_frame({"TRCK", _, Txt}) -> {track, parse_txt(Txt)}; parse_frame(_) -> skipped. parse_txt(<<0:8,Txt/binary>>) -> Txt; parse_txt(<<1:8,16#ff,16#fe, Txt/binary>>) -> unicode_to_ascii(Txt). unicode_to_ascii(Bin) -> list_to_binary(uni_to_ascii1(binary_to_list(Bin))). uni_to_ascii1([X,_|Y]) -> [X|uni_to_ascii1(Y)]; uni_to_ascii1([]) -> []. gather_frames(B) when byte_size(B) < 10 -> []; gather_frames(<<0,0,0,0,_/binary>>) -> []; gather_frames(<<$P,$R,$I,$V,_/binary>>) -> []; gather_frames(<<Id1,Id2,Id3,Id4,SafeN:32,Flags:16,Rest/binary>>) -> <<_A:1,_B:1,_C:1,_:5,I:1,J:1,_K:1,_:5>> = <<Flags:16>>, case {I, J} of {0, 0} -> Tag = [Id1,Id2,Id3,Id4], case is_tag(Tag) of true -> Size = syncsafe2int(SafeN), {Data, Next} = split_binary(Rest, Size), [{Tag,Flags,Data}|gather_frames(Next)]; false -> [] end; _ -> %% bad flags [] end; gather_frames(CC) -> [{error, CC}]. is_tag([H|T]) when $A =< H, H =< $Z -> is_tag(T); is_tag([H|T]) when $0 =< H, H =< $9 -> is_tag(T); is_tag([]) -> true; is_tag(_) -> false. syncsafe2int(N) -> <<_:1,N1:7,_:1,N2:7,_:1,N3:7,_:1,N4:7>> = <<N:32>>, <<I:32>> = <<0:4,N1:7,N2:7,N3:7,N4:7>>, I. parse_v1_tag(<<$T,$A,$G,B/binary>>) -> {Title, B1} = split_binary(B, 30), {Artist, B2} = split_binary(B1, 30), {Album, B3} = split_binary(B2, 30), {_Year, B4} = split_binary(B3, 4), {_Comment, <<K, Track,_Gendre>>} = split_binary(B4, 28), L = [{title,trim(Title)},{artist,trim(Artist)}, {album, trim(Album)}], case K of 0 -> {"ID3v1.1", [{track,Track}|L]}; _ -> {"ID3v1", L} end; parse_v1_tag(_) -> no. trim(Bin) -> list_to_binary(trim_blanks(binary_to_list(Bin))). trim_blanks(X) -> reverse(skip_blanks_and_zero(reverse(X))). skip_blanks_and_zero([$\s|T]) -> skip_blanks_and_zero(T); skip_blanks_and_zero([0|T]) -> skip_blanks_and_zero(T); skip_blanks_and_zero(X) -> X.
null
https://raw.githubusercontent.com/FlowerWrong/mblog/3233ede938d2019a7b57391405197ac19c805b27/categories/erlang/demo/jaerlang2_code/mp3_manager.erl
erlang
--- Copyrights apply to this code. It may not be used to create training material, courses, books, articles, and the like. Contact us if you are in doubt. We make no guarantees that this code is fit for any purpose. Visit for more book information. --- see if we can find a tag at the end bad flags
Excerpted from " Programming Erlang , Second Edition " , published by The Pragmatic Bookshelf . -module(mp3_manager). -import(lists, [map/2, reverse/1]). -compile(export_all). start1() -> Files = lib_files_find:files("/Volumes/joe/piano_concertos", "*.mp3", true), V = map(fun handle/1, Files), lib_misc:dump("mp3data", V). start2() -> Files = lib_files_find:files("/windows/backup/music/artists", "*.mp3", true), V = map(fun handle/1, Files), lib_misc:dump("mp3data", V). handle(File) -> (catch read_id3_tag(File)). read_id3_tag(File) -> case file:open(File, [read,binary,raw]) of {ok, S} -> Size = filelib:file_size(File), Result = (catch analyse1(S, Size)), file:close(S), {File, Result}; Error -> {File, Error} end. analyse1(S, Size) -> {ok, B1} = file:pread(S, 0, 10), case parse_start_tag(B1) of {"ID3v2.3.0", {_Unsync, Extended, _Experimental, Len}} -> {ok, Data} = file:pread(S, 10, Len), case Extended of 1 -> {Extended, Data1} = split_binary(Data, 10), parse_frames(Data1); 0 -> parse_frames(Data) end; no -> {ok, B2} = file:pread(S, Size-128, 128), parse_v1_tag(B2) end. parse_start_tag(<<$I,$D,$3,3,0,Unsync:1,Extended:1,Experimental:1,_:5,K:32>>) -> Tag = "ID3v2.3.0", Size = syncsafe2int(K), {Tag, {Unsync, Extended, Experimental, Size}}; parse_start_tag(_) -> no. parse_frames(B) -> F = gather_frames(B), G = map(fun parse_frame/1, F), H = [{I,J}||{I,J}<-G], {ok, H}. parse_frame({"TIT2", _, Txt}) -> {title, parse_txt(Txt)}; parse_frame({"TPE1", _, Txt}) -> {performer, parse_txt(Txt)}; parse_frame({"TALB", _, Txt}) -> {album, parse_txt(Txt)}; parse_frame({"TRCK", _, Txt}) -> {track, parse_txt(Txt)}; parse_frame(_) -> skipped. parse_txt(<<0:8,Txt/binary>>) -> Txt; parse_txt(<<1:8,16#ff,16#fe, Txt/binary>>) -> unicode_to_ascii(Txt). unicode_to_ascii(Bin) -> list_to_binary(uni_to_ascii1(binary_to_list(Bin))). uni_to_ascii1([X,_|Y]) -> [X|uni_to_ascii1(Y)]; uni_to_ascii1([]) -> []. gather_frames(B) when byte_size(B) < 10 -> []; gather_frames(<<0,0,0,0,_/binary>>) -> []; gather_frames(<<$P,$R,$I,$V,_/binary>>) -> []; gather_frames(<<Id1,Id2,Id3,Id4,SafeN:32,Flags:16,Rest/binary>>) -> <<_A:1,_B:1,_C:1,_:5,I:1,J:1,_K:1,_:5>> = <<Flags:16>>, case {I, J} of {0, 0} -> Tag = [Id1,Id2,Id3,Id4], case is_tag(Tag) of true -> Size = syncsafe2int(SafeN), {Data, Next} = split_binary(Rest, Size), [{Tag,Flags,Data}|gather_frames(Next)]; false -> [] end; _ -> [] end; gather_frames(CC) -> [{error, CC}]. is_tag([H|T]) when $A =< H, H =< $Z -> is_tag(T); is_tag([H|T]) when $0 =< H, H =< $9 -> is_tag(T); is_tag([]) -> true; is_tag(_) -> false. syncsafe2int(N) -> <<_:1,N1:7,_:1,N2:7,_:1,N3:7,_:1,N4:7>> = <<N:32>>, <<I:32>> = <<0:4,N1:7,N2:7,N3:7,N4:7>>, I. parse_v1_tag(<<$T,$A,$G,B/binary>>) -> {Title, B1} = split_binary(B, 30), {Artist, B2} = split_binary(B1, 30), {Album, B3} = split_binary(B2, 30), {_Year, B4} = split_binary(B3, 4), {_Comment, <<K, Track,_Gendre>>} = split_binary(B4, 28), L = [{title,trim(Title)},{artist,trim(Artist)}, {album, trim(Album)}], case K of 0 -> {"ID3v1.1", [{track,Track}|L]}; _ -> {"ID3v1", L} end; parse_v1_tag(_) -> no. trim(Bin) -> list_to_binary(trim_blanks(binary_to_list(Bin))). trim_blanks(X) -> reverse(skip_blanks_and_zero(reverse(X))). skip_blanks_and_zero([$\s|T]) -> skip_blanks_and_zero(T); skip_blanks_and_zero([0|T]) -> skip_blanks_and_zero(T); skip_blanks_and_zero(X) -> X.
3ef0f6a96bc1c5ef4d39f18aa966da115054a4a910df25cc20d04fcef356408b
freizl/dive-into-haskell
fibs.hs
# LANGUAGE TypeFamilies , QuasiQuotes , # LANGUAGE MultiParamTypeClasses , TemplateHaskell # {-# LANGUAGE OverloadedStrings #-} import Yesod import qualified Data.Text as T import Web.Routes.Quasi hiding (parseRoutes) data Fibs = Fibs START newtype Natural = Natural Int -- we might even like to go with Word here deriving (Show, Read, Eq, Num, Ord) START instance SinglePiece Natural where toSinglePiece (Natural i) = T.pack $ show i fromSinglePiece s = case reads $ T.unpack s of (i, _):_ | i < 1 -> Nothing | otherwise -> Just $ Natural i [] -> Nothing -- STOP mkYesod "Fibs" [$parseRoutes| / HomeR GET /fibs/#Natural FibsR GET |] instance Yesod Fibs where approot _ = "" fibs = 1 : 1 : zipWith (+) fibs (tail fibs) getHomeR = defaultLayout $ do addHamlet [$hamlet|<a href="@{FibsR 1}">a fibs|] getFibsR :: Natural -> GHandler Fibs Fibs RepPlain getFibsR (Natural i) = return $ RepPlain $ toContent $ show $ fibs !! (i - 1) main = warpDebug 3000 Fibs
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/codes/web/yesod/misc/fibs.hs
haskell
# LANGUAGE OverloadedStrings # we might even like to go with Word here STOP
# LANGUAGE TypeFamilies , QuasiQuotes , # LANGUAGE MultiParamTypeClasses , TemplateHaskell # import Yesod import qualified Data.Text as T import Web.Routes.Quasi hiding (parseRoutes) data Fibs = Fibs START deriving (Show, Read, Eq, Num, Ord) START instance SinglePiece Natural where toSinglePiece (Natural i) = T.pack $ show i fromSinglePiece s = case reads $ T.unpack s of (i, _):_ | i < 1 -> Nothing | otherwise -> Just $ Natural i [] -> Nothing mkYesod "Fibs" [$parseRoutes| / HomeR GET /fibs/#Natural FibsR GET |] instance Yesod Fibs where approot _ = "" fibs = 1 : 1 : zipWith (+) fibs (tail fibs) getHomeR = defaultLayout $ do addHamlet [$hamlet|<a href="@{FibsR 1}">a fibs|] getFibsR :: Natural -> GHandler Fibs Fibs RepPlain getFibsR (Natural i) = return $ RepPlain $ toContent $ show $ fibs !! (i - 1) main = warpDebug 3000 Fibs
7dc69df882b00b8e363d689ec62d671082b07dbd034066877e898ddd8441bd8d
haskell-mafia/boris
test-io.hs
import Disorder.Core.Main import qualified Test.IO.Boris.Build main :: IO () main = disorderMain [ Test.IO.Boris.Build.tests ]
null
https://raw.githubusercontent.com/haskell-mafia/boris/fb670071600e8b2d8dbb9191fcf6bf8488f83f5a/boris-build/test/test-io.hs
haskell
import Disorder.Core.Main import qualified Test.IO.Boris.Build main :: IO () main = disorderMain [ Test.IO.Boris.Build.tests ]
aa13203b1462bf42ba3ff5d2efa86666e790564357c444ba1ba36ef3e8cfe9af
vitorenesduarte/exp
exp_resource.erl
%% Copyright ( c ) 2018 . All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(exp_resource). -author("Vitor Enes <"). -include("exp.hrl"). -behaviour(gen_server). exp_resource callbacks -export([start_link/0]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). %% mochiweb callbacks -export([loop/1]). -record(state, {}). -spec start_link() -> {ok, pid()} | ignore | {error, term()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). %% gen_server callbacks init([]) -> lager:info("exp_resource initialized"), Loop = fun(Req) -> ?MODULE:loop(Req) end, mochiweb_http:start([{loop, Loop} | ?WEB_CONFIG]), {ok, #state{}}. handle_call(Msg, _From, State) -> lager:warning("Unhandled call message: ~p", [Msg]), {noreply, State}. handle_cast(Msg, State) -> lager:warning("Unhandled cast message: ~p", [Msg]), {noreply, State}. handle_info(Msg, State) -> lager:warning("Unhandled info message: ~p", [Msg]), {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %% mochiweb loop(Req) -> Path = Req:get(path), case string:tokens(Path, "/") of ["membership"] -> {ok, Names} = ldb_hao:members(), Req:ok({ _ContentType = "application/javascript", ldb_json:encode(Names) }); _ -> Req:not_found() end.
null
https://raw.githubusercontent.com/vitorenesduarte/exp/99486aba658c1b5f077275ceca3eef173375d050/src/exp_resource.erl
erlang
Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- gen_server callbacks mochiweb callbacks gen_server callbacks mochiweb
Copyright ( c ) 2018 . All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(exp_resource). -author("Vitor Enes <"). -include("exp.hrl"). -behaviour(gen_server). exp_resource callbacks -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -export([loop/1]). -record(state, {}). -spec start_link() -> {ok, pid()} | ignore | {error, term()}. start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init([]) -> lager:info("exp_resource initialized"), Loop = fun(Req) -> ?MODULE:loop(Req) end, mochiweb_http:start([{loop, Loop} | ?WEB_CONFIG]), {ok, #state{}}. handle_call(Msg, _From, State) -> lager:warning("Unhandled call message: ~p", [Msg]), {noreply, State}. handle_cast(Msg, State) -> lager:warning("Unhandled cast message: ~p", [Msg]), {noreply, State}. handle_info(Msg, State) -> lager:warning("Unhandled info message: ~p", [Msg]), {noreply, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. loop(Req) -> Path = Req:get(path), case string:tokens(Path, "/") of ["membership"] -> {ok, Names} = ldb_hao:members(), Req:ok({ _ContentType = "application/javascript", ldb_json:encode(Names) }); _ -> Req:not_found() end.
2e50de097dcdbf7f1d32e7230fe2971841eaa6dac88c120d9797495caed6b7cc
openweb-nl/kafka-graphql-examples
views.cljs
(ns nl.openweb.bank.views (:require [re-frame.core :as re-frame] [nl.openweb.bank.subs :as subs] [nl.openweb.bank.templates :as templates])) (defn main-panel [] [:div (let [selected-nav (re-frame/subscribe [::subs/nav])] (apply templates/nav-bar @selected-nav)) [:div.section [:div.container [:div.columns [:div.column.is-one-quarter (let [show-left (re-frame/subscribe [::subs/show-left])] (when @show-left (let [left (re-frame/subscribe [::subs/left])] (apply templates/left-content @left))))] [:div.column.is-half (let [middle (re-frame/subscribe [::subs/middle])] (apply templates/middle-content @middle))] (let [selected-nav (re-frame/subscribe [::subs/selected-nav])] (if-not (= :results @selected-nav) [:div.column.is-one-quarter (when (= :client @selected-nav) (let [login-status (re-frame/subscribe [::subs/login-status])] (templates/login @login-status))) (let [max-items (re-frame/subscribe [::subs/max-items])] (templates/max-items-buttons @max-items)) (let [show-arguments (re-frame/subscribe [::subs/show-arguments])] (templates/show-argument-buttons @show-arguments))]))]]]])
null
https://raw.githubusercontent.com/openweb-nl/kafka-graphql-examples/a404a265b5b0f13968a24d00c6494981063937fe/frontend/src/cljs/nl/openweb/bank/views.cljs
clojure
(ns nl.openweb.bank.views (:require [re-frame.core :as re-frame] [nl.openweb.bank.subs :as subs] [nl.openweb.bank.templates :as templates])) (defn main-panel [] [:div (let [selected-nav (re-frame/subscribe [::subs/nav])] (apply templates/nav-bar @selected-nav)) [:div.section [:div.container [:div.columns [:div.column.is-one-quarter (let [show-left (re-frame/subscribe [::subs/show-left])] (when @show-left (let [left (re-frame/subscribe [::subs/left])] (apply templates/left-content @left))))] [:div.column.is-half (let [middle (re-frame/subscribe [::subs/middle])] (apply templates/middle-content @middle))] (let [selected-nav (re-frame/subscribe [::subs/selected-nav])] (if-not (= :results @selected-nav) [:div.column.is-one-quarter (when (= :client @selected-nav) (let [login-status (re-frame/subscribe [::subs/login-status])] (templates/login @login-status))) (let [max-items (re-frame/subscribe [::subs/max-items])] (templates/max-items-buttons @max-items)) (let [show-arguments (re-frame/subscribe [::subs/show-arguments])] (templates/show-argument-buttons @show-arguments))]))]]]])
92b44f1011a33f9c4e45bf405ba245718b1af7ba722ba7d8a23a27cfe45ae799
jtdaugherty/dbmigrations
BackendTest.hs
{-# LANGUAGE OverloadedStrings #-} -- | A test that is not executed as part of this package's test suite but rather -- acts as a conformance test suit for database specific backend -- implementations. All backend specific executable packages are expected to -- have a test suite that runs this test. module Database.Schema.Migrations.Test.BackendTest ( BackendConnection (..) , tests ) where import Data.ByteString ( ByteString ) import Control.Monad ( forM_ ) import Test.HUnit import Database.Schema.Migrations.Migration ( Migration(..), newMigration ) import Database.Schema.Migrations.Backend ( Backend(..) ) -- | A typeclass for database connections that needs to implemented for each -- specific database type to use this test. class BackendConnection c where | Whether this backend supports transactional DDL ; if it does n't , -- we'll skip any tests that rely on that behavior. supportsTransactionalDDL :: c -> Bool -- | Commits the current transaction. commit :: c -> IO () -- | Executes an IO action inside a transaction. withTransaction :: c -> (c -> IO a) -> IO a -- | Retrieves a list of all tables in the current database/scheme. getTables :: c -> IO [ByteString] catchAll :: c -> (IO a -> IO a -> IO a) -- | Returns a backend instance. makeBackend :: c -> Backend testSuite :: BackendConnection bc => Bool -> [bc -> IO ()] testSuite transactDDL = [ isBootstrappedFalseTest , bootstrapTest , isBootstrappedTrueTest , if transactDDL then applyMigrationFailure else (const $ return ()) , applyMigrationSuccess , revertMigrationFailure , revertMigrationNothing , revertMigrationJust ] tests :: BackendConnection bc => bc -> IO () tests conn = do let acts = testSuite $ supportsTransactionalDDL conn forM_ acts $ \act -> do commit conn act conn bootstrapTest :: BackendConnection bc => bc -> IO () bootstrapTest conn = do let backend = makeBackend conn bs <- getBootstrapMigration backend applyMigration backend bs assertEqual "installed_migrations table exists" ["installed_migrations"] =<< getTables conn assertEqual "successfully bootstrapped" [mId bs] =<< getMigrations backend isBootstrappedTrueTest :: BackendConnection bc => bc -> IO () isBootstrappedTrueTest conn = do result <- isBootstrapped $ makeBackend conn assertBool "Bootstrapped check" result isBootstrappedFalseTest :: BackendConnection bc => bc -> IO () isBootstrappedFalseTest conn = do result <- isBootstrapped $ makeBackend conn assertBool "Bootstrapped check" $ not result ignoreSqlExceptions :: BackendConnection bc => bc -> IO a -> IO (Maybe a) ignoreSqlExceptions conn act = (catchAll conn) (act >>= return . Just) (return Nothing) applyMigrationSuccess :: BackendConnection bc => bc -> IO () applyMigrationSuccess conn = do let backend = makeBackend conn let m1 = (newMigration "validMigration") { mApply = "CREATE TABLE valid1 (a int)" } -- Apply the migrations, ignore exceptions withTransaction conn $ \conn' -> applyMigration (makeBackend conn') m1 -- Check that none of the migrations were installed assertEqual "Installed migrations" ["root", "validMigration"] =<< getMigrations backend assertEqual "Installed tables" ["installed_migrations", "valid1"] =<< getTables conn |Does a failure to apply a migration imply a transaction rollback ? applyMigrationFailure :: BackendConnection bc => bc -> IO () applyMigrationFailure conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "CREATE TABLE validButTemporary (a int)" } m2 = (newMigration "third") { mApply = "INVALID SQL" } -- Apply the migrations, ignore exceptions _ <- ignoreSqlExceptions conn $ withTransaction conn $ \conn' -> do let backend' = makeBackend conn' applyMigration backend' m1 applyMigration backend' m2 -- Check that none of the migrations were installed assertEqual "Installed migrations" ["root"] =<< getMigrations backend assertEqual "Installed tables" ["installed_migrations"] =<< getTables conn revertMigrationFailure :: BackendConnection bc => bc -> IO () revertMigrationFailure conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "CREATE TABLE validRMF (a int)" , mRevert = Just "DROP TABLE validRMF"} m2 = (newMigration "third") { mApply = "alter table validRMF add column b int" , mRevert = Just "INVALID REVERT SQL"} applyMigration backend m1 applyMigration backend m2 installedBeforeRevert <- getMigrations backend commitBackend backend -- Revert the migrations, ignore exceptions; the revert will fail, -- but withTransaction will roll back. _ <- ignoreSqlExceptions conn $ withTransaction conn $ \conn' -> do let backend' = makeBackend conn' revertMigration backend' m2 revertMigration backend' m1 -- Check that none of the migrations were reverted assertEqual "successfully roll back failed revert" installedBeforeRevert =<< getMigrations backend revertMigrationNothing :: BackendConnection bc => bc -> IO () revertMigrationNothing conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "create table revert_nothing (a int)" , mRevert = Nothing } applyMigration backend m1 installedAfterApply <- getMigrations backend assertBool "Check that the migration was applied" $ "second" `elem` installedAfterApply -- Revert the migration, which should do nothing EXCEPT remove it -- from the installed list revertMigration backend m1 installed <- getMigrations backend assertBool "Check that the migration was reverted" $ not $ "second" `elem` installed revertMigrationJust :: BackendConnection bc => bc -> IO () revertMigrationJust conn = do let name = "revertable" backend = makeBackend conn let m1 = (newMigration name) { mApply = "CREATE TABLE the_test_table (a int)" , mRevert = Just "DROP TABLE the_test_table" } applyMigration backend m1 installedAfterApply <- getMigrations backend assertBool "Check that the migration was applied" $ name `elem` installedAfterApply -- Revert the migration, which should do nothing EXCEPT remove it -- from the installed list revertMigration backend m1 installed <- getMigrations backend assertBool "Check that the migration was reverted" $ not $ name `elem` installed
null
https://raw.githubusercontent.com/jtdaugherty/dbmigrations/80336a736ac394a2d38c65661b249b2fae142b64/src/Database/Schema/Migrations/Test/BackendTest.hs
haskell
# LANGUAGE OverloadedStrings # | A test that is not executed as part of this package's test suite but rather acts as a conformance test suit for database specific backend implementations. All backend specific executable packages are expected to have a test suite that runs this test. | A typeclass for database connections that needs to implemented for each specific database type to use this test. we'll skip any tests that rely on that behavior. | Commits the current transaction. | Executes an IO action inside a transaction. | Retrieves a list of all tables in the current database/scheme. | Returns a backend instance. Apply the migrations, ignore exceptions Check that none of the migrations were installed Apply the migrations, ignore exceptions Check that none of the migrations were installed Revert the migrations, ignore exceptions; the revert will fail, but withTransaction will roll back. Check that none of the migrations were reverted Revert the migration, which should do nothing EXCEPT remove it from the installed list Revert the migration, which should do nothing EXCEPT remove it from the installed list
module Database.Schema.Migrations.Test.BackendTest ( BackendConnection (..) , tests ) where import Data.ByteString ( ByteString ) import Control.Monad ( forM_ ) import Test.HUnit import Database.Schema.Migrations.Migration ( Migration(..), newMigration ) import Database.Schema.Migrations.Backend ( Backend(..) ) class BackendConnection c where | Whether this backend supports transactional DDL ; if it does n't , supportsTransactionalDDL :: c -> Bool commit :: c -> IO () withTransaction :: c -> (c -> IO a) -> IO a getTables :: c -> IO [ByteString] catchAll :: c -> (IO a -> IO a -> IO a) makeBackend :: c -> Backend testSuite :: BackendConnection bc => Bool -> [bc -> IO ()] testSuite transactDDL = [ isBootstrappedFalseTest , bootstrapTest , isBootstrappedTrueTest , if transactDDL then applyMigrationFailure else (const $ return ()) , applyMigrationSuccess , revertMigrationFailure , revertMigrationNothing , revertMigrationJust ] tests :: BackendConnection bc => bc -> IO () tests conn = do let acts = testSuite $ supportsTransactionalDDL conn forM_ acts $ \act -> do commit conn act conn bootstrapTest :: BackendConnection bc => bc -> IO () bootstrapTest conn = do let backend = makeBackend conn bs <- getBootstrapMigration backend applyMigration backend bs assertEqual "installed_migrations table exists" ["installed_migrations"] =<< getTables conn assertEqual "successfully bootstrapped" [mId bs] =<< getMigrations backend isBootstrappedTrueTest :: BackendConnection bc => bc -> IO () isBootstrappedTrueTest conn = do result <- isBootstrapped $ makeBackend conn assertBool "Bootstrapped check" result isBootstrappedFalseTest :: BackendConnection bc => bc -> IO () isBootstrappedFalseTest conn = do result <- isBootstrapped $ makeBackend conn assertBool "Bootstrapped check" $ not result ignoreSqlExceptions :: BackendConnection bc => bc -> IO a -> IO (Maybe a) ignoreSqlExceptions conn act = (catchAll conn) (act >>= return . Just) (return Nothing) applyMigrationSuccess :: BackendConnection bc => bc -> IO () applyMigrationSuccess conn = do let backend = makeBackend conn let m1 = (newMigration "validMigration") { mApply = "CREATE TABLE valid1 (a int)" } withTransaction conn $ \conn' -> applyMigration (makeBackend conn') m1 assertEqual "Installed migrations" ["root", "validMigration"] =<< getMigrations backend assertEqual "Installed tables" ["installed_migrations", "valid1"] =<< getTables conn |Does a failure to apply a migration imply a transaction rollback ? applyMigrationFailure :: BackendConnection bc => bc -> IO () applyMigrationFailure conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "CREATE TABLE validButTemporary (a int)" } m2 = (newMigration "third") { mApply = "INVALID SQL" } _ <- ignoreSqlExceptions conn $ withTransaction conn $ \conn' -> do let backend' = makeBackend conn' applyMigration backend' m1 applyMigration backend' m2 assertEqual "Installed migrations" ["root"] =<< getMigrations backend assertEqual "Installed tables" ["installed_migrations"] =<< getTables conn revertMigrationFailure :: BackendConnection bc => bc -> IO () revertMigrationFailure conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "CREATE TABLE validRMF (a int)" , mRevert = Just "DROP TABLE validRMF"} m2 = (newMigration "third") { mApply = "alter table validRMF add column b int" , mRevert = Just "INVALID REVERT SQL"} applyMigration backend m1 applyMigration backend m2 installedBeforeRevert <- getMigrations backend commitBackend backend _ <- ignoreSqlExceptions conn $ withTransaction conn $ \conn' -> do let backend' = makeBackend conn' revertMigration backend' m2 revertMigration backend' m1 assertEqual "successfully roll back failed revert" installedBeforeRevert =<< getMigrations backend revertMigrationNothing :: BackendConnection bc => bc -> IO () revertMigrationNothing conn = do let backend = makeBackend conn let m1 = (newMigration "second") { mApply = "create table revert_nothing (a int)" , mRevert = Nothing } applyMigration backend m1 installedAfterApply <- getMigrations backend assertBool "Check that the migration was applied" $ "second" `elem` installedAfterApply revertMigration backend m1 installed <- getMigrations backend assertBool "Check that the migration was reverted" $ not $ "second" `elem` installed revertMigrationJust :: BackendConnection bc => bc -> IO () revertMigrationJust conn = do let name = "revertable" backend = makeBackend conn let m1 = (newMigration name) { mApply = "CREATE TABLE the_test_table (a int)" , mRevert = Just "DROP TABLE the_test_table" } applyMigration backend m1 installedAfterApply <- getMigrations backend assertBool "Check that the migration was applied" $ name `elem` installedAfterApply revertMigration backend m1 installed <- getMigrations backend assertBool "Check that the migration was reverted" $ not $ name `elem` installed
54073b785e90df381fb77efad1e18296232f171fa45efd295dec64cb99cd96c7
clash-lang/clash-compiler
T1019.hs
module T1019 where import Clash.Prelude f :: SNat m -> Integer f = snatToInteger # NOINLINE f # topEntity = f (SNat @(LCM 733301111 742))
null
https://raw.githubusercontent.com/clash-lang/clash-compiler/8e461a910f2f37c900705a0847a9b533bce4d2ea/tests/shouldwork/Numbers/T1019.hs
haskell
module T1019 where import Clash.Prelude f :: SNat m -> Integer f = snatToInteger # NOINLINE f # topEntity = f (SNat @(LCM 733301111 742))
50531f9f57b093b24bc3098e3dc41fbbe317ab8c961b33bd2c2b5278d9c5b759
cyverse-archive/DiscoveryEnvironmentBackend
messenger.clj
(ns monkey.messenger "This namespace implements the Messages protocol where langhor is used to interface with an AMQP broker." (:require [clojure.tools.logging :as log] [langohr.basic :as basic] [langohr.channel :as ch] [langohr.consumers :as consumer] [langohr.core :as amqp] [langohr.exchange :as exchange] [langohr.queue :as queue] [monkey.props :as props]) (:import [clojure.lang IFn PersistentArrayMap])) TODO redesign so that the connection logic becomes testable (defn- attempt-connect [props] (try (let [conn (amqp/connect {:host (props/amqp-host props) :port (props/amqp-port props) :username (props/amqp-user props) :password (props/amqp-password props)})] (log/info "successfully connected to AMQP broker") conn) (catch Throwable t (log/error t "failed to connect to AMQP broker")))) (defn- connect [props] (if-let [conn (attempt-connect props)] conn (do (Thread/sleep (props/retry-period props)) (recur props)))) (defn- prepare-queue [ch props] (let [exchange (props/amqp-exchange-name props) queue (props/amqp-queue props)] (exchange/direct ch exchange :durable (props/amqp-exchange-durable? props) :auto-delete (props/amqp-exchange-auto-delete? props)) (queue/declare ch queue :durable true) (doseq [key ["index.all" "index.tags"]] (queue/bind ch queue exchange :routing-key key)) queue)) (defn- handle-delivery [deliver ch metadata _] (let [delivery-tag (:delivery-tag metadata)] (try (log/info "received reindex tags message") (deliver) (basic/ack ch delivery-tag) (catch Throwable t (log/error t "metadata reindexing failed, rescheduling") (basic/reject ch delivery-tag true))))) (defn- receive [conn props notify-received] (let [ch (ch/open conn) queue (prepare-queue ch props)] (consumer/blocking-subscribe ch queue (partial handle-delivery notify-received)))) (defn- silently-close [conn] (try (amqp/close conn) (catch Throwable _))) (defn listen "This function monitors an AMQP exchange for tags reindexing messages. When it receives a message, it calls the provided function to trigger a reindexing. It never returns. Parameters: props - the configuration properties notify-received - the function to call when a message is received" [^PersistentArrayMap props ^IFn notify-received] (let [conn (connect props)] (try (receive conn props notify-received) (catch Throwable t (log/error t "reconnecting to AMQP broker")) (finally (silently-close conn)))) (Thread/sleep (props/retry-period props)) (recur props notify-received))
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/monkey/src/monkey/messenger.clj
clojure
(ns monkey.messenger "This namespace implements the Messages protocol where langhor is used to interface with an AMQP broker." (:require [clojure.tools.logging :as log] [langohr.basic :as basic] [langohr.channel :as ch] [langohr.consumers :as consumer] [langohr.core :as amqp] [langohr.exchange :as exchange] [langohr.queue :as queue] [monkey.props :as props]) (:import [clojure.lang IFn PersistentArrayMap])) TODO redesign so that the connection logic becomes testable (defn- attempt-connect [props] (try (let [conn (amqp/connect {:host (props/amqp-host props) :port (props/amqp-port props) :username (props/amqp-user props) :password (props/amqp-password props)})] (log/info "successfully connected to AMQP broker") conn) (catch Throwable t (log/error t "failed to connect to AMQP broker")))) (defn- connect [props] (if-let [conn (attempt-connect props)] conn (do (Thread/sleep (props/retry-period props)) (recur props)))) (defn- prepare-queue [ch props] (let [exchange (props/amqp-exchange-name props) queue (props/amqp-queue props)] (exchange/direct ch exchange :durable (props/amqp-exchange-durable? props) :auto-delete (props/amqp-exchange-auto-delete? props)) (queue/declare ch queue :durable true) (doseq [key ["index.all" "index.tags"]] (queue/bind ch queue exchange :routing-key key)) queue)) (defn- handle-delivery [deliver ch metadata _] (let [delivery-tag (:delivery-tag metadata)] (try (log/info "received reindex tags message") (deliver) (basic/ack ch delivery-tag) (catch Throwable t (log/error t "metadata reindexing failed, rescheduling") (basic/reject ch delivery-tag true))))) (defn- receive [conn props notify-received] (let [ch (ch/open conn) queue (prepare-queue ch props)] (consumer/blocking-subscribe ch queue (partial handle-delivery notify-received)))) (defn- silently-close [conn] (try (amqp/close conn) (catch Throwable _))) (defn listen "This function monitors an AMQP exchange for tags reindexing messages. When it receives a message, it calls the provided function to trigger a reindexing. It never returns. Parameters: props - the configuration properties notify-received - the function to call when a message is received" [^PersistentArrayMap props ^IFn notify-received] (let [conn (connect props)] (try (receive conn props notify-received) (catch Throwable t (log/error t "reconnecting to AMQP broker")) (finally (silently-close conn)))) (Thread/sleep (props/retry-period props)) (recur props notify-received))
f190f720e3af3b46f2f0ffe82363e556b08855b5847733b7d144155c20585435
mkhan45/RustScript2
strings.ml
open Base open Stdio open Rustscript.Run open Util let () = let ss, state = test_state () |> run_file (test_file "strings.rsc") in assert_equal_expressions "result" "T" ss state; printf "Passed\n"
null
https://raw.githubusercontent.com/mkhan45/RustScript2/4e8cc6ab422116bd0a551aa43164926e413285ff/test/strings.ml
ocaml
open Base open Stdio open Rustscript.Run open Util let () = let ss, state = test_state () |> run_file (test_file "strings.rsc") in assert_equal_expressions "result" "T" ss state; printf "Passed\n"
55d08cdd2d09e74eafc28f0a3631072bc9b6a5b66b24536479d8de54ffeac921
tiensonqin/lymchat
main.cljs
(ns ^:figwheel-no-load env.ios.main (:require [reagent.core :as r] [lymchat.ios.core :as core] [figwheel.client :as figwheel :include-macros true])) (enable-console-print!) (def cnt (r/atom 0)) (defn reloader [] @cnt [core/app-root]) (def root-el (r/as-element [reloader])) (figwheel/watch-and-reload :websocket-url "ws:3449/figwheel-ws" :heads-up-display false :jsload-callback #(swap! cnt inc)) (core/init)
null
https://raw.githubusercontent.com/tiensonqin/lymchat/824026607d30c12bc50afb06f677d1fa95ff1f2f/env/dev/env/ios/main.cljs
clojure
(ns ^:figwheel-no-load env.ios.main (:require [reagent.core :as r] [lymchat.ios.core :as core] [figwheel.client :as figwheel :include-macros true])) (enable-console-print!) (def cnt (r/atom 0)) (defn reloader [] @cnt [core/app-root]) (def root-el (r/as-element [reloader])) (figwheel/watch-and-reload :websocket-url "ws:3449/figwheel-ws" :heads-up-display false :jsload-callback #(swap! cnt inc)) (core/init)
a757596b75625d2ea85ec397f818587c9ff9d9664f4b2bc11b1f3696f90f677c
kelamg/HtDP2e-workthrough
ex525.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex525) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (define MT (empty-scene 400 400)) (define A (make-posn 200 50)) (define B (make-posn 27 350)) (define C (make-posn 373 350)) (define COLOR 'black) ; Image Posn Posn Posn -> Image ; adds the black triangle a, b, c to scene (define (add-triangle scene a b c) (scene+line (scene+line (scene+line scene (posn-x a) (posn-y a) (posn-x b) (posn-y b) COLOR) (posn-x b) (posn-y b) (posn-x c) (posn-y c) COLOR) (posn-x c) (posn-y c) (posn-x a) (posn-y a) COLOR)) ; Posn Posn Posn -> Boolean ; is the triangle a, b, c too small to be divided (define (too-small? a b c) (<= (min (distance a b) (distance b c) (distance c a)) pi)) ; Posn Posn -> Number produces the eucledian distance between two Posns (define (distance a b) (sqrt (+ (sqr (- (posn-y a) (posn-y b))) (sqr (- (posn-x a) (posn-x b)))))) ; Posn Posn -> Posn ; determines the midpoint between a and b (define (mid-point a b) (make-posn (* 0.5 (+ (posn-x a) (posn-x b))) (* 0.5 (+ (posn-y a) (posn-y b))))) ; Image Posn Posn Posn -> Image ; generative adds the triangle (a, b, c) to s, subdivides it into three triangles by taking the ; midpoints of its sides; stop if (a, b, c) is too small accumulator the function accumulates the triangles scene0 (define (add-sierpinski scene0 a b c) (cond [(too-small? a b c) scene0] [else (local ((define scene1 (add-triangle scene0 a b c)) (define mid-a-b (mid-point a b)) (define mid-b-c (mid-point b c)) (define mid-c-a (mid-point c a)) (define scene2 (add-sierpinski scene1 a mid-a-b mid-c-a)) (define scene3 (add-sierpinski scene2 b mid-b-c mid-a-b))) ; —IN— (add-sierpinski scene3 c mid-c-a mid-b-c))])) ; uncomment to run ; (add-sierpinski MT A B C)
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Accumulators/ex525.rkt
racket
about the language level of this file in a form that our tools can easily process. Image Posn Posn Posn -> Image adds the black triangle a, b, c to scene Posn Posn Posn -> Boolean is the triangle a, b, c too small to be divided Posn Posn -> Number Posn Posn -> Posn determines the midpoint between a and b Image Posn Posn Posn -> Image generative adds the triangle (a, b, c) to s, midpoints of its sides; stop if (a, b, c) is too small —IN— uncomment to run (add-sierpinski MT A B C)
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex525) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/image) (define MT (empty-scene 400 400)) (define A (make-posn 200 50)) (define B (make-posn 27 350)) (define C (make-posn 373 350)) (define COLOR 'black) (define (add-triangle scene a b c) (scene+line (scene+line (scene+line scene (posn-x a) (posn-y a) (posn-x b) (posn-y b) COLOR) (posn-x b) (posn-y b) (posn-x c) (posn-y c) COLOR) (posn-x c) (posn-y c) (posn-x a) (posn-y a) COLOR)) (define (too-small? a b c) (<= (min (distance a b) (distance b c) (distance c a)) pi)) produces the eucledian distance between two Posns (define (distance a b) (sqrt (+ (sqr (- (posn-y a) (posn-y b))) (sqr (- (posn-x a) (posn-x b)))))) (define (mid-point a b) (make-posn (* 0.5 (+ (posn-x a) (posn-x b))) (* 0.5 (+ (posn-y a) (posn-y b))))) subdivides it into three triangles by taking the accumulator the function accumulates the triangles scene0 (define (add-sierpinski scene0 a b c) (cond [(too-small? a b c) scene0] [else (local ((define scene1 (add-triangle scene0 a b c)) (define mid-a-b (mid-point a b)) (define mid-b-c (mid-point b c)) (define mid-c-a (mid-point c a)) (define scene2 (add-sierpinski scene1 a mid-a-b mid-c-a)) (define scene3 (add-sierpinski scene2 b mid-b-c mid-a-b))) (add-sierpinski scene3 c mid-c-a mid-b-c))]))
dfeb53b8004f8954740e1cd801d64e7571428a7958b82277441204cf55c0fa0a
haskell-tools/haskell-tools
SemicolonDo.hs
module Expr.SemicolonDo where import Control.Monad.Identity a = do { n <- Identity () ; return () }
null
https://raw.githubusercontent.com/haskell-tools/haskell-tools/b1189ab4f63b29bbf1aa14af4557850064931e32/src/refactor/examples/Expr/SemicolonDo.hs
haskell
module Expr.SemicolonDo where import Control.Monad.Identity a = do { n <- Identity () ; return () }
62b5a0bef386269f03357381908d45ed7d391ff7cd7e212d9b82b754872b1245
yuriy-chumak/ol
version-1-4.scm
OpenGL 1.4 ( 24 Jul 2002 ) (define-library (OpenGL version-1-4) (export (exports (OpenGL version-1-3)) GL_VERSION_1_4 glWindowPos2iv glPointParameterf glSecondaryColor3f # define GL_BLEND_DST_RGB 0x80C8 ;; #define GL_BLEND_SRC_RGB 0x80C9 # define 0x80CA # define GL_BLEND_SRC_ALPHA 0x80CB ;; #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 ;; #define GL_DEPTH_COMPONENT16 0x81A5 GL_DEPTH_COMPONENT24 # define GL_DEPTH_COMPONENT32 0x81A7 # define GL_MIRRORED_REPEAT 0x8370 ;; #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD ;; #define GL_TEXTURE_LOD_BIAS 0x8501 # define GL_INCR_WRAP 0x8507 # define GL_DECR_WRAP 0x8508 # define GL_TEXTURE_DEPTH_SIZE 0x884A # define GL_TEXTURE_COMPARE_MODE 0x884C # define 0x884D GL_POINT_SIZE_MIN GL_POINT_SIZE_MAX ;; #define GL_POINT_DISTANCE_ATTENUATION 0x8129 # define GL_GENERATE_MIPMAP 0x8191 # define # define GL_FOG_COORDINATE_SOURCE 0x8450 ;; #define GL_FOG_COORDINATE 0x8451 ;; #define GL_FRAGMENT_DEPTH 0x8452 # define GL_CURRENT_FOG_COORDINATE 0x8453 ;; #define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 ;; #define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 # define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 # define GL_FOG_COORDINATE_ARRAY 0x8457 # define GL_COLOR_SUM # define GL_CURRENT_SECONDARY_COLOR 0x8459 # define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A # define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B # define GL_SECONDARY_COLOR_ARRAY_STRIDE # define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D # define ;; #define GL_TEXTURE_FILTER_CONTROL 0x8500 ;; #define GL_DEPTH_TEXTURE_MODE 0x884B # define GL_COMPARE_R_TO_TEXTURE 0x884E # define 0x8005 ;; #define GL_BLEND_EQUATION 0x8009 # define GL_CONSTANT_COLOR 0x8001 # define 0x8002 # define 0x8003 # define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 ;; #define GL_FUNC_ADD 0x8006 # define GL_FUNC_REVERSE_SUBTRACT 0x800B ;; #define GL_FUNC_SUBTRACT 0x800A ;; #define GL_MIN 0x8007 ;; #define GL_MAX 0x8008 GLAPI void APIENTRY glBlendFuncSeparate ( GLenum sfactorRGB , GLenum dfactorRGB , GLenum sfactorAlpha , GLenum dfactorAlpha ) ; GLAPI void APIENTRY glMultiDrawArrays ( GLenum mode , const GLint * first , const * count , ) ; GLAPI void APIENTRY glMultiDrawElements ( GLenum mode , const * count , GLenum type , const void * const*indices , ) ; GLAPI void APIENTRY glPointParameterf ( GLenum pname , GLfloat param ) ; glPointParameterf GLAPI void APIENTRY glPointParameterfv ( GLenum pname , const GLfloat * params ) ; GLAPI void APIENTRY ( GLenum pname , GLint param ) ; GLAPI void APIENTRY glPointParameteriv ( GLenum pname , const GLint * params ) ; GLAPI void APIENTRY glFogCoordf ( GLfloat coord ) ; GLAPI void APIENTRY glFogCoordfv ( const GLfloat * coord ) ; GLAPI void APIENTRY glFogCoordd ( coord ) ; GLAPI void APIENTRY glFogCoorddv ( const * coord ) ; GLAPI void APIENTRY glFogCoordPointer ( GLenum type , stride , const void * pointer ) ; GLAPI void APIENTRY glSecondaryColor3b ( GLbyte red , green , blue ) ; GLAPI void APIENTRY glSecondaryColor3bv ( const * v ) ; GLAPI void APIENTRY glSecondaryColor3d ( red , green , blue ) ; GLAPI void APIENTRY glSecondaryColor3dv ( const * v ) ; GLAPI void APIENTRY glSecondaryColor3f ( GLfloat red , GLfloat green , GLfloat blue ) ; GLAPI void APIENTRY glSecondaryColor3fv ( const GLfloat * v ) ; GLAPI void APIENTRY glSecondaryColor3i ( GLint red , GLint green , GLint blue ) ; GLAPI void APIENTRY glSecondaryColor3iv ( const GLint * v ) ; GLAPI void APIENTRY glSecondaryColor3s ( GLshort red , GLshort green , GLshort blue ) ; GLAPI void APIENTRY glSecondaryColor3sv ( const GLshort * v ) ; GLAPI void APIENTRY glSecondaryColor3ub ( GLubyte red , GLubyte green , GLubyte blue ) ; GLAPI void APIENTRY ( const GLubyte * v ) ; GLAPI void APIENTRY glSecondaryColor3ui ( GLuint red , GLuint green , GLuint blue ) ; GLAPI void APIENTRY glSecondaryColor3uiv ( const GLuint * v ) ; GLAPI void APIENTRY glSecondaryColor3us ( GLushort red , GLushort green , GLushort blue ) ; GLAPI void APIENTRY glSecondaryColor3usv ( const GLushort * v ) ; GLAPI void APIENTRY glSecondaryColorPointer ( GLint size , GLenum type , stride , const void * pointer ) ; GLAPI void APIENTRY glWindowPos2d ( , ) ; GLAPI void APIENTRY glWindowPos2dv ( const * v ) ; GLAPI void APIENTRY glWindowPos2f ( GLfloat x , y ) ; GLAPI void APIENTRY glWindowPos2fv ( const GLfloat * v ) ; GLAPI void APIENTRY glWindowPos2i ( GLint x , GLint y ) ; GLAPI void APIENTRY glWindowPos2iv ( const GLint * v ) ; GLAPI void APIENTRY glWindowPos2s ( GLshort x , GLshort y ) ; GLAPI void APIENTRY glWindowPos2sv ( const GLshort * v ) ; GLAPI void APIENTRY glWindowPos3d ( , , ) ; GLAPI void APIENTRY ( const * v ) ; GLAPI void APIENTRY glWindowPos3f ( GLfloat x , GLfloat y , GLfloat z ) ; GLAPI void APIENTRY glWindowPos3fv ( const GLfloat * v ) ; GLAPI void APIENTRY glWindowPos3i ( GLint x , GLint y , GLint z ) ; GLAPI void APIENTRY glWindowPos3iv ( const GLint * v ) ; GLAPI void APIENTRY glWindowPos3s ( GLshort x , GLshort y , GLshort z ) ; GLAPI void APIENTRY glWindowPos3sv ( const GLshort * v ) ; GLAPI void APIENTRY ( GLfloat red , GLfloat green , GLfloat blue , GLfloat alpha ) ; GLAPI void APIENTRY glBlendEquation ( GLenum mode ) ; ) (import (scheme core) (OpenGL version-1-3)) (begin (define GL_VERSION_1_4 1) (setq GL GL_LIBRARY) (define glWindowPos2iv (GL GLvoid "glWindowPos2iv" (fft* GLint))) (define GL_DEPTH_COMPONENT24 #x81A6) (define GL_POINT_SIZE_MIN #x8126) (define GL_POINT_SIZE_MAX #x8127) (define glPointParameterf (GL GLvoid "glPointParameterf" GLenum GLfloat)) (define glSecondaryColor3f (GL GLvoid "glSecondaryColor3f" GLfloat GLfloat GLfloat)) ))
null
https://raw.githubusercontent.com/yuriy-chumak/ol/69f9159b6955ee11d7e30e9eb9b55c47c64d9720/libraries/OpenGL/version-1-4.scm
scheme
#define GL_BLEND_SRC_RGB 0x80C9 #define GL_POINT_FADE_THRESHOLD_SIZE 0x8128 #define GL_DEPTH_COMPONENT16 0x81A5 #define GL_MAX_TEXTURE_LOD_BIAS 0x84FD #define GL_TEXTURE_LOD_BIAS 0x8501 #define GL_POINT_DISTANCE_ATTENUATION 0x8129 #define GL_FOG_COORDINATE 0x8451 #define GL_FRAGMENT_DEPTH 0x8452 #define GL_FOG_COORDINATE_ARRAY_TYPE 0x8454 #define GL_FOG_COORDINATE_ARRAY_STRIDE 0x8455 #define GL_TEXTURE_FILTER_CONTROL 0x8500 #define GL_DEPTH_TEXTURE_MODE 0x884B #define GL_BLEND_EQUATION 0x8009 #define GL_FUNC_ADD 0x8006 #define GL_FUNC_SUBTRACT 0x800A #define GL_MIN 0x8007 #define GL_MAX 0x8008
OpenGL 1.4 ( 24 Jul 2002 ) (define-library (OpenGL version-1-4) (export (exports (OpenGL version-1-3)) GL_VERSION_1_4 glWindowPos2iv glPointParameterf glSecondaryColor3f # define GL_BLEND_DST_RGB 0x80C8 # define 0x80CA # define GL_BLEND_SRC_ALPHA 0x80CB GL_DEPTH_COMPONENT24 # define GL_DEPTH_COMPONENT32 0x81A7 # define GL_MIRRORED_REPEAT 0x8370 # define GL_INCR_WRAP 0x8507 # define GL_DECR_WRAP 0x8508 # define GL_TEXTURE_DEPTH_SIZE 0x884A # define GL_TEXTURE_COMPARE_MODE 0x884C # define 0x884D GL_POINT_SIZE_MIN GL_POINT_SIZE_MAX # define GL_GENERATE_MIPMAP 0x8191 # define # define GL_FOG_COORDINATE_SOURCE 0x8450 # define GL_CURRENT_FOG_COORDINATE 0x8453 # define GL_FOG_COORDINATE_ARRAY_POINTER 0x8456 # define GL_FOG_COORDINATE_ARRAY 0x8457 # define GL_COLOR_SUM # define GL_CURRENT_SECONDARY_COLOR 0x8459 # define GL_SECONDARY_COLOR_ARRAY_SIZE 0x845A # define GL_SECONDARY_COLOR_ARRAY_TYPE 0x845B # define GL_SECONDARY_COLOR_ARRAY_STRIDE # define GL_SECONDARY_COLOR_ARRAY_POINTER 0x845D # define # define GL_COMPARE_R_TO_TEXTURE 0x884E # define 0x8005 # define GL_CONSTANT_COLOR 0x8001 # define 0x8002 # define 0x8003 # define GL_ONE_MINUS_CONSTANT_ALPHA 0x8004 # define GL_FUNC_REVERSE_SUBTRACT 0x800B glPointParameterf ) (import (scheme core) (OpenGL version-1-3)) (begin (define GL_VERSION_1_4 1) (setq GL GL_LIBRARY) (define glWindowPos2iv (GL GLvoid "glWindowPos2iv" (fft* GLint))) (define GL_DEPTH_COMPONENT24 #x81A6) (define GL_POINT_SIZE_MIN #x8126) (define GL_POINT_SIZE_MAX #x8127) (define glPointParameterf (GL GLvoid "glPointParameterf" GLenum GLfloat)) (define glSecondaryColor3f (GL GLvoid "glSecondaryColor3f" GLfloat GLfloat GLfloat)) ))
c52a85f33e152c952eb51506291f8303d0828a4b0c75eecea6e3c2b35b528e4a
Kakadu/fp2022
demo.ml
* Copyright 2021 - 2022 , * SPDX - License - Identifier : LGPL-3.0 - or - later open Python_lib.Interpreter open Eval (Result) let () = let path = String.trim (Stdio.In_channel.input_all Caml.stdin) in let ic = open_in path in try let code = Stdio.In_channel.input_all ic in let y = parse_and_interpet code in match y with | Ok x -> print_endline x | Error x -> print_endline x; close_in ic with | e -> close_in ic; raise e ;;
null
https://raw.githubusercontent.com/Kakadu/fp2022/27ec5cd84ad68b54bb1c7191bab59320684386ab/Python/demos/demo.ml
ocaml
* Copyright 2021 - 2022 , * SPDX - License - Identifier : LGPL-3.0 - or - later open Python_lib.Interpreter open Eval (Result) let () = let path = String.trim (Stdio.In_channel.input_all Caml.stdin) in let ic = open_in path in try let code = Stdio.In_channel.input_all ic in let y = parse_and_interpet code in match y with | Ok x -> print_endline x | Error x -> print_endline x; close_in ic with | e -> close_in ic; raise e ;;
82ad0d390f96521cc1f0a016900d957e2b30c3b9bf056f74d602caaeae915b1e
mikera/core.matrix
polynomial.clj
(ns clojure.core.matrix.demo.polynomial (:use clojure.core.matrix)) ;; our task is to find a polynomial that fits a set of points ;; a sey of [x y points] (def points [[0 1] [ 1 4] [2 10] [3 19] [4 31] [5 46]]) (def n (count points)) (def m (matrix (mapv (fn [[x y]] (mapv (fn [i] (pow x i)) (range n))) points))) (def y (mapv second points)) ;; let x be the polynomial coefficients we have y ;; so x= (inv m).y (def x (mmul (inverse (array :vectorz m)) y)) ;; now create a function that computes the polynomial (defn f [t] (mmul x (mapv #(pow t %) (range n))))
null
https://raw.githubusercontent.com/mikera/core.matrix/0a35f6e3d6d2335cb56f6f3e5744bfa1dd0390aa/src/test/clojure/clojure/core/matrix/demo/polynomial.clj
clojure
our task is to find a polynomial that fits a set of points a sey of [x y points] let x be the polynomial coefficients so x= (inv m).y now create a function that computes the polynomial
(ns clojure.core.matrix.demo.polynomial (:use clojure.core.matrix)) (def points [[0 1] [ 1 4] [2 10] [3 19] [4 31] [5 46]]) (def n (count points)) (def m (matrix (mapv (fn [[x y]] (mapv (fn [i] (pow x i)) (range n))) points))) (def y (mapv second points)) we have y (def x (mmul (inverse (array :vectorz m)) y)) (defn f [t] (mmul x (mapv #(pow t %) (range n))))
aa1bcc9f501d73d7acb0151084f944ceacd0429b40fff474ef741cd58f94458d
sbcl/sbcl
memory.lisp
;;;; the RISC-V definitions of some general purpose memory reference VOPs ;;;; inherited by basic memory reference operations This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the ;;;; public domain. The software is in the public domain and is ;;;; provided with absolutely no warranty. See the COPYING and CREDITS ;;;; files for more information. (in-package "SB-VM") Cell - Ref and Cell - Set are used to define VOPs like CAR , where the offset to be read or written is a property of the VOP used . (define-vop (cell-ref) (:args (object :scs (descriptor-reg))) (:results (value :scs (descriptor-reg any-reg))) (:variant-vars offset lowtag) (:generator 4 (loadw value object offset lowtag))) (define-vop (cell-set) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg zero))) (:variant-vars offset lowtag) (:generator 4 (storew value object offset lowtag))) (define-vop (set-instance-hashed) (:args (object :scs (descriptor-reg))) (:temporary (:sc non-descriptor-reg) baseptr bit temp) (:generator 5 (inst addi baseptr object (- instance-pointer-lowtag)) (inst li bit (ash 1 stable-hash-required-flag)) (inst amoor temp bit baseptr :aq :rl)))
null
https://raw.githubusercontent.com/sbcl/sbcl/c6049bdd1b83d07833a29a88bb77e8846b1d260a/src/compiler/riscv/memory.lisp
lisp
the RISC-V definitions of some general purpose memory reference VOPs inherited by basic memory reference operations more information. public domain. The software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information.
This software is part of the SBCL system . See the README file for This software is derived from the CMU CL system , which was written at Carnegie Mellon University and released into the (in-package "SB-VM") Cell - Ref and Cell - Set are used to define VOPs like CAR , where the offset to be read or written is a property of the VOP used . (define-vop (cell-ref) (:args (object :scs (descriptor-reg))) (:results (value :scs (descriptor-reg any-reg))) (:variant-vars offset lowtag) (:generator 4 (loadw value object offset lowtag))) (define-vop (cell-set) (:args (object :scs (descriptor-reg)) (value :scs (descriptor-reg any-reg zero))) (:variant-vars offset lowtag) (:generator 4 (storew value object offset lowtag))) (define-vop (set-instance-hashed) (:args (object :scs (descriptor-reg))) (:temporary (:sc non-descriptor-reg) baseptr bit temp) (:generator 5 (inst addi baseptr object (- instance-pointer-lowtag)) (inst li bit (ash 1 stable-hash-required-flag)) (inst amoor temp bit baseptr :aq :rl)))
2ae0ef41388cb38651d4faf763143ec4ca832e45b2e3455773a4dc8b89a625b9
janestreet/learn-ocaml-workshop
frogger.ml
open Base open Scaffold module Direction = struct type t = | Up | Down | Left | Right end module Frog = struct type t = { position : Position.t ; facing : Direction.t } [@@deriving fields] let create = Fields.create end module Non_frog_character = struct module Kind = struct type t = | Car | Log end type t = { horizontal_speed : int ; position : Position.t ; kind : Kind.t ; image : Image.t } [@@deriving fields] let create = Fields.create end module Game_state = struct type t = | Playing | Won | Dead end module World = struct type t = { state : Game_state.t ; frog : Frog.t ; nfcs : Non_frog_character.t list } [@@deriving fields] let create = Fields.create end let create_frog () = let position = Position.create ~x:(Scaffold.Board.num_cols / 2) ~y:0 in Frog.create ~position ~facing:Direction.Up ;; let create_nfcs () = let max_speed = 1 in List.mapi Scaffold.Board.rows ~f:(fun idx row -> let make_nfc kind col direction_sign = let horizontal_speed = direction_sign * (1 + Random.int max_speed) in let position = Position.create ~x:col ~y:idx in let image = match (kind : Non_frog_character.Kind.t) with | Car -> ( let dir left right = if horizontal_speed < 0 then left else right in match Random.int 3 with | 0 -> dir Image.car1_left Image.car1_right | 1 -> dir Image.car2_left Image.car2_right | 2 -> dir Image.car3_left Image.car3_right | _ -> assert false) | Log -> ( match Random.int 3 with | 0 -> Image.log1 | 1 -> Image.log2 | 2 -> Image.log3 | _ -> assert false) in Non_frog_character.create ~kind ~horizontal_speed ~position ~image in let make_one_row kind = let num_nfcs_per_row = 3 in let max_gap = 3 in let start_pos = Random.int Board.num_cols in let gap_to_leave_between_nfcs = match (kind : Non_frog_character.Kind.t) with | Car -> 1 + Random.int max_gap | Log -> 0 in let sign = 2 * (idx % 2) - 1 in (* Alternating directions *) List.init num_nfcs_per_row ~f:(fun idx -> make_nfc kind ((start_pos + idx * (gap_to_leave_between_nfcs + 1)) % Board.num_cols) sign) in match row with | Safe_strip -> [] | Road -> make_one_row Non_frog_character.Kind.Car | River -> make_one_row Non_frog_character.Kind.Log) |> List.concat ;; let create () = World.create ~state:Game_state.Playing ~frog:(create_frog ()) ~nfcs:(create_nfcs ()) ;; let rec detect_collision (frog_pos : Position.t) nfcs = let is_colliding (nfc : Non_frog_character.t) = if Int.(<>) frog_pos.y nfc.position.y then false else let width = match nfc.kind with | Car -> 1 | Log -> 1 in (nfc.position.x <= frog_pos.x) && (frog_pos.x < nfc.position.x + width) in match nfcs with | [] -> None | nfc :: rest -> if is_colliding nfc then Some nfc else detect_collision frog_pos rest ;; let pos_is_in_river (pos : Position.t) = match List.nth_exn Scaffold.Board.rows pos.y with | Safe_strip | Road -> false | River -> true ;; let should_die frog_pos collision_result = let frog_is_in_river = pos_is_in_river frog_pos in match (collision_result : Non_frog_character.t option) with | Some { kind = Car; _ } -> true | Some { kind = Log; _ } -> false | None -> frog_is_in_river ;; let should_win (frog_pos : Position.t) = Int.(=) frog_pos.y (List.length Scaffold.Board.rows - 1) ;; let compute_new_game_state frog_pos collision_result = if should_die frog_pos collision_result then Game_state.Dead else if should_win frog_pos then Won else Playing ;; let tick (world : World.t) = match world.state with | Won | Dead -> world | Playing -> let new_nfcs = List.map world.nfcs ~f:(fun nfc -> let new_position = Position.create ~x:((nfc.position.x + nfc.horizontal_speed) % Scaffold.Board.num_cols) ~y:nfc.position.y in { nfc with position = new_position }) in let collision_result_before = detect_collision world.frog.position world.nfcs in let new_frog = let new_frog_position = let dx = match collision_result_before with | Some { kind = Log; horizontal_speed; _ } -> horizontal_speed | _ -> 0 in Position.create ~x:(world.frog.position.x + dx) ~y:(world.frog.position.y) in { world.frog with position = new_frog_position } in let collision_result_after = detect_collision new_frog.position new_nfcs in let new_game_state = compute_new_game_state new_frog.position collision_result_after in World.create ~state:new_game_state ~frog:new_frog ~nfcs:new_nfcs ;; let clamp ~min ~max x = if x < min then min else if x > max then max else x ;; let handle_input (world : World.t) key = let num_rows = List.length Scaffold.Board.rows in let num_cols = Scaffold.Board.num_cols in match world.state with | Won | Dead -> world | Playing -> let new_frog = let new_pos, new_dir = let old_pos = world.frog.position in match key with | Key.Arrow_up -> { old_pos with y = clamp ~min:0 ~max:(num_rows - 1) (old_pos.y + 1)}, Direction.Up | Key.Arrow_down -> { old_pos with y = clamp ~min:0 ~max:(num_rows - 1) (old_pos.y - 1)}, Direction.Down | Key.Arrow_left -> { old_pos with x = clamp ~min:0 ~max:(num_cols - 1) (old_pos.x - 1)}, Direction.Left | Key.Arrow_right -> { old_pos with x = clamp ~min:0 ~max:(num_cols - 1) (old_pos.x + 1)}, Direction.Right in Frog.create ~position:new_pos ~facing:new_dir in let new_game_state = let collision_result = detect_collision new_frog.position world.nfcs in compute_new_game_state new_frog.position collision_result in World.create ~state:new_game_state ~frog:new_frog ~nfcs:world.nfcs ;; let draw (world : World.t) = let draw_frog_command = let frog_image = match world.state with | Dead -> Image.skull_and_crossbones | Won -> Image.confetti | Playing -> ( match world.frog.facing with | Up -> Image.frog_up | Down -> Image.frog_down | Left -> Image.frog_left | Right -> Image.frog_right) in (frog_image, world.frog.position) in let draw_nfc (nfc : Non_frog_character.t) = (nfc.image, nfc.position) in (List.map world.nfcs ~f:draw_nfc) @ [draw_frog_command] ;; let handle_event world event = match (event : Event.t) with | Tick -> tick world | Keypress k -> handle_input world k ;; let finished world = match World.state world with | Playing -> false | Won | Dead -> true ;;
null
https://raw.githubusercontent.com/janestreet/learn-ocaml-workshop/1ba9576b48b48a892644eb20c201c2c4aa643c32/solutions/frogger/frogger.ml
ocaml
Alternating directions
open Base open Scaffold module Direction = struct type t = | Up | Down | Left | Right end module Frog = struct type t = { position : Position.t ; facing : Direction.t } [@@deriving fields] let create = Fields.create end module Non_frog_character = struct module Kind = struct type t = | Car | Log end type t = { horizontal_speed : int ; position : Position.t ; kind : Kind.t ; image : Image.t } [@@deriving fields] let create = Fields.create end module Game_state = struct type t = | Playing | Won | Dead end module World = struct type t = { state : Game_state.t ; frog : Frog.t ; nfcs : Non_frog_character.t list } [@@deriving fields] let create = Fields.create end let create_frog () = let position = Position.create ~x:(Scaffold.Board.num_cols / 2) ~y:0 in Frog.create ~position ~facing:Direction.Up ;; let create_nfcs () = let max_speed = 1 in List.mapi Scaffold.Board.rows ~f:(fun idx row -> let make_nfc kind col direction_sign = let horizontal_speed = direction_sign * (1 + Random.int max_speed) in let position = Position.create ~x:col ~y:idx in let image = match (kind : Non_frog_character.Kind.t) with | Car -> ( let dir left right = if horizontal_speed < 0 then left else right in match Random.int 3 with | 0 -> dir Image.car1_left Image.car1_right | 1 -> dir Image.car2_left Image.car2_right | 2 -> dir Image.car3_left Image.car3_right | _ -> assert false) | Log -> ( match Random.int 3 with | 0 -> Image.log1 | 1 -> Image.log2 | 2 -> Image.log3 | _ -> assert false) in Non_frog_character.create ~kind ~horizontal_speed ~position ~image in let make_one_row kind = let num_nfcs_per_row = 3 in let max_gap = 3 in let start_pos = Random.int Board.num_cols in let gap_to_leave_between_nfcs = match (kind : Non_frog_character.Kind.t) with | Car -> 1 + Random.int max_gap | Log -> 0 in List.init num_nfcs_per_row ~f:(fun idx -> make_nfc kind ((start_pos + idx * (gap_to_leave_between_nfcs + 1)) % Board.num_cols) sign) in match row with | Safe_strip -> [] | Road -> make_one_row Non_frog_character.Kind.Car | River -> make_one_row Non_frog_character.Kind.Log) |> List.concat ;; let create () = World.create ~state:Game_state.Playing ~frog:(create_frog ()) ~nfcs:(create_nfcs ()) ;; let rec detect_collision (frog_pos : Position.t) nfcs = let is_colliding (nfc : Non_frog_character.t) = if Int.(<>) frog_pos.y nfc.position.y then false else let width = match nfc.kind with | Car -> 1 | Log -> 1 in (nfc.position.x <= frog_pos.x) && (frog_pos.x < nfc.position.x + width) in match nfcs with | [] -> None | nfc :: rest -> if is_colliding nfc then Some nfc else detect_collision frog_pos rest ;; let pos_is_in_river (pos : Position.t) = match List.nth_exn Scaffold.Board.rows pos.y with | Safe_strip | Road -> false | River -> true ;; let should_die frog_pos collision_result = let frog_is_in_river = pos_is_in_river frog_pos in match (collision_result : Non_frog_character.t option) with | Some { kind = Car; _ } -> true | Some { kind = Log; _ } -> false | None -> frog_is_in_river ;; let should_win (frog_pos : Position.t) = Int.(=) frog_pos.y (List.length Scaffold.Board.rows - 1) ;; let compute_new_game_state frog_pos collision_result = if should_die frog_pos collision_result then Game_state.Dead else if should_win frog_pos then Won else Playing ;; let tick (world : World.t) = match world.state with | Won | Dead -> world | Playing -> let new_nfcs = List.map world.nfcs ~f:(fun nfc -> let new_position = Position.create ~x:((nfc.position.x + nfc.horizontal_speed) % Scaffold.Board.num_cols) ~y:nfc.position.y in { nfc with position = new_position }) in let collision_result_before = detect_collision world.frog.position world.nfcs in let new_frog = let new_frog_position = let dx = match collision_result_before with | Some { kind = Log; horizontal_speed; _ } -> horizontal_speed | _ -> 0 in Position.create ~x:(world.frog.position.x + dx) ~y:(world.frog.position.y) in { world.frog with position = new_frog_position } in let collision_result_after = detect_collision new_frog.position new_nfcs in let new_game_state = compute_new_game_state new_frog.position collision_result_after in World.create ~state:new_game_state ~frog:new_frog ~nfcs:new_nfcs ;; let clamp ~min ~max x = if x < min then min else if x > max then max else x ;; let handle_input (world : World.t) key = let num_rows = List.length Scaffold.Board.rows in let num_cols = Scaffold.Board.num_cols in match world.state with | Won | Dead -> world | Playing -> let new_frog = let new_pos, new_dir = let old_pos = world.frog.position in match key with | Key.Arrow_up -> { old_pos with y = clamp ~min:0 ~max:(num_rows - 1) (old_pos.y + 1)}, Direction.Up | Key.Arrow_down -> { old_pos with y = clamp ~min:0 ~max:(num_rows - 1) (old_pos.y - 1)}, Direction.Down | Key.Arrow_left -> { old_pos with x = clamp ~min:0 ~max:(num_cols - 1) (old_pos.x - 1)}, Direction.Left | Key.Arrow_right -> { old_pos with x = clamp ~min:0 ~max:(num_cols - 1) (old_pos.x + 1)}, Direction.Right in Frog.create ~position:new_pos ~facing:new_dir in let new_game_state = let collision_result = detect_collision new_frog.position world.nfcs in compute_new_game_state new_frog.position collision_result in World.create ~state:new_game_state ~frog:new_frog ~nfcs:world.nfcs ;; let draw (world : World.t) = let draw_frog_command = let frog_image = match world.state with | Dead -> Image.skull_and_crossbones | Won -> Image.confetti | Playing -> ( match world.frog.facing with | Up -> Image.frog_up | Down -> Image.frog_down | Left -> Image.frog_left | Right -> Image.frog_right) in (frog_image, world.frog.position) in let draw_nfc (nfc : Non_frog_character.t) = (nfc.image, nfc.position) in (List.map world.nfcs ~f:draw_nfc) @ [draw_frog_command] ;; let handle_event world event = match (event : Event.t) with | Tick -> tick world | Keypress k -> handle_input world k ;; let finished world = match World.state world with | Playing -> false | Won | Dead -> true ;;
12c329035565940ac263075c958e6260e4f2a6c53f7a37d60b66c1617a890386
hypernumbers/hypernumbers
dh_matrix.erl
%%%------------------------------------------------------------------- @author ( C ) 2008 - 2014 , Hypernumbers.com %%% @doc handle matrix functions %%% @end %%% Created : by %%%------------------------------------------------------------------- %%%------------------------------------------------------------------- %%% %%% LICENSE %%% %%% 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 version 3 %%% %%% 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 </>. %%%------------------------------------------------------------------- -module(dh_matrix). -export([ multiply/2 ]). multiply(M1, M2) -> NRows = length(M1), mmult(length(M2), NRows, NRows,[], M1, M2). sumprod(0, _, _, Sum, _, _) -> Sum; sumprod(I, C, R, Sum, M1, M2) -> NewSum = Sum + (lists:nth(I, lists:nth(R,M1)) * lists:nth(C, lists:nth(I,M2))), sumprod(I-1, C, R, NewSum, M1, M2). rowmult(_, 0, _, L, _, _) -> L; rowmult(I, C, R, L, M1, M2) -> SumProd = sumprod(I, C, R, 0, M1, M2), rowmult(I, C-1, R, [SumProd|L], M1, M2). mmult(_, _, 0, MM, _, _) -> MM; mmult(I, C, R, MM, M1, M2) -> NewRow = rowmult(I, C, R, [], M1, M2), mmult(I, C, R-1, [NewRow|MM], M1, M2).
null
https://raw.githubusercontent.com/hypernumbers/hypernumbers/281319f60c0ac60fb009ee6d1e4826f4f2d51c4e/lib/hypernumbers-1.0/src/dh_matrix.erl
erlang
------------------------------------------------------------------- @doc handle matrix functions @end Created : by ------------------------------------------------------------------- ------------------------------------------------------------------- LICENSE This program is free software: you can redistribute it and/or modify This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. along with this program. If not, see </>. -------------------------------------------------------------------
@author ( C ) 2008 - 2014 , Hypernumbers.com it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 You should have received a copy of the GNU Affero General Public License -module(dh_matrix). -export([ multiply/2 ]). multiply(M1, M2) -> NRows = length(M1), mmult(length(M2), NRows, NRows,[], M1, M2). sumprod(0, _, _, Sum, _, _) -> Sum; sumprod(I, C, R, Sum, M1, M2) -> NewSum = Sum + (lists:nth(I, lists:nth(R,M1)) * lists:nth(C, lists:nth(I,M2))), sumprod(I-1, C, R, NewSum, M1, M2). rowmult(_, 0, _, L, _, _) -> L; rowmult(I, C, R, L, M1, M2) -> SumProd = sumprod(I, C, R, 0, M1, M2), rowmult(I, C-1, R, [SumProd|L], M1, M2). mmult(_, _, 0, MM, _, _) -> MM; mmult(I, C, R, MM, M1, M2) -> NewRow = rowmult(I, C, R, [], M1, M2), mmult(I, C, R-1, [NewRow|MM], M1, M2).
72dd026a61ddc0170e9b09bbc709cdc13b18f50f10fc321aea8180743e14b7ba
cedlemo/OCaml-libmpdclient
mpd_lwt_playlist_info.ml
* Copyright 2017 , * This file is part of . * * OCaml - libmpdclient 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 * any later version . * * OCaml - libmpdclient 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 . If not , see < / > . * Copyright 2017 Cedric LE MOIGNE, * This file is part of OCaml-libmpdclient. * * OCaml-libmpdclient 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 * any later version. * * OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>. *) open Lwt.Infix compile with * ocamlfind ocamlc -o mpd_playlist_info -package str , unix -linkpkg -g * or * ocamlfind ocamlc -o mpd_playlist_info -package str , unix , libmpdclient -linkpkg -g mpd_playlist_info.ml * ocamlfind ocamlc -o mpd_playlist_info -package str,unix -linkpkg -g mpd_responses.ml mpd.ml mpd_playlist_info.ml * or * ocamlfind ocamlc -o mpd_playlist_info -package str,unix,libmpdclient -linkpkg -g mpd_playlist_info.ml *) let host = "127.0.0.1" let port = 6600 let lwt_print_line str = Lwt_io.write_line Lwt_io.stdout str let main_thread = let open Mpd in Connection_lwt.initialize host port >>= fun connection -> Client_lwt.initialize connection >>= fun client -> Queue_lwt.playlist client >>= function | Queue_lwt.PlaylistError message -> lwt_print_line ("err" ^ message) | Queue_lwt.Playlist playlist -> Lwt.return playlist >>= fun p -> let n = List.length p in lwt_print_line ("Number of songs : " ^ (string_of_int n)) >>= fun () -> Lwt_list.iter_s (fun song -> let id = string_of_int (Song.id song) in let title = Song.title song in let album = Song.album song in lwt_print_line (String.concat " " ["\t*"; id; title; album]) ) p >>= fun () -> Client_lwt.close client let () = Lwt_main.run main_thread
null
https://raw.githubusercontent.com/cedlemo/OCaml-libmpdclient/49922f4fa0c1471324c613301675ffc06ff3147c/samples/mpd_lwt_playlist_info.ml
ocaml
* Copyright 2017 , * This file is part of . * * OCaml - libmpdclient 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 * any later version . * * OCaml - libmpdclient 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 . If not , see < / > . * Copyright 2017 Cedric LE MOIGNE, * This file is part of OCaml-libmpdclient. * * OCaml-libmpdclient 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 * any later version. * * OCaml-libmpdclient 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 OCaml-libmpdclient. If not, see </>. *) open Lwt.Infix compile with * ocamlfind ocamlc -o mpd_playlist_info -package str , unix -linkpkg -g * or * ocamlfind ocamlc -o mpd_playlist_info -package str , unix , libmpdclient -linkpkg -g mpd_playlist_info.ml * ocamlfind ocamlc -o mpd_playlist_info -package str,unix -linkpkg -g mpd_responses.ml mpd.ml mpd_playlist_info.ml * or * ocamlfind ocamlc -o mpd_playlist_info -package str,unix,libmpdclient -linkpkg -g mpd_playlist_info.ml *) let host = "127.0.0.1" let port = 6600 let lwt_print_line str = Lwt_io.write_line Lwt_io.stdout str let main_thread = let open Mpd in Connection_lwt.initialize host port >>= fun connection -> Client_lwt.initialize connection >>= fun client -> Queue_lwt.playlist client >>= function | Queue_lwt.PlaylistError message -> lwt_print_line ("err" ^ message) | Queue_lwt.Playlist playlist -> Lwt.return playlist >>= fun p -> let n = List.length p in lwt_print_line ("Number of songs : " ^ (string_of_int n)) >>= fun () -> Lwt_list.iter_s (fun song -> let id = string_of_int (Song.id song) in let title = Song.title song in let album = Song.album song in lwt_print_line (String.concat " " ["\t*"; id; title; album]) ) p >>= fun () -> Client_lwt.close client let () = Lwt_main.run main_thread
fe6f6a6f01e227b64ba096403bc9ac54f9d01d9760099627ebb4a5254844565c
ghcjs/ghcjs-dom
RTCIceCandidateEvent.hs
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} module GHCJS.DOM.JSFFI.Generated.RTCIceCandidateEvent (js_getCandidate, getCandidate, RTCIceCandidateEvent(..), gTypeRTCIceCandidateEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"candidate\"]" js_getCandidate :: RTCIceCandidateEvent -> IO RTCIceCandidate | < -US/docs/Web/API/RTCIceCandidateEvent.candidate Mozilla RTCIceCandidateEvent.candidate documentation > getCandidate :: (MonadIO m) => RTCIceCandidateEvent -> m RTCIceCandidate getCandidate self = liftIO (js_getCandidate self)
null
https://raw.githubusercontent.com/ghcjs/ghcjs-dom/749963557d878d866be2d0184079836f367dd0ea/ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/RTCIceCandidateEvent.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # LANGUAGE ForeignFunctionInterface # # LANGUAGE JavaScriptFFI # module GHCJS.DOM.JSFFI.Generated.RTCIceCandidateEvent (js_getCandidate, getCandidate, RTCIceCandidateEvent(..), gTypeRTCIceCandidateEvent) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import qualified Prelude (error) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull, jsUndefined) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad (void) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import Data.Maybe (fromJust) import Data.Traversable (mapM) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"candidate\"]" js_getCandidate :: RTCIceCandidateEvent -> IO RTCIceCandidate | < -US/docs/Web/API/RTCIceCandidateEvent.candidate Mozilla RTCIceCandidateEvent.candidate documentation > getCandidate :: (MonadIO m) => RTCIceCandidateEvent -> m RTCIceCandidate getCandidate self = liftIO (js_getCandidate self)
54894c1667dfbed04acba441539d6e0597625debd907cfa6ad491098a65911ec
screenshotbot/screenshotbot-oss
test-login.lisp
;;;; Copyright 2018-Present Modern Interpreters Inc. ;;;; This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (defpackage :screenshotbot/login/test-login (:use #:cl #:fiveam) (:import-from #:screenshotbot/login/common #:signin-get) (:import-from #:util/testing #:screenshot-static-page #:with-fake-request) (:import-from #:util/form-errors #:with-form-errors) (:import-from #:screenshotbot/testing #:with-installation) (:local-nicknames (#:a #:alexandria))) (in-package :screenshotbot/login/test-login) (util/fiveam:def-suite) (test login-screenshot-test (with-installation () (with-fake-request () (auth:with-sessions () (screenshot-static-page :screenshotbot "login" (markup:write-html (signin-get))))))) (test login-error-screen (with-installation () (with-fake-request () (auth:with-sessions () (screenshot-static-page :screenshotbot "login-error-screen" (markup:write-html (with-form-errors (:errors `((:password . "Incorrect password")) :password "foo" :email "" :was-validated t) (signin-get))))))))
null
https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/e2b32b8b536796122b7111c456728a5101a1ed08/src/screenshotbot/login/test-login.lisp
lisp
Copyright 2018-Present Modern Interpreters Inc.
This Source Code Form is subject to the terms of the Mozilla Public License , v. 2.0 . If a copy of the MPL was not distributed with this file , You can obtain one at /. (defpackage :screenshotbot/login/test-login (:use #:cl #:fiveam) (:import-from #:screenshotbot/login/common #:signin-get) (:import-from #:util/testing #:screenshot-static-page #:with-fake-request) (:import-from #:util/form-errors #:with-form-errors) (:import-from #:screenshotbot/testing #:with-installation) (:local-nicknames (#:a #:alexandria))) (in-package :screenshotbot/login/test-login) (util/fiveam:def-suite) (test login-screenshot-test (with-installation () (with-fake-request () (auth:with-sessions () (screenshot-static-page :screenshotbot "login" (markup:write-html (signin-get))))))) (test login-error-screen (with-installation () (with-fake-request () (auth:with-sessions () (screenshot-static-page :screenshotbot "login-error-screen" (markup:write-html (with-form-errors (:errors `((:password . "Incorrect password")) :password "foo" :email "" :was-validated t) (signin-get))))))))
6cecb2020e41da02dcd9879b9035a2b90bb45c9a3d64af597c23ae62272c6030
yuriy-chumak/ol
integers.scm
#!/usr/bin/env ol (import (otus fasl) (otus ffi)) (import (lib kore)) (define (page req) (http_populate_get req) (let*((out "analyze result:\n") ;; byte (byte (box 0)) (out (if (eq? (http_argument_get_byte req "id" byte) 1) (string-append out "byte: " (number->string (unbox byte)) "\n") out)) ;; int16/uint16 (int (box 0)) (out (if (eq? (http_argument_get_int16 req "id" int) 1) (string-append out "int16: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint16 req "id" int) 1) (string-append out "uint16: " (number->string (unbox int)) "\n") out)) ;; int32/uint32 (int (box 0)) (out (if (eq? (http_argument_get_int32 req "id" int) 1) (string-append out "int32: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint32 req "id" int) 1) (string-append out "uint32: " (number->string (unbox int)) "\n") out)) int64 / uint64 (int (box 0)) ; we should allocate large number (out (if (eq? (http_argument_get_int64 req "id" int) 1) (string-append out "int64: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint64 req "id" int) 1) (string-append out "uint64: " (number->string (unbox int)) "\n") out)) ;; float/double (int (box #i0)) ; we should allocate large number (out (if (eq? (http_argument_get_float req "id" int) 1) (string-append out "float: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_double req "id" int) 1) (string-append out "double: " (number->string (unbox int)) "\n") out)) ;; end with newline (out (string-append out "\n"))) (print "out: " out) 200 OK (define response (string->utf8 out)) (http_response req 200 response (size response))) KORE_RESULT_OK) (fasl-save (make-kore-page page) "tmp.bin")
null
https://raw.githubusercontent.com/yuriy-chumak/ol/73230a893bee928c0111ad2416fd527e7d6749ee/samples/kore/integers/integers.scm
scheme
byte int16/uint16 int32/uint32 we should allocate large number float/double we should allocate large number end with newline
#!/usr/bin/env ol (import (otus fasl) (otus ffi)) (import (lib kore)) (define (page req) (http_populate_get req) (let*((out "analyze result:\n") (byte (box 0)) (out (if (eq? (http_argument_get_byte req "id" byte) 1) (string-append out "byte: " (number->string (unbox byte)) "\n") out)) (int (box 0)) (out (if (eq? (http_argument_get_int16 req "id" int) 1) (string-append out "int16: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint16 req "id" int) 1) (string-append out "uint16: " (number->string (unbox int)) "\n") out)) (int (box 0)) (out (if (eq? (http_argument_get_int32 req "id" int) 1) (string-append out "int32: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint32 req "id" int) 1) (string-append out "uint32: " (number->string (unbox int)) "\n") out)) int64 / uint64 (out (if (eq? (http_argument_get_int64 req "id" int) 1) (string-append out "int64: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_uint64 req "id" int) 1) (string-append out "uint64: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_float req "id" int) 1) (string-append out "float: " (number->string (unbox int)) "\n") out)) (out (if (eq? (http_argument_get_double req "id" int) 1) (string-append out "double: " (number->string (unbox int)) "\n") out)) (out (string-append out "\n"))) (print "out: " out) 200 OK (define response (string->utf8 out)) (http_response req 200 response (size response))) KORE_RESULT_OK) (fasl-save (make-kore-page page) "tmp.bin")
495d3d505ce7445c932b65db69a3cf1a48eb6923a3b612ed51571a62b71fc7cb
jumarko/clojure-experiments
intro_to_lists.clj
(ns four-clojure.intro-to-lists) (= (list :a :b :c) '(:a :b :c))
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/four_clojure/intro_to_lists.clj
clojure
(ns four-clojure.intro-to-lists) (= (list :a :b :c) '(:a :b :c))
f09b113c6e13327bdd147885c6e001fe7a4527f65f36d5288eed45c7e2b5a4f9
uw-unsat/serval-sosp19
keystone.rkt
#lang rosette (require (except-in rackunit fail) rackunit/text-ui rosette/lib/roseunit serval/llvm serval/lib/core serval/lib/unittest (prefix-in keystone: "generated/monitors/keystone.map.rkt") (prefix-in keystone: "generated/monitors/keystone.globals.rkt")) (require "generated/monitors/keystone.ll.rkt") (define (make-arg type) (define-symbolic* symbolic-arg type) symbolic-arg) (define (make-bv32) (make-arg (bitvector 32))) (define (rep-invariant mregions) #t) (define (verify-llvm-assert expr ri) (define sol (verify (assert (=> ri expr)))) (when (sat? sol) (define-values (loc msg) (assertion-info sol)) (displayln (cons loc msg)))) (define (check-llvm-ub func [args null]) (define machine (make-machine keystone:symbols keystone:globals)) (define s (machine-mregions machine)) (parameterize ([current-machine machine]) (define ri (rep-invariant s)) (define asserted (with-asserts-only (begin (assert ri) (apply func args)))) (for-each (lambda (e) (verify-llvm-assert e ri)) asserted))) (define keystone-tests (test-suite+ "keystone tests" (test-case+ "destroy_enclave" (check-llvm-ub @destroy_enclave (list (make-bv32)))) )) (module+ test (time (run-tests keystone-tests)))
null
https://raw.githubusercontent.com/uw-unsat/serval-sosp19/175c42660fad84b44e4c9f6f723fd3c9450d65d4/monitors/keystone/verif/keystone.rkt
racket
#lang rosette (require (except-in rackunit fail) rackunit/text-ui rosette/lib/roseunit serval/llvm serval/lib/core serval/lib/unittest (prefix-in keystone: "generated/monitors/keystone.map.rkt") (prefix-in keystone: "generated/monitors/keystone.globals.rkt")) (require "generated/monitors/keystone.ll.rkt") (define (make-arg type) (define-symbolic* symbolic-arg type) symbolic-arg) (define (make-bv32) (make-arg (bitvector 32))) (define (rep-invariant mregions) #t) (define (verify-llvm-assert expr ri) (define sol (verify (assert (=> ri expr)))) (when (sat? sol) (define-values (loc msg) (assertion-info sol)) (displayln (cons loc msg)))) (define (check-llvm-ub func [args null]) (define machine (make-machine keystone:symbols keystone:globals)) (define s (machine-mregions machine)) (parameterize ([current-machine machine]) (define ri (rep-invariant s)) (define asserted (with-asserts-only (begin (assert ri) (apply func args)))) (for-each (lambda (e) (verify-llvm-assert e ri)) asserted))) (define keystone-tests (test-suite+ "keystone tests" (test-case+ "destroy_enclave" (check-llvm-ub @destroy_enclave (list (make-bv32)))) )) (module+ test (time (run-tests keystone-tests)))
78789fbd42d3c69f65eb46fe4a91b3d6cac096b5d53abd409a100c2a4a38e75b
yurug/ocaml-crontab
check.ml
let () = Io.check ()
null
https://raw.githubusercontent.com/yurug/ocaml-crontab/59b0d84bfe3d7f2a9ee1e00c6f6733dba2765c55/tests/check.ml
ocaml
let () = Io.check ()
881bd5699917c9a15b23c2af73121e90e300594dbcf4fe24e3562e40a9783dd0
Frama-C/Frama-C-snapshot
wpReport.ml
(**************************************************************************) (* *) This file is part of WP plug - in of Frama - C. (* *) Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies (* alternatives) *) (* *) (* you can redistribute it and/or modify it under the terms of the GNU *) Lesser General Public License as published by the Free Software Foundation , version 2.1 . (* *) (* It is distributed in the hope that it will be useful, *) (* but WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *) (* GNU Lesser General Public License for more details. *) (* *) See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . (* *) (**************************************************************************) (* -------------------------------------------------------------------------- *) (* --- Fast Report for WP --- *) (* -------------------------------------------------------------------------- *) let ladder = [| 1.0 ; 2.0 ; 3.0 ; 5.0 ; 10.0 ; 15.0 ; 20.0 ; 30.0 ; 40.0 ; 1 ' , 1'30 , 2 ' , 3 ' 5 ' , 10 ' , 15 ' , 30 ' 1h (* -------------------------------------------------------------------------- *) (* --- Step Ranges --- *) (* -------------------------------------------------------------------------- *) let n0 = 16 let d0 = 4 Number of steps is divided into an infinite number of successive bundles . Each bundle number , ... is divided into n0 small intervals of size 2^k * d0 . The rank r - th of a number n is the r - th interval in some bundle k. A number of steps is stabilized to its original rank r is it still belongs to the intervals that would be immediately before or after the original interval ( in the _ same _ bundle ) . Number of steps is divided into an infinite number of successive bundles. Each bundle number k=0,... is divided into n0 small intervals of size 2^k * d0. The rank r-th of a number n is the r-th interval in some bundle k. A number of steps is stabilized to its original rank r is it still belongs to the intervals that would be immediately before or after the original interval (in the _same_ bundle). *) let a0 = n0 * d0 first index of bundle k let dk k = d0 lsl k (* size of small intervals in bundle k *) Compute the range of values for rank If ~limit : false , returns all the values n that have the rank k. If ~limit : true , returns all the values n that are stabilized at rank k. Compute the range of values for rank k. If ~limit:false, returns all the values n that have the rank k. If ~limit:true, returns all the values n that are stabilized at rank k. *) let range ?(limit=true) r = let k = r / n0 in let i = r mod n0 in let a = ak k in let d = dk k in let i1 = if limit then i-1 else i in let i2 = if limit then i+2 else i+1 in max 1 (a + i1*d) , a + i2*d (* Compute the rank of number n *) let rank n = (* invariant a == ak k and a <= n *) let rec aux a k n = let b = ak (succ k) - 1 in if n <= b then let d = dk k in let i = (n-a) / d in n0 * k + i else aux b (succ k) n in let a = ak 0 in if n < a then (-1) else aux a 0 n (* -------------------------------------------------------------------------- *) (* --- Statistics --- *) (* -------------------------------------------------------------------------- *) type res = VALID | UNSUCCESS | INCONCLUSIVE | NORESULT let result (r:VCS.result) = match r.VCS.verdict with | VCS.NoResult | VCS.Checked | VCS.Computing _ -> NORESULT | VCS.Failed -> INCONCLUSIVE | VCS.Invalid | VCS.Unknown | VCS.Timeout | VCS.Stepout -> UNSUCCESS | VCS.Valid -> VALID let best_result a b = match a,b with | NORESULT,c | c,NORESULT -> c | VALID,_ | _,VALID -> VALID | UNSUCCESS,_ | _,UNSUCCESS -> UNSUCCESS | INCONCLUSIVE,INCONCLUSIVE -> INCONCLUSIVE type stats = { mutable valid : int ; (* Result is Valid *) verdict is , Unknown , Timeout , or Stepout , Invalid mutable inconclusive : int ; (* verdict is Failed *) mutable total : int ; (* valid + unsuccess + inconclusive *) mutable steps : int ; mutable time : float ; mutable rank : int ; } let stats () = { total=0 ; valid=0 ; unsuccess=0 ; inconclusive=0 ; steps=0 ; rank=(-1) ; time=0.0 ; } let add_stat (r:res) (st:int) (tm:float) (s:stats) = begin s.total <- succ s.total ; match r with | VALID -> if tm > s.time then s.time <- tm ; if st > s.steps then s.steps <- st ; s.valid <- succ s.valid | NORESULT | UNSUCCESS -> s.unsuccess <- succ s.unsuccess | INCONCLUSIVE -> s.inconclusive <- succ s.inconclusive end let add_qedstat (ts:float) (s:stats) = if ts > s.time then s.time <- ts let get_field js fd = try Json.field fd js with Not_found | Invalid_argument _ -> `Null let json_assoc fields = let fields = List.filter (fun (_,d) -> d<>`Null) fields in if fields = [] then `Null else `Assoc fields let json_of_stats s = let add fd v w = if v > 0 then (fd , `Int v)::w else w in json_assoc begin add "total" s.total @@ add "valid" s.valid @@ add "failed" s.inconclusive @@ add "unknown" s.unsuccess @@ (if s.rank >= 0 then [ "rank" , `Int s.rank ] else []) end let rankify_stats s js = let n = s.steps in if n > 0 then try let r0 = Json.field "rank" js |> Json.int in let a,b = range r0 in if a <= n && n <= b then s.rank <- r0 else s.rank <- rank n with Not_found | Invalid_argument _ -> s.rank <- rank n else s.rank <- (-1) (* -------------------------------------------------------------------------- *) (* --- Stats by Prover --- *) (* -------------------------------------------------------------------------- *) type pstats = { main : stats ; prover : (VCS.prover,stats) Hashtbl.t ; } let pstats () = { main = stats () ; prover = Hashtbl.create 7 ; } let json_of_pstats p = json_assoc begin Hashtbl.fold (fun p s w -> (VCS.name_of_prover p , json_of_stats s) :: w) p.prover [ "wp:main" , json_of_stats p.main ] end let rankify_pstats p js = begin rankify_stats p.main (get_field js "wp:main") ; Hashtbl.iter (fun p s -> rankify_stats s (get_field js @@ VCS.name_of_prover p) ; ) p.prover ; end let get_prover fs prover = try Hashtbl.find fs.prover prover with Not_found -> let s = stats () in Hashtbl.add fs.prover prover s ; s let add_results (plist:pstats list) (wpo:Wpo.t) = let ok = ref NORESULT in let tm = ref 0.0 in let sm = ref 0 in List.iter (fun (p,r) -> let re = result r in let st = Wpo.get_steps r in let tc = Wpo.get_time r in let ts = r.VCS.solver_time in if re <> NORESULT then begin List.iter (fun fs -> add_stat re st tc (get_prover fs p)) plist ; if p <> VCS.Qed && ts > 0.0 then List.iter (fun fs -> add_qedstat ts (get_prover fs VCS.Qed)) plist ; end ; ok := best_result !ok re ; if tc > !tm then tm := tc ; if st > !sm then sm := st ; ) (Wpo.get_results wpo) ; List.iter (fun fs -> add_stat !ok !sm !tm fs.main) plist (* -------------------------------------------------------------------------- *) (* --- Stats by Section --- *) (* -------------------------------------------------------------------------- *) type coverage = { mutable covered : Property.Set.t ; mutable proved : Property.Set.t ; } let coverage () = { covered = Property.Set.empty ; proved = Property.Set.empty } let add_cover (s:coverage) ok p = begin s.covered <- Property.Set.add p s.covered ; if ok then s.proved <- Property.Set.add p s.proved ; end type dstats = { dstats : pstats ; dcoverage : coverage ; mutable dmap : pstats Property.Map.t ; } let dstats () = { dstats = pstats () ; dcoverage = coverage () ; dmap = Property.Map.empty ; } let js_prop = Property.Names.get_prop_name_id let json_of_dstats d = json_assoc begin Property.Map.fold (fun prop ps w -> (js_prop prop , json_of_pstats ps) :: w) d.dmap [ "wp:section" , json_of_pstats d.dstats ] end let rankify_dstats d js = begin rankify_pstats d.dstats (get_field js "wp:section") ; Property.Map.iter (fun prop ps -> rankify_pstats ps (get_field js @@ js_prop prop) ) d.dmap ; end (* -------------------------------------------------------------------------- *) (* --- Stats WP --- *) (* -------------------------------------------------------------------------- *) type entry = | Axiom of string | Fun of Kernel_function.t let decode_chapter= function | Axiom _ -> "axiomatic" | Fun _ -> "function" module Smap = FCMap.Make (struct type t = entry let compare s1 s2 = match s1 , s2 with | Axiom a , Axiom b -> String.compare a b | Axiom _ , Fun _ -> (-1) | Fun _ , Axiom _ -> 1 | Fun f , Fun g -> Kernel_function.compare f g end) type fcstat = { global : pstats ; gcoverage : coverage ; mutable dsmap : dstats Smap.t ; } let json_of_fcstat (fc : fcstat) = begin let functions = ref [] in let axiomatics = ref [] in Smap.iter (fun entry ds -> let acc , key = match entry with | Axiom a -> axiomatics , a | Fun kf -> functions , Kernel_function.get_name kf in acc := ( key , json_of_dstats ds ) :: !acc ; ) fc.dsmap ; json_assoc [ "wp:global" , json_of_pstats fc.global ; "wp:axiomatics" , json_assoc (List.rev (!axiomatics)) ; "wp:functions" , json_assoc (List.rev (!functions)) ; ] ; end let rankify_fcstat fc js = begin rankify_pstats fc.global (get_field js "wp:global") ; let jfunctions = get_field js "wp:functions" in let jaxiomatics = get_field js "wp:axiomatics" in Smap.iter (fun entry ds -> let js = match entry with | Axiom a -> get_field jaxiomatics a | Fun kf -> get_field jfunctions (Kernel_function.get_name kf) in rankify_dstats ds js ) fc.dsmap ; end (* -------------------------------------------------------------------------- *) --- Computing Statistics --- (* -------------------------------------------------------------------------- *) let get_section gs s = try Smap.find s gs.dsmap with Not_found -> let ds = dstats () in gs.dsmap <- Smap.add s ds gs.dsmap ; ds let get_property ds p = try Property.Map.find p ds.dmap with Not_found -> let ps = pstats () in ds.dmap <- Property.Map.add p ps ds.dmap ; ps let add_goal (gs:fcstat) wpo = begin let section = match Wpo.get_index wpo with | Wpo.Axiomatic None -> Axiom "" | Wpo.Axiomatic (Some a) -> Axiom a | Wpo.Function(kf,_) -> Fun kf in let ds : dstats = get_section gs section in let (ok,prop) = Wpo.get_proof wpo in let ps : pstats = get_property ds prop in add_results [gs.global ; ds.dstats ; ps] wpo ; add_cover gs.gcoverage ok prop ; add_cover ds.dcoverage ok prop ; end let fcstat () = let fcstat : fcstat = { global = pstats () ; gcoverage = coverage () ; dsmap = Smap.empty ; } in Wpo.iter ~on_goal:(add_goal fcstat) () ; fcstat (* -------------------------------------------------------------------------- *) (* --- Iteration on Stats --- *) (* -------------------------------------------------------------------------- *) type istat = { fcstat: fcstat; chapters : (string * (entry * dstats) list) list; } (** start chapter stats *) let start_stat4chap fcstat = let chapter = ref "" in let decode_chapter e = let code = decode_chapter e in let is_new_code = (code <> !chapter) in if is_new_code then chapter := code; is_new_code in let close_chapter (na,ca,ga) = if ca = [] then !chapter,[],ga else !chapter,[],((na,List.rev ca)::ga) in let (_,_,ga) = let acc = Smap.fold (fun entry ds acc -> let is_new_chapter = decode_chapter entry in let (na,ca,ga) = if is_new_chapter then close_chapter acc else acc in na,((entry,ds)::ca),ga ) fcstat.dsmap ("",[],[]) in if !chapter <> "" then close_chapter acc else acc in if ga = [] then None else Some { fcstat = fcstat; chapters = List.rev ga; } (** next chapters stats *) let next_stat4chap istat = match istat.chapters with | ([] | _::[]) -> None | _::l -> Some { istat with chapters = l } type cistat = { cfcstat: fcstat; chapter : string; sections : (entry * dstats) list; } (** start section stats of a chapter*) let start_stat4sect istat = match istat.chapters with | [] -> None | (c,s)::_ -> Some { cfcstat = istat.fcstat; chapter = c; sections = s; } (** next section stats *) let next_stat4sect cistat = match cistat.sections with | ([] | _::[]) -> None | _::l -> Some { cistat with sections = l } type sistat = { sfcstat: fcstat; schapter : string ; section : (entry * dstats); properties : (Property.t * pstats) list; } (** start property stats of a section *) let start_stat4prop cistat = match cistat.sections with | [] -> None | ((_,ds) as s)::_ -> Some { sfcstat = cistat.cfcstat; schapter = cistat.chapter; section = s; properties = List.rev (Property.Map.fold (fun p ps acc -> (p,ps)::acc) ds.dmap []); } (** next property stats *) let next_stat4prop sistat = match sistat.properties with | ([] | _::[]) -> None | _::l -> Some { sfcstat = sistat.sfcstat; schapter = sistat.schapter; section = sistat.section; properties = l; } (** generic iterator *) let iter_stat ?first ?sep ?last ~from start next= if first<>None || sep<>None || last <> None then let items = ref (start from) in if !items <> None then begin let apply v = function | None -> () | Some app -> app v in let next app = let item = (Extlib.the !items) in apply item app; items := next item in next first; if sep<>None || last <> None then begin while !items <> None do next sep; done; apply () last; end end (* -------------------------------------------------------------------------- *) (* --- Rendering Numbers --- *) (* -------------------------------------------------------------------------- *) type config = { mutable status_passed : string ; mutable status_failed : string ; mutable status_inconclusive : string ; mutable status_untried : string ; mutable global_prefix : string ; mutable lemma_prefix : string ; mutable axiomatic_prefix : string ; mutable function_prefix : string ; mutable property_prefix : string ; mutable global_section: string ; mutable axiomatic_section: string ; mutable function_section : string ; mutable console : bool ; mutable zero : string ; } let pp_zero ~config fmt = if config.console then Format.fprintf fmt "%4s" config.zero else Format.pp_print_string fmt config.zero let percent ~config fmt number total = if total <= 0 || number < 0 then pp_zero ~config fmt else if number >= total then Format.pp_print_string fmt (if config.console then " 100" else "100") else let ratio = float_of_int number /. float_of_int total in Format.fprintf fmt "%4.1f" (100.0 *. ratio) let number ~config fmt k = if k = 0 then pp_zero ~config fmt else if config.console then Format.fprintf fmt "%4d" k else Format.pp_print_int fmt k let properties ~config fmt (s:coverage) = function | "" -> percent config fmt (Property.Set.cardinal s.proved) (Property.Set.cardinal s.covered) | "total" -> number config fmt (Property.Set.cardinal s.covered) | "valid" -> number config fmt (Property.Set.cardinal s.proved) | "failed" -> number config fmt (Property.Set.cardinal s.covered - Property.Set.cardinal s.proved) | _ -> raise Exit let is_stat_name = function | "success" | "total" | "valid" | "" | "failed" | "status" | "inconclusive" | "unsuccess" | "time" | "perf" | "steps" | "range" -> true | _ -> false let stat ~config fmt s = function | "success" -> percent config fmt s.valid s.total | "total" -> number config fmt s.total | "valid" | "" -> number config fmt s.valid | "failed" -> number config fmt (s.unsuccess + s.inconclusive) | "status" -> let msg = if s.inconclusive > 0 then config.status_inconclusive else if s.unsuccess > 0 then config.status_failed else if s.valid >= s.total then config.status_passed else config.status_untried in Format.pp_print_string fmt msg | "inconclusive" -> number config fmt s.inconclusive | "unsuccess" -> number config fmt s.unsuccess | "time" -> if s.time > 0.0 then Rformat.pp_time_range ladder fmt s.time | "perf" -> if s.time > Rformat.epsilon then Format.fprintf fmt "(%a)" Rformat.pp_time s.time | "steps" -> if s.steps > 0 then Format.fprintf fmt "(%d)" s.steps | "range" -> if s.rank >= 0 then let a,b = range s.rank in Format.fprintf fmt "(%d..%d)" a b | _ -> raise Exit let pstats ~config fmt s cmd arg = match cmd with | "wp" | "qed" -> stat ~config fmt (get_prover s VCS.Qed) arg | cmd when is_stat_name cmd -> stat ~config fmt s.main cmd | prover -> match (VCS.prover_of_name prover) with | None -> Wp_parameters.error ~once:true "Unknown prover name %s" prover | Some prover -> stat ~config fmt (get_prover s prover) arg let pcstats ~config fmt (s,c) cmd arg = match cmd with | "prop" -> properties ~config fmt c arg | _ -> pstats ~config fmt s cmd arg (* -------------------------------------------------------------------------- *) (* --- Rformat Environments --- *) (* -------------------------------------------------------------------------- *) let env_toplevel ~config gstat fmt cmd arg = try pcstats config fmt (gstat.global, gstat.gcoverage) cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown toplevel-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown toplevel-format '%%%s:%s'" cmd arg let env_chapter chapter_name fmt cmd arg = try match cmd with | "chapter" | "name" -> Format.pp_print_string fmt chapter_name | _ -> raise Exit with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown chapter-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown chapter-format '%%%s:%s'" cmd arg let env_section ~config ~name sstat fmt cmd arg = try let entry,ds = match sstat.sections with | section_item::_others -> section_item | _ -> raise Exit in match cmd with | "chapter" -> let chapter = match entry with | Axiom _ -> config.axiomatic_section | Fun _ -> config.function_section in Format.pp_print_string fmt chapter | "name" | "section" | "global" | "axiomatic" | "function" -> if cmd <> "name" && cmd <> "section" && name <> cmd then Wp_parameters.error "Invalid section-format '%%%s' inside a section %s" cmd name; let prefix,name = match entry with | Axiom "" -> config.lemma_prefix,"" | Axiom a -> config.axiomatic_prefix,a | Fun kf -> config.function_prefix, ( Kernel_function.get_name kf) in Format.fprintf fmt "%s%s" prefix name | _ -> pcstats config fmt (ds.dstats, ds.dcoverage) cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown section-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown section-format '%%%s:%s'" cmd arg let env_property ~config ~name pstat fmt cmd arg = try let entry = fst pstat.section in let p,stat = match pstat.properties with | property_item::_others -> property_item | _ -> raise Exit in match cmd with | "chapter" -> let chapter = match entry with | Axiom _ -> config.axiomatic_section | Fun _ -> config.function_section in Format.pp_print_string fmt chapter | "section" | "global" | "axiomatic" | "function" -> if cmd <> "section" && name <> cmd then Wp_parameters.error "Invalid property-format '%%%s' inside a section %s" cmd name; let prefix,name = match entry with | Axiom "" -> config.lemma_prefix,"" | Axiom a -> config.axiomatic_prefix,a | Fun kf -> config.function_prefix, ( Kernel_function.get_name kf) in Format.fprintf fmt "%s%s" prefix name | "name" -> Format.fprintf fmt "%s%s" config.property_prefix (Property.Names.get_prop_name_id p) | "property" -> Description.pp_local fmt p | _ -> pstats config fmt stat cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown property-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown property-format '%%%s:%s'" cmd arg (* -------------------------------------------------------------------------- *) (* --- Statistics Printing --- *) (* -------------------------------------------------------------------------- *) let print_property (pstat:sistat) ~config ~name ~prop fmt = Rformat.pretty (env_property ~config ~name pstat) fmt prop let print_section (sstat:cistat) ~config ~name ~sect ~prop fmt = if sect <> "" then Rformat.pretty (env_section ~config ~name sstat) fmt sect ; if prop <> "" then let print_property pstat = print_property pstat ~config ~name ~prop fmt in iter_stat ~first:print_property ~sep:print_property ~from:sstat start_stat4prop next_stat4prop let print_chapter (cstat:istat) ~config ~chap ~sect ~glob ~axio ~func ~prop fmt = let chapter_item = match cstat.chapters with | chapter_item::_others -> chapter_item | _ -> raise Exit in let section_name = fst chapter_item in let section,chapter_name = match section_name with | "global" -> glob,config.global_section | "axiomatic" -> axio,config.axiomatic_section | "function" -> func,config.function_section | _ -> sect,"" in let section,section_name = if section <> "" then section,section_name else sect,"" in if chap <> "" then Rformat.pretty (env_chapter chapter_name) fmt chap ; if section <> "" || prop <> "" then let print_section sstat = print_section sstat ~config ~name:section_name ~sect:section ~prop fmt in iter_stat ~first:print_section ~sep:print_section ~from:cstat start_stat4sect next_stat4sect let print gstat ~config ~head ~tail ~chap ~sect ~glob ~axio ~func ~prop fmt = begin if head <> "" then Rformat.pretty (env_toplevel ~config gstat) fmt head ; if chap <> "" || sect <> "" || glob <> "" || axio <> "" || func <> "" || prop <> "" then let print_chapter cstat = print_chapter cstat ~config ~chap ~sect ~glob ~axio ~func ~prop fmt in iter_stat ~first:print_chapter ~sep:print_chapter ~from:gstat start_stat4chap next_stat4chap ; if tail <> "" then Rformat.pretty (env_toplevel ~config gstat) fmt tail ; end (* -------------------------------------------------------------------------- *) (* --- Report Printing --- *) (* -------------------------------------------------------------------------- *) type section = END | HEAD | TAIL | CHAPTER | SECTION | GLOB_SECTION | AXIO_SECTION | FUNC_SECTION | PROPERTY let export gstat specfile = let config = { console = false ; zero = "-" ; status_passed = " Ok " ; status_failed = "Failed" ; status_inconclusive = "*Bug**" ; status_untried = " " ; lemma_prefix = "Lemma " ; global_prefix = "(Global) " ; axiomatic_prefix = "Axiomatic " ; function_prefix = "" ; property_prefix = "" ; global_section = "Globals" ; axiomatic_section = "Axiomatics" ; function_section = "Functions" ; } in let head = Buffer.create 64 in let tail = Buffer.create 64 in let chap = Buffer.create 64 in (* chapter *) let sect = Buffer.create 64 in (* default section *) let glob = Buffer.create 64 in (* section *) let axio = Buffer.create 64 in (* section *) let func = Buffer.create 64 in (* section *) let sect_prop = Buffer.create 64 in (* default sub-section *) let file = ref None in let section = ref HEAD in begin let cin = open_in specfile in try while true do let line = input_line cin in match Rformat.command line with | Rformat.ARG("AXIOMATIC_PREFIX",f) -> config.axiomatic_prefix <- f | Rformat.ARG("FUNCTION_PREFIX",f) -> config.function_prefix <- f | Rformat.ARG("PROPERTY_PREFIX",f) -> config.property_prefix <- f | Rformat.ARG("LEMMA_PREFIX",f) -> config.lemma_prefix <- f | Rformat.ARG("GLOBAL_SECTION",f) -> config.global_section <- f | Rformat.ARG("AXIOMATIC_SECTION",f) -> config.axiomatic_section <- f | Rformat.ARG("FUNCTION_SECTION",f) -> config.function_section <- f | Rformat.ARG("PASSED",s) -> config.status_passed <- s | Rformat.ARG("FAILED",s) -> config.status_failed <- s | Rformat.ARG("INCONCLUSIVE",s) -> config.status_inconclusive <- s | Rformat.ARG("UNTRIED",s) -> config.status_untried <- s | Rformat.ARG("ZERO",z) -> config.zero <- z | Rformat.ARG("FILE",f) -> file := Some f | Rformat.ARG("SUFFIX",e) -> let basename = Wp_parameters.ReportName.get () in let filename = basename ^ e in file := Some filename | Rformat.CMD "CONSOLE" -> config.console <- true | Rformat.CMD "END" -> section := END | Rformat.CMD "HEAD" -> section := HEAD | Rformat.CMD "TAIL" -> section := TAIL | Rformat.CMD "CHAPTER" -> section := CHAPTER | Rformat.CMD "SECTION" -> section := SECTION | Rformat.CMD "GLOBAL" -> section := GLOB_SECTION | Rformat.CMD "AXIOMATIC" -> section := AXIO_SECTION | Rformat.CMD "FUNCTION" -> section := FUNC_SECTION | Rformat.CMD "PROPERTY" -> section := PROPERTY | Rformat.CMD a | Rformat.ARG(a,_) -> Wp_parameters.error "Report '%s': unknown command '%s'" specfile a | Rformat.TEXT -> if !section <> END then let text = match !section with | HEAD -> head | CHAPTER -> chap | SECTION -> sect | GLOB_SECTION -> glob | AXIO_SECTION -> axio | FUNC_SECTION -> func | PROPERTY -> sect_prop | TAIL|END -> tail in Buffer.add_string text line ; Buffer.add_char text '\n' ; done with | End_of_file -> close_in cin | err -> close_in cin ; raise err end ; match !file with | None -> Log.print_on_output (print gstat ~config ~head:(Buffer.contents head) ~tail:(Buffer.contents tail) ~chap:(Buffer.contents chap) ~sect:(Buffer.contents sect) ~glob:(Buffer.contents glob) ~axio:(Buffer.contents axio) ~func:(Buffer.contents func) ~prop:(Buffer.contents sect_prop)) | Some report -> Wp_parameters.feedback "Report '%s'" report ; let cout = open_out report in let fout = Format.formatter_of_out_channel cout in try print gstat ~config ~head:(Buffer.contents head) ~tail:(Buffer.contents tail) ~chap:(Buffer.contents chap) ~sect:(Buffer.contents sect) ~glob:(Buffer.contents glob) ~axio:(Buffer.contents axio) ~func:(Buffer.contents func) ~prop:(Buffer.contents sect_prop) fout ; Format.pp_print_flush fout () ; close_out cout ; with err -> Format.pp_print_flush fout () ; close_out cout ; raise err (* -------------------------------------------------------------------------- *) let export_json gstat ?jinput ~joutput () = begin let js = try let jfile = match jinput with | None -> Wp_parameters.feedback "Report '%s'" joutput ; joutput | Some jinput -> Wp_parameters.feedback "Report in: '%s'" jinput ; Wp_parameters.feedback "Report out: '%s'" joutput ; jinput in if Sys.file_exists jfile then Json.load_file jfile else `Null with Json.Error(file,line,msg) -> let source = Log.source ~file ~line in Wp_parameters.error ~source "Incorrect json file: %s" msg ; `Null in rankify_fcstat gstat js ; Json.save_file joutput (json_of_fcstat gstat) ; end (* -------------------------------------------------------------------------- *)
null
https://raw.githubusercontent.com/Frama-C/Frama-C-snapshot/639a3647736bf8ac127d00ebe4c4c259f75f9b87/src/plugins/wp/wpReport.ml
ocaml
************************************************************************ alternatives) you can redistribute it and/or modify it under the terms of the GNU It is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. ************************************************************************ -------------------------------------------------------------------------- --- Fast Report for WP --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Step Ranges --- -------------------------------------------------------------------------- size of small intervals in bundle k Compute the rank of number n invariant a == ak k and a <= n -------------------------------------------------------------------------- --- Statistics --- -------------------------------------------------------------------------- Result is Valid verdict is Failed valid + unsuccess + inconclusive -------------------------------------------------------------------------- --- Stats by Prover --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Stats by Section --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Stats WP --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Iteration on Stats --- -------------------------------------------------------------------------- * start chapter stats * next chapters stats * start section stats of a chapter * next section stats * start property stats of a section * next property stats * generic iterator -------------------------------------------------------------------------- --- Rendering Numbers --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Rformat Environments --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Statistics Printing --- -------------------------------------------------------------------------- -------------------------------------------------------------------------- --- Report Printing --- -------------------------------------------------------------------------- chapter default section section section section default sub-section -------------------------------------------------------------------------- --------------------------------------------------------------------------
This file is part of WP plug - in of Frama - C. Copyright ( C ) 2007 - 2019 CEA ( Commissariat a l'energie atomique et aux energies Lesser General Public License as published by the Free Software Foundation , version 2.1 . See the GNU Lesser General Public License version 2.1 for more details ( enclosed in the file licenses / LGPLv2.1 ) . let ladder = [| 1.0 ; 2.0 ; 3.0 ; 5.0 ; 10.0 ; 15.0 ; 20.0 ; 30.0 ; 40.0 ; 1 ' , 1'30 , 2 ' , 3 ' 5 ' , 10 ' , 15 ' , 30 ' 1h let n0 = 16 let d0 = 4 Number of steps is divided into an infinite number of successive bundles . Each bundle number , ... is divided into n0 small intervals of size 2^k * d0 . The rank r - th of a number n is the r - th interval in some bundle k. A number of steps is stabilized to its original rank r is it still belongs to the intervals that would be immediately before or after the original interval ( in the _ same _ bundle ) . Number of steps is divided into an infinite number of successive bundles. Each bundle number k=0,... is divided into n0 small intervals of size 2^k * d0. The rank r-th of a number n is the r-th interval in some bundle k. A number of steps is stabilized to its original rank r is it still belongs to the intervals that would be immediately before or after the original interval (in the _same_ bundle). *) let a0 = n0 * d0 first index of bundle k Compute the range of values for rank If ~limit : false , returns all the values n that have the rank k. If ~limit : true , returns all the values n that are stabilized at rank k. Compute the range of values for rank k. If ~limit:false, returns all the values n that have the rank k. If ~limit:true, returns all the values n that are stabilized at rank k. *) let range ?(limit=true) r = let k = r / n0 in let i = r mod n0 in let a = ak k in let d = dk k in let i1 = if limit then i-1 else i in let i2 = if limit then i+2 else i+1 in max 1 (a + i1*d) , a + i2*d let rank n = let rec aux a k n = let b = ak (succ k) - 1 in if n <= b then let d = dk k in let i = (n-a) / d in n0 * k + i else aux b (succ k) n in let a = ak 0 in if n < a then (-1) else aux a 0 n type res = VALID | UNSUCCESS | INCONCLUSIVE | NORESULT let result (r:VCS.result) = match r.VCS.verdict with | VCS.NoResult | VCS.Checked | VCS.Computing _ -> NORESULT | VCS.Failed -> INCONCLUSIVE | VCS.Invalid | VCS.Unknown | VCS.Timeout | VCS.Stepout -> UNSUCCESS | VCS.Valid -> VALID let best_result a b = match a,b with | NORESULT,c | c,NORESULT -> c | VALID,_ | _,VALID -> VALID | UNSUCCESS,_ | _,UNSUCCESS -> UNSUCCESS | INCONCLUSIVE,INCONCLUSIVE -> INCONCLUSIVE type stats = { verdict is , Unknown , Timeout , or Stepout , Invalid mutable steps : int ; mutable time : float ; mutable rank : int ; } let stats () = { total=0 ; valid=0 ; unsuccess=0 ; inconclusive=0 ; steps=0 ; rank=(-1) ; time=0.0 ; } let add_stat (r:res) (st:int) (tm:float) (s:stats) = begin s.total <- succ s.total ; match r with | VALID -> if tm > s.time then s.time <- tm ; if st > s.steps then s.steps <- st ; s.valid <- succ s.valid | NORESULT | UNSUCCESS -> s.unsuccess <- succ s.unsuccess | INCONCLUSIVE -> s.inconclusive <- succ s.inconclusive end let add_qedstat (ts:float) (s:stats) = if ts > s.time then s.time <- ts let get_field js fd = try Json.field fd js with Not_found | Invalid_argument _ -> `Null let json_assoc fields = let fields = List.filter (fun (_,d) -> d<>`Null) fields in if fields = [] then `Null else `Assoc fields let json_of_stats s = let add fd v w = if v > 0 then (fd , `Int v)::w else w in json_assoc begin add "total" s.total @@ add "valid" s.valid @@ add "failed" s.inconclusive @@ add "unknown" s.unsuccess @@ (if s.rank >= 0 then [ "rank" , `Int s.rank ] else []) end let rankify_stats s js = let n = s.steps in if n > 0 then try let r0 = Json.field "rank" js |> Json.int in let a,b = range r0 in if a <= n && n <= b then s.rank <- r0 else s.rank <- rank n with Not_found | Invalid_argument _ -> s.rank <- rank n else s.rank <- (-1) type pstats = { main : stats ; prover : (VCS.prover,stats) Hashtbl.t ; } let pstats () = { main = stats () ; prover = Hashtbl.create 7 ; } let json_of_pstats p = json_assoc begin Hashtbl.fold (fun p s w -> (VCS.name_of_prover p , json_of_stats s) :: w) p.prover [ "wp:main" , json_of_stats p.main ] end let rankify_pstats p js = begin rankify_stats p.main (get_field js "wp:main") ; Hashtbl.iter (fun p s -> rankify_stats s (get_field js @@ VCS.name_of_prover p) ; ) p.prover ; end let get_prover fs prover = try Hashtbl.find fs.prover prover with Not_found -> let s = stats () in Hashtbl.add fs.prover prover s ; s let add_results (plist:pstats list) (wpo:Wpo.t) = let ok = ref NORESULT in let tm = ref 0.0 in let sm = ref 0 in List.iter (fun (p,r) -> let re = result r in let st = Wpo.get_steps r in let tc = Wpo.get_time r in let ts = r.VCS.solver_time in if re <> NORESULT then begin List.iter (fun fs -> add_stat re st tc (get_prover fs p)) plist ; if p <> VCS.Qed && ts > 0.0 then List.iter (fun fs -> add_qedstat ts (get_prover fs VCS.Qed)) plist ; end ; ok := best_result !ok re ; if tc > !tm then tm := tc ; if st > !sm then sm := st ; ) (Wpo.get_results wpo) ; List.iter (fun fs -> add_stat !ok !sm !tm fs.main) plist type coverage = { mutable covered : Property.Set.t ; mutable proved : Property.Set.t ; } let coverage () = { covered = Property.Set.empty ; proved = Property.Set.empty } let add_cover (s:coverage) ok p = begin s.covered <- Property.Set.add p s.covered ; if ok then s.proved <- Property.Set.add p s.proved ; end type dstats = { dstats : pstats ; dcoverage : coverage ; mutable dmap : pstats Property.Map.t ; } let dstats () = { dstats = pstats () ; dcoverage = coverage () ; dmap = Property.Map.empty ; } let js_prop = Property.Names.get_prop_name_id let json_of_dstats d = json_assoc begin Property.Map.fold (fun prop ps w -> (js_prop prop , json_of_pstats ps) :: w) d.dmap [ "wp:section" , json_of_pstats d.dstats ] end let rankify_dstats d js = begin rankify_pstats d.dstats (get_field js "wp:section") ; Property.Map.iter (fun prop ps -> rankify_pstats ps (get_field js @@ js_prop prop) ) d.dmap ; end type entry = | Axiom of string | Fun of Kernel_function.t let decode_chapter= function | Axiom _ -> "axiomatic" | Fun _ -> "function" module Smap = FCMap.Make (struct type t = entry let compare s1 s2 = match s1 , s2 with | Axiom a , Axiom b -> String.compare a b | Axiom _ , Fun _ -> (-1) | Fun _ , Axiom _ -> 1 | Fun f , Fun g -> Kernel_function.compare f g end) type fcstat = { global : pstats ; gcoverage : coverage ; mutable dsmap : dstats Smap.t ; } let json_of_fcstat (fc : fcstat) = begin let functions = ref [] in let axiomatics = ref [] in Smap.iter (fun entry ds -> let acc , key = match entry with | Axiom a -> axiomatics , a | Fun kf -> functions , Kernel_function.get_name kf in acc := ( key , json_of_dstats ds ) :: !acc ; ) fc.dsmap ; json_assoc [ "wp:global" , json_of_pstats fc.global ; "wp:axiomatics" , json_assoc (List.rev (!axiomatics)) ; "wp:functions" , json_assoc (List.rev (!functions)) ; ] ; end let rankify_fcstat fc js = begin rankify_pstats fc.global (get_field js "wp:global") ; let jfunctions = get_field js "wp:functions" in let jaxiomatics = get_field js "wp:axiomatics" in Smap.iter (fun entry ds -> let js = match entry with | Axiom a -> get_field jaxiomatics a | Fun kf -> get_field jfunctions (Kernel_function.get_name kf) in rankify_dstats ds js ) fc.dsmap ; end --- Computing Statistics --- let get_section gs s = try Smap.find s gs.dsmap with Not_found -> let ds = dstats () in gs.dsmap <- Smap.add s ds gs.dsmap ; ds let get_property ds p = try Property.Map.find p ds.dmap with Not_found -> let ps = pstats () in ds.dmap <- Property.Map.add p ps ds.dmap ; ps let add_goal (gs:fcstat) wpo = begin let section = match Wpo.get_index wpo with | Wpo.Axiomatic None -> Axiom "" | Wpo.Axiomatic (Some a) -> Axiom a | Wpo.Function(kf,_) -> Fun kf in let ds : dstats = get_section gs section in let (ok,prop) = Wpo.get_proof wpo in let ps : pstats = get_property ds prop in add_results [gs.global ; ds.dstats ; ps] wpo ; add_cover gs.gcoverage ok prop ; add_cover ds.dcoverage ok prop ; end let fcstat () = let fcstat : fcstat = { global = pstats () ; gcoverage = coverage () ; dsmap = Smap.empty ; } in Wpo.iter ~on_goal:(add_goal fcstat) () ; fcstat type istat = { fcstat: fcstat; chapters : (string * (entry * dstats) list) list; } let start_stat4chap fcstat = let chapter = ref "" in let decode_chapter e = let code = decode_chapter e in let is_new_code = (code <> !chapter) in if is_new_code then chapter := code; is_new_code in let close_chapter (na,ca,ga) = if ca = [] then !chapter,[],ga else !chapter,[],((na,List.rev ca)::ga) in let (_,_,ga) = let acc = Smap.fold (fun entry ds acc -> let is_new_chapter = decode_chapter entry in let (na,ca,ga) = if is_new_chapter then close_chapter acc else acc in na,((entry,ds)::ca),ga ) fcstat.dsmap ("",[],[]) in if !chapter <> "" then close_chapter acc else acc in if ga = [] then None else Some { fcstat = fcstat; chapters = List.rev ga; } let next_stat4chap istat = match istat.chapters with | ([] | _::[]) -> None | _::l -> Some { istat with chapters = l } type cistat = { cfcstat: fcstat; chapter : string; sections : (entry * dstats) list; } let start_stat4sect istat = match istat.chapters with | [] -> None | (c,s)::_ -> Some { cfcstat = istat.fcstat; chapter = c; sections = s; } let next_stat4sect cistat = match cistat.sections with | ([] | _::[]) -> None | _::l -> Some { cistat with sections = l } type sistat = { sfcstat: fcstat; schapter : string ; section : (entry * dstats); properties : (Property.t * pstats) list; } let start_stat4prop cistat = match cistat.sections with | [] -> None | ((_,ds) as s)::_ -> Some { sfcstat = cistat.cfcstat; schapter = cistat.chapter; section = s; properties = List.rev (Property.Map.fold (fun p ps acc -> (p,ps)::acc) ds.dmap []); } let next_stat4prop sistat = match sistat.properties with | ([] | _::[]) -> None | _::l -> Some { sfcstat = sistat.sfcstat; schapter = sistat.schapter; section = sistat.section; properties = l; } let iter_stat ?first ?sep ?last ~from start next= if first<>None || sep<>None || last <> None then let items = ref (start from) in if !items <> None then begin let apply v = function | None -> () | Some app -> app v in let next app = let item = (Extlib.the !items) in apply item app; items := next item in next first; if sep<>None || last <> None then begin while !items <> None do next sep; done; apply () last; end end type config = { mutable status_passed : string ; mutable status_failed : string ; mutable status_inconclusive : string ; mutable status_untried : string ; mutable global_prefix : string ; mutable lemma_prefix : string ; mutable axiomatic_prefix : string ; mutable function_prefix : string ; mutable property_prefix : string ; mutable global_section: string ; mutable axiomatic_section: string ; mutable function_section : string ; mutable console : bool ; mutable zero : string ; } let pp_zero ~config fmt = if config.console then Format.fprintf fmt "%4s" config.zero else Format.pp_print_string fmt config.zero let percent ~config fmt number total = if total <= 0 || number < 0 then pp_zero ~config fmt else if number >= total then Format.pp_print_string fmt (if config.console then " 100" else "100") else let ratio = float_of_int number /. float_of_int total in Format.fprintf fmt "%4.1f" (100.0 *. ratio) let number ~config fmt k = if k = 0 then pp_zero ~config fmt else if config.console then Format.fprintf fmt "%4d" k else Format.pp_print_int fmt k let properties ~config fmt (s:coverage) = function | "" -> percent config fmt (Property.Set.cardinal s.proved) (Property.Set.cardinal s.covered) | "total" -> number config fmt (Property.Set.cardinal s.covered) | "valid" -> number config fmt (Property.Set.cardinal s.proved) | "failed" -> number config fmt (Property.Set.cardinal s.covered - Property.Set.cardinal s.proved) | _ -> raise Exit let is_stat_name = function | "success" | "total" | "valid" | "" | "failed" | "status" | "inconclusive" | "unsuccess" | "time" | "perf" | "steps" | "range" -> true | _ -> false let stat ~config fmt s = function | "success" -> percent config fmt s.valid s.total | "total" -> number config fmt s.total | "valid" | "" -> number config fmt s.valid | "failed" -> number config fmt (s.unsuccess + s.inconclusive) | "status" -> let msg = if s.inconclusive > 0 then config.status_inconclusive else if s.unsuccess > 0 then config.status_failed else if s.valid >= s.total then config.status_passed else config.status_untried in Format.pp_print_string fmt msg | "inconclusive" -> number config fmt s.inconclusive | "unsuccess" -> number config fmt s.unsuccess | "time" -> if s.time > 0.0 then Rformat.pp_time_range ladder fmt s.time | "perf" -> if s.time > Rformat.epsilon then Format.fprintf fmt "(%a)" Rformat.pp_time s.time | "steps" -> if s.steps > 0 then Format.fprintf fmt "(%d)" s.steps | "range" -> if s.rank >= 0 then let a,b = range s.rank in Format.fprintf fmt "(%d..%d)" a b | _ -> raise Exit let pstats ~config fmt s cmd arg = match cmd with | "wp" | "qed" -> stat ~config fmt (get_prover s VCS.Qed) arg | cmd when is_stat_name cmd -> stat ~config fmt s.main cmd | prover -> match (VCS.prover_of_name prover) with | None -> Wp_parameters.error ~once:true "Unknown prover name %s" prover | Some prover -> stat ~config fmt (get_prover s prover) arg let pcstats ~config fmt (s,c) cmd arg = match cmd with | "prop" -> properties ~config fmt c arg | _ -> pstats ~config fmt s cmd arg let env_toplevel ~config gstat fmt cmd arg = try pcstats config fmt (gstat.global, gstat.gcoverage) cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown toplevel-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown toplevel-format '%%%s:%s'" cmd arg let env_chapter chapter_name fmt cmd arg = try match cmd with | "chapter" | "name" -> Format.pp_print_string fmt chapter_name | _ -> raise Exit with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown chapter-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown chapter-format '%%%s:%s'" cmd arg let env_section ~config ~name sstat fmt cmd arg = try let entry,ds = match sstat.sections with | section_item::_others -> section_item | _ -> raise Exit in match cmd with | "chapter" -> let chapter = match entry with | Axiom _ -> config.axiomatic_section | Fun _ -> config.function_section in Format.pp_print_string fmt chapter | "name" | "section" | "global" | "axiomatic" | "function" -> if cmd <> "name" && cmd <> "section" && name <> cmd then Wp_parameters.error "Invalid section-format '%%%s' inside a section %s" cmd name; let prefix,name = match entry with | Axiom "" -> config.lemma_prefix,"" | Axiom a -> config.axiomatic_prefix,a | Fun kf -> config.function_prefix, ( Kernel_function.get_name kf) in Format.fprintf fmt "%s%s" prefix name | _ -> pcstats config fmt (ds.dstats, ds.dcoverage) cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown section-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown section-format '%%%s:%s'" cmd arg let env_property ~config ~name pstat fmt cmd arg = try let entry = fst pstat.section in let p,stat = match pstat.properties with | property_item::_others -> property_item | _ -> raise Exit in match cmd with | "chapter" -> let chapter = match entry with | Axiom _ -> config.axiomatic_section | Fun _ -> config.function_section in Format.pp_print_string fmt chapter | "section" | "global" | "axiomatic" | "function" -> if cmd <> "section" && name <> cmd then Wp_parameters.error "Invalid property-format '%%%s' inside a section %s" cmd name; let prefix,name = match entry with | Axiom "" -> config.lemma_prefix,"" | Axiom a -> config.axiomatic_prefix,a | Fun kf -> config.function_prefix, ( Kernel_function.get_name kf) in Format.fprintf fmt "%s%s" prefix name | "name" -> Format.fprintf fmt "%s%s" config.property_prefix (Property.Names.get_prop_name_id p) | "property" -> Description.pp_local fmt p | _ -> pstats config fmt stat cmd arg with Exit -> if arg="" then Wp_parameters.error ~once:true "Unknown property-format '%%%s'" cmd else Wp_parameters.error ~once:true "Unknown property-format '%%%s:%s'" cmd arg let print_property (pstat:sistat) ~config ~name ~prop fmt = Rformat.pretty (env_property ~config ~name pstat) fmt prop let print_section (sstat:cistat) ~config ~name ~sect ~prop fmt = if sect <> "" then Rformat.pretty (env_section ~config ~name sstat) fmt sect ; if prop <> "" then let print_property pstat = print_property pstat ~config ~name ~prop fmt in iter_stat ~first:print_property ~sep:print_property ~from:sstat start_stat4prop next_stat4prop let print_chapter (cstat:istat) ~config ~chap ~sect ~glob ~axio ~func ~prop fmt = let chapter_item = match cstat.chapters with | chapter_item::_others -> chapter_item | _ -> raise Exit in let section_name = fst chapter_item in let section,chapter_name = match section_name with | "global" -> glob,config.global_section | "axiomatic" -> axio,config.axiomatic_section | "function" -> func,config.function_section | _ -> sect,"" in let section,section_name = if section <> "" then section,section_name else sect,"" in if chap <> "" then Rformat.pretty (env_chapter chapter_name) fmt chap ; if section <> "" || prop <> "" then let print_section sstat = print_section sstat ~config ~name:section_name ~sect:section ~prop fmt in iter_stat ~first:print_section ~sep:print_section ~from:cstat start_stat4sect next_stat4sect let print gstat ~config ~head ~tail ~chap ~sect ~glob ~axio ~func ~prop fmt = begin if head <> "" then Rformat.pretty (env_toplevel ~config gstat) fmt head ; if chap <> "" || sect <> "" || glob <> "" || axio <> "" || func <> "" || prop <> "" then let print_chapter cstat = print_chapter cstat ~config ~chap ~sect ~glob ~axio ~func ~prop fmt in iter_stat ~first:print_chapter ~sep:print_chapter ~from:gstat start_stat4chap next_stat4chap ; if tail <> "" then Rformat.pretty (env_toplevel ~config gstat) fmt tail ; end type section = END | HEAD | TAIL | CHAPTER | SECTION | GLOB_SECTION | AXIO_SECTION | FUNC_SECTION | PROPERTY let export gstat specfile = let config = { console = false ; zero = "-" ; status_passed = " Ok " ; status_failed = "Failed" ; status_inconclusive = "*Bug**" ; status_untried = " " ; lemma_prefix = "Lemma " ; global_prefix = "(Global) " ; axiomatic_prefix = "Axiomatic " ; function_prefix = "" ; property_prefix = "" ; global_section = "Globals" ; axiomatic_section = "Axiomatics" ; function_section = "Functions" ; } in let head = Buffer.create 64 in let tail = Buffer.create 64 in let file = ref None in let section = ref HEAD in begin let cin = open_in specfile in try while true do let line = input_line cin in match Rformat.command line with | Rformat.ARG("AXIOMATIC_PREFIX",f) -> config.axiomatic_prefix <- f | Rformat.ARG("FUNCTION_PREFIX",f) -> config.function_prefix <- f | Rformat.ARG("PROPERTY_PREFIX",f) -> config.property_prefix <- f | Rformat.ARG("LEMMA_PREFIX",f) -> config.lemma_prefix <- f | Rformat.ARG("GLOBAL_SECTION",f) -> config.global_section <- f | Rformat.ARG("AXIOMATIC_SECTION",f) -> config.axiomatic_section <- f | Rformat.ARG("FUNCTION_SECTION",f) -> config.function_section <- f | Rformat.ARG("PASSED",s) -> config.status_passed <- s | Rformat.ARG("FAILED",s) -> config.status_failed <- s | Rformat.ARG("INCONCLUSIVE",s) -> config.status_inconclusive <- s | Rformat.ARG("UNTRIED",s) -> config.status_untried <- s | Rformat.ARG("ZERO",z) -> config.zero <- z | Rformat.ARG("FILE",f) -> file := Some f | Rformat.ARG("SUFFIX",e) -> let basename = Wp_parameters.ReportName.get () in let filename = basename ^ e in file := Some filename | Rformat.CMD "CONSOLE" -> config.console <- true | Rformat.CMD "END" -> section := END | Rformat.CMD "HEAD" -> section := HEAD | Rformat.CMD "TAIL" -> section := TAIL | Rformat.CMD "CHAPTER" -> section := CHAPTER | Rformat.CMD "SECTION" -> section := SECTION | Rformat.CMD "GLOBAL" -> section := GLOB_SECTION | Rformat.CMD "AXIOMATIC" -> section := AXIO_SECTION | Rformat.CMD "FUNCTION" -> section := FUNC_SECTION | Rformat.CMD "PROPERTY" -> section := PROPERTY | Rformat.CMD a | Rformat.ARG(a,_) -> Wp_parameters.error "Report '%s': unknown command '%s'" specfile a | Rformat.TEXT -> if !section <> END then let text = match !section with | HEAD -> head | CHAPTER -> chap | SECTION -> sect | GLOB_SECTION -> glob | AXIO_SECTION -> axio | FUNC_SECTION -> func | PROPERTY -> sect_prop | TAIL|END -> tail in Buffer.add_string text line ; Buffer.add_char text '\n' ; done with | End_of_file -> close_in cin | err -> close_in cin ; raise err end ; match !file with | None -> Log.print_on_output (print gstat ~config ~head:(Buffer.contents head) ~tail:(Buffer.contents tail) ~chap:(Buffer.contents chap) ~sect:(Buffer.contents sect) ~glob:(Buffer.contents glob) ~axio:(Buffer.contents axio) ~func:(Buffer.contents func) ~prop:(Buffer.contents sect_prop)) | Some report -> Wp_parameters.feedback "Report '%s'" report ; let cout = open_out report in let fout = Format.formatter_of_out_channel cout in try print gstat ~config ~head:(Buffer.contents head) ~tail:(Buffer.contents tail) ~chap:(Buffer.contents chap) ~sect:(Buffer.contents sect) ~glob:(Buffer.contents glob) ~axio:(Buffer.contents axio) ~func:(Buffer.contents func) ~prop:(Buffer.contents sect_prop) fout ; Format.pp_print_flush fout () ; close_out cout ; with err -> Format.pp_print_flush fout () ; close_out cout ; raise err let export_json gstat ?jinput ~joutput () = begin let js = try let jfile = match jinput with | None -> Wp_parameters.feedback "Report '%s'" joutput ; joutput | Some jinput -> Wp_parameters.feedback "Report in: '%s'" jinput ; Wp_parameters.feedback "Report out: '%s'" joutput ; jinput in if Sys.file_exists jfile then Json.load_file jfile else `Null with Json.Error(file,line,msg) -> let source = Log.source ~file ~line in Wp_parameters.error ~source "Incorrect json file: %s" msg ; `Null in rankify_fcstat gstat js ; Json.save_file joutput (json_of_fcstat gstat) ; end
6effcf8b6fa3921ad3eb6f84095377107dbc69de5d83769724710c93d1525c4d
xapi-project/xen-api-libs
udev.ml
open Printf external socket_netlink_udev : unit -> Unix.file_descr = "stub_socket_netlink_udev" external bind_netlink_udev : Unix.file_descr -> unit = "stub_bind_netlink_udev" external receive_events_udev : Unix.file_descr -> string = "stub_receive_events_udev" exception Timeout let wait_for action event timeout = let socket = socket_netlink_udev () in bind_netlink_udev socket; let devpath = sprintf "/sys%s" event in let fileexists = Sys.file_exists devpath in let cc = ref false in allow to go faster by just checking the file exists or not for specific action in the sys if action == "add" && fileexists then ( cc := true ) else if action == "remove" && not fileexists then ( cc := true ); if not !cc then ( let time = ref timeout in let found = ref false in while !time > 0.0 && !found = false do let t1 = Unix.gettimeofday () in let (is,_,_) = Unix.select [socket] [] [] !time in let t2 = Unix.gettimeofday () in time := !time -. (t2 -. t1); if List.mem socket is then ( let s = receive_events_udev socket in let idx = String.index s '@' in if idx > -1 then ( let ac = String.sub s 0 idx in let ev = String.sub s (idx+1) (String.length s - idx - 1) in if ac = action && event = ev then ( found := true ) ) ) done; if not !found then ( Unix.close socket; raise Timeout ) ); Unix.close socket; ()
null
https://raw.githubusercontent.com/xapi-project/xen-api-libs/d603ee2b8456bc2aac99b0a4955f083e22f4f314/udev/udev.ml
ocaml
open Printf external socket_netlink_udev : unit -> Unix.file_descr = "stub_socket_netlink_udev" external bind_netlink_udev : Unix.file_descr -> unit = "stub_bind_netlink_udev" external receive_events_udev : Unix.file_descr -> string = "stub_receive_events_udev" exception Timeout let wait_for action event timeout = let socket = socket_netlink_udev () in bind_netlink_udev socket; let devpath = sprintf "/sys%s" event in let fileexists = Sys.file_exists devpath in let cc = ref false in allow to go faster by just checking the file exists or not for specific action in the sys if action == "add" && fileexists then ( cc := true ) else if action == "remove" && not fileexists then ( cc := true ); if not !cc then ( let time = ref timeout in let found = ref false in while !time > 0.0 && !found = false do let t1 = Unix.gettimeofday () in let (is,_,_) = Unix.select [socket] [] [] !time in let t2 = Unix.gettimeofday () in time := !time -. (t2 -. t1); if List.mem socket is then ( let s = receive_events_udev socket in let idx = String.index s '@' in if idx > -1 then ( let ac = String.sub s 0 idx in let ev = String.sub s (idx+1) (String.length s - idx - 1) in if ac = action && event = ev then ( found := true ) ) ) done; if not !found then ( Unix.close socket; raise Timeout ) ); Unix.close socket; ()
a07d5159ca754910adbb007792d541e174938d875f271a662f2d88f6ce3781b9
roman/Haskell-Reactive-Extensions
MergeTest.hs
module Rx.Observable.MergeTest (tests) where import Test.HUnit import Test.Hspec import Control.Concurrent.Async (async, wait) import Control.Monad (forM_, replicateM, replicateM_) import qualified Rx.Observable as Rx import qualified Rx.Subject as Rx tests :: Spec tests = describe "Rx.Observable.Merge" $ describe "merge" $ it "completes after all inner Observables are completed" $ do let innerSubjectCount = 10 subjects@(firstSubject:subjects1) <- replicateM innerSubjectCount Rx.newPublishSubject sourceSubject <- Rx.newPublishSubject let source = Rx.foldLeft (+) 0 $ Rx.merge $ Rx.toAsyncObservable sourceSubject aResult <- async $ Rx.toMaybe source forM_ subjects $ \subject -> do Rx.onNext sourceSubject $ Rx.toAsyncObservable subject replicateM_ 100 $ Rx.onNext subject (1 :: Int) Rx.onCompleted sourceSubject -- If merge doesn't wait for inner observables -- this numbers should not be in the total count mapM_ Rx.onCompleted subjects1 replicateM_ 50 $ Rx.onNext firstSubject 1 mapM_ Rx.onCompleted subjects mResult <- wait aResult case mResult of Just result -> assertEqual "should be the same as folding" (innerSubjectCount * 100 + 50) result Nothing -> assertFailure "Rx failed when it shouldn't have"
null
https://raw.githubusercontent.com/roman/Haskell-Reactive-Extensions/0faddbb671be7f169eeadbe6163e8d0b2be229fb/rx-core/test/Rx/Observable/MergeTest.hs
haskell
If merge doesn't wait for inner observables this numbers should not be in the total count
module Rx.Observable.MergeTest (tests) where import Test.HUnit import Test.Hspec import Control.Concurrent.Async (async, wait) import Control.Monad (forM_, replicateM, replicateM_) import qualified Rx.Observable as Rx import qualified Rx.Subject as Rx tests :: Spec tests = describe "Rx.Observable.Merge" $ describe "merge" $ it "completes after all inner Observables are completed" $ do let innerSubjectCount = 10 subjects@(firstSubject:subjects1) <- replicateM innerSubjectCount Rx.newPublishSubject sourceSubject <- Rx.newPublishSubject let source = Rx.foldLeft (+) 0 $ Rx.merge $ Rx.toAsyncObservable sourceSubject aResult <- async $ Rx.toMaybe source forM_ subjects $ \subject -> do Rx.onNext sourceSubject $ Rx.toAsyncObservable subject replicateM_ 100 $ Rx.onNext subject (1 :: Int) Rx.onCompleted sourceSubject mapM_ Rx.onCompleted subjects1 replicateM_ 50 $ Rx.onNext firstSubject 1 mapM_ Rx.onCompleted subjects mResult <- wait aResult case mResult of Just result -> assertEqual "should be the same as folding" (innerSubjectCount * 100 + 50) result Nothing -> assertFailure "Rx failed when it shouldn't have"
10e94e671ab2c09da6b5f605e017a5c6ef6985cb4252c023cad908a7e592fdcf
larcenists/larceny
comparators.body.scm
SRFI 114 comparators #; (define-syntax define-predefined-comparator ;; Define a comparator through a constructor function that caches its result. ;; It is to be used to retrieve the predefined comparators. ;; (syntax-rules () ((_ ?who ?build-form) (begin (define-syntax ?who (identifier-syntax (builder))) (define builder (let ((C #f)) (lambda () (or C (receive-and-return (rv) ?build-form (set! C rv)))))) #| end of BEGIN |# )) )) (define-syntax define-predefined-comparator (syntax-rules () ((_ ?who ?build-form) (define ?who ?build-form)))) ;;; -------------------------------------------------------------------- (define (make-ipair-comparison car-K cdr-K) (let ((car-compare (comparator-comparison-procedure car-K)) (cdr-compare (comparator-comparison-procedure cdr-K))) (lambda (a b) (let ((result (car-compare (icar a) (icar b)))) (if (zero? result) (cdr-compare (icdr a) (icdr b)) result))))) ;;; -------------------------------------------------------------------- (define (make-ipair-comparator car-K cdr-K) (define car-test-proc (comparator-type-test-procedure car-K)) (define cdr-test-proc (comparator-type-test-procedure cdr-K)) (define (test-proc obj) (and (ipair? obj) (car-test-proc (icar obj)) (cdr-test-proc (icdr obj)))) (make-comparator test-proc #t (make-ipair-comparison car-K cdr-K) (make-ipair-hash car-K cdr-K))) (define (make-ipair-hash car-K cdr-K) (let ((car-hash (comparator-hash-function car-K)) (cdr-hash (comparator-hash-function cdr-K))) (lambda (obj) (+ (car-hash (icar obj)) (cdr-hash (icdr obj)))))) (define ipair-comparator (make-ipair-comparator default-comparator default-comparator)) ;;; -------------------------------------------------------------------- (define (make-ilist-comparator K) (define element-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (if (ipair? obj) (and (element-test-proc (icar obj)) (test-proc (icdr obj))) (null? obj))) (make-listwise-comparator test-proc K null? icar icdr)) (define ilist-comparator (make-ilist-comparator default-comparator)) ;;; -------------------------------------------------------------------- (define (make-icar-comparator K) (define icar-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (and (ipair? obj) (icar-test-proc (icar obj)))) (make-comparator test-proc #t (let ((compare (comparator-comparison-procedure K))) (lambda (a b) (compare (icar a) (icar b)))) (let ((hash (comparator-hash-function K))) (lambda (obj) (hash (icar obj)))))) (define (make-icdr-comparator K) (define icdr-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (and (ipair? obj) (icdr-test-proc (icdr obj)))) (make-comparator test-proc #t (let ((compare (comparator-comparison-procedure K))) (lambda (a b) (compare (icdr a) (icdr b)))) (let ((hash (comparator-hash-function K))) (lambda (obj) (hash (icdr obj)))))) ;;; -------------------------------------------------------------------- (define (make-improper-ilist-comparator K) (make-comparator #t #t (make-improper-ilist-comparison K) (make-improper-ilist-hash K))) (define (make-improper-ilist-comparison K) (let ((pair-compare (make-ipair-comparison K K)) (item-compare (comparator-comparison-procedure K))) (lambda (a b) and B.TYPE are the indexes of the object types . (let* ((a.type (improper-list-type a)) (b.type (improper-list-type b)) (result (real-comparison a.type b.type))) (if (zero? result) ;;A and B have the same type index; they are: both pairs, both nulls, ;;both some other object. (cond ((ipair? a) (pair-compare a b)) ((null? a) 0) (else (item-compare a b))) result))))) (define (improper-list-type obj) ;;Compute type index for inexact list comparisons. ;; (cond ((null? obj) 0) ((ipair? obj) 1) (else 2))) (define (real-comparison a b) ;;Comparison procedure for real numbers only. ;; (cond ((< a b) -1) ((> a b) +1) (else 0))) (define (make-improper-ilist-hash K) (let ((hash (comparator-hash-function K))) (lambda (obj) (cond ((ipair? obj) (+ (hash (icar obj)) (hash (icdr obj)))) ((null? obj) 0) (else (hash obj)))))) eof
null
https://raw.githubusercontent.com/larcenists/larceny/fef550c7d3923deb7a5a1ccd5a628e54cf231c75/lib/SRFI/srfi/116/comparators.body.scm
scheme
Define a comparator through a constructor function that caches its result. It is to be used to retrieve the predefined comparators. end of BEGIN -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- -------------------------------------------------------------------- A and B have the same type index; they are: both pairs, both nulls, both some other object. Compute type index for inexact list comparisons. Comparison procedure for real numbers only.
SRFI 114 comparators (define-syntax define-predefined-comparator (syntax-rules () ((_ ?who ?build-form) (begin (define-syntax ?who (identifier-syntax (builder))) (define builder (let ((C #f)) (lambda () (or C (receive-and-return (rv) ?build-form (set! C rv)))))) )) (define-syntax define-predefined-comparator (syntax-rules () ((_ ?who ?build-form) (define ?who ?build-form)))) (define (make-ipair-comparison car-K cdr-K) (let ((car-compare (comparator-comparison-procedure car-K)) (cdr-compare (comparator-comparison-procedure cdr-K))) (lambda (a b) (let ((result (car-compare (icar a) (icar b)))) (if (zero? result) (cdr-compare (icdr a) (icdr b)) result))))) (define (make-ipair-comparator car-K cdr-K) (define car-test-proc (comparator-type-test-procedure car-K)) (define cdr-test-proc (comparator-type-test-procedure cdr-K)) (define (test-proc obj) (and (ipair? obj) (car-test-proc (icar obj)) (cdr-test-proc (icdr obj)))) (make-comparator test-proc #t (make-ipair-comparison car-K cdr-K) (make-ipair-hash car-K cdr-K))) (define (make-ipair-hash car-K cdr-K) (let ((car-hash (comparator-hash-function car-K)) (cdr-hash (comparator-hash-function cdr-K))) (lambda (obj) (+ (car-hash (icar obj)) (cdr-hash (icdr obj)))))) (define ipair-comparator (make-ipair-comparator default-comparator default-comparator)) (define (make-ilist-comparator K) (define element-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (if (ipair? obj) (and (element-test-proc (icar obj)) (test-proc (icdr obj))) (null? obj))) (make-listwise-comparator test-proc K null? icar icdr)) (define ilist-comparator (make-ilist-comparator default-comparator)) (define (make-icar-comparator K) (define icar-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (and (ipair? obj) (icar-test-proc (icar obj)))) (make-comparator test-proc #t (let ((compare (comparator-comparison-procedure K))) (lambda (a b) (compare (icar a) (icar b)))) (let ((hash (comparator-hash-function K))) (lambda (obj) (hash (icar obj)))))) (define (make-icdr-comparator K) (define icdr-test-proc (comparator-type-test-procedure K)) (define (test-proc obj) (and (ipair? obj) (icdr-test-proc (icdr obj)))) (make-comparator test-proc #t (let ((compare (comparator-comparison-procedure K))) (lambda (a b) (compare (icdr a) (icdr b)))) (let ((hash (comparator-hash-function K))) (lambda (obj) (hash (icdr obj)))))) (define (make-improper-ilist-comparator K) (make-comparator #t #t (make-improper-ilist-comparison K) (make-improper-ilist-hash K))) (define (make-improper-ilist-comparison K) (let ((pair-compare (make-ipair-comparison K K)) (item-compare (comparator-comparison-procedure K))) (lambda (a b) and B.TYPE are the indexes of the object types . (let* ((a.type (improper-list-type a)) (b.type (improper-list-type b)) (result (real-comparison a.type b.type))) (if (zero? result) (cond ((ipair? a) (pair-compare a b)) ((null? a) 0) (else (item-compare a b))) result))))) (define (improper-list-type obj) (cond ((null? obj) 0) ((ipair? obj) 1) (else 2))) (define (real-comparison a b) (cond ((< a b) -1) ((> a b) +1) (else 0))) (define (make-improper-ilist-hash K) (let ((hash (comparator-hash-function K))) (lambda (obj) (cond ((ipair? obj) (+ (hash (icar obj)) (hash (icdr obj)))) ((null? obj) 0) (else (hash obj)))))) eof
8edee78c423b41d6d41e055a9bc4b3eca791b97c510737c7b5d35c01ea5b4f87
VisionsGlobalEmpowerment/webchange
constructor.cljs
(ns webchange.ui.components.audio-wave.constructor (:require ["wavesurfer.js/dist/plugin/wavesurfer.regions.js" :as Regions] ["wavesurfer.js/dist/plugin/wavesurfer.timeline.js" :as Timeline] ["/audio-script" :as AudioScript] [wavesurfer.js :as WaveSurferConstructor] [webchange.ui.components.audio-wave.config :refer [get-config]] [webchange.ui.components.audio-wave.audio-loader :as loader] [webchange.ui.components.audio-wave.wave-utils :as w] [webchange.utils.element :as el])) (def AudioScriptPlugin AudioScript) (def RegionsPlugin Regions) (def TimelinePlugin Timeline) (def WaveSurfer WaveSurferConstructor) (defn- create [constructor params] (->> (clj->js params) (.create constructor))) (defn create-wavesurfer [element audio-url {:keys [on-ready script-class-name timeline-class-name wave-class-name]}] (el/remove-children element) (let [timeline-div (->> (el/create {:class-name timeline-class-name}) (el/insert-before element)) script-div (->> (el/create {:class-name script-class-name}) (el/insert-before element)) ws-div (->> (el/create {:class-name wave-class-name}) (el/insert-before element)) wavesurfer (create WaveSurfer (merge (get-config :wave-surfer) {:container ws-div :height 64 :minPxPerSec 250 :scrollParent true :plugins [(create RegionsPlugin (get-config :region-plugin)) (create AudioScriptPlugin (merge (get-config :audio-script) {:container script-div :timing []})) (create TimelinePlugin (merge (get-config :time-line) {:container timeline-div}))]}))] (when (fn? on-ready) (w/subscribe wavesurfer "ready" #(on-ready wavesurfer))) (loader/get-audio-blob audio-url #(w/load-blob wavesurfer %)) wavesurfer))
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/c898e0632a518bf6d9dca6f2e0c2bb6460376427/src/cljs/webchange/ui/components/audio_wave/constructor.cljs
clojure
(ns webchange.ui.components.audio-wave.constructor (:require ["wavesurfer.js/dist/plugin/wavesurfer.regions.js" :as Regions] ["wavesurfer.js/dist/plugin/wavesurfer.timeline.js" :as Timeline] ["/audio-script" :as AudioScript] [wavesurfer.js :as WaveSurferConstructor] [webchange.ui.components.audio-wave.config :refer [get-config]] [webchange.ui.components.audio-wave.audio-loader :as loader] [webchange.ui.components.audio-wave.wave-utils :as w] [webchange.utils.element :as el])) (def AudioScriptPlugin AudioScript) (def RegionsPlugin Regions) (def TimelinePlugin Timeline) (def WaveSurfer WaveSurferConstructor) (defn- create [constructor params] (->> (clj->js params) (.create constructor))) (defn create-wavesurfer [element audio-url {:keys [on-ready script-class-name timeline-class-name wave-class-name]}] (el/remove-children element) (let [timeline-div (->> (el/create {:class-name timeline-class-name}) (el/insert-before element)) script-div (->> (el/create {:class-name script-class-name}) (el/insert-before element)) ws-div (->> (el/create {:class-name wave-class-name}) (el/insert-before element)) wavesurfer (create WaveSurfer (merge (get-config :wave-surfer) {:container ws-div :height 64 :minPxPerSec 250 :scrollParent true :plugins [(create RegionsPlugin (get-config :region-plugin)) (create AudioScriptPlugin (merge (get-config :audio-script) {:container script-div :timing []})) (create TimelinePlugin (merge (get-config :time-line) {:container timeline-div}))]}))] (when (fn? on-ready) (w/subscribe wavesurfer "ready" #(on-ready wavesurfer))) (loader/get-audio-blob audio-url #(w/load-blob wavesurfer %)) wavesurfer))
d1286267cd67227a7cab9a6792579643c87626a5075fe197b069a14423059a92
robertluo/fun-map
wrapper.cljc
(ns robertluo.fun-map.wrapper "Protocols that sharing with other namespaces") (defprotocol ValueWrapper "A wrapper for a value." (-wrapped? [this m] "is this a wrapper?") (-unwrap [this m k] "unwrap the real value from a wrapper on the key of k")) ;; Make sure common value is not wrapped #?(:clj (extend-protocol ValueWrapper Object (-wrapped? [_ _] false) (-unwrap [this _ k] (ex-info "Unwrap a common value" {:key k :value this})) nil (-wrapped? [_ _] false) (-unwrap [_ _ k] (ex-info "Unwrap a nil" {:key k})) clojure.lang.IDeref (-wrapped? [_ m] (not (some-> m meta ::keep-ref))) (-unwrap [d _ _] (deref d)))) (deftype FunctionWrapper [f] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (f m k)) #?@(:cljs [IPrintWithWriter (-pr-writer [_ wtr _] (-write wtr (str "<<" f ">>")))]) ) (def fun-wrapper "construct a new FunctionWrapper" ->FunctionWrapper) (defn wrapper-entry "returns a k,v pair from map `m` and input k-v pair. If `v` is a wrapped, then recursive unwrap it." [m [k v]] #?(:clj (if (-wrapped? v m) (recur m [k (-unwrap v m k)]) [k v]) :cljs (cond (satisfies? ValueWrapper v) (recur m [k (-unwrap v m k)]) (satisfies? IDeref v) (recur m [k (deref v)]) :else [k v]))) ;;;;;;;;;;; High order wrappers (deftype CachedWrapper [wrapped a-val-pair focus-fn] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (let [[val focus-val] @a-val-pair new-focus-val (if focus-fn (focus-fn m) ::unrealized)] (if (or (= ::unrealized val) (not= new-focus-val focus-val)) (first (swap! a-val-pair (fn [_] [(-unwrap wrapped m k) new-focus-val]))) val))) #?@(:cljs [IPrintWithWriter (-pr-writer [this wtr _] (-write wtr (str "<<" (let [v (-> (.-a_val_pair this) deref first)] (if (= ::unrealized v) "unrealized" v)) ">>")))])) (defn cache-wrapper "construct a CachedWrapper" [wrapped focus] (CachedWrapper. wrapped (atom [::unrealized ::unrealized]) focus)) (deftype TracedWrapper [wrapped trace-fn] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (let [v (-unwrap wrapped m k)] (when-let [trace-fn (or trace-fn (some-> m meta :robertluo.fun-map/trace))] (trace-fn k v)) v))) (def trace-wrapper "constructs a TraceWrapper" ->TracedWrapper) ;; Fine print the wrappers #?(:clj (do (defmethod print-method FunctionWrapper [^FunctionWrapper o ^java.io.Writer wtr] (.write wtr (str "<<" (.f o) ">>"))) (defmethod print-method CachedWrapper [^CachedWrapper o ^java.io.Writer wtr] (.write wtr (str "<<" (let [v (-> (.a_val_pair o) deref first)] (if (= ::unrealized v) "unrealized" v)) ">>")))))
null
https://raw.githubusercontent.com/robertluo/fun-map/ea2d418dac2b77171f877c4d6fbc4d14d72ea04d/src/robertluo/fun_map/wrapper.cljc
clojure
Make sure common value is not wrapped High order wrappers Fine print the wrappers
(ns robertluo.fun-map.wrapper "Protocols that sharing with other namespaces") (defprotocol ValueWrapper "A wrapper for a value." (-wrapped? [this m] "is this a wrapper?") (-unwrap [this m k] "unwrap the real value from a wrapper on the key of k")) #?(:clj (extend-protocol ValueWrapper Object (-wrapped? [_ _] false) (-unwrap [this _ k] (ex-info "Unwrap a common value" {:key k :value this})) nil (-wrapped? [_ _] false) (-unwrap [_ _ k] (ex-info "Unwrap a nil" {:key k})) clojure.lang.IDeref (-wrapped? [_ m] (not (some-> m meta ::keep-ref))) (-unwrap [d _ _] (deref d)))) (deftype FunctionWrapper [f] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (f m k)) #?@(:cljs [IPrintWithWriter (-pr-writer [_ wtr _] (-write wtr (str "<<" f ">>")))]) ) (def fun-wrapper "construct a new FunctionWrapper" ->FunctionWrapper) (defn wrapper-entry "returns a k,v pair from map `m` and input k-v pair. If `v` is a wrapped, then recursive unwrap it." [m [k v]] #?(:clj (if (-wrapped? v m) (recur m [k (-unwrap v m k)]) [k v]) :cljs (cond (satisfies? ValueWrapper v) (recur m [k (-unwrap v m k)]) (satisfies? IDeref v) (recur m [k (deref v)]) :else [k v]))) (deftype CachedWrapper [wrapped a-val-pair focus-fn] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (let [[val focus-val] @a-val-pair new-focus-val (if focus-fn (focus-fn m) ::unrealized)] (if (or (= ::unrealized val) (not= new-focus-val focus-val)) (first (swap! a-val-pair (fn [_] [(-unwrap wrapped m k) new-focus-val]))) val))) #?@(:cljs [IPrintWithWriter (-pr-writer [this wtr _] (-write wtr (str "<<" (let [v (-> (.-a_val_pair this) deref first)] (if (= ::unrealized v) "unrealized" v)) ">>")))])) (defn cache-wrapper "construct a CachedWrapper" [wrapped focus] (CachedWrapper. wrapped (atom [::unrealized ::unrealized]) focus)) (deftype TracedWrapper [wrapped trace-fn] ValueWrapper (-wrapped? [_ _] true) (-unwrap [_ m k] (let [v (-unwrap wrapped m k)] (when-let [trace-fn (or trace-fn (some-> m meta :robertluo.fun-map/trace))] (trace-fn k v)) v))) (def trace-wrapper "constructs a TraceWrapper" ->TracedWrapper) #?(:clj (do (defmethod print-method FunctionWrapper [^FunctionWrapper o ^java.io.Writer wtr] (.write wtr (str "<<" (.f o) ">>"))) (defmethod print-method CachedWrapper [^CachedWrapper o ^java.io.Writer wtr] (.write wtr (str "<<" (let [v (-> (.a_val_pair o) deref first)] (if (= ::unrealized v) "unrealized" v)) ">>")))))
6ad15b05c5ef1476fa92655087b0b4babc02507a4267f9477e257a7e700fdaa5
fukamachi/gotanda
core.lisp
(eval-when (:compile-toplevel :load-toplevel :execute) (let ((*standard-output* (make-broadcast-stream))) (require 'asdf) (require 'lisp-unit) (require 'cl-interpol) (require 'gotanda))) (cl-interpol:enable-interpol-syntax) (clsql:enable-sql-reader-syntax) ;;==================== Initialize ;;==================== (in-package :clsql) (got:initialize-database) (start-transaction) ;; drop all tables and create it again (dolist (table-str (list-tables)) (let ((table (intern table-str :got))) (drop-table table) (create-view-from-class table))) (in-package :got) (loop for p in '(define-test run-tests assert-true assert-eq assert-equal assert-equality) do (shadowing-import (intern (symbol-name p) :lisp-unit))) ;;==================== ;; Test Start ;;==================== (defmacro assert-time (form &rest args) `(assert-equality #'clsql:time= ,form (clsql:make-time ,@(loop for arg in args for label in '(:year :month :day :hour :minute :second) until (null arg) append (list label arg))))) (define-test str->date (assert-time (str->date "2003-04-07") 2003 4 7) (assert-time (str->date "2003-4-7") 2003 4 7) (assert-time (str->date "2003-21-32") 2003 21 32) (assert-time (str->date "1987-10-3 18:11:29") 1987 10 3 18 11 29)) (define-test split-params (assert-equal '("create" "task" "--body" "Buy Milk #shopping") (split-params "create task --body \"Buy Milk #shopping\"")) (assert-equal '("create task" "--body" "Buy Milk") (split-params "create\\ task --body \"Buy Milk\"")) (assert-equal '("create" "task") (split-params #?" create\t task \n")) (assert-equal '("list" "--tag" "#shopping") (split-params "list --tag \"#shopping\"")) (assert-equal '("list" "nil" "< 2010-04-07") (split-params "list nil \"< 2010-04-07\""))) (define-test create-task (assert-eq nil (select-one task :body "Buy Milk #shopping")) (let ((task (create-task :body "Buy Milk #shopping"))) (assert-true task) (assert-equal "Buy Milk #shopping" (get-body task))) (let ((task (select-one task :body "Buy Milk #shopping"))) (assert-true task) (assert-equal 1 (get-id task)) (assert-equal "Buy Milk #shopping" (get-body task)))) (define-test edit-task (let ((task (select-one task))) (edit-task task :body "Editted"))) (define-test list-task (create-task :body "Produce Astro Boy #invent" :deadline "2003-04-07") (assert-true (list-task :tag "#invent")) (assert-true (list-task :tag t :deadline (list '< (clsql:get-time)))) (assert-true (list-task :tag t :deadline (list '> (clsql:make-time))))) ;;==================== ;; Test End ;;==================== (run-tests) (clsql:rollback)
null
https://raw.githubusercontent.com/fukamachi/gotanda/d911fed8f839c172e67d17e52e3a913c042178b1/test/core.lisp
lisp
==================== ==================== drop all tables and create it again ==================== Test Start ==================== ==================== Test End ====================
(eval-when (:compile-toplevel :load-toplevel :execute) (let ((*standard-output* (make-broadcast-stream))) (require 'asdf) (require 'lisp-unit) (require 'cl-interpol) (require 'gotanda))) (cl-interpol:enable-interpol-syntax) (clsql:enable-sql-reader-syntax) Initialize (in-package :clsql) (got:initialize-database) (start-transaction) (dolist (table-str (list-tables)) (let ((table (intern table-str :got))) (drop-table table) (create-view-from-class table))) (in-package :got) (loop for p in '(define-test run-tests assert-true assert-eq assert-equal assert-equality) do (shadowing-import (intern (symbol-name p) :lisp-unit))) (defmacro assert-time (form &rest args) `(assert-equality #'clsql:time= ,form (clsql:make-time ,@(loop for arg in args for label in '(:year :month :day :hour :minute :second) until (null arg) append (list label arg))))) (define-test str->date (assert-time (str->date "2003-04-07") 2003 4 7) (assert-time (str->date "2003-4-7") 2003 4 7) (assert-time (str->date "2003-21-32") 2003 21 32) (assert-time (str->date "1987-10-3 18:11:29") 1987 10 3 18 11 29)) (define-test split-params (assert-equal '("create" "task" "--body" "Buy Milk #shopping") (split-params "create task --body \"Buy Milk #shopping\"")) (assert-equal '("create task" "--body" "Buy Milk") (split-params "create\\ task --body \"Buy Milk\"")) (assert-equal '("create" "task") (split-params #?" create\t task \n")) (assert-equal '("list" "--tag" "#shopping") (split-params "list --tag \"#shopping\"")) (assert-equal '("list" "nil" "< 2010-04-07") (split-params "list nil \"< 2010-04-07\""))) (define-test create-task (assert-eq nil (select-one task :body "Buy Milk #shopping")) (let ((task (create-task :body "Buy Milk #shopping"))) (assert-true task) (assert-equal "Buy Milk #shopping" (get-body task))) (let ((task (select-one task :body "Buy Milk #shopping"))) (assert-true task) (assert-equal 1 (get-id task)) (assert-equal "Buy Milk #shopping" (get-body task)))) (define-test edit-task (let ((task (select-one task))) (edit-task task :body "Editted"))) (define-test list-task (create-task :body "Produce Astro Boy #invent" :deadline "2003-04-07") (assert-true (list-task :tag "#invent")) (assert-true (list-task :tag t :deadline (list '< (clsql:get-time)))) (assert-true (list-task :tag t :deadline (list '> (clsql:make-time))))) (run-tests) (clsql:rollback)
6ffb0274d61ece7d6d992a3a940ea1f8665be47ce1e57605f28310c18850a938
seereason/atp-haskell
DP.hs
| The Davis - Putnam and Davis - Putnam - Loveland - Logemann procedures . -- Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . ) # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Data.Logic.ATP.DP ( dp, dpsat, dptaut , dpli, dplisat, dplitaut , dpll, dpllsat, dplltaut , dplb, dplbsat, dplbtaut , testDP ) where import Data.Logic.ATP.DefCNF (NumAtom(ai, ma), defcnfs) import Data.Logic.ATP.Formulas (IsFormula(AtomOf)) import Data.Logic.ATP.Lib (Failing(Success, Failure), failing, allpairs, minimize, maximize, defined, (|->), setmapfilter, flatten) import Data.Logic.ATP.Lit (IsLiteral, (.~.), negative, positive, negate, negated) import Data.Logic.ATP.Prop (trivial, JustPropositional, PFormula) import Data.Logic.ATP.PropExamples (Knows(K), prime) import Data.Map.Strict as Map (empty, Map) import Data.Set as Set (delete, difference, empty, filter, findMin, fold, insert, intersection, map, member, minView, null, partition, Set, singleton, size, union) import Prelude hiding (negate, pure) import Test.HUnit instance NumAtom (Knows Integer) where ma n = K "p" n Nothing ai (K _ n _) = n | The DP procedure . dp :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Bool dp clauses | Set.null clauses = True | Set.member Set.empty clauses = False | otherwise = try1 where try1 :: Bool try1 = failing (const try2) dp (one_literal_rule clauses) try2 :: Bool try2 = failing (const try3) dp (affirmative_negative_rule clauses) try3 :: Bool try3 = dp (resolution_rule clauses) one_literal_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Failing (Set (Set lit)) one_literal_rule clauses = case Set.minView (Set.filter (\ cl -> Set.size cl == 1) clauses) of Nothing -> Failure ["one_literal_rule"] Just (s, _) -> let u = Set.findMin s in let u' = (.~.) u in let clauses1 = Set.filter (\ cl -> not (Set.member u cl)) clauses in Success (Set.map (\ cl -> Set.delete u' cl) clauses1) affirmative_negative_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Failing (Set (Set lit)) affirmative_negative_rule clauses = let (neg',pos) = Set.partition negative (flatten clauses) in let neg = Set.map (.~.) neg' in let pos_only = Set.difference pos neg neg_only = Set.difference neg pos in let pure = Set.union pos_only (Set.map (.~.) neg_only) in if Set.null pure then Failure ["affirmative_negative_rule"] else Success (Set.filter (\ cl -> Set.null (Set.intersection cl pure)) clauses) resolve_on :: (IsLiteral lit, Ord lit) => lit -> Set (Set lit) -> Set (Set lit) resolve_on p clauses = let p' = (.~.) p (pos,notpos) = Set.partition (Set.member p) clauses in let (neg,other) = Set.partition (Set.member p') notpos in let pos' = Set.map (Set.filter (\ l -> l /= p)) pos neg' = Set.map (Set.filter (\ l -> l /= p')) neg in let res0 = allpairs Set.union pos' neg' in Set.union other (Set.filter (not . trivial) res0) resolution_blowup :: (IsLiteral lit, Ord lit) => Set (Set lit) -> lit -> Int resolution_blowup cls l = let m = Set.size (Set.filter (Set.member l) cls) n = Set.size (Set.filter (Set.member ((.~.) l)) cls) in m * n - m - n resolution_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Set (Set lit) resolution_rule clauses = resolve_on p clauses where pvs = Set.filter positive (flatten clauses) Just p = minimize (resolution_blowup clauses) pvs | Davis - Putnam satisfiability tester . dpsat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dpsat = dp . defcnfs | Davis - Putnam tautology checker . dptaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dptaut = not . dpsat . negate -- Examples. test01 :: Test test01 = TestCase (assertEqual "dptaut(prime 11) p. 84" True (dptaut (prime 11 :: PFormula (Knows Integer)))) | The same thing but with the DPLL procedure . ( p. 84 ) dpll :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Bool dpll clauses | Set.null clauses = True | Set.member Set.empty clauses = False | otherwise = try1 where try1 = failing (const try2) dpll (one_literal_rule clauses) try2 = failing (const try3) dpll (affirmative_negative_rule clauses) try3 = dpll (Set.insert (Set.singleton p) clauses) || dpll (Set.insert (Set.singleton (negate p)) clauses) Just p = maximize (posneg_count clauses) pvs pvs = Set.filter positive (flatten clauses) | failing ( const try3 ) | otherwise = case one_literal_rule clauses > > = dpll of Success x Failure _ - > case affirmative_negative_rule clauses > > = dpll of Success x - > Success x Failure _ - > let pvs = Set.filter positive ( flatten clauses ) in case maximize ( posneg_count clauses ) pvs of Nothing - > Failure [ " dpll " ] Just p - > case ( dpll ( Set.insert ( Set.singleton p ) clauses ) , dpll ( Set.insert ( Set.singleton ( negate p ) ) clauses ) ) of ( Success a , Success b ) - > Success ( a || b ) ( Failure a , Failure b ) - > Failure ( a + + b ) ( Failure a , _ ) - > Failure a ( _ , Failure b ) - > Failure b | failing (const try3) | otherwise = case one_literal_rule clauses >>= dpll of Success x -> Success x Failure _ -> case affirmative_negative_rule clauses >>= dpll of Success x -> Success x Failure _ -> let pvs = Set.filter positive (flatten clauses) in case maximize (posneg_count clauses) pvs of Nothing -> Failure ["dpll"] Just p -> case (dpll (Set.insert (Set.singleton p) clauses), dpll (Set.insert (Set.singleton (negate p)) clauses)) of (Success a, Success b) -> Success (a || b) (Failure a, Failure b) -> Failure (a ++ b) (Failure a, _) -> Failure a (_, Failure b) -> Failure b -} posneg_count :: (IsLiteral formula, Ord formula) => Set (Set formula) -> formula -> Int posneg_count cls l = let m = Set.size(Set.filter (Set.member l) cls) n = Set.size(Set.filter (Set.member (negate l)) cls) in m + n dpllsat :: (JustPropositional pf, Ord pf, AtomOf pf ~ Knows Integer) => pf -> Bool dpllsat = dpll . defcnfs dplltaut :: (JustPropositional pf, Ord pf, AtomOf pf ~ Knows Integer) => pf -> Bool dplltaut = not . dpllsat . negate -- Example. test02 :: Test test02 = TestCase (assertEqual "dplltaut(prime 11)" True (dplltaut (prime 11 :: PFormula (Knows Integer)))) -- | Iterative implementation with explicit trail instead of recursion. dpli :: (IsLiteral formula, Ord formula) => Set (formula, TrailMix) -> Set (Set formula) -> Bool dpli trail cls = let (cls', trail') = unit_propagate (cls, trail) in if Set.member Set.empty cls' then case Set.minView trail of Just ((p,Guessed), tt) -> dpli (Set.insert (negate p, Deduced) tt) cls _ -> False else : : Set ( pf , TrailMix ) s | Set.null s -> True ps -> let Just p = maximize (posneg_count cls') ps in dpli (Set.insert (p {-:: pf-}, Guessed) trail') cls data TrailMix = Guessed | Deduced deriving (Eq, Ord) unassigned :: (IsLiteral formula, Ord formula, Eq formula) => Set (Set formula) -> Set (formula, TrailMix) -> Set formula unassigned cls trail = Set.difference (flatten (Set.map (Set.map litabs) cls)) (Set.map (litabs . fst) trail) where litabs p = if negated p then negate p else p unit_subpropagate :: (IsLiteral formula, Ord formula) => (Set (Set formula), Map formula (), Set (formula, TrailMix)) -> (Set (Set formula), Map formula (), Set (formula, TrailMix)) unit_subpropagate (cls,fn,trail) = let cls' = Set.map (Set.filter (not . defined fn . negate)) cls in let uu cs = case Set.minView cs of Nothing -> Failure ["unit_subpropagate"] Just (c, _) -> if Set.size cs == 1 && not (defined fn c) then Success cs else Failure ["unit_subpropagate"] in let newunits = flatten (setmapfilter uu cls') in if Set.null newunits then (cls',fn,trail) else let trail' = Set.fold (\ p t -> Set.insert (p,Deduced) t) trail newunits fn' = Set.fold (\ u -> (u |-> ())) fn newunits in unit_subpropagate (cls',fn',trail') unit_propagate :: forall t. (IsLiteral t, Ord t) => (Set (Set t), Set (t, TrailMix)) -> (Set (Set t), Set (t, TrailMix)) unit_propagate (cls,trail) = let fn = Set.fold (\ (x,_) -> (x |-> ())) Map.empty trail in let (cls',_fn',trail') = unit_subpropagate (cls,fn,trail) in (cls',trail') backtrack :: forall t. Set (t, TrailMix) -> Set (t, TrailMix) backtrack trail = case Set.minView trail of Just ((_p,Deduced), tt) -> backtrack tt _ -> trail dplisat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplisat = dpli Set.empty . defcnfs dplitaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplitaut = not . dplisat . negate -- | With simple non-chronological backjumping and learning. dplb :: (IsLiteral formula, Ord formula) => Set (formula, TrailMix) -> Set (Set formula) -> Bool dplb trail cls = let (cls',trail') = unit_propagate (cls,trail) in if Set.member Set.empty cls' then case Set.minView (backtrack trail) of Just ((p,Guessed), tt) -> let trail'' = backjump cls p tt in let declits = Set.filter (\ (_,d) -> d == Guessed) trail'' in let conflict = Set.insert (negate p) (Set.map (negate . fst) declits) in dplb (Set.insert (negate p, Deduced) trail'') (Set.insert conflict cls) _ -> False else case unassigned cls trail' of s | Set.null s -> True ps -> let Just p = maximize (posneg_count cls') ps in dplb (Set.insert (p,Guessed) trail') cls backjump :: (IsLiteral a, Ord a) => Set (Set a) -> a -> Set (a, TrailMix) -> Set (a, TrailMix) backjump cls p trail = case Set.minView (backtrack trail) of Just ((_q,Guessed), tt) -> let (cls',_trail') = unit_propagate (cls, Set.insert (p,Guessed) tt) in if Set.member Set.empty cls' then backjump cls p tt else trail _ -> trail dplbsat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplbsat = dplb Set.empty . defcnfs dplbtaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplbtaut = not . dplbsat . negate -- | Examples. test03 :: Test test03 = TestList [TestCase (assertEqual "dplitaut(prime 101)" True (dplitaut (prime 101 :: PFormula (Knows Integer)))), TestCase (assertEqual "dplbtaut(prime 101)" True (dplbtaut (prime 101 :: PFormula (Knows Integer))))] testDP :: Test testDP = TestLabel "DP" (TestList [test01, test02, test03])
null
https://raw.githubusercontent.com/seereason/atp-haskell/8b3431236369b9bf5b8723225f65cfac1832a0f9/src/Data/Logic/ATP/DP.hs
haskell
Examples. Example. | Iterative implementation with explicit trail instead of recursion. :: pf | With simple non-chronological backjumping and learning. | Examples.
| The Davis - Putnam and Davis - Putnam - Loveland - Logemann procedures . Copyright ( c ) 2003 - 2007 , . ( See " LICENSE.txt " for details . ) # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module Data.Logic.ATP.DP ( dp, dpsat, dptaut , dpli, dplisat, dplitaut , dpll, dpllsat, dplltaut , dplb, dplbsat, dplbtaut , testDP ) where import Data.Logic.ATP.DefCNF (NumAtom(ai, ma), defcnfs) import Data.Logic.ATP.Formulas (IsFormula(AtomOf)) import Data.Logic.ATP.Lib (Failing(Success, Failure), failing, allpairs, minimize, maximize, defined, (|->), setmapfilter, flatten) import Data.Logic.ATP.Lit (IsLiteral, (.~.), negative, positive, negate, negated) import Data.Logic.ATP.Prop (trivial, JustPropositional, PFormula) import Data.Logic.ATP.PropExamples (Knows(K), prime) import Data.Map.Strict as Map (empty, Map) import Data.Set as Set (delete, difference, empty, filter, findMin, fold, insert, intersection, map, member, minView, null, partition, Set, singleton, size, union) import Prelude hiding (negate, pure) import Test.HUnit instance NumAtom (Knows Integer) where ma n = K "p" n Nothing ai (K _ n _) = n | The DP procedure . dp :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Bool dp clauses | Set.null clauses = True | Set.member Set.empty clauses = False | otherwise = try1 where try1 :: Bool try1 = failing (const try2) dp (one_literal_rule clauses) try2 :: Bool try2 = failing (const try3) dp (affirmative_negative_rule clauses) try3 :: Bool try3 = dp (resolution_rule clauses) one_literal_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Failing (Set (Set lit)) one_literal_rule clauses = case Set.minView (Set.filter (\ cl -> Set.size cl == 1) clauses) of Nothing -> Failure ["one_literal_rule"] Just (s, _) -> let u = Set.findMin s in let u' = (.~.) u in let clauses1 = Set.filter (\ cl -> not (Set.member u cl)) clauses in Success (Set.map (\ cl -> Set.delete u' cl) clauses1) affirmative_negative_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Failing (Set (Set lit)) affirmative_negative_rule clauses = let (neg',pos) = Set.partition negative (flatten clauses) in let neg = Set.map (.~.) neg' in let pos_only = Set.difference pos neg neg_only = Set.difference neg pos in let pure = Set.union pos_only (Set.map (.~.) neg_only) in if Set.null pure then Failure ["affirmative_negative_rule"] else Success (Set.filter (\ cl -> Set.null (Set.intersection cl pure)) clauses) resolve_on :: (IsLiteral lit, Ord lit) => lit -> Set (Set lit) -> Set (Set lit) resolve_on p clauses = let p' = (.~.) p (pos,notpos) = Set.partition (Set.member p) clauses in let (neg,other) = Set.partition (Set.member p') notpos in let pos' = Set.map (Set.filter (\ l -> l /= p)) pos neg' = Set.map (Set.filter (\ l -> l /= p')) neg in let res0 = allpairs Set.union pos' neg' in Set.union other (Set.filter (not . trivial) res0) resolution_blowup :: (IsLiteral lit, Ord lit) => Set (Set lit) -> lit -> Int resolution_blowup cls l = let m = Set.size (Set.filter (Set.member l) cls) n = Set.size (Set.filter (Set.member ((.~.) l)) cls) in m * n - m - n resolution_rule :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Set (Set lit) resolution_rule clauses = resolve_on p clauses where pvs = Set.filter positive (flatten clauses) Just p = minimize (resolution_blowup clauses) pvs | Davis - Putnam satisfiability tester . dpsat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dpsat = dp . defcnfs | Davis - Putnam tautology checker . dptaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dptaut = not . dpsat . negate test01 :: Test test01 = TestCase (assertEqual "dptaut(prime 11) p. 84" True (dptaut (prime 11 :: PFormula (Knows Integer)))) | The same thing but with the DPLL procedure . ( p. 84 ) dpll :: (IsLiteral lit, Ord lit) => Set (Set lit) -> Bool dpll clauses | Set.null clauses = True | Set.member Set.empty clauses = False | otherwise = try1 where try1 = failing (const try2) dpll (one_literal_rule clauses) try2 = failing (const try3) dpll (affirmative_negative_rule clauses) try3 = dpll (Set.insert (Set.singleton p) clauses) || dpll (Set.insert (Set.singleton (negate p)) clauses) Just p = maximize (posneg_count clauses) pvs pvs = Set.filter positive (flatten clauses) | failing ( const try3 ) | otherwise = case one_literal_rule clauses > > = dpll of Success x Failure _ - > case affirmative_negative_rule clauses > > = dpll of Success x - > Success x Failure _ - > let pvs = Set.filter positive ( flatten clauses ) in case maximize ( posneg_count clauses ) pvs of Nothing - > Failure [ " dpll " ] Just p - > case ( dpll ( Set.insert ( Set.singleton p ) clauses ) , dpll ( Set.insert ( Set.singleton ( negate p ) ) clauses ) ) of ( Success a , Success b ) - > Success ( a || b ) ( Failure a , Failure b ) - > Failure ( a + + b ) ( Failure a , _ ) - > Failure a ( _ , Failure b ) - > Failure b | failing (const try3) | otherwise = case one_literal_rule clauses >>= dpll of Success x -> Success x Failure _ -> case affirmative_negative_rule clauses >>= dpll of Success x -> Success x Failure _ -> let pvs = Set.filter positive (flatten clauses) in case maximize (posneg_count clauses) pvs of Nothing -> Failure ["dpll"] Just p -> case (dpll (Set.insert (Set.singleton p) clauses), dpll (Set.insert (Set.singleton (negate p)) clauses)) of (Success a, Success b) -> Success (a || b) (Failure a, Failure b) -> Failure (a ++ b) (Failure a, _) -> Failure a (_, Failure b) -> Failure b -} posneg_count :: (IsLiteral formula, Ord formula) => Set (Set formula) -> formula -> Int posneg_count cls l = let m = Set.size(Set.filter (Set.member l) cls) n = Set.size(Set.filter (Set.member (negate l)) cls) in m + n dpllsat :: (JustPropositional pf, Ord pf, AtomOf pf ~ Knows Integer) => pf -> Bool dpllsat = dpll . defcnfs dplltaut :: (JustPropositional pf, Ord pf, AtomOf pf ~ Knows Integer) => pf -> Bool dplltaut = not . dpllsat . negate test02 :: Test test02 = TestCase (assertEqual "dplltaut(prime 11)" True (dplltaut (prime 11 :: PFormula (Knows Integer)))) dpli :: (IsLiteral formula, Ord formula) => Set (formula, TrailMix) -> Set (Set formula) -> Bool dpli trail cls = let (cls', trail') = unit_propagate (cls, trail) in if Set.member Set.empty cls' then case Set.minView trail of Just ((p,Guessed), tt) -> dpli (Set.insert (negate p, Deduced) tt) cls _ -> False else : : Set ( pf , TrailMix ) s | Set.null s -> True ps -> let Just p = maximize (posneg_count cls') ps in data TrailMix = Guessed | Deduced deriving (Eq, Ord) unassigned :: (IsLiteral formula, Ord formula, Eq formula) => Set (Set formula) -> Set (formula, TrailMix) -> Set formula unassigned cls trail = Set.difference (flatten (Set.map (Set.map litabs) cls)) (Set.map (litabs . fst) trail) where litabs p = if negated p then negate p else p unit_subpropagate :: (IsLiteral formula, Ord formula) => (Set (Set formula), Map formula (), Set (formula, TrailMix)) -> (Set (Set formula), Map formula (), Set (formula, TrailMix)) unit_subpropagate (cls,fn,trail) = let cls' = Set.map (Set.filter (not . defined fn . negate)) cls in let uu cs = case Set.minView cs of Nothing -> Failure ["unit_subpropagate"] Just (c, _) -> if Set.size cs == 1 && not (defined fn c) then Success cs else Failure ["unit_subpropagate"] in let newunits = flatten (setmapfilter uu cls') in if Set.null newunits then (cls',fn,trail) else let trail' = Set.fold (\ p t -> Set.insert (p,Deduced) t) trail newunits fn' = Set.fold (\ u -> (u |-> ())) fn newunits in unit_subpropagate (cls',fn',trail') unit_propagate :: forall t. (IsLiteral t, Ord t) => (Set (Set t), Set (t, TrailMix)) -> (Set (Set t), Set (t, TrailMix)) unit_propagate (cls,trail) = let fn = Set.fold (\ (x,_) -> (x |-> ())) Map.empty trail in let (cls',_fn',trail') = unit_subpropagate (cls,fn,trail) in (cls',trail') backtrack :: forall t. Set (t, TrailMix) -> Set (t, TrailMix) backtrack trail = case Set.minView trail of Just ((_p,Deduced), tt) -> backtrack tt _ -> trail dplisat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplisat = dpli Set.empty . defcnfs dplitaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplitaut = not . dplisat . negate dplb :: (IsLiteral formula, Ord formula) => Set (formula, TrailMix) -> Set (Set formula) -> Bool dplb trail cls = let (cls',trail') = unit_propagate (cls,trail) in if Set.member Set.empty cls' then case Set.minView (backtrack trail) of Just ((p,Guessed), tt) -> let trail'' = backjump cls p tt in let declits = Set.filter (\ (_,d) -> d == Guessed) trail'' in let conflict = Set.insert (negate p) (Set.map (negate . fst) declits) in dplb (Set.insert (negate p, Deduced) trail'') (Set.insert conflict cls) _ -> False else case unassigned cls trail' of s | Set.null s -> True ps -> let Just p = maximize (posneg_count cls') ps in dplb (Set.insert (p,Guessed) trail') cls backjump :: (IsLiteral a, Ord a) => Set (Set a) -> a -> Set (a, TrailMix) -> Set (a, TrailMix) backjump cls p trail = case Set.minView (backtrack trail) of Just ((_q,Guessed), tt) -> let (cls',_trail') = unit_propagate (cls, Set.insert (p,Guessed) tt) in if Set.member Set.empty cls' then backjump cls p tt else trail _ -> trail dplbsat :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplbsat = dplb Set.empty . defcnfs dplbtaut :: (JustPropositional pf, Ord pf, NumAtom (AtomOf pf)) => pf -> Bool dplbtaut = not . dplbsat . negate test03 :: Test test03 = TestList [TestCase (assertEqual "dplitaut(prime 101)" True (dplitaut (prime 101 :: PFormula (Knows Integer)))), TestCase (assertEqual "dplbtaut(prime 101)" True (dplbtaut (prime 101 :: PFormula (Knows Integer))))] testDP :: Test testDP = TestLabel "DP" (TestList [test01, test02, test03])
e6091c6560b6bf79c8c5184456af4b4ca485df4bdf870694a40a3f79b2e7775f
ocaml/opam
opamCliMain.mli
(**************************************************************************) (* *) (* Copyright 2020 OCamlPro *) (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) * Handles calling opam plugins ( à la git ) . E.g. [ opam publish ] runs [ opam - publish ] from PATH , with specific addition of and the current switch bin directory ) . Note that this does load some configuration and env , but only handles a leading [ ] argument . @raise InvalidCLI [opam-publish] from PATH, with specific addition of OpamPath.plugins_bin and the current switch bin directory). Note that this does load some configuration and env, but only handles a leading [--yes] argument. @raise InvalidCLI *) val check_and_run_external_commands: unit -> OpamCLIVersion.Sourced.t * string list * Handles flushing buffers and catching exceptions from the main call , including special cases like [ OpamStd . . Exec ] that is expected to do a [ Unix.exec ] , but after all proper cleanup has been done . including special cases like [OpamStd.Sys.Exec] that is expected to do a [Unix.exec], but after all proper cleanup has been done. *) val main_catch_all: (unit -> unit) -> unit (** Handling of debug JSON output, according to [OpamClientConfig.json_out] *) val json_out: unit -> unit (** [run default command_list] runs command-line argument parsing and processing of the command *) val run: unit -> unit (** Default entry point with handling of debug finalisers *) val main: unit -> unit
null
https://raw.githubusercontent.com/ocaml/opam/074df6b6d87d4114116ea41311892b342cfad3de/src/client/opamCliMain.mli
ocaml
************************************************************************ Copyright 2020 OCamlPro All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * Handling of debug JSON output, according to [OpamClientConfig.json_out] * [run default command_list] runs command-line argument parsing and processing of the command * Default entry point with handling of debug finalisers
GNU Lesser General Public License version 2.1 , with the special * Handles calling opam plugins ( à la git ) . E.g. [ opam publish ] runs [ opam - publish ] from PATH , with specific addition of and the current switch bin directory ) . Note that this does load some configuration and env , but only handles a leading [ ] argument . @raise InvalidCLI [opam-publish] from PATH, with specific addition of OpamPath.plugins_bin and the current switch bin directory). Note that this does load some configuration and env, but only handles a leading [--yes] argument. @raise InvalidCLI *) val check_and_run_external_commands: unit -> OpamCLIVersion.Sourced.t * string list * Handles flushing buffers and catching exceptions from the main call , including special cases like [ OpamStd . . Exec ] that is expected to do a [ Unix.exec ] , but after all proper cleanup has been done . including special cases like [OpamStd.Sys.Exec] that is expected to do a [Unix.exec], but after all proper cleanup has been done. *) val main_catch_all: (unit -> unit) -> unit val json_out: unit -> unit val run: unit -> unit val main: unit -> unit
faba9fca569dd7ab7f5992d11310ddb4f3e13fe7bf6268a3c2db99e8e480c85d
elastic/runbld
opts_test.clj
(ns runbld.opts-test (:require [clj-time.core :as t] [clojure.test :refer :all] [runbld.io :as io] [runbld.java :as java] [runbld.opts :as opts] [runbld.test-support :as ts] [schema.test])) (use-fixtures :once schema.test/validate-schemas) (use-fixtures :each (ts/redirect-logging-fixture)) (deftest basic (let [java-home (:home (java/jvm-facts)) program (if (opts/windows?) "CMD.EXE" "zsh")] (is (= {:program program :args (if (opts/windows?) ["/C"] ["-x"]) :inherit-exit-code true :inherit-env false, :scriptfile "/path/to/script.zsh" The case will resolve differently on Windows between ;; user.dir and io/abspath (c: vs C:) :cwd (io/abspath (System/getProperty "user.dir")) :stdout ".stdout.log" :stderr ".stderr.log" :output ".output.log" :env {:JAVA_HOME java-home}} (:process (opts/parse-args ["-c" "test/config/opts.yml" "-j" "test,foo,master" "--java-home" java-home "-p" program "/path/to/script.zsh"])))))) (deftest profile1 (let [java-home (:home (java/jvm-facts)) program (if (opts/windows?) "CMD.EXE" "zsh")] (is (= {:from "" :to ""} (-> ["-c" "test/config/opts.yml" "-j" "test,foo,master" "-p" program "--java-home" java-home "/path/to/script.zsh"] opts/parse-args :email (select-keys [:from :to])))))) (deftest stdin (let [java-home (:home (java/jvm-facts)) prog "l33t code" scriptfile (-> ["-c" "test/config/opts.yml" "-j" "test,foo,master" "--java-home" java-home (opts/make-script "-" (java.io.StringReader. prog))] opts/parse-args :process :scriptfile)] (is (re-find #".*stdin.*" scriptfile)) (is (= prog (slurp scriptfile)))))
null
https://raw.githubusercontent.com/elastic/runbld/7afcb1d95a464dc068f95abf3ad8a7566202ce28/test/runbld/opts_test.clj
clojure
user.dir and io/abspath (c: vs C:)
(ns runbld.opts-test (:require [clj-time.core :as t] [clojure.test :refer :all] [runbld.io :as io] [runbld.java :as java] [runbld.opts :as opts] [runbld.test-support :as ts] [schema.test])) (use-fixtures :once schema.test/validate-schemas) (use-fixtures :each (ts/redirect-logging-fixture)) (deftest basic (let [java-home (:home (java/jvm-facts)) program (if (opts/windows?) "CMD.EXE" "zsh")] (is (= {:program program :args (if (opts/windows?) ["/C"] ["-x"]) :inherit-exit-code true :inherit-env false, :scriptfile "/path/to/script.zsh" The case will resolve differently on Windows between :cwd (io/abspath (System/getProperty "user.dir")) :stdout ".stdout.log" :stderr ".stderr.log" :output ".output.log" :env {:JAVA_HOME java-home}} (:process (opts/parse-args ["-c" "test/config/opts.yml" "-j" "test,foo,master" "--java-home" java-home "-p" program "/path/to/script.zsh"])))))) (deftest profile1 (let [java-home (:home (java/jvm-facts)) program (if (opts/windows?) "CMD.EXE" "zsh")] (is (= {:from "" :to ""} (-> ["-c" "test/config/opts.yml" "-j" "test,foo,master" "-p" program "--java-home" java-home "/path/to/script.zsh"] opts/parse-args :email (select-keys [:from :to])))))) (deftest stdin (let [java-home (:home (java/jvm-facts)) prog "l33t code" scriptfile (-> ["-c" "test/config/opts.yml" "-j" "test,foo,master" "--java-home" java-home (opts/make-script "-" (java.io.StringReader. prog))] opts/parse-args :process :scriptfile)] (is (re-find #".*stdin.*" scriptfile)) (is (= prog (slurp scriptfile)))))
db6d5c2869ab4d616b4668db6073768bc0c5a6dfc26ce8804d93e6a79b93a96b
EligiusSantori/L2Apf
server_list.scm
(module system racket/base (provide login-client-packet/server-list) (require "../../packet.scm") (define (login-client-packet/server-list struct) (let ((s (open-output-bytes))) (begin (write-byte #x05 s) (write-bytes (cdr (assoc 'login-key struct)) s) (write-byte #x04 s) (write-bytes (make-bytes 6) s) (write-bytes (checksum (get-output-bytes s)) s) (write-bytes (make-bytes 4) s) (get-output-bytes s) ) ) ) )
null
https://raw.githubusercontent.com/EligiusSantori/L2Apf/30ffe0828e8a401f58d39984efd862c8aeab8c30/packet/login/client/server_list.scm
scheme
(module system racket/base (provide login-client-packet/server-list) (require "../../packet.scm") (define (login-client-packet/server-list struct) (let ((s (open-output-bytes))) (begin (write-byte #x05 s) (write-bytes (cdr (assoc 'login-key struct)) s) (write-byte #x04 s) (write-bytes (make-bytes 6) s) (write-bytes (checksum (get-output-bytes s)) s) (write-bytes (make-bytes 4) s) (get-output-bytes s) ) ) ) )
e98fb6415defb120174118975176bee9ac8f9bd36b85979f55f76a20fdf4a548
heraldry/heraldicon
motto.cljs
(ns heraldicon.frontend.component.motto (:require [heraldicon.context :as c] [heraldicon.frontend.component.core :as component] [heraldicon.frontend.component.ribbon :as ribbon] [heraldicon.frontend.element.core :as element] [heraldicon.frontend.language :refer [tr]] [heraldicon.interface :as interface] [heraldicon.localization.string :as string] [heraldicon.util.core :as util] [re-frame.core :as rf])) (rf/reg-sub ::name (fn [[_ path] _] (rf/subscribe [:get (drop-last path)])) (fn [elements [_ path]] ;; TODO: fix numbering/naming (let [idx (last path) mottos (keep-indexed (fn [idx element] (when (-> element :type (= :heraldry.motto.type/motto)) idx)) elements) slogans (keep-indexed (fn [idx element] (when (-> element :type (= :heraldry.motto.type/slogan)) idx)) elements) relevant-elements (if (some (set [idx]) mottos) mottos slogans)] (string/str-tr (when (-> relevant-elements count (> 1)) (str (inc (util/index-of idx relevant-elements)) ". ")) (if (= relevant-elements mottos) :string.entity/motto :string.entity/slogan))))) (defn- form [context] [:<> (element/elements context [:type :anchor :geometry]) [:div {:style {:font-size "1.3em" :margin-top "0.5em" :margin-bottom "0.5em"}} [tr :string.entity/tincture]] (element/elements context [:tincture-foreground :tincture-background :tincture-text]) [:div {:style {:font-size "1.3em" :margin-top "0.5em" :margin-bottom "0.5em"}} [tr :string.entity/ribbon]] [element/element (c/++ context :ribbon-variant)] (when (interface/get-raw-data (c/++ context :ribbon-variant)) (let [ribbon-context (c/++ context :ribbon)] [:<> [ribbon/form ribbon-context] [ribbon/segments-form ribbon-context]]))]) (defmethod component/node :heraldry/motto [{:keys [path]}] {:title @(rf/subscribe [::name path])}) (defmethod component/form :heraldry/motto [_context] form)
null
https://raw.githubusercontent.com/heraldry/heraldicon/f742958ce1e85f47c8222f99c6c594792ac5a793/src/heraldicon/frontend/component/motto.cljs
clojure
TODO: fix numbering/naming
(ns heraldicon.frontend.component.motto (:require [heraldicon.context :as c] [heraldicon.frontend.component.core :as component] [heraldicon.frontend.component.ribbon :as ribbon] [heraldicon.frontend.element.core :as element] [heraldicon.frontend.language :refer [tr]] [heraldicon.interface :as interface] [heraldicon.localization.string :as string] [heraldicon.util.core :as util] [re-frame.core :as rf])) (rf/reg-sub ::name (fn [[_ path] _] (rf/subscribe [:get (drop-last path)])) (fn [elements [_ path]] (let [idx (last path) mottos (keep-indexed (fn [idx element] (when (-> element :type (= :heraldry.motto.type/motto)) idx)) elements) slogans (keep-indexed (fn [idx element] (when (-> element :type (= :heraldry.motto.type/slogan)) idx)) elements) relevant-elements (if (some (set [idx]) mottos) mottos slogans)] (string/str-tr (when (-> relevant-elements count (> 1)) (str (inc (util/index-of idx relevant-elements)) ". ")) (if (= relevant-elements mottos) :string.entity/motto :string.entity/slogan))))) (defn- form [context] [:<> (element/elements context [:type :anchor :geometry]) [:div {:style {:font-size "1.3em" :margin-top "0.5em" :margin-bottom "0.5em"}} [tr :string.entity/tincture]] (element/elements context [:tincture-foreground :tincture-background :tincture-text]) [:div {:style {:font-size "1.3em" :margin-top "0.5em" :margin-bottom "0.5em"}} [tr :string.entity/ribbon]] [element/element (c/++ context :ribbon-variant)] (when (interface/get-raw-data (c/++ context :ribbon-variant)) (let [ribbon-context (c/++ context :ribbon)] [:<> [ribbon/form ribbon-context] [ribbon/segments-form ribbon-context]]))]) (defmethod component/node :heraldry/motto [{:keys [path]}] {:title @(rf/subscribe [::name path])}) (defmethod component/form :heraldry/motto [_context] form)
2870d78e72c3c79a39bb1e0d4c072fdca2a1b815d26cd5714a1442c7a1f698db
fdlk/advent-2019
project.clj
(defproject advent-2019 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [criterium "0.4.5"] [org.clojure/math.combinatorics "0.1.6"] [org.clojure/data.priority-map "0.0.10"] [org.clojure/math.numeric-tower "0.0.4"]] :main ^:skip-aot advent-2019.day25 :target-path "target/%s" :plugins [[lein-cljfmt "0.6.6"]] :jvm-opts ["-Xmx16g"] :profiles {:uberjar {:aot :all}})
null
https://raw.githubusercontent.com/fdlk/advent-2019/e7496448f9b67a550ac091f0df24d9890f437766/project.clj
clojure
(defproject advent-2019 "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "EPL-2.0 OR GPL-2.0-or-later WITH Classpath-exception-2.0" :url "-2.0/"} :dependencies [[org.clojure/clojure "1.10.0"] [criterium "0.4.5"] [org.clojure/math.combinatorics "0.1.6"] [org.clojure/data.priority-map "0.0.10"] [org.clojure/math.numeric-tower "0.0.4"]] :main ^:skip-aot advent-2019.day25 :target-path "target/%s" :plugins [[lein-cljfmt "0.6.6"]] :jvm-opts ["-Xmx16g"] :profiles {:uberjar {:aot :all}})
b050029b0f59cd726ad32f83406d5dc4ef73cdc95b9b61ad874e7056f5a41481
helmutkian/cl-wasm-runtime
test-engine.lisp
(in-package #:cl-wasm-runtime.test) (5am:def-suite cl-wasm-runtime.test.engine :in cl-wasm-runtime.test) (5am:in-suite cl-wasm-runtime.test.engine) (5am:test test-make-wasm-engine (5am:with-fixture test-module-fixture () (5am:finishes (let* ((engine (make-wasm-engine)) (store (make-wasm-store engine)) (module (make-wasm-module store *test-wasm-binary*)) (instance (make-wasm-instance store module)) (exports (exports instance)) (sum (get-export exports "sum" 'wasm-func))) (5am:is (= 42 (wasm-funcall sum 37 5)))))))
null
https://raw.githubusercontent.com/helmutkian/cl-wasm-runtime/a838629cd4c94c76034491dd0d7f8d10383603ed/test/test-engine.lisp
lisp
(in-package #:cl-wasm-runtime.test) (5am:def-suite cl-wasm-runtime.test.engine :in cl-wasm-runtime.test) (5am:in-suite cl-wasm-runtime.test.engine) (5am:test test-make-wasm-engine (5am:with-fixture test-module-fixture () (5am:finishes (let* ((engine (make-wasm-engine)) (store (make-wasm-store engine)) (module (make-wasm-module store *test-wasm-binary*)) (instance (make-wasm-instance store module)) (exports (exports instance)) (sum (get-export exports "sum" 'wasm-func))) (5am:is (= 42 (wasm-funcall sum 37 5)))))))
63c36b5a48ac69e3f4b0f1557dde38bae196bba82e2a79494f511e9d9ca31cb6
cmsc430/www
lambdas.rkt
#lang racket (require "ast.rkt") (provide lambdas lambdas-ds) Prog - > [ ] List all of the lambda expressions in p (define (lambdas p) (match p [(Prog ds) (lambdas-ds ds)])) Defns - > [ ] ;; List all of the lambda expressions in ds (define (lambdas-ds ds) (match ds ['() '()] [(cons (Defn f l) ds) (append (lambdas-e l) (lambdas-ds ds))])) Expr - > [ ] ;; List all of the lambda expressions in e (define (lambdas-e e) (match e [(Prim p es) (append-map lambdas-e es)] [(If e1 e2 e3) (append (lambdas-e e1) (lambdas-e e2) (lambdas-e e3))] [(Begin es) (append-map lambdas-e es)] [(Let xs es e) (append (append-map lambdas-e es) (lambdas-e e))] [(App e1 es) (append (lambdas-e e1) (append-map lambdas-e es))] [(Lam f xs e1) (cons e (lambdas-e e1))] [(LamRest f xs x e1) (cons e (lambdas-e e1))] [(LamCase f cs) (cons e (lambdas-cs cs))] [(Apply e es el) (append (lambdas-e e) (append-map lambdas-e es) (lambdas-e el))] [(Match e ps es) (append (lambdas-e e) (append-map lambdas-pat ps) (append-map lambdas-e es))] [_ '()])) [ LamCaseClause ] - > [ ] (define (lambdas-cs cs) (match cs ['() '()] [(cons (Lam f xs e) cs) (append (lambdas-e e) (lambdas-cs cs))] [(cons (LamRest f xs x e) cs) (append (lambdas-e e) (lambdas-cs cs))])) Pat - > [ ] (define (lambdas-pat p) (match p [(PBox p) (lambdas-pat p)] [(PCons p1 p2) (append (lambdas-pat p1) (lambdas-pat p2))] [(PAnd p1 p2) (append (lambdas-pat p1) (lambdas-pat p2))] [(PStruct n ps) (append-map lambdas-pat ps)] [(PPred e) (lambdas-e e)] [_ '()]))
null
https://raw.githubusercontent.com/cmsc430/www/3a2cc63191b75e477660961794958cead7cae35a/langs/outlaw/lambdas.rkt
racket
List all of the lambda expressions in ds List all of the lambda expressions in e
#lang racket (require "ast.rkt") (provide lambdas lambdas-ds) Prog - > [ ] List all of the lambda expressions in p (define (lambdas p) (match p [(Prog ds) (lambdas-ds ds)])) Defns - > [ ] (define (lambdas-ds ds) (match ds ['() '()] [(cons (Defn f l) ds) (append (lambdas-e l) (lambdas-ds ds))])) Expr - > [ ] (define (lambdas-e e) (match e [(Prim p es) (append-map lambdas-e es)] [(If e1 e2 e3) (append (lambdas-e e1) (lambdas-e e2) (lambdas-e e3))] [(Begin es) (append-map lambdas-e es)] [(Let xs es e) (append (append-map lambdas-e es) (lambdas-e e))] [(App e1 es) (append (lambdas-e e1) (append-map lambdas-e es))] [(Lam f xs e1) (cons e (lambdas-e e1))] [(LamRest f xs x e1) (cons e (lambdas-e e1))] [(LamCase f cs) (cons e (lambdas-cs cs))] [(Apply e es el) (append (lambdas-e e) (append-map lambdas-e es) (lambdas-e el))] [(Match e ps es) (append (lambdas-e e) (append-map lambdas-pat ps) (append-map lambdas-e es))] [_ '()])) [ LamCaseClause ] - > [ ] (define (lambdas-cs cs) (match cs ['() '()] [(cons (Lam f xs e) cs) (append (lambdas-e e) (lambdas-cs cs))] [(cons (LamRest f xs x e) cs) (append (lambdas-e e) (lambdas-cs cs))])) Pat - > [ ] (define (lambdas-pat p) (match p [(PBox p) (lambdas-pat p)] [(PCons p1 p2) (append (lambdas-pat p1) (lambdas-pat p2))] [(PAnd p1 p2) (append (lambdas-pat p1) (lambdas-pat p2))] [(PStruct n ps) (append-map lambdas-pat ps)] [(PPred e) (lambdas-e e)] [_ '()]))
0256d6112e1b6bd89fd8f18db0f26aa81537d74207f7f824b253c93b42f43398
nanit/kubernetes-custom-hpa
server.clj
(ns custom-hpa.web.server (:require [taoensso.timbre :as logger] [compojure.core :refer [defroutes GET]] [org.httpkit.server :as http-kit] [custom-hpa.monitor.prometheus :as prometheus])) (defonce ^:private server (atom nil)) (defroutes app-routes (GET "/ping" [] {:status 200 :body "pong"}) (GET "/metrics" [] {:status 200 :body (prometheus/export)})) (defn- stop-server [] (@server :timeout 5000) (reset! server nil)) (defn start [port] (logger/debug "Starting web server") (.addShutdownHook (Runtime/getRuntime) (Thread. stop-server)) (reset! server (http-kit/run-server app-routes {:port port})))
null
https://raw.githubusercontent.com/nanit/kubernetes-custom-hpa/e6f07f271336c3ede1e8cdfcf426f639469c2f33/app/src/custom_hpa/web/server.clj
clojure
(ns custom-hpa.web.server (:require [taoensso.timbre :as logger] [compojure.core :refer [defroutes GET]] [org.httpkit.server :as http-kit] [custom-hpa.monitor.prometheus :as prometheus])) (defonce ^:private server (atom nil)) (defroutes app-routes (GET "/ping" [] {:status 200 :body "pong"}) (GET "/metrics" [] {:status 200 :body (prometheus/export)})) (defn- stop-server [] (@server :timeout 5000) (reset! server nil)) (defn start [port] (logger/debug "Starting web server") (.addShutdownHook (Runtime/getRuntime) (Thread. stop-server)) (reset! server (http-kit/run-server app-routes {:port port})))
9b1f709d5d7659fd464f2aa3bb238c44ad79a967c180060d6ac22962712e8726
tek/ribosome
Settings.hs
|The effect ' Settings ' abstracts Neovim variables module Ribosome.Effect.Settings where import Prelude hiding (get) import Ribosome.Data.Setting (Setting) import Ribosome.Data.SettingError (SettingError) import Ribosome.Host.Class.Msgpack.Decode (MsgpackDecode) import Ribosome.Host.Class.Msgpack.Encode (MsgpackEncode) |This effects abstracts Neovim variables with associated defaults . data Settings :: Effect where |Get the value of the setting 's Neovim variable or return the default if it is undefined . Get :: MsgpackDecode a => Setting a -> Settings m a |Set the value of the setting 's Neovim variable . Update :: MsgpackEncode a => Setting a -> a -> Settings m () makeSem_ ''Settings |Get the value of the setting 's Neovim variable or return the default if it is undefined . get :: ∀ a r . MsgpackDecode a => Member Settings r => Setting a -> Sem r a |Set the value of the setting 's Neovim variable . update :: ∀ a r . MsgpackEncode a => Member Settings r => Setting a -> a -> Sem r () |Get the setting 's value or return the supplied fallback value if the Neovim variable is undefined and the setting -- has no default value. or :: MsgpackDecode a => Member (Settings !! SettingError) r => a -> Setting a -> Sem r a or a s = a <! get s |Get ' Just ' the setting 's value or return ' Nothing ' if the Neovim variable is undefined and the setting has no -- default value. maybe :: MsgpackDecode a => Member (Settings !! SettingError) r => Setting a -> Sem r (Maybe a) maybe s = Nothing <! (Just <$> get s)
null
https://raw.githubusercontent.com/tek/ribosome/a676b4f0085916777bfdacdcc761f82d933edb80/packages/ribosome/lib/Ribosome/Effect/Settings.hs
haskell
has no default value. default value.
|The effect ' Settings ' abstracts Neovim variables module Ribosome.Effect.Settings where import Prelude hiding (get) import Ribosome.Data.Setting (Setting) import Ribosome.Data.SettingError (SettingError) import Ribosome.Host.Class.Msgpack.Decode (MsgpackDecode) import Ribosome.Host.Class.Msgpack.Encode (MsgpackEncode) |This effects abstracts Neovim variables with associated defaults . data Settings :: Effect where |Get the value of the setting 's Neovim variable or return the default if it is undefined . Get :: MsgpackDecode a => Setting a -> Settings m a |Set the value of the setting 's Neovim variable . Update :: MsgpackEncode a => Setting a -> a -> Settings m () makeSem_ ''Settings |Get the value of the setting 's Neovim variable or return the default if it is undefined . get :: ∀ a r . MsgpackDecode a => Member Settings r => Setting a -> Sem r a |Set the value of the setting 's Neovim variable . update :: ∀ a r . MsgpackEncode a => Member Settings r => Setting a -> a -> Sem r () |Get the setting 's value or return the supplied fallback value if the Neovim variable is undefined and the setting or :: MsgpackDecode a => Member (Settings !! SettingError) r => a -> Setting a -> Sem r a or a s = a <! get s |Get ' Just ' the setting 's value or return ' Nothing ' if the Neovim variable is undefined and the setting has no maybe :: MsgpackDecode a => Member (Settings !! SettingError) r => Setting a -> Sem r (Maybe a) maybe s = Nothing <! (Just <$> get s)
5556b21c19bbffd27cfc3f96ab5e94bc7bcee4fedde4332d71bc96aa35a5fd1c
wireapp/wire-server
V72_DropManagedConversations.hs
-- This file is part of the Wire Server implementation. -- Copyright ( C ) 2022 Wire Swiss GmbH < > -- -- 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 </>. module V72_DropManagedConversations where import Cassandra.Schema import Imports import Text.RawString.QQ migration :: Migration migration = Migration 72 "Drop the managed column from team_conv" $ do schema' [r| ALTER TABLE team_conv DROP ( managed ); |]
null
https://raw.githubusercontent.com/wireapp/wire-server/40f81847fc80c564f8d356d32c5063470f8a7315/services/galley/schema/src/V72_DropManagedConversations.hs
haskell
This file is part of the Wire Server implementation. This program is free software: you can redistribute it and/or modify it under 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. with this program. If not, see </>.
Copyright ( C ) 2022 Wire Swiss GmbH < > 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 You should have received a copy of the GNU Affero General Public License along module V72_DropManagedConversations where import Cassandra.Schema import Imports import Text.RawString.QQ migration :: Migration migration = Migration 72 "Drop the managed column from team_conv" $ do schema' [r| ALTER TABLE team_conv DROP ( managed ); |]
6f45f44ec4a2a9ab25b24f79640e5167391ca5027c99f8d559a9e3de6de4a91e
tech-sketch/functional_programming_parallelism_sample
core.clj
(ns par3.core (:require [clojure.java.io :as io] [clojure.string :as cs]) (:import [org.atilika.kuromoji Tokenizer Token]) (:gen-class)) (defn readFile [file enc] (with-open [rdr (io/reader file :encoding enc)] (doall (line-seq rdr)))) (defn morphological [lines] (let [tokenizer (.build (Tokenizer/builder)) tokens (flatten (map #(into [] (.tokenize tokenizer %)) lines)) parts ["名詞" "動詞" "形容詞" "副詞"]] (map (fn [token] (if (.isKnown token) (.getBaseForm token) (.getSurfaceForm token))) (filter (fn [token] (some #(= (first (cs/split (.getPartOfSpeech token) #",")) %) parts)) tokens)))) (defn combiner [words] (map #(vector (first %) (count (second %))) (group-by str words))) (defn wordCount [futures] (let [combined (apply concat (map deref futures))] (sort-by second > (map (fn [w] (vector (first w) (reduce + (map #(second %) (second w))))) (group-by #(first %) combined))))) (defn -main [file enc] (let [nthreads (.. Runtime getRuntime availableProcessors) lines (readFile file enc) fragments (partition-all (quot (count lines) nthreads) lines) futures (map #(future (combiner (morphological %))) fragments)] (println (apply str (map #(str (first %) ":" (second %) "\n") (wordCount (doall futures))))) (shutdown-agents)))
null
https://raw.githubusercontent.com/tech-sketch/functional_programming_parallelism_sample/7d045754363aaa7768e2732dba13cd56ccab120f/clojure/par3/src/par3/core.clj
clojure
(ns par3.core (:require [clojure.java.io :as io] [clojure.string :as cs]) (:import [org.atilika.kuromoji Tokenizer Token]) (:gen-class)) (defn readFile [file enc] (with-open [rdr (io/reader file :encoding enc)] (doall (line-seq rdr)))) (defn morphological [lines] (let [tokenizer (.build (Tokenizer/builder)) tokens (flatten (map #(into [] (.tokenize tokenizer %)) lines)) parts ["名詞" "動詞" "形容詞" "副詞"]] (map (fn [token] (if (.isKnown token) (.getBaseForm token) (.getSurfaceForm token))) (filter (fn [token] (some #(= (first (cs/split (.getPartOfSpeech token) #",")) %) parts)) tokens)))) (defn combiner [words] (map #(vector (first %) (count (second %))) (group-by str words))) (defn wordCount [futures] (let [combined (apply concat (map deref futures))] (sort-by second > (map (fn [w] (vector (first w) (reduce + (map #(second %) (second w))))) (group-by #(first %) combined))))) (defn -main [file enc] (let [nthreads (.. Runtime getRuntime availableProcessors) lines (readFile file enc) fragments (partition-all (quot (count lines) nthreads) lines) futures (map #(future (combiner (morphological %))) fragments)] (println (apply str (map #(str (first %) ":" (second %) "\n") (wordCount (doall futures))))) (shutdown-agents)))
3b61e522169f4fe2e283664a8d02b81eda05ed529edc87809a1e9dedcd78427b
ghcjs/ghcjs-base
Types.hs
{-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE PolyKinds # module JavaScript.TypedArray.Internal.Types where import GHCJS.Types import GHCJS.Internal.Types import Data.Int import Data.Typeable import Data.Word newtype SomeTypedArray (e :: TypedArrayElem) (m :: MutabilityType s) = SomeTypedArray JSVal deriving Typeable instance IsJSVal (SomeTypedArray e m) newtype SomeSTTypedArray s e = SomeSTTypedArray deriving ( ) newtype SomeSTTypedArray s e = SomeSTTypedArray JSVal deriving (Typeable) -} type SomeSTTypedArray s (e :: TypedArrayElem) = SomeTypedArray e (STMutable s) -- ----------------------------------------------------------------------------- data TypedArrayElem = Int8Elem | Int16Elem | Int32Elem | Uint8Elem | Uint16Elem | Uint32Elem | Uint8ClampedElem | Float32Elem | Float64Elem -- ----------------------------------------------------------------------------- type SomeInt8Array = SomeTypedArray Int8Elem type SomeInt16Array = SomeTypedArray Int16Elem type SomeInt32Array = SomeTypedArray Int32Elem type SomeUint8Array = SomeTypedArray Uint8Elem type SomeUint16Array = SomeTypedArray Uint16Elem type SomeUint32Array = SomeTypedArray Uint32Elem type SomeFloat32Array = SomeTypedArray Float32Elem type SomeFloat64Array = SomeTypedArray Float64Elem type SomeUint8ClampedArray = SomeTypedArray Uint8ClampedElem -- ----------------------------------------------------------------------------- type Int8Array = SomeInt8Array Immutable type Int16Array = SomeInt16Array Immutable type Int32Array = SomeInt32Array Immutable type Uint8Array = SomeUint8Array Immutable type Uint16Array = SomeUint16Array Immutable type Uint32Array = SomeUint32Array Immutable type Uint8ClampedArray = SomeUint8ClampedArray Immutable type Float32Array = SomeFloat32Array Immutable type Float64Array = SomeFloat64Array Immutable -- ----------------------------------------------------------------------------- type IOInt8Array = SomeInt8Array Mutable type IOInt16Array = SomeInt16Array Mutable type IOInt32Array = SomeInt32Array Mutable type IOUint8Array = SomeUint8Array Mutable type IOUint16Array = SomeUint16Array Mutable type IOUint32Array = SomeUint32Array Mutable type IOUint8ClampedArray = SomeUint8ClampedArray Mutable type IOFloat32Array = SomeFloat32Array Mutable type IOFloat64Array = SomeFloat64Array Mutable -- ----------------------------------------------------------------------------- type STInt8Array s = SomeSTTypedArray s Int8Elem type STInt16Array s = SomeSTTypedArray s Int16Elem type STInt32Array s = SomeSTTypedArray s Int32Elem type STUint8Array s = SomeSTTypedArray s Uint8Elem type STUint16Array s = SomeSTTypedArray s Uint16Elem type STUint32Array s = SomeSTTypedArray s Uint32Elem type STFloat32Array s = SomeSTTypedArray s Float32Elem type STFloat64Array s = SomeSTTypedArray s Float64Elem type STUint8ClampedArray s = SomeSTTypedArray s Uint8ClampedElem -- ----------------------------------------------------------------------------- type family Elem x where Elem (SomeUint8Array m) = Word8 Elem (SomeUint8ClampedArray m) = Word8 Elem (SomeUint16Array m) = Word16 Elem (SomeUint32Array m) = Word Elem (SomeInt8Array m) = Int8 Elem (SomeInt16Array m) = Int16 Elem (SomeInt32Array m) = Int Elem (SomeFloat32Array m) = Double Elem (SomeFloat64Array m) = Double Elem (STUint8Array s) = Word8 Elem (STUint8ClampedArray s) = Word8 Elem (STUint16Array s) = Word16 Elem (STUint32Array s) = Word Elem (STInt8Array s) = Int8 Elem (STInt16Array s) = Int16 Elem (STInt32Array s) = Int Elem (STFloat32Array s) = Double Elem (STFloat64Array s) = Double
null
https://raw.githubusercontent.com/ghcjs/ghcjs-base/18f31dec5d9eae1ef35ff8bbf163394942efd227/JavaScript/TypedArray/Internal/Types.hs
haskell
# LANGUAGE DeriveDataTypeable # ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -----------------------------------------------------------------------------
# LANGUAGE TypeFamilies # # LANGUAGE DataKinds # # LANGUAGE PolyKinds # module JavaScript.TypedArray.Internal.Types where import GHCJS.Types import GHCJS.Internal.Types import Data.Int import Data.Typeable import Data.Word newtype SomeTypedArray (e :: TypedArrayElem) (m :: MutabilityType s) = SomeTypedArray JSVal deriving Typeable instance IsJSVal (SomeTypedArray e m) newtype SomeSTTypedArray s e = SomeSTTypedArray deriving ( ) newtype SomeSTTypedArray s e = SomeSTTypedArray JSVal deriving (Typeable) -} type SomeSTTypedArray s (e :: TypedArrayElem) = SomeTypedArray e (STMutable s) data TypedArrayElem = Int8Elem | Int16Elem | Int32Elem | Uint8Elem | Uint16Elem | Uint32Elem | Uint8ClampedElem | Float32Elem | Float64Elem type SomeInt8Array = SomeTypedArray Int8Elem type SomeInt16Array = SomeTypedArray Int16Elem type SomeInt32Array = SomeTypedArray Int32Elem type SomeUint8Array = SomeTypedArray Uint8Elem type SomeUint16Array = SomeTypedArray Uint16Elem type SomeUint32Array = SomeTypedArray Uint32Elem type SomeFloat32Array = SomeTypedArray Float32Elem type SomeFloat64Array = SomeTypedArray Float64Elem type SomeUint8ClampedArray = SomeTypedArray Uint8ClampedElem type Int8Array = SomeInt8Array Immutable type Int16Array = SomeInt16Array Immutable type Int32Array = SomeInt32Array Immutable type Uint8Array = SomeUint8Array Immutable type Uint16Array = SomeUint16Array Immutable type Uint32Array = SomeUint32Array Immutable type Uint8ClampedArray = SomeUint8ClampedArray Immutable type Float32Array = SomeFloat32Array Immutable type Float64Array = SomeFloat64Array Immutable type IOInt8Array = SomeInt8Array Mutable type IOInt16Array = SomeInt16Array Mutable type IOInt32Array = SomeInt32Array Mutable type IOUint8Array = SomeUint8Array Mutable type IOUint16Array = SomeUint16Array Mutable type IOUint32Array = SomeUint32Array Mutable type IOUint8ClampedArray = SomeUint8ClampedArray Mutable type IOFloat32Array = SomeFloat32Array Mutable type IOFloat64Array = SomeFloat64Array Mutable type STInt8Array s = SomeSTTypedArray s Int8Elem type STInt16Array s = SomeSTTypedArray s Int16Elem type STInt32Array s = SomeSTTypedArray s Int32Elem type STUint8Array s = SomeSTTypedArray s Uint8Elem type STUint16Array s = SomeSTTypedArray s Uint16Elem type STUint32Array s = SomeSTTypedArray s Uint32Elem type STFloat32Array s = SomeSTTypedArray s Float32Elem type STFloat64Array s = SomeSTTypedArray s Float64Elem type STUint8ClampedArray s = SomeSTTypedArray s Uint8ClampedElem type family Elem x where Elem (SomeUint8Array m) = Word8 Elem (SomeUint8ClampedArray m) = Word8 Elem (SomeUint16Array m) = Word16 Elem (SomeUint32Array m) = Word Elem (SomeInt8Array m) = Int8 Elem (SomeInt16Array m) = Int16 Elem (SomeInt32Array m) = Int Elem (SomeFloat32Array m) = Double Elem (SomeFloat64Array m) = Double Elem (STUint8Array s) = Word8 Elem (STUint8ClampedArray s) = Word8 Elem (STUint16Array s) = Word16 Elem (STUint32Array s) = Word Elem (STInt8Array s) = Int8 Elem (STInt16Array s) = Int16 Elem (STInt32Array s) = Int Elem (STFloat32Array s) = Double Elem (STFloat64Array s) = Double
57001772b5e4b5fe3a968ee7a6a985739d9c4f5e448af53722046d7f769033a4
Eonblast/Trinity
hello.erl
: Supervisor and Gen Server Skeleton % ----------------------------------------------- file : eonbeam / dev/3 / i_supervisortest2 / hello.erl % This file is just a preliminary test, not really important. % Starts, tests and terminates the hello_gen_server directly, without supervisor. % Then uses the supervisor to start and restart the genserver, checking responses. % Start with: erl -s hello run -s init stop -noshell -module(hello). -export([run/0]). run() -> %% DIRECT PART: (identical to h) ---------------------------------- io:format("hello: starting gen_server (directly, stand alone)~n"), {ok, GenServer} = hello_gen_server:start_link(), io:format("hello: sending hello to gen_server~n"), world = gen_server:call(GenServer, hello), io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(GenServer, stop), io:format("hello: gen_server stopped~n"), receive after 100 -> nil end, % let stop %% SUPERVISOR PART: ----------------------------------------------- io:format("- - -~n"), % kind of magicians gesture: check that the gen server is not running anymore undefined = whereis(hello_gen_server), io:format("hello: starting supervisor (will NOT start gen server) **~n"), {ok, SuperPid} = hello_supervisor:start_link(), % ** different from h ** io:format("hello: add dynamic gen server child to the supervisor **~n"), {ok, _} = supervisor:start_child(SuperPid, % child specs: {hello_gen_server, % child id (a special kind of id!) MFA permanent, % kind (permantent = always restart) 1, % max time to shutdown worker, % type [hello_gen_server] % used modules (for code changes) }), % ------------------------------------------------ io:format("hello: sending hello to gen_server~n"), world = gen_server:call(hello_gen_server, hello), % ------------------------------------------------ io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(hello_gen_server, stop), io:format("hello: gen_server stopped (but the supervisor should restart it)~n"), receive after 100 -> nil end, % let restart % check that the gen server is in fact running again true = erlang:is_process_alive(whereis(hello_gen_server)), io:format("hello: sending hello to gen_server~n"), world = gen_server:call(hello_gen_server, hello), io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(hello_gen_server, stop), io:format("hello: gen_server stopped (and now the supervisor should NOT restart it)~n"), because of the strategy set in hello_supervisor.erl receive after 100 -> nil end, % let restart (not, of course) % check that the gen server process is really gone. undefined = whereis(hello_gen_server), io:format("hello: bingo~n"), % else would have crashed before ok.
null
https://raw.githubusercontent.com/Eonblast/Trinity/15bcc0fa0997d7dd360f1542493e63208645bd88/i_supervisortest2/hello.erl
erlang
----------------------------------------------- This file is just a preliminary test, not really important. Starts, tests and terminates the hello_gen_server directly, without supervisor. Then uses the supervisor to start and restart the genserver, checking responses. Start with: erl -s hello run -s init stop -noshell DIRECT PART: (identical to h) ---------------------------------- let stop SUPERVISOR PART: ----------------------------------------------- kind of magicians gesture: check that the gen server is not running anymore ** different from h ** child specs: child id (a special kind of id!) kind (permantent = always restart) max time to shutdown type used modules (for code changes) ------------------------------------------------ ------------------------------------------------ let restart check that the gen server is in fact running again let restart (not, of course) check that the gen server process is really gone. else would have crashed before
: Supervisor and Gen Server Skeleton file : eonbeam / dev/3 / i_supervisortest2 / hello.erl -module(hello). -export([run/0]). run() -> io:format("hello: starting gen_server (directly, stand alone)~n"), {ok, GenServer} = hello_gen_server:start_link(), io:format("hello: sending hello to gen_server~n"), world = gen_server:call(GenServer, hello), io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(GenServer, stop), io:format("hello: gen_server stopped~n"), io:format("- - -~n"), undefined = whereis(hello_gen_server), io:format("hello: starting supervisor (will NOT start gen server) **~n"), {ok, SuperPid} = hello_supervisor:start_link(), io:format("hello: add dynamic gen server child to the supervisor **~n"), {ok, _} = supervisor:start_child(SuperPid, MFA }), io:format("hello: sending hello to gen_server~n"), world = gen_server:call(hello_gen_server, hello), io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(hello_gen_server, stop), io:format("hello: gen_server stopped (but the supervisor should restart it)~n"), true = erlang:is_process_alive(whereis(hello_gen_server)), io:format("hello: sending hello to gen_server~n"), world = gen_server:call(hello_gen_server, hello), io:format("hello: sending stop to gen_server~n"), ok = gen_server:call(hello_gen_server, stop), io:format("hello: gen_server stopped (and now the supervisor should NOT restart it)~n"), because of the strategy set in hello_supervisor.erl undefined = whereis(hello_gen_server), ok.
13ebe7d675e0a30c500fa49b313114c8fc0f3f096cda37d3ef9c28aafed4f833
dym/movitz
functions.lisp
;;;;------------------------------------------------------------------ ;;;; Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . ;;;; ;;;; For distribution policy, see the accompanying file COPYING. ;;;; ;;;; Filename: functions.lisp ;;;; Description: Misc. function-oriented functions Author : < > Created at : Tue Mar 12 22:58:54 2002 ;;;; $ I d : functions.lisp , v 1.32 2009 - 07 - 19 18:58:33 Exp $ ;;;; ;;;;------------------------------------------------------------------ (require :muerte/basic-macros) (require :muerte/setf) (provide :muerte/functions) (in-package muerte) (defvar *setf-namespace* nil "This hash-table is initialized by dump-image.") (defun identity (x) x) (defun constantly-prototype (&rest ignore) (declare (ignore ignore)) 'value) (defun constantly-true (&rest ignore) (declare (ignore ignore)) t) (defun constantly-false (&rest ignore) (declare (ignore ignore)) nil) (define-compiler-macro constantly (&whole form value-form &environment env) (cond ((movitz:movitz-constantp value-form env) (let ((value (movitz:movitz-eval value-form env))) (case (translate-program value :muerte.cl :cl) ((t) `(function constantly-true)) ((nil) `(function constantly-false)) (t form)))) (t form))) (defun constantly (x) (lambda () x)) (defun complement-prototype (&rest args) (declare (dynamic-extent args)) (not (apply 'function args))) (define-compiler-macro complement (&whole form function-form &environment env) (cond ((and (listp function-form) (eq 'function (first function-form)) (typep (movitz:movitz-eval (translate-program function-form :cl :muerte.cl) env) 'movitz:movitz-funobj)) `(make-prototyped-function `(complement ,(second function-form)) complement-prototype ,(movitz:movitz-eval (translate-program function-form :cl :muerte.cl)))) (t form))) (defun complement (function) (lambda (&rest args) (declare (dynamic-extent args)) (not (apply function args)))) (defun unbound-function (&edx edx &rest args) "This is the function that is the unbound value for function cells." (declare (dynamic-extent args)) (let ((function-name (typecase edx (symbol edx) (compiled-function (funobj-name edx)) (t '(unknown))))) ;; (when los0::*funbound-counter* ( incf ( gethash function - name los0::*funbound - counter * 0 ) ) ) (with-simple-restart (continue "Return NIL from ~S." function-name) (error 'undefined-function-call :name function-name :arguments (copy-list args)))) nil) funobj object (defun funobj-type (funobj) (check-type funobj function) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:xorl :ecx :ecx) (:compile-form (:result-mode :eax) funobj) (:movb (:eax (:offset movitz-funobj funobj-type)) :cl))) (defun (setf funobj-type) (type funobj) (check-type funobj function) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:compile-two-forms (:eax :untagged-fixnum-ecx) funobj type) (:movb :cl (:eax (:offset movitz-funobj funobj-type))))) (defun funobj-code-vector (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'code-vector) :type :code-vector)) (defun (setf funobj-code-vector) (code-vector funobj) (check-type funobj function) (check-type code-vector code-vector) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'code-vector) :type :code-vector) code-vector)) (defun funobj-code-vector%1op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) ;; Set up atomically continuation. (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) ;; ..this allows us to detect recursive atomicallies. (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) ;; Now inside atomically section. (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%1op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) ;; return the integer offset (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%1op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%1op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%1op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:addl 2 :eax) ; this cell stores word+2 (:movl :eax (:ebx (:offset movitz-funobj code-vector%1op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%1op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%1op)))))) code-vector) (defun funobj-code-vector%2op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) ;; Set up atomically continuation. (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) ;; ..this allows us to detect recursive atomicallies. (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) ;; Now inside atomically section. (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%2op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) return the integer offset EAX - EBX (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%2op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%2op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%2op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:addl 2 :eax) ; this cell stores word+2 (:movl :eax (:ebx (:offset movitz-funobj code-vector%2op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%2op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%2op)))))) code-vector) (defun funobj-code-vector%3op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) ;; Set up atomically continuation. (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) ;; ..this allows us to detect recursive atomicallies. (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) ;; Now inside atomically section. (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%3op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) return the integer offset EAX - EBX (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%3op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%3op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%3op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:addl 2 :eax) ; this cell stores word+2 (:movl :eax (:ebx (:offset movitz-funobj code-vector%3op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%3op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%3op)))))) code-vector) (defun funobj-name (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'name))) (defun (setf funobj-name) (name funobj) (check-type funobj function) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'name)) name)) (defun funobj-lambda-list (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'lambda-list))) (defun (setf funobj-lambda-list) (lambda-list funobj) (check-type funobj function) (check-type lambda-list list) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'lambda-list)) lambda-list)) (defun funobj-num-constants (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-constants) :type :unsigned-byte16)) (defun (setf funobj-num-constants) (num-constants funobj) (check-type funobj function) (check-type num-constants (unsigned-byte 16)) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-constants) :type :unsigned-byte16) num-constants)) (defun funobj-num-jumpers (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-jumpers) :type :unsigned-byte14)) (defun (setf funobj-num-jumpers) (num-jumpers funobj) (check-type funobj function) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-jumpers) :type :unsigned-byte14) num-jumpers) #+ignore (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) num-jumpers funobj) (:movw :ax (:ebx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::num-jumpers))))) (defun funobj-constant-ref (funobj index) (check-type funobj function) (assert (below index (funobj-num-constants funobj)) (index) "Index ~D out of range, ~S has ~D constants." index funobj (funobj-num-constants funobj)) (if (>= index (funobj-num-jumpers funobj)) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'constant0) :index index) ;; For a jumper, return its offset relative to the code-vector. This is tricky wrt . to potential GC interrupts , because we 're doing ;; pointer arithmetics. (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ecx) funobj index) (:movl #.movitz:+code-vector-transient-word+ :ebx) (:addl (:eax #.(bt:slot-offset 'movitz:movitz-funobj 'movitz:code-vector)) :ebx) ; code-vector (word) into ebx (:subl (:eax :ecx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0)) :ebx) (:negl :ebx) (:leal ((:ebx #.movitz:+movitz-fixnum-factor+)) :eax)))) (defun (setf funobj-constant-ref) (value funobj index) (check-type funobj function) (assert (below index (funobj-num-constants funobj)) (index) "Index ~D out of range, ~S has ~D constants." index funobj (funobj-num-constants funobj)) (if (>= index (funobj-num-jumpers funobj)) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'constant0) :index index) value) (progn (assert (below value (length (funobj-code-vector funobj))) (value) "The jumper value ~D is invalid because the code-vector's size is ~D." value (length (funobj-code-vector funobj))) (progn ;; XXX without-gc (with-inline-assembly (:returns :nothing) (:compile-two-forms (:eax :edx) funobj index) (:compile-form (:result-mode :ecx) value) (:movl #.movitz:+code-vector-transient-word+ :ebx) (:addl (:eax #.(bt:slot-offset 'movitz:movitz-funobj 'movitz:code-vector)) :ebx) ; code-vector (word) into ebx (:shrl #.movitz:+movitz-fixnum-shift+ :ecx) ; value (:movl :ecx (:eax :edx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0))) (:addl :ebx (:eax :edx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0))))) value))) (defun funobj-debug-info (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'debug-info) :type :unsigned-byte16)) (defun funobj-frame-raw-locals (funobj) "The number of unboxed slots in this function's stack-frame(s)." (declare (ignore funobj)) 0) (defun funobj-frame-headers-p (funobj) "Can this function place header-vals in its stack-frame?" (declare (ignore funobj)) t) (defun make-funobj (&key (name :unnamed) (code-vector (funobj-code-vector #'constantly-prototype)) (constants nil) lambda-list) (setf code-vector (etypecase code-vector (code-vector code-vector) (list (make-array (length code-vector) :element-type 'code :initial-contents code-vector)) (vector (make-array (length code-vector) :element-type 'code :initial-contents code-vector)))) (let* ((num-constants (length constants)) (funobj (macrolet ((do-it () `(with-allocation-assembly ((+ num-constants ,(movitz::movitz-type-word-size 'movitz-funobj)) :object-register :eax :size-register :ecx) (:movl ,(movitz:tag :funobj) (:eax ,movitz:+other-type-offset+)) (:load-lexical (:lexical-binding num-constants) :edx) (:movl :edx :ecx) (:shll ,(- 16 movitz:+movitz-fixnum-shift+) :ecx) (:movl :ecx (:eax (:offset movitz-funobj num-jumpers))) (:xorl :ecx :ecx) (:xorl :ebx :ebx) (:testl :edx :edx) (:jmp 'init-done) init-loop (:movl :ecx (:eax :ebx ,movitz:+other-type-offset+)) (:addl 4 :ebx) (:cmpl :ebx :edx) (:ja 'init-loop) init-done (:leal (:edx ,(bt:sizeof 'movitz:movitz-funobj)) :ecx)))) (do-it)))) (setf (funobj-name funobj) name (funobj-code-vector funobj) code-vector ;; revert to default trampolines for now.. (funobj-code-vector%1op funobj) (symbol-value 'trampoline-funcall%1op) (funobj-code-vector%2op funobj) (symbol-value 'trampoline-funcall%2op) (funobj-code-vector%3op funobj) (symbol-value 'trampoline-funcall%3op) (funobj-lambda-list funobj) lambda-list) (do* ((i 0 (1+ i)) (p constants (cdr p)) (x (car p))) ((endp p)) (setf (funobj-constant-ref funobj i) x)) funobj)) (defun install-function (name constants code-vector) (let ((funobj (make-funobj :name name :constants constants :code-vector code-vector))) (warn "installing ~S for ~S.." funobj name) (setf (symbol-function name) funobj))) (defun replace-funobj (dst src &optional (name (funobj-name src))) "Copy each element of src to dst. Dst's num-constants must be initialized, so that we can be reasonably sure of dst's size." (assert (= (funobj-num-constants src) (funobj-num-constants dst))) (setf (funobj-name dst) name (funobj-num-jumpers dst) (funobj-num-jumpers src) (funobj-code-vector dst) (funobj-code-vector src) (funobj-code-vector%1op dst) (funobj-code-vector%1op src) (funobj-code-vector%2op dst) (funobj-code-vector%2op src) (funobj-code-vector%3op dst) (funobj-code-vector%3op src) (funobj-lambda-list dst) (funobj-lambda-list src)) (dotimes (i (funobj-num-constants src)) (setf (funobj-constant-ref dst i) (funobj-constant-ref src i))) dst) (defun copy-funobj (old-funobj) (check-type old-funobj function) (%shallow-copy-object old-funobj (+ (funobj-num-constants old-funobj) (movitz-type-word-size 'movitz-funobj)))) (defun install-funobj-name (name funobj) (setf (funobj-name funobj) name) funobj) (defun fdefinition (function-name) (etypecase function-name (symbol (symbol-function function-name)) ((cons (eql setf)) (symbol-function (gethash (cadr function-name) *setf-namespace*))))) (defun (setf fdefinition) (value function-name) (etypecase function-name (symbol (setf (symbol-function function-name) value)) ((cons (eql setf)) (let* ((setf-name (cadr function-name)) (setf-symbol (or (gethash setf-name *setf-namespace*) (setf (gethash setf-name *setf-namespace*) (make-symbol (format nil "~A-~A" 'setf 'setf-name)))))) (setf (symbol-function setf-symbol) value))))) (defun fmakunbound (function-name) (setf (fdefinition function-name) (load-global-constant unbound-function)) function-name) (defun make-macro-function (expander name) "From a regular function, such as a (lambda (form env) ...), make a bona fide macro-function." (let ((macro-function (install-funobj-name name (lambda (&edx edx &optional form env (first-extra nil extras-p) &rest more-extras) (declare (ignore first-extra more-extras)) (verify-macroexpand-call edx name extras-p) (funcall expander form env))))) (setf (funobj-type macro-function) #.(bt:enum-value 'movitz::movitz-funobj-type :macro-function)) macro-function))
null
https://raw.githubusercontent.com/dym/movitz/56176e1ebe3eabc15c768df92eca7df3c197cb3d/losp/muerte/functions.lisp
lisp
------------------------------------------------------------------ For distribution policy, see the accompanying file COPYING. Filename: functions.lisp Description: Misc. function-oriented functions ------------------------------------------------------------------ (when los0::*funbound-counter* Set up atomically continuation. ..this allows us to detect recursive atomicallies. Now inside atomically section. return the integer offset this cell stores word+2 Set up atomically continuation. ..this allows us to detect recursive atomicallies. Now inside atomically section. this cell stores word+2 Set up atomically continuation. ..this allows us to detect recursive atomicallies. Now inside atomically section. this cell stores word+2 For a jumper, return its offset relative to the code-vector. pointer arithmetics. code-vector (word) into ebx XXX without-gc code-vector (word) into ebx value revert to default trampolines for now..
Copyright ( C ) 2001 - 2005 , Department of Computer Science , University of Tromso , Norway . Author : < > Created at : Tue Mar 12 22:58:54 2002 $ I d : functions.lisp , v 1.32 2009 - 07 - 19 18:58:33 Exp $ (require :muerte/basic-macros) (require :muerte/setf) (provide :muerte/functions) (in-package muerte) (defvar *setf-namespace* nil "This hash-table is initialized by dump-image.") (defun identity (x) x) (defun constantly-prototype (&rest ignore) (declare (ignore ignore)) 'value) (defun constantly-true (&rest ignore) (declare (ignore ignore)) t) (defun constantly-false (&rest ignore) (declare (ignore ignore)) nil) (define-compiler-macro constantly (&whole form value-form &environment env) (cond ((movitz:movitz-constantp value-form env) (let ((value (movitz:movitz-eval value-form env))) (case (translate-program value :muerte.cl :cl) ((t) `(function constantly-true)) ((nil) `(function constantly-false)) (t form)))) (t form))) (defun constantly (x) (lambda () x)) (defun complement-prototype (&rest args) (declare (dynamic-extent args)) (not (apply 'function args))) (define-compiler-macro complement (&whole form function-form &environment env) (cond ((and (listp function-form) (eq 'function (first function-form)) (typep (movitz:movitz-eval (translate-program function-form :cl :muerte.cl) env) 'movitz:movitz-funobj)) `(make-prototyped-function `(complement ,(second function-form)) complement-prototype ,(movitz:movitz-eval (translate-program function-form :cl :muerte.cl)))) (t form))) (defun complement (function) (lambda (&rest args) (declare (dynamic-extent args)) (not (apply function args)))) (defun unbound-function (&edx edx &rest args) "This is the function that is the unbound value for function cells." (declare (dynamic-extent args)) (let ((function-name (typecase edx (symbol edx) (compiled-function (funobj-name edx)) (t '(unknown))))) ( incf ( gethash function - name los0::*funbound - counter * 0 ) ) ) (with-simple-restart (continue "Return NIL from ~S." function-name) (error 'undefined-function-call :name function-name :arguments (copy-list args)))) nil) funobj object (defun funobj-type (funobj) (check-type funobj function) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:xorl :ecx :ecx) (:compile-form (:result-mode :eax) funobj) (:movb (:eax (:offset movitz-funobj funobj-type)) :cl))) (defun (setf funobj-type) (type funobj) (check-type funobj function) (with-inline-assembly (:returns :untagged-fixnum-ecx) (:compile-two-forms (:eax :untagged-fixnum-ecx) funobj type) (:movb :cl (:eax (:offset movitz-funobj funobj-type))))) (defun funobj-code-vector (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'code-vector) :type :code-vector)) (defun (setf funobj-code-vector) (code-vector funobj) (check-type funobj function) (check-type code-vector code-vector) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'code-vector) :type :code-vector) code-vector)) (defun funobj-code-vector%1op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%1op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%1op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%1op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%1op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:movl :eax (:ebx (:offset movitz-funobj code-vector%1op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%1op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%1op)))))) code-vector) (defun funobj-code-vector%2op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%2op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) return the integer offset EAX - EBX (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%2op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%2op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%2op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:movl :eax (:ebx (:offset movitz-funobj code-vector%2op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%2op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%2op)))))) code-vector) (defun funobj-code-vector%3op (funobj) "This slot is not a lisp value, it is a direct address to code entry point. In practice it is either a pointer into the regular code-vector, or it points (with offset 2) to another vector entirely. The former is represented as a lisp integer that is the index into the code-vector, the latter is represented as that vector." (check-type funobj function) (with-inline-assembly (:returns :eax) (:declare-label-set restart-jumper (retry)) (:locally (:pushl (:edi (:edi-offset :dynamic-env)))) (:pushl 'restart-jumper) (:locally (:pushl (:edi (:edi-offset :atomically-continuation)))) (:pushl :ebp) retry (:movl (:esp) :ebp) (:locally (:movl :esp (:edi (:edi-offset :atomically-continuation)))) (:compile-form (:result-mode :ebx) funobj) EAX = code - vector (:movl (:ebx (:offset movitz-funobj code-vector%3op)) :ecx) determine if ECX is a pointer into EAX (:subl :eax :ecx) (:jl 'return-vector) (:leal ((:ecx #.movitz:+movitz-fixnum-factor+)) :ecx) (:cmpl (:eax (:offset movitz-basic-vector num-elements -2)) :ecx) (:jnc 'return-vector) return the integer offset EAX - EBX (:movl :ecx :eax) (:jmp 'done) return-vector (:testl 7 (:ebx (:offset movitz-funobj code-vector%3op))) (:jnz '(:sub-program () (:int 63))) (:movl #xfffffffe :eax) (:addl (:ebx (:offset movitz-funobj code-vector%3op)) :eax) done (:locally (:movl 0 (:edi (:edi-offset atomically-continuation)))) (:leal (:esp 16) :esp))) (defun (setf funobj-code-vector%3op) (code-vector funobj) (check-type funobj function) (etypecase code-vector (code-vector (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:compile-form (:result-mode :eax) code-vector) (:movl :eax (:ebx (:offset movitz-funobj code-vector%3op))))) (integer (with-inline-assembly (:returns :nothing) (:compile-form (:result-mode :ebx) funobj) (:movl (:ebx (:offset movitz-funobj code-vector)) :eax) (:movl :eax (:ebx (:offset movitz-funobj code-vector%3op))) (:compile-form (:result-mode :untagged-fixnum-ecx) code-vector) (:addl :ecx (:ebx (:offset movitz-funobj code-vector%3op)))))) code-vector) (defun funobj-name (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'name))) (defun (setf funobj-name) (name funobj) (check-type funobj function) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'name)) name)) (defun funobj-lambda-list (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'lambda-list))) (defun (setf funobj-lambda-list) (lambda-list funobj) (check-type funobj function) (check-type lambda-list list) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'lambda-list)) lambda-list)) (defun funobj-num-constants (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-constants) :type :unsigned-byte16)) (defun (setf funobj-num-constants) (num-constants funobj) (check-type funobj function) (check-type num-constants (unsigned-byte 16)) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-constants) :type :unsigned-byte16) num-constants)) (defun funobj-num-jumpers (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-jumpers) :type :unsigned-byte14)) (defun (setf funobj-num-jumpers) (num-jumpers funobj) (check-type funobj function) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'num-jumpers) :type :unsigned-byte14) num-jumpers) #+ignore (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ebx) num-jumpers funobj) (:movw :ax (:ebx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::num-jumpers))))) (defun funobj-constant-ref (funobj index) (check-type funobj function) (assert (below index (funobj-num-constants funobj)) (index) "Index ~D out of range, ~S has ~D constants." index funobj (funobj-num-constants funobj)) (if (>= index (funobj-num-jumpers funobj)) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'constant0) :index index) This is tricky wrt . to potential GC interrupts , because we 're doing (with-inline-assembly (:returns :eax) (:compile-two-forms (:eax :ecx) funobj index) (:movl #.movitz:+code-vector-transient-word+ :ebx) (:addl (:eax #.(bt:slot-offset 'movitz:movitz-funobj 'movitz:code-vector)) (:subl (:eax :ecx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0)) :ebx) (:negl :ebx) (:leal ((:ebx #.movitz:+movitz-fixnum-factor+)) :eax)))) (defun (setf funobj-constant-ref) (value funobj index) (check-type funobj function) (assert (below index (funobj-num-constants funobj)) (index) "Index ~D out of range, ~S has ~D constants." index funobj (funobj-num-constants funobj)) (if (>= index (funobj-num-jumpers funobj)) (setf (memref funobj (movitz-type-slot-offset 'movitz-funobj 'constant0) :index index) value) (progn (assert (below value (length (funobj-code-vector funobj))) (value) "The jumper value ~D is invalid because the code-vector's size is ~D." value (length (funobj-code-vector funobj))) (with-inline-assembly (:returns :nothing) (:compile-two-forms (:eax :edx) funobj index) (:compile-form (:result-mode :ecx) value) (:movl #.movitz:+code-vector-transient-word+ :ebx) (:addl (:eax #.(bt:slot-offset 'movitz:movitz-funobj 'movitz:code-vector)) (:movl :ecx (:eax :edx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0))) (:addl :ebx (:eax :edx #.(bt:slot-offset 'movitz:movitz-funobj 'movitz::constant0))))) value))) (defun funobj-debug-info (funobj) (check-type funobj function) (memref funobj (movitz-type-slot-offset 'movitz-funobj 'debug-info) :type :unsigned-byte16)) (defun funobj-frame-raw-locals (funobj) "The number of unboxed slots in this function's stack-frame(s)." (declare (ignore funobj)) 0) (defun funobj-frame-headers-p (funobj) "Can this function place header-vals in its stack-frame?" (declare (ignore funobj)) t) (defun make-funobj (&key (name :unnamed) (code-vector (funobj-code-vector #'constantly-prototype)) (constants nil) lambda-list) (setf code-vector (etypecase code-vector (code-vector code-vector) (list (make-array (length code-vector) :element-type 'code :initial-contents code-vector)) (vector (make-array (length code-vector) :element-type 'code :initial-contents code-vector)))) (let* ((num-constants (length constants)) (funobj (macrolet ((do-it () `(with-allocation-assembly ((+ num-constants ,(movitz::movitz-type-word-size 'movitz-funobj)) :object-register :eax :size-register :ecx) (:movl ,(movitz:tag :funobj) (:eax ,movitz:+other-type-offset+)) (:load-lexical (:lexical-binding num-constants) :edx) (:movl :edx :ecx) (:shll ,(- 16 movitz:+movitz-fixnum-shift+) :ecx) (:movl :ecx (:eax (:offset movitz-funobj num-jumpers))) (:xorl :ecx :ecx) (:xorl :ebx :ebx) (:testl :edx :edx) (:jmp 'init-done) init-loop (:movl :ecx (:eax :ebx ,movitz:+other-type-offset+)) (:addl 4 :ebx) (:cmpl :ebx :edx) (:ja 'init-loop) init-done (:leal (:edx ,(bt:sizeof 'movitz:movitz-funobj)) :ecx)))) (do-it)))) (setf (funobj-name funobj) name (funobj-code-vector funobj) code-vector (funobj-code-vector%1op funobj) (symbol-value 'trampoline-funcall%1op) (funobj-code-vector%2op funobj) (symbol-value 'trampoline-funcall%2op) (funobj-code-vector%3op funobj) (symbol-value 'trampoline-funcall%3op) (funobj-lambda-list funobj) lambda-list) (do* ((i 0 (1+ i)) (p constants (cdr p)) (x (car p))) ((endp p)) (setf (funobj-constant-ref funobj i) x)) funobj)) (defun install-function (name constants code-vector) (let ((funobj (make-funobj :name name :constants constants :code-vector code-vector))) (warn "installing ~S for ~S.." funobj name) (setf (symbol-function name) funobj))) (defun replace-funobj (dst src &optional (name (funobj-name src))) "Copy each element of src to dst. Dst's num-constants must be initialized, so that we can be reasonably sure of dst's size." (assert (= (funobj-num-constants src) (funobj-num-constants dst))) (setf (funobj-name dst) name (funobj-num-jumpers dst) (funobj-num-jumpers src) (funobj-code-vector dst) (funobj-code-vector src) (funobj-code-vector%1op dst) (funobj-code-vector%1op src) (funobj-code-vector%2op dst) (funobj-code-vector%2op src) (funobj-code-vector%3op dst) (funobj-code-vector%3op src) (funobj-lambda-list dst) (funobj-lambda-list src)) (dotimes (i (funobj-num-constants src)) (setf (funobj-constant-ref dst i) (funobj-constant-ref src i))) dst) (defun copy-funobj (old-funobj) (check-type old-funobj function) (%shallow-copy-object old-funobj (+ (funobj-num-constants old-funobj) (movitz-type-word-size 'movitz-funobj)))) (defun install-funobj-name (name funobj) (setf (funobj-name funobj) name) funobj) (defun fdefinition (function-name) (etypecase function-name (symbol (symbol-function function-name)) ((cons (eql setf)) (symbol-function (gethash (cadr function-name) *setf-namespace*))))) (defun (setf fdefinition) (value function-name) (etypecase function-name (symbol (setf (symbol-function function-name) value)) ((cons (eql setf)) (let* ((setf-name (cadr function-name)) (setf-symbol (or (gethash setf-name *setf-namespace*) (setf (gethash setf-name *setf-namespace*) (make-symbol (format nil "~A-~A" 'setf 'setf-name)))))) (setf (symbol-function setf-symbol) value))))) (defun fmakunbound (function-name) (setf (fdefinition function-name) (load-global-constant unbound-function)) function-name) (defun make-macro-function (expander name) "From a regular function, such as a (lambda (form env) ...), make a bona fide macro-function." (let ((macro-function (install-funobj-name name (lambda (&edx edx &optional form env (first-extra nil extras-p) &rest more-extras) (declare (ignore first-extra more-extras)) (verify-macroexpand-call edx name extras-p) (funcall expander form env))))) (setf (funobj-type macro-function) #.(bt:enum-value 'movitz::movitz-funobj-type :macro-function)) macro-function))
c482c9840095b56678833eacb709269c400b4c4274ea224de3aabf9f63d23892
winny-/aoc
day03.rkt
#lang racket (define (read2 ip) (match (read-line ip) [(? eof-object? e) e] [s (string->number s 2)])) (define (integer-width i) (let loop ([n i]) (if (zero? n) 0 (add1 (loop (arithmetic-shift n -1)))))) (define (part1 ls) (define width (integer-width (argmax identity ls))) (define gamma (for/fold ([acc (make-list width 0)] #:result (for/fold ([n 0]) ([freq acc] [pos (in-naturals 0)]) (if (> freq (quotient (length ls) 2)) (+ n (arithmetic-shift 1 pos)) n))) ([n ls]) (for/list ([num-set acc] [pos (in-naturals 0)]) (+ (if (bitwise-bit-set? n pos) 1 0) num-set)))) (define epsilon (bitwise-xor gamma (for/sum ([pos (in-range width)]) (arithmetic-shift 1 pos)))) (* gamma epsilon)) (define (part2 ls) (define width (integer-width (argmax identity ls))) (define (f fn) (for/fold ([acc ls] #:result (car acc)) ([pos (in-cycle (in-range (sub1 width) -1 -1))] #:break (<= (length acc) 1)) (define-values (set unset) (partition (curryr bitwise-bit-set? pos) acc)) (define most-frequent (>= (length set) (length unset))) (if (fn most-frequent) set unset))) (* (f identity) (f not))) (module+ main (define ls (port->list read2)) (part1 ls) (part2 ls)) ;; Local Variables: ;; compile-command: "racket day03.rkt < sample.txt" ;; End:
null
https://raw.githubusercontent.com/winny-/aoc/76902981237b7e7a5a486e6c56e4a95cca0779af/2021/day03/day03.rkt
racket
Local Variables: compile-command: "racket day03.rkt < sample.txt" End:
#lang racket (define (read2 ip) (match (read-line ip) [(? eof-object? e) e] [s (string->number s 2)])) (define (integer-width i) (let loop ([n i]) (if (zero? n) 0 (add1 (loop (arithmetic-shift n -1)))))) (define (part1 ls) (define width (integer-width (argmax identity ls))) (define gamma (for/fold ([acc (make-list width 0)] #:result (for/fold ([n 0]) ([freq acc] [pos (in-naturals 0)]) (if (> freq (quotient (length ls) 2)) (+ n (arithmetic-shift 1 pos)) n))) ([n ls]) (for/list ([num-set acc] [pos (in-naturals 0)]) (+ (if (bitwise-bit-set? n pos) 1 0) num-set)))) (define epsilon (bitwise-xor gamma (for/sum ([pos (in-range width)]) (arithmetic-shift 1 pos)))) (* gamma epsilon)) (define (part2 ls) (define width (integer-width (argmax identity ls))) (define (f fn) (for/fold ([acc ls] #:result (car acc)) ([pos (in-cycle (in-range (sub1 width) -1 -1))] #:break (<= (length acc) 1)) (define-values (set unset) (partition (curryr bitwise-bit-set? pos) acc)) (define most-frequent (>= (length set) (length unset))) (if (fn most-frequent) set unset))) (* (f identity) (f not))) (module+ main (define ls (port->list read2)) (part1 ls) (part2 ls))
7b864105103d04fc494d1f64258cc57465e4299e78af2161c3b5d7ff72ef8b4c
qkrgud55/ocamlmulti
globroots.ml
module type GLOBREF = sig type t val register: string -> t val get: t -> string val set: t -> string -> unit val remove: t -> unit end module Classic : GLOBREF = struct type t external register: string -> t = "gb_classic_register" external get: t -> string = "gb_get" external set: t -> string -> unit = "gb_classic_set" external remove: t -> unit = "gb_classic_remove" end module Generational : GLOBREF = struct type t external register: string -> t = "gb_generational_register" external get: t -> string = "gb_get" external set: t -> string -> unit = "gb_generational_set" external remove: t -> unit = "gb_generational_remove" end module Test(G: GLOBREF) = struct let size = 1024 let vals = Array.init size string_of_int let a = Array.init size (fun i -> G.register (string_of_int i)) let check () = for i = 0 to size - 1 do if G.get a.(i) <> vals.(i) then begin print_string "Error on "; print_int i; print_string ": "; print_string (String.escaped (G.get a.(i))); print_newline() end done let change () = match Random.int 37 with | 0 -> Gc.full_major() | 1|2|3|4 -> Gc.minor() | 5|6|7|8|9|10|11|12 -> (* update with young value *) let i = Random.int size in G.set a.(i) (string_of_int i) | 13|14|15|16|17|18|19|20 -> (* update with old value *) let i = Random.int size in G.set a.(i) vals.(i) | 21|22|23|24|25|26|27|28 -> (* re-register young value *) let i = Random.int size in G.remove a.(i); a.(i) <- G.register (string_of_int i) 29|30|31|32|33|34|35|36 let i = Random.int size in G.remove a.(i); a.(i) <- G.register vals.(i) let test n = for i = 1 to n do change(); print_string "."; flush stdout done end module TestClassic = Test(Classic) module TestGenerational = Test(Generational) let _ = let n = if Array.length Sys.argv < 2 then 10000 else int_of_string Sys.argv.(1) in print_string "Non-generational API\n"; TestClassic.test n; print_newline(); print_string "Generational API\n"; TestGenerational.test n; print_newline()
null
https://raw.githubusercontent.com/qkrgud55/ocamlmulti/74fe84df0ce7be5ee03fb4ac0520fb3e9f4b6d1f/testsuite/tests/gc-roots/globroots.ml
ocaml
update with young value update with old value re-register young value
module type GLOBREF = sig type t val register: string -> t val get: t -> string val set: t -> string -> unit val remove: t -> unit end module Classic : GLOBREF = struct type t external register: string -> t = "gb_classic_register" external get: t -> string = "gb_get" external set: t -> string -> unit = "gb_classic_set" external remove: t -> unit = "gb_classic_remove" end module Generational : GLOBREF = struct type t external register: string -> t = "gb_generational_register" external get: t -> string = "gb_get" external set: t -> string -> unit = "gb_generational_set" external remove: t -> unit = "gb_generational_remove" end module Test(G: GLOBREF) = struct let size = 1024 let vals = Array.init size string_of_int let a = Array.init size (fun i -> G.register (string_of_int i)) let check () = for i = 0 to size - 1 do if G.get a.(i) <> vals.(i) then begin print_string "Error on "; print_int i; print_string ": "; print_string (String.escaped (G.get a.(i))); print_newline() end done let change () = match Random.int 37 with | 0 -> Gc.full_major() | 1|2|3|4 -> Gc.minor() let i = Random.int size in G.set a.(i) (string_of_int i) let i = Random.int size in G.set a.(i) vals.(i) let i = Random.int size in G.remove a.(i); a.(i) <- G.register (string_of_int i) 29|30|31|32|33|34|35|36 let i = Random.int size in G.remove a.(i); a.(i) <- G.register vals.(i) let test n = for i = 1 to n do change(); print_string "."; flush stdout done end module TestClassic = Test(Classic) module TestGenerational = Test(Generational) let _ = let n = if Array.length Sys.argv < 2 then 10000 else int_of_string Sys.argv.(1) in print_string "Non-generational API\n"; TestClassic.test n; print_newline(); print_string "Generational API\n"; TestGenerational.test n; print_newline()
946380b2fd074e0dbe6a19e3bc3e5e847cf97df8401cfacfe636c95dbdd70aa1
craigfe/ppx_effects
main.ml
open Stdlib.Effect open Stdlib.Effect.Deep exception%effect E : string let comp () = print_string "0 "; print_string (perform E); print_string "3 " let () = try comp () with [%effect? E, k] -> print_string "1 "; continue k "2 "; print_string "4 " let () = match comp () with | e -> e | [%effect? E, k] -> print_string "1 "; continue k "2 "; print_string "4 "
null
https://raw.githubusercontent.com/craigfe/ppx_effects/ea728e6de95838c2c7df380b301b5e88dafa40d7/test/passing/main.ml
ocaml
open Stdlib.Effect open Stdlib.Effect.Deep exception%effect E : string let comp () = print_string "0 "; print_string (perform E); print_string "3 " let () = try comp () with [%effect? E, k] -> print_string "1 "; continue k "2 "; print_string "4 " let () = match comp () with | e -> e | [%effect? E, k] -> print_string "1 "; continue k "2 "; print_string "4 "
2814fdadc718fe7de3d95b85359dcdc444d9fe483c18065f1ce1cc69ce1d9262
ericclack/overtone-loops
drums1.clj
(ns overtone-loops.music.drums1 (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) (set-up) ;; 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & (defloop ticks 1 cymbal-pedal [4 3 4 3 ]) (defloop hats 1/2 cymbal-closed [_ 5 _ 7 _ 7 _ 7]) (defloop crashes 1 cymbal-open [_ _ 3 _ _ _ _ _ ]) (defloop kicks 1/2 bass-hard [6 _ 4 _ _ _ 4 _ 6 _ 4 _ _ _ 4 _]) (defloop snares 1/2 snare-hard [_ _ _ _ 6 _ _ 3 _ _ _ 1 6 1 _ 3]) ;; --------------------------------------------- (bpm 130) (beats-in-bar 4) (at-bar 1 (ticks) (hats) (kicks) ) (at-bar 3 (crashes) ) (at-bar 5 (snares) ) (comment (silence (on-next-bar) ticks hats kicks crashes snares) (stop) )
null
https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/music/drums1.clj
clojure
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & ---------------------------------------------
(ns overtone-loops.music.drums1 (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) (set-up) (defloop ticks 1 cymbal-pedal [4 3 4 3 ]) (defloop hats 1/2 cymbal-closed [_ 5 _ 7 _ 7 _ 7]) (defloop crashes 1 cymbal-open [_ _ 3 _ _ _ _ _ ]) (defloop kicks 1/2 bass-hard [6 _ 4 _ _ _ 4 _ 6 _ 4 _ _ _ 4 _]) (defloop snares 1/2 snare-hard [_ _ _ _ 6 _ _ 3 _ _ _ 1 6 1 _ 3]) (bpm 130) (beats-in-bar 4) (at-bar 1 (ticks) (hats) (kicks) ) (at-bar 3 (crashes) ) (at-bar 5 (snares) ) (comment (silence (on-next-bar) ticks hats kicks crashes snares) (stop) )
4036f3998bdc0307f9b6972e7c035b8495c6fa866c3dacfe002e2d9dedbf75b2
samrushing/irken-compiler
aa_map.scm
;; -*- Mode: Irken -*- ;; Note : for a while this was used as the main mapping data structure for Irken . in late 2016 I removed recursive types from the compiler , added a delete ! ;; to the red-black code, and deprecated this module. It's possible to rewrite ;; this using a datatype to capture the recursion, I just haven't bothered yet. this code is based on the C examples given by , and as such is n't very representative of an Irken / ML style . I 'd like to make a pure functional ;; implementation, and if possible make skew & split tail-recursive by making ;; them work from the bottom up rather than top down. [another approach would be to just adapt 's non - recursive code ] . ;; I'm bothered by the fact that this uses an entire extra word to hold the ;; level data. *theoretically*, it should be possible to write these algorithms without it ( i.e. , one bit per node for color ) , yet I wonder ;; if they could be kept as simple. ;; Note: as it stands, this code is pure as long as you don't use delete. ;; however it is rare that one needs both deletion and purity, so feel free ;; to use the 'pure' subset of this data structure thus. (define (node/make level key val left right) { level = level key = key val = val left = left right = right }) ;; Ok, this is interesting. If I use the following definition of tree/nil: ;; ;; (define tree/nil ;; {level = 0 ;; left = tree/nil ;; right = tree/nil ;; key = (magic #u) = ( magic # u ) ;; }) ;; ;; The typer will let me get away with this: (tree/nil). Why? (define tree/nil (let ((node (node/make 0 (magic #u) (magic #u) (magic #u) (magic #u)))) (set! node.left node) (set! node.right node) node)) (define (tree/empty) tree/nil) (define (tree/skew d) (if (and (> d.level 0) (= d.left.level d.level)) (node/make d.level d.left.key d.left.val d.left.left (node/make d.level d.key d.val d.left.right (tree/skew d.right))) d)) (define (tree/split b) (if (and (= b.right.right.level b.level) (not (= b.level 0))) (node/make (+ 1 b.level) b.right.key b.right.val (node/make b.level b.key b.val b.left b.right.left) (tree/split b.right.right)) b)) ;; urghhh, probably should have put '<' as the last arg. (define (tree/insert root < key val) (let loop ((n root)) (if (= n.level 0) (node/make 1 key val tree/nil tree/nil) (tree/split (tree/skew (if (< key n.key) (node/make n.level n.key n.val (loop n.left) n.right) (node/make n.level n.key n.val n.left (loop n.right))) ))))) (defmacro tree/insert! (tree/insert! root < key val) -> (set! root (tree/insert root < key val))) (defmacro tree/delete! (tree/delete! root key < =) -> (set! root (tree/delete root key < =))) ;; XXX make this pure. ;; [see for a working pure delete] (define (tree/delete root key key-less? key-equal?) (let recur ((root root) (key key)) (if (not (eq? root tree/nil)) (if (key-equal? key root.key) (if (and (not (eq? root.left tree/nil)) (not (eq? root.right tree/nil))) (let loop ((heir root.left)) (cond ((not (eq? heir.right tree/nil)) (loop heir.right)) (else (set! root.key heir.key) (set! root.val heir.val) (set! root.left (recur root.left root.key))))) (set! root (if (eq? root.left tree/nil) root.right root.left))) (if (key-less? root.key key) (set! root.right (recur root.right key)) (set! root.left (recur root.left key)) ))) (if (or (< root.left.level (- root.level 1)) (< root.right.level (- root.level 1))) (begin (set! root.level (- root.level 1)) (if (> root.right.level root.level) (set! root.right.level root.level)) (tree/skew (tree/split root))) root ))) (define (tree/member root < key) (let member0 ((t root)) (cond ((= t.level 0) (maybe:no)) ((< key t.key) (member0 t.left)) ((< t.key key) (member0 t.right)) (else (maybe:yes t.val))))) (define (tree/inorder p t) (let recur ((t t)) (cond ((= t.level 0) #u) (else (recur t.left) (p t.key t.val) (recur t.right))))) (define (tree/reverse p t) (let recur ((t t)) (cond ((= t.level 0) #u) (else (recur t.right) (p t.key t.val) (recur t.left))))) (define (tree/keys t) (let ((r '())) (tree/reverse (lambda (k v) (push! r k)) t) r)) (define (tree/values t) (let ((r '())) (tree/reverse (lambda (k v) (push! r v)) t) r)) (define (tree/dump d p t) (let recur ((d d) (t t)) (if (= t.level 0) #u (begin (recur (+ d 1) t.left) (p t.key t.val d) (recur (+ d 1) t.right))))) ;; the defn of make-generator, call/cc, etc... makes it pretty hard to pass more than one arg through a continuation . so instead we 'll ;; use a 'pair' constructor to iterate through the tree... (define (tree/make-generator tree) (make-generator (lambda (consumer) (tree/inorder (lambda (k v) (consumer (maybe:yes (:pair k v)))) tree) (forever (consumer (maybe:no)))) ))
null
https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/lib/aa_map.scm
scheme
-*- Mode: Irken -*- to the red-black code, and deprecated this module. It's possible to rewrite this using a datatype to capture the recursion, I just haven't bothered yet. implementation, and if possible make skew & split tail-recursive by making them work from the bottom up rather than top down. [another approach would be I'm bothered by the fact that this uses an entire extra word to hold the level data. *theoretically*, it should be possible to write these if they could be kept as simple. Note: as it stands, this code is pure as long as you don't use delete. however it is rare that one needs both deletion and purity, so feel free to use the 'pure' subset of this data structure thus. Ok, this is interesting. If I use the following definition of tree/nil: (define tree/nil {level = 0 left = tree/nil right = tree/nil key = (magic #u) }) The typer will let me get away with this: (tree/nil). Why? urghhh, probably should have put '<' as the last arg. XXX make this pure. [see for a working pure delete] the defn of make-generator, call/cc, etc... makes it pretty hard use a 'pair' constructor to iterate through the tree...
Note : for a while this was used as the main mapping data structure for Irken . in late 2016 I removed recursive types from the compiler , added a delete ! this code is based on the C examples given by , and as such is n't very representative of an Irken / ML style . I 'd like to make a pure functional to just adapt 's non - recursive code ] . algorithms without it ( i.e. , one bit per node for color ) , yet I wonder (define (node/make level key val left right) { level = level key = key val = val left = left right = right }) = ( magic # u ) (define tree/nil (let ((node (node/make 0 (magic #u) (magic #u) (magic #u) (magic #u)))) (set! node.left node) (set! node.right node) node)) (define (tree/empty) tree/nil) (define (tree/skew d) (if (and (> d.level 0) (= d.left.level d.level)) (node/make d.level d.left.key d.left.val d.left.left (node/make d.level d.key d.val d.left.right (tree/skew d.right))) d)) (define (tree/split b) (if (and (= b.right.right.level b.level) (not (= b.level 0))) (node/make (+ 1 b.level) b.right.key b.right.val (node/make b.level b.key b.val b.left b.right.left) (tree/split b.right.right)) b)) (define (tree/insert root < key val) (let loop ((n root)) (if (= n.level 0) (node/make 1 key val tree/nil tree/nil) (tree/split (tree/skew (if (< key n.key) (node/make n.level n.key n.val (loop n.left) n.right) (node/make n.level n.key n.val n.left (loop n.right))) ))))) (defmacro tree/insert! (tree/insert! root < key val) -> (set! root (tree/insert root < key val))) (defmacro tree/delete! (tree/delete! root key < =) -> (set! root (tree/delete root key < =))) (define (tree/delete root key key-less? key-equal?) (let recur ((root root) (key key)) (if (not (eq? root tree/nil)) (if (key-equal? key root.key) (if (and (not (eq? root.left tree/nil)) (not (eq? root.right tree/nil))) (let loop ((heir root.left)) (cond ((not (eq? heir.right tree/nil)) (loop heir.right)) (else (set! root.key heir.key) (set! root.val heir.val) (set! root.left (recur root.left root.key))))) (set! root (if (eq? root.left tree/nil) root.right root.left))) (if (key-less? root.key key) (set! root.right (recur root.right key)) (set! root.left (recur root.left key)) ))) (if (or (< root.left.level (- root.level 1)) (< root.right.level (- root.level 1))) (begin (set! root.level (- root.level 1)) (if (> root.right.level root.level) (set! root.right.level root.level)) (tree/skew (tree/split root))) root ))) (define (tree/member root < key) (let member0 ((t root)) (cond ((= t.level 0) (maybe:no)) ((< key t.key) (member0 t.left)) ((< t.key key) (member0 t.right)) (else (maybe:yes t.val))))) (define (tree/inorder p t) (let recur ((t t)) (cond ((= t.level 0) #u) (else (recur t.left) (p t.key t.val) (recur t.right))))) (define (tree/reverse p t) (let recur ((t t)) (cond ((= t.level 0) #u) (else (recur t.right) (p t.key t.val) (recur t.left))))) (define (tree/keys t) (let ((r '())) (tree/reverse (lambda (k v) (push! r k)) t) r)) (define (tree/values t) (let ((r '())) (tree/reverse (lambda (k v) (push! r v)) t) r)) (define (tree/dump d p t) (let recur ((d d) (t t)) (if (= t.level 0) #u (begin (recur (+ d 1) t.left) (p t.key t.val d) (recur (+ d 1) t.right))))) to pass more than one arg through a continuation . so instead we 'll (define (tree/make-generator tree) (make-generator (lambda (consumer) (tree/inorder (lambda (k v) (consumer (maybe:yes (:pair k v)))) tree) (forever (consumer (maybe:no)))) ))
61161d98ad8d27bfea13c42e622b2010cf588f2f1b732bbe24bb843fcb01cb3e
gergoerdi/tandoori
var.hs
data Foo = Foo1 | Foo2 data Bar = Bar1 | Bar2 test = let v1 = Foo1 v2 = Bar1 (v3, v4) = (Foo2, Bar2) in (v1, v2, v3, v4)
null
https://raw.githubusercontent.com/gergoerdi/tandoori/515142ce76b96efa75d7044c9077d85394585556/input/var.hs
haskell
data Foo = Foo1 | Foo2 data Bar = Bar1 | Bar2 test = let v1 = Foo1 v2 = Bar1 (v3, v4) = (Foo2, Bar2) in (v1, v2, v3, v4)
fc3e45b9e8ad820a34f50080519775dc2ef14bab3dfd22d972a97de84d314312
oshyshko/adventofcode
D03.hs
module Y15.D03 where import qualified Data.Set as S import Geom.XY import Imports char2move :: Char -> XY char2move = \case '<' -> XY (-1) 0 '^' -> XY 0 (-1) '>' -> XY 1 0 'v' -> XY 0 1 x -> error $ "Unexpected character: " ++ [x] ^^<<v<<v><v^^<><>^^ ... moves2houses :: String -> [XY] moves2houses = scanl (+) 0 . map char2move solve1 :: String -> Int solve1 = S.size . S.fromList . moves2houses solve2 :: String -> Int solve2 xs = let (santaPairs, robotPairs) = partition (even . fst) $ zip [(0::Int)..] xs santaHouses = moves2houses $ snd <$> santaPairs robotHouses = moves2houses $ snd <$> robotPairs in S.size . S.fromList $ santaHouses ++ robotHouses
null
https://raw.githubusercontent.com/oshyshko/adventofcode/95b6bb4d514cf02680ba1a62de5a5dca2bf9e92d/src/Y15/D03.hs
haskell
module Y15.D03 where import qualified Data.Set as S import Geom.XY import Imports char2move :: Char -> XY char2move = \case '<' -> XY (-1) 0 '^' -> XY 0 (-1) '>' -> XY 1 0 'v' -> XY 0 1 x -> error $ "Unexpected character: " ++ [x] ^^<<v<<v><v^^<><>^^ ... moves2houses :: String -> [XY] moves2houses = scanl (+) 0 . map char2move solve1 :: String -> Int solve1 = S.size . S.fromList . moves2houses solve2 :: String -> Int solve2 xs = let (santaPairs, robotPairs) = partition (even . fst) $ zip [(0::Int)..] xs santaHouses = moves2houses $ snd <$> santaPairs robotHouses = moves2houses $ snd <$> robotPairs in S.size . S.fromList $ santaHouses ++ robotHouses
f5db6d29661b3eb49fb1c23beb15c0f66da0be72c8d31848085e21b169305dcb
ssadler/zeno
TestUtils.hs
module TestUtils ( module Out , module TestUtils_Node , (@?=) ) where import Control.Monad.Logger import Test.Tasty.HUnit as Out hiding ((@?=)) import Test.Hspec as Out import Test.QuickCheck as Out hiding (Fixed) import Test.Tasty.QuickCheck as Out hiding (Fixed) import Test.Tasty as Out hiding (after, after_) import qualified Test.Tasty.HUnit as HUnit import GHC.Stack as Out (HasCallStack) import Debug.Trace as Out import Control.Monad.IO.Class import TestUtils_Node (@?=) :: (HasCallStack, MonadIO m, Eq a, Show a) => a -> a -> m () (@?=) a b = liftIO $ a HUnit.@?= b
null
https://raw.githubusercontent.com/ssadler/zeno/9f715d7104a7b7b00dee9fe35275fb217532fdb6/test/TestUtils.hs
haskell
module TestUtils ( module Out , module TestUtils_Node , (@?=) ) where import Control.Monad.Logger import Test.Tasty.HUnit as Out hiding ((@?=)) import Test.Hspec as Out import Test.QuickCheck as Out hiding (Fixed) import Test.Tasty.QuickCheck as Out hiding (Fixed) import Test.Tasty as Out hiding (after, after_) import qualified Test.Tasty.HUnit as HUnit import GHC.Stack as Out (HasCallStack) import Debug.Trace as Out import Control.Monad.IO.Class import TestUtils_Node (@?=) :: (HasCallStack, MonadIO m, Eq a, Show a) => a -> a -> m () (@?=) a b = liftIO $ a HUnit.@?= b
361622beffcc864e84934b338edc944fc4e036b6e9dd4f50b28e7183c58f2e84
mrosset/nomad
guix-local.scm
;; guix-local.scm Copyright ( C ) 2017 - 2019 < > This file is part of Nomad Nomad 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. Nomad is distributed in the hope that it will be useful , but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ;; See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along ;; with this program. If not, see </>. (load (string-append (dirname (current-filename)) "/guix/gnu/packages/nomad.scm")) (use-modules (guix packages) (guix gexp) (guix git-download) ((gnu packages nomad) #:prefix nomad:) (gnu packages guile-xyz)) (define %source-dir (dirname (current-filename))) (define nomad-local (package (inherit nomad:nomad) (name "nomad") (version "git") (source (local-file %source-dir #:recursive? #t #:select? (git-predicate %source-dir))))) nomad-local
null
https://raw.githubusercontent.com/mrosset/nomad/c94a65ede94d86eff039d2ef62d5ef3df609568a/guix-local.scm
scheme
guix-local.scm (at your option) any later version. 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. with this program. If not, see </>.
Copyright ( C ) 2017 - 2019 < > This file is part of Nomad Nomad 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 Nomad is distributed in the hope that it will be useful , but You should have received a copy of the GNU General Public License along (load (string-append (dirname (current-filename)) "/guix/gnu/packages/nomad.scm")) (use-modules (guix packages) (guix gexp) (guix git-download) ((gnu packages nomad) #:prefix nomad:) (gnu packages guile-xyz)) (define %source-dir (dirname (current-filename))) (define nomad-local (package (inherit nomad:nomad) (name "nomad") (version "git") (source (local-file %source-dir #:recursive? #t #:select? (git-predicate %source-dir))))) nomad-local
95137233bdfc96dc3f260c247094f44efbb96d319a1273d14b481b64034572fa
helium/blockchain-http
bh_route_snapshots_SUITE.erl
-module(bh_route_snapshots_SUITE). -compile([nowarn_export_all, export_all]). -include("ct_utils.hrl"). -include("../src/bh_route_handler.hrl"). all() -> [ list_test, current_test ]. init_per_suite(Config) -> ?init_bh(Config). end_per_suite(Config) -> ?end_bh(Config). list_test(_Config) -> {ok, {_, _, FirstJson}} = ?json_request("/v1/snapshots"), #{ <<"data">> := FirstTxns, <<"cursor">> := Cursor } = FirstJson, ?assert(length(FirstTxns) =< ?SNAPSHOT_LIST_LIMIT), {ok, {_, _, NextJson}} = ?json_request(["/v1/snapshots?cursor=", Cursor]), #{ <<"data">> := NextTxns } = NextJson, ?assert(length(NextTxns) =< ?SNAPSHOT_LIST_LIMIT). current_test(_Config) -> {ok, {_, _, Json}} = ?json_request("/v1/snapshots/current"), ?assertMatch(#{ <<"data">> := #{ <<"block">> := _, <<"snapshot_hash">> := _ }}, Json).
null
https://raw.githubusercontent.com/helium/blockchain-http/3d17c608891b758a6bee1cab42cae35357cde57f/test/bh_route_snapshots_SUITE.erl
erlang
-module(bh_route_snapshots_SUITE). -compile([nowarn_export_all, export_all]). -include("ct_utils.hrl"). -include("../src/bh_route_handler.hrl"). all() -> [ list_test, current_test ]. init_per_suite(Config) -> ?init_bh(Config). end_per_suite(Config) -> ?end_bh(Config). list_test(_Config) -> {ok, {_, _, FirstJson}} = ?json_request("/v1/snapshots"), #{ <<"data">> := FirstTxns, <<"cursor">> := Cursor } = FirstJson, ?assert(length(FirstTxns) =< ?SNAPSHOT_LIST_LIMIT), {ok, {_, _, NextJson}} = ?json_request(["/v1/snapshots?cursor=", Cursor]), #{ <<"data">> := NextTxns } = NextJson, ?assert(length(NextTxns) =< ?SNAPSHOT_LIST_LIMIT). current_test(_Config) -> {ok, {_, _, Json}} = ?json_request("/v1/snapshots/current"), ?assertMatch(#{ <<"data">> := #{ <<"block">> := _, <<"snapshot_hash">> := _ }}, Json).
7f216f4e229ce09d9770f6d49c076d10e32374232d84188a4ecbb37b23edcbfe
helmutkian/cl-wasm-runtime
wasm-module.lisp
(in-package #:cl-wasm-runtime) (define-wasm-sharable-ref module) (cffi:defcfun "wasm_module_new" %wasm-module-type ; own (store %wasm-store-type) (binary %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_validate" :boolean (store %wasm-store-type) (binary %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_imports" :void (module %wasm-module-type) (out %wasm-importtype-vec-type)) (cffi:defcfun "wasm_module_exports" :void (module %wasm-module-type) (out %wasm-exporttype-type)) (cffi:defcfun "wasm_module_serialize" :void (module %wasm-module-type) (out %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_deserialize" %wasm-module-type (store %wasm-store-type) (binary %wasm-byte-vec-type)) (defclass wasm-module-imports (wasm-importtype-vec) ((imports-list :reader imports))) (defun make-wasm-module-imports (module) (let* ((pointer (cffi:foreign-alloc '(:struct %wasm-importtype-vec-struct))) (imports (make-instance 'wasm-module-imports :pointer pointer :parent module :delete-function (then-free #'%wasm-importtype-vec-delete)))) (%wasm-module-imports module imports) (enable-gc imports) (setf (slot-value imports 'imports-list) (to-list imports)) imports)) (defclass wasm-module-exports (wasm-exporttype-vec) ((exports-list))) (defun make-wasm-module-exports (module) (let* ((pointer (cffi:foreign-alloc '(:struct %wasm-exporttype-vec-struct))) (exports (make-instance 'wasm-module-exports :pointer pointer :parent module :delete-function (then-free #'%wasm-exporttype-vec-delete)))) (%wasm-module-exports module exports) (enable-gc exports) (setf (slot-value exports 'exports-list) (to-list exports)) exports)) (define-wasm-object-class module () ((exports) (imports))) (defun wrap-wasm-module (store pointer) (let ((module (make-instance 'wasm-module :pointer pointer :parent store))) (enable-gc module) (setf (slot-value module 'exports) (make-wasm-module-exports module) (slot-value module 'imports) (make-wasm-module-imports module)) module)) (defun make-wasm-module (store binary) (wrap-wasm-module store (%wasm-module-new store binary))) (defmethod exports ((module wasm-module)) (slot-value (slot-value module 'exports) 'exports-list)) (defmethod imports ((module wasm-module)) (slot-value (slot-value module 'imports) 'imports-list)) (defun serialize (module) (cffi:with-foreign-object (byte-vec '(:struct %wasm-byte-vec-struct)) (%wasm-module-serialize module byte-vec) (wasm-byte-vec-copy byte-vec))) (defun deserialize (store byte-vec) (wrap-wasm-module store (%wasm-module-deserialize store byte-vec))) (defun load-wasm (path) (with-open-file (in path :element-type 'fast-io:octet) (fast-io:with-fast-input (buf nil in) (let ((bin (fast-io:make-octet-vector (file-length in)))) (fast-io:fast-read-sequence bin buf) (octets-to-wasm-byte-vec bin))))) (defun load-wasm-module (store path) (make-wasm-module store (load-wasm path)))
null
https://raw.githubusercontent.com/helmutkian/cl-wasm-runtime/4ce7085d49fe983700db34fb0bad0997aa5c7da8/wasm-module.lisp
lisp
own
(in-package #:cl-wasm-runtime) (define-wasm-sharable-ref module) (store %wasm-store-type) (binary %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_validate" :boolean (store %wasm-store-type) (binary %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_imports" :void (module %wasm-module-type) (out %wasm-importtype-vec-type)) (cffi:defcfun "wasm_module_exports" :void (module %wasm-module-type) (out %wasm-exporttype-type)) (cffi:defcfun "wasm_module_serialize" :void (module %wasm-module-type) (out %wasm-byte-vec-type)) (cffi:defcfun "wasm_module_deserialize" %wasm-module-type (store %wasm-store-type) (binary %wasm-byte-vec-type)) (defclass wasm-module-imports (wasm-importtype-vec) ((imports-list :reader imports))) (defun make-wasm-module-imports (module) (let* ((pointer (cffi:foreign-alloc '(:struct %wasm-importtype-vec-struct))) (imports (make-instance 'wasm-module-imports :pointer pointer :parent module :delete-function (then-free #'%wasm-importtype-vec-delete)))) (%wasm-module-imports module imports) (enable-gc imports) (setf (slot-value imports 'imports-list) (to-list imports)) imports)) (defclass wasm-module-exports (wasm-exporttype-vec) ((exports-list))) (defun make-wasm-module-exports (module) (let* ((pointer (cffi:foreign-alloc '(:struct %wasm-exporttype-vec-struct))) (exports (make-instance 'wasm-module-exports :pointer pointer :parent module :delete-function (then-free #'%wasm-exporttype-vec-delete)))) (%wasm-module-exports module exports) (enable-gc exports) (setf (slot-value exports 'exports-list) (to-list exports)) exports)) (define-wasm-object-class module () ((exports) (imports))) (defun wrap-wasm-module (store pointer) (let ((module (make-instance 'wasm-module :pointer pointer :parent store))) (enable-gc module) (setf (slot-value module 'exports) (make-wasm-module-exports module) (slot-value module 'imports) (make-wasm-module-imports module)) module)) (defun make-wasm-module (store binary) (wrap-wasm-module store (%wasm-module-new store binary))) (defmethod exports ((module wasm-module)) (slot-value (slot-value module 'exports) 'exports-list)) (defmethod imports ((module wasm-module)) (slot-value (slot-value module 'imports) 'imports-list)) (defun serialize (module) (cffi:with-foreign-object (byte-vec '(:struct %wasm-byte-vec-struct)) (%wasm-module-serialize module byte-vec) (wasm-byte-vec-copy byte-vec))) (defun deserialize (store byte-vec) (wrap-wasm-module store (%wasm-module-deserialize store byte-vec))) (defun load-wasm (path) (with-open-file (in path :element-type 'fast-io:octet) (fast-io:with-fast-input (buf nil in) (let ((bin (fast-io:make-octet-vector (file-length in)))) (fast-io:fast-read-sequence bin buf) (octets-to-wasm-byte-vec bin))))) (defun load-wasm-module (store path) (make-wasm-module store (load-wasm path)))
9710199573b61cbc0d0d49421ce16613f212b8701e65a897e00d28515f804c9e
ThoughtWorksInc/stonecutter
map.clj
(ns stonecutter.util.map) (defn deep-merge "Recursively merges maps. If keys are not maps, the last value wins." [& vals] (if (every? map? vals) (apply merge-with deep-merge vals) (last vals)))
null
https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/src/stonecutter/util/map.clj
clojure
(ns stonecutter.util.map) (defn deep-merge "Recursively merges maps. If keys are not maps, the last value wins." [& vals] (if (every? map? vals) (apply merge-with deep-merge vals) (last vals)))
537c1082c4af191044769ececfb82affccfdb4a50f2a386cafe093d88fc17008
clojure/jvm.tools.analyzer
reflection.clj
Copyright ( c ) and contributors . All rights reserved . ; The use and distribution terms for this software are covered by the ; Eclipse Public License 1.0 (-1.0.php) ; which can be found in the file epl-v10.html at the root of this distribution. ; By using this software in any fashion, you are agreeing to be bound by ; the terms of this license. ; You must not remove this notice, or any other, from this software. (ns clojure.jvm.tools.analyzer.examples.reflection "Same as *warn-on-reflection*" (:require [clojure.jvm.tools.analyzer :as analyze])) (defn check-new [exp] (when (not (:ctor exp)) (println "WARNING: Unresolved constructor" (:class exp) (-> exp :env :ns :name)))) (defn check-static-method [exp] (when (not (:method exp)) (println "WARNING: Unresolved static method" (:method-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-instance-method [exp] (when (not (:method exp)) (println "WARNING: Unresolved instance method" (:method-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-static-field [exp] (when (not (:field exp)) (println "WARNING: Unresolved static field" (:field-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-instance-field [exp] (when (not (:field exp)) (println "WARNING: Unresolved instance field" (:field-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-for-reflection [exp] (condp = (:op exp) :new (check-new exp) :static-method (check-static-method exp) :instance-method (check-instance-method exp) :static-field (check-static-field exp) :instance-field (check-instance-field exp) nil) (doseq [c (analyze/children exp)] (check-for-reflection c))) (comment (def analyzed (doall (map analyze/analyze-ns '[clojure.test clojure.set clojure.java.io clojure.stacktrace clojure.pprint clojure.walk clojure.string clojure.repl clojure.core.protocols clojure.template] (repeat {:children true})))) (doseq [exprs analyzed exp exprs] (check-for-reflection exp)) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 1)) {:children true}) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 1)) {:children true}) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 (even? 1))) {:children true}) )
null
https://raw.githubusercontent.com/clojure/jvm.tools.analyzer/15ca8ddc5f966c3cb964b17171803ec367fa5861/src/main/clojure/clojure/jvm/tools/analyzer/examples/reflection.clj
clojure
The use and distribution terms for this software are covered by the Eclipse Public License 1.0 (-1.0.php) which can be found in the file epl-v10.html at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.
Copyright ( c ) and contributors . All rights reserved . (ns clojure.jvm.tools.analyzer.examples.reflection "Same as *warn-on-reflection*" (:require [clojure.jvm.tools.analyzer :as analyze])) (defn check-new [exp] (when (not (:ctor exp)) (println "WARNING: Unresolved constructor" (:class exp) (-> exp :env :ns :name)))) (defn check-static-method [exp] (when (not (:method exp)) (println "WARNING: Unresolved static method" (:method-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-instance-method [exp] (when (not (:method exp)) (println "WARNING: Unresolved instance method" (:method-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-static-field [exp] (when (not (:field exp)) (println "WARNING: Unresolved static field" (:field-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-instance-field [exp] (when (not (:field exp)) (println "WARNING: Unresolved instance field" (:field-name exp) (:class exp) (-> exp :env :ns :name)))) (defn check-for-reflection [exp] (condp = (:op exp) :new (check-new exp) :static-method (check-static-method exp) :instance-method (check-instance-method exp) :static-field (check-static-field exp) :instance-field (check-instance-field exp) nil) (doseq [c (analyze/children exp)] (check-for-reflection c))) (comment (def analyzed (doall (map analyze/analyze-ns '[clojure.test clojure.set clojure.java.io clojure.stacktrace clojure.pprint clojure.walk clojure.string clojure.repl clojure.core.protocols clojure.template] (repeat {:children true})))) (doseq [exprs analyzed exp exprs] (check-for-reflection exp)) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 1)) {:children true}) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 1)) {:children true}) (analyze/analyze-one {:ns {:name 'clojure.core} :context :eval} '(Integer. (+ 1 (even? 1))) {:children true}) )
2848ef75eeaac58979dde6d9b00db0b043b7c633771cf43479a61d4c3a4f259c
camllight/camllight
source.ml
(************************ Source management ****************************) #open "misc";; #open "primitives";; (*** Conversion function. ***) let source_of_module module = find_in_path (module ^ ".ml");; (*** Buffer cache ***) (* Buffer and cache (to associate lines and positions in the buffer). *) type BUFFER == string * (int * int) list ref;; let buffer_max_count = ref 10;; let cache_size = 30;; let buffer_list = ref ([] : (string * BUFFER) list);; let flush_buffer_list () = buffer_list := [];; let get_buffer module = try assoc module !buffer_list with Not_found -> let inchan = open_in (source_of_module module) in let (content, _) as buffer = (create_string (in_channel_length inchan), ref []) in fast_really_input inchan content 0 (in_channel_length inchan); buffer_list := (list_truncate !buffer_max_count ((module, buffer)::!buffer_list)); buffer;; let buffer_content = (fst : BUFFER -> string);; let buffer_length x = string_length (buffer_content x);; (*** Position conversions. ***) (* Insert a new pair (position, line) in the cache of the given buffer. *) let insert_pos buffer ((position, line) as pair) = let rec new_list = function [] -> [(position, line)] | ((pos, lin) as a::l) as l' -> if lin < line then pair::l' else if lin = line then l' else a::(new_list l) in let buffer_cache = snd buffer in buffer_cache := new_list !buffer_cache;; (* Position of the next linefeed after `pos'. *) (* Position just after the buffer end if no linefeed found. *) (* Raise `Out_of_range' if already there. *) let next_linefeed (buffer, _) pos = let length = string_length buffer in if pos >= length then raise Out_of_range else let rec search p = if (p = length) || (nth_char buffer p = `\n`) then p else search (p + 1) in search pos;; (* Go to next line. *) let next_line buffer (pos, line) = (next_linefeed buffer pos + 1, line + 1);; (* Convert a position in the buffer to a line number. *) let line_of_pos buffer position = let rec find = function [] -> if position < 0 then raise Out_of_range else (0, 1) | ((pos, line) as pair)::l -> if pos > position then find l else pair and find_line previous = let (pos, line) as next = next_line buffer previous in if pos <= position then find_line next else previous in let result = find_line (find !(snd buffer)) in insert_pos buffer result; result;; (* Convert a line number to a position. *) let pos_of_line buffer line = let rec find = function [] -> if line <= 0 then raise Out_of_range else (0, 1) | ((pos, lin) as pair)::l -> if lin > line then find l else pair and find_pos previous = let (_, lin) as next = next_line buffer previous in if lin <= line then find_pos next else previous in let result = find_pos (find !(snd buffer)) in insert_pos buffer result; result;; (* Convert a coordinate (line / column) into a position. *) --- The first line and column are line 1 and column 1 . let point_of_coord buffer line column = fst (pos_of_line buffer line) + column - 1;;
null
https://raw.githubusercontent.com/camllight/camllight/0cc537de0846393322058dbb26449427bfc76786/sources/contrib/debugger/source.ml
ocaml
*********************** Source management *************************** ** Conversion function. ** ** Buffer cache ** Buffer and cache (to associate lines and positions in the buffer). ** Position conversions. ** Insert a new pair (position, line) in the cache of the given buffer. Position of the next linefeed after `pos'. Position just after the buffer end if no linefeed found. Raise `Out_of_range' if already there. Go to next line. Convert a position in the buffer to a line number. Convert a line number to a position. Convert a coordinate (line / column) into a position.
#open "misc";; #open "primitives";; let source_of_module module = find_in_path (module ^ ".ml");; type BUFFER == string * (int * int) list ref;; let buffer_max_count = ref 10;; let cache_size = 30;; let buffer_list = ref ([] : (string * BUFFER) list);; let flush_buffer_list () = buffer_list := [];; let get_buffer module = try assoc module !buffer_list with Not_found -> let inchan = open_in (source_of_module module) in let (content, _) as buffer = (create_string (in_channel_length inchan), ref []) in fast_really_input inchan content 0 (in_channel_length inchan); buffer_list := (list_truncate !buffer_max_count ((module, buffer)::!buffer_list)); buffer;; let buffer_content = (fst : BUFFER -> string);; let buffer_length x = string_length (buffer_content x);; let insert_pos buffer ((position, line) as pair) = let rec new_list = function [] -> [(position, line)] | ((pos, lin) as a::l) as l' -> if lin < line then pair::l' else if lin = line then l' else a::(new_list l) in let buffer_cache = snd buffer in buffer_cache := new_list !buffer_cache;; let next_linefeed (buffer, _) pos = let length = string_length buffer in if pos >= length then raise Out_of_range else let rec search p = if (p = length) || (nth_char buffer p = `\n`) then p else search (p + 1) in search pos;; let next_line buffer (pos, line) = (next_linefeed buffer pos + 1, line + 1);; let line_of_pos buffer position = let rec find = function [] -> if position < 0 then raise Out_of_range else (0, 1) | ((pos, line) as pair)::l -> if pos > position then find l else pair and find_line previous = let (pos, line) as next = next_line buffer previous in if pos <= position then find_line next else previous in let result = find_line (find !(snd buffer)) in insert_pos buffer result; result;; let pos_of_line buffer line = let rec find = function [] -> if line <= 0 then raise Out_of_range else (0, 1) | ((pos, lin) as pair)::l -> if lin > line then find l else pair and find_pos previous = let (_, lin) as next = next_line buffer previous in if lin <= line then find_pos next else previous in let result = find_pos (find !(snd buffer)) in insert_pos buffer result; result;; --- The first line and column are line 1 and column 1 . let point_of_coord buffer line column = fst (pos_of_line buffer line) + column - 1;;
35850d6f846001fa39f4b9402a612b8296e6c6c386c182ffa90b6265ab8c150a
earl-ducaine/cl-garnet
garnet-errors.lisp
;;; -*- Mode: COMMON-LISP; Package: GARNET-GADGETS -*- ;; ;;-------------------------------------------------------------------;; Copyright 1993 ; ; ;;-------------------------------------------------------------------;; ;; This code is in the Public Domain. Anyone who can get some use ;; ;; from it is welcome. ;; ;; This code comes with no warranty. ;; ;;-------------------------------------------------------------------;; $ Id$ (in-package "GARNET-GADGETS") ;;; Garnet error handler functions ;; ;; ;; These functions provide a concrete instantiation of some of the abstract error handling facilities in abstract-errors.lisp . This file must be loaded after abstract-errors.lisp . (defun protect-errors (context condition &key (allow-debugger (eql *user-type* :programmer))) "Error handler which prompts user for a choice of :ABORT, :DEBUG, :CONTINE, :USE-VALUE and :STORE-VALUE restarts. <context> is used to supply a context for the error. <allow-debugger> is used to determine whether or not the user can enter the LISP debugger. Should be invoked with an expression such as: (handler-bind ((error \#'(lambda (condition) (protect-errors context-string condition)))) ...) " (gg:garnet-error-handler context condition :allow-debugger allow-debugger)) (defmacro with-protected-errors (context &body forms) "Executes forms in a protected environment where errors are handled by prompting-error-handler, which creates queries the user with options to abort or continue, possibly with various recovery strategies. If rga:*user-type* is :programmer, then allows debugging. <context> should be a string describing user meaningful context in which error occured." `(handler-bind ((error (lambda (condition) (protect-errors ,context condition)))) ,.forms)) (defun protected-eval (form &rest args &key (default-value nil dv?) (context (format nil "Evaluating ~S" form)) (allow-debug (eq *user-type* :programmer)) (local-abort nil) (abort-val nil)) "This function executes a form in an environment where errors are caught and handled by a special protected-error. This gadget prints the error message and allows for several different restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE. <form> is the form to be evaluated. <default-value> if supplied, produces a continue restart which returns that value. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the debug switch is suppressed. <context> is a string defining the context of the error. Default value is `Evaluating <form>'. This abtract function allows the type of error handler to be hidden from the routine which sets it up. In particular, both promting-protected-eval and protected-eval could be bound to this symbol." (declare (ignore default-value dv? context local-abort abort-val)) (apply #'gg:garnet-protected-eval form :allow-debug allow-debug args)) (defun protected-read (&optional (stream *standard-input*) &rest args &key (context (format nil "Reading from ~S" stream)) (read-package *package*) (read-bindings nil) (default-value nil) (allow-debug nil) (local-abort nil) (abort-val nil)) "This works rather like protected-eval except it tries to read from the <stream>. <stream> is the stream to be read from (if omitted *standard-input*). <read-package> (default :user) selects the package to read from. This is because I don't want to make any assumptions about what the binding of package will be at eval time especially in a multiprocessed lisp, and I think this is safer. If you want the string to be read in a different package, you can try using :read-package *package* <read-bindings> is a list of (var . form)'s as in a let statement. These bindings are made (with the let) before reading the string to allow for effects such as binding the readtable. <default-value> (default nil) this establishes a continue restart which returns this value. Note that this is slightly different from protected-eval in that it is always available. <allow-debug> (default (eq *user-type* :programmer) if true, this includes a button which allows the debugger to be entered on an error. Note that the default value is different from protected-eval. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. (Same as protected-eval). This abtract function allows the type of error handler to be hidden from the routine which sets it up. In particular, both promting-protected-eval and protected-eval could be bound to this symbol." (declare (ignore context read-package read-bindings default-value local-abort abort-val)) (apply #'gg:garnet-protected-read stream :allow-debug allow-debug args)) (defun protected-read-from-string (string &rest args &key (start 0) (context (format nil "Parsing ~S" string)) (end (length string)) (read-package *package*) (read-bindings nil) (default-value nil) (allow-debug nil) (local-abort nil) (abort-val nil)) "This works rather like protected-eval except it tries to read from the <stream>. <string> is the string to be read from (probably the :string of a text input gadget). <start> and <end> allow selecting a substring. <read-package> (default :user) selects the package to read from. This is because I don't want to make any assumptions about what the binding of package will be at eval time especially in a multiprocessed lisp, and I think this is safer. If you want the string to be read in a different package, you can try using :read-package *package* <read-bindings> is a list of (var . form)'s as in a let statement. These bindings are made (with the let) before reading the string to allow for effects such as binding the readtable. <default-value> (default nil) this establishes a continue restart which returns this value. Note that this is slightly different from protected-eval in that it is always available. <allow-debug> (default (eq *user-type* :programmer) if true, this includes a button which allows the debugger to be entered on an error. Note that the default value is different from protected-eval. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. (Same as protected-eval)." (declare (ignore start context end read-package read-bindings default-value local-abort abort-val)) (apply #'gg:garnet-protected-read-from-string string :allow-debug allow-debug args)) (defun call-prompter (prompt &rest args &key (stream *query-io*) (local-abort nil) (default-value nil dv?) (abort-val :ABORT) (eval-input? nil) (satisfy-test #'(lambda (obj) T)) &allow-other-keys) "Prompts user for an input. <Prompt> is printed with ~A as a prompt. <stream> defaults to *query-io*. If <local-abort> is true a local abort is set up which will return the values <abort-val> and :ABORT. If <default-value> is supplied, a CONTINUE restart is set up which allows the user to select the default value. If <eval-input?> is true, then the expression is evaluated before it is returned; if not, the unevaluated expression is returned. The value supplied by the user is passed to <satisfy-test>. If that test fails, the user is prompted again. This is mostly a dummy function for hiding the prompter type from the implementation mechanism." (declare (ignore stream local-abort default-value dv? abort-val eval-input? satisfy-test)) (apply #'gg:do-prompt prompt :allow-other-keys t args)) (when gem::*x11-server-available* (kr:s-value (kr:g-value gg:error-prompter-gadget :window) :title (format nil "~A:Prompter" *application-long-name*)) (kr:s-value (kr:g-value gg:error-prompter-gadget :window) :icon-title (format nil "~A:Prompter" *application-short-name*)) (kr:s-value (kr:g-value gg:protected-eval-error-gadget :window) :title (format nil "~A:Error-Handler" *application-long-name*)) (kr:s-value (kr:g-value gg:protected-eval-error-gadget :window) :icon-title (format nil "~A:Error" *application-short-name*)) (kr:create-instance 'message-display gg:Motif-Error-Gadget (:modal-p nil) (:window-top (floor gem:*screen-height* 2)) (:window-left (floor gem:*screen-width* 2))) (kr:create-instance 'selector-display gg:motif-query-gadget #-(and)gg:query-gadget (:modal-p nil) (:window-top (floor gem:*screen-height* 2)) (:window-left (floor gem:*screen-width* 2))) (kr:s-value (kr:g-value message-display :window) :title (format nil "~A:Message" *application-long-name*)) (kr:s-value (kr:g-value message-display :window) :icon-title (format nil "~A:Message" *application-short-name*))) (defun call-displayer (message &rest keys &key (stream *standard-output*) (beep t) (wait nil) &allow-other-keys) "A generic display function which sends a display to the specified location. <stream> indicates the stream to which the message is to be sent in the text based version. <beep> is a logical value indicating whether or not the device should make some sort of alert signal. This is meant to be called through call-displayer." (declare (ignore keys stream)) (kr:s-value message-display :beep-p beep) (if wait (gg:display-error-and-wait message-display message) (gg:display-error message-display message))) (when gem::*x11-server-available* (kr:s-value (kr:g-value selector-display :window) :title (format nil "~A:Selection" *application-long-name*)) (kr:s-value (kr:g-value selector-display :window) :icon-title (format nil "~A:Selection" *application-short-name*))) (defun call-selector (message &rest keys &key (stream *query-io*) (in-stream stream) (out-stream stream) (beep t) (option-list '(:yes :no)) &allow-other-keys) "This function offers the user a choice of items from a menu of keywords. The user can either type the keword or select the option by number. <stream> is the stream (default *query-io*) and <option-list> is the list of options (default '(:yes no)). <message> is displayed first on the stream as a prompt." (declare (type String message) (type Stream stream in-stream out-stream) (type List option-list) #-(and)(:returns (type (Member option-list) option))) (declare (ignore keys in-stream out-stream)) (kr:s-value selector-display :beep-p beep) (gg:display-query-and-wait selector-display message option-list))
null
https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/protected-eval/garnet-errors.lisp
lisp
-*- Mode: COMMON-LISP; Package: GARNET-GADGETS -*- ;; -------------------------------------------------------------------;; ; -------------------------------------------------------------------;; This code is in the Public Domain. Anyone who can get some use ;; from it is welcome. ;; This code comes with no warranty. ;; -------------------------------------------------------------------;; Garnet error handler functions These functions provide a concrete instantiation of some of if not, the unevaluated expression is returned.
$ Id$ (in-package "GARNET-GADGETS") the abstract error handling facilities in abstract-errors.lisp . This file must be loaded after abstract-errors.lisp . (defun protect-errors (context condition &key (allow-debugger (eql *user-type* :programmer))) "Error handler which prompts user for a choice of :ABORT, :DEBUG, :CONTINE, :USE-VALUE and :STORE-VALUE restarts. <context> is used to supply a context for the error. <allow-debugger> is used to determine whether or not the user can enter the LISP debugger. Should be invoked with an expression such as: (handler-bind ((error \#'(lambda (condition) (protect-errors context-string condition)))) ...) " (gg:garnet-error-handler context condition :allow-debugger allow-debugger)) (defmacro with-protected-errors (context &body forms) "Executes forms in a protected environment where errors are handled by prompting-error-handler, which creates queries the user with options to abort or continue, possibly with various recovery strategies. If rga:*user-type* is :programmer, then allows debugging. <context> should be a string describing user meaningful context in which error occured." `(handler-bind ((error (lambda (condition) (protect-errors ,context condition)))) ,.forms)) (defun protected-eval (form &rest args &key (default-value nil dv?) (context (format nil "Evaluating ~S" form)) (allow-debug (eq *user-type* :programmer)) (local-abort nil) (abort-val nil)) "This function executes a form in an environment where errors are caught and handled by a special protected-error. This gadget prints the error message and allows for several different restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE. <form> is the form to be evaluated. <default-value> if supplied, produces a continue restart which returns that value. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the debug switch is suppressed. <context> is a string defining the context of the error. Default value is `Evaluating <form>'. This abtract function allows the type of error handler to be hidden from the routine which sets it up. In particular, both promting-protected-eval and protected-eval could be bound to this symbol." (declare (ignore default-value dv? context local-abort abort-val)) (apply #'gg:garnet-protected-eval form :allow-debug allow-debug args)) (defun protected-read (&optional (stream *standard-input*) &rest args &key (context (format nil "Reading from ~S" stream)) (read-package *package*) (read-bindings nil) (default-value nil) (allow-debug nil) (local-abort nil) (abort-val nil)) "This works rather like protected-eval except it tries to read from the <stream>. <stream> is the stream to be read from (if omitted *standard-input*). <read-package> (default :user) selects the package to read from. This is because I don't want to make any assumptions about what the binding of package will be at eval time especially in a multiprocessed lisp, and I think this is safer. If you want the string to be read in a different package, you can try using :read-package *package* <read-bindings> is a list of (var . form)'s as in a let statement. These bindings are made (with the let) before reading the string to allow for effects such as binding the readtable. <default-value> (default nil) this establishes a continue restart which returns this value. Note that this is slightly different from protected-eval in that it is always available. <allow-debug> (default (eq *user-type* :programmer) if true, this includes a button which allows the debugger to be entered on an error. Note that the default value is different from protected-eval. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. (Same as protected-eval). This abtract function allows the type of error handler to be hidden from the routine which sets it up. In particular, both promting-protected-eval and protected-eval could be bound to this symbol." (declare (ignore context read-package read-bindings default-value local-abort abort-val)) (apply #'gg:garnet-protected-read stream :allow-debug allow-debug args)) (defun protected-read-from-string (string &rest args &key (start 0) (context (format nil "Parsing ~S" string)) (end (length string)) (read-package *package*) (read-bindings nil) (default-value nil) (allow-debug nil) (local-abort nil) (abort-val nil)) "This works rather like protected-eval except it tries to read from the <stream>. <string> is the string to be read from (probably the :string of a text input gadget). <start> and <end> allow selecting a substring. <read-package> (default :user) selects the package to read from. This is because I don't want to make any assumptions about what the binding of package will be at eval time especially in a multiprocessed lisp, and I think this is safer. If you want the string to be read in a different package, you can try using :read-package *package* <read-bindings> is a list of (var . form)'s as in a let statement. These bindings are made (with the let) before reading the string to allow for effects such as binding the readtable. <default-value> (default nil) this establishes a continue restart which returns this value. Note that this is slightly different from protected-eval in that it is always available. <allow-debug> (default (eq *user-type* :programmer) if true, this includes a button which allows the debugger to be entered on an error. Note that the default value is different from protected-eval. If <local-abort> is true (default nil), then a local restart is established for abort which returns (values <abort-val> :abort) where <abort-val> is another parameter. (Same as protected-eval)." (declare (ignore start context end read-package read-bindings default-value local-abort abort-val)) (apply #'gg:garnet-protected-read-from-string string :allow-debug allow-debug args)) (defun call-prompter (prompt &rest args &key (stream *query-io*) (local-abort nil) (default-value nil dv?) (abort-val :ABORT) (eval-input? nil) (satisfy-test #'(lambda (obj) T)) &allow-other-keys) "Prompts user for an input. <Prompt> is printed with ~A as a prompt. <stream> defaults to *query-io*. If <local-abort> is true a local abort is set up which will return the values <abort-val> and :ABORT. If <default-value> is supplied, a CONTINUE restart is set up which allows the user to select the default value. If <eval-input?> is true, then the expression is evaluated before it The value supplied by the user is passed to <satisfy-test>. If that test fails, the user is prompted again. This is mostly a dummy function for hiding the prompter type from the implementation mechanism." (declare (ignore stream local-abort default-value dv? abort-val eval-input? satisfy-test)) (apply #'gg:do-prompt prompt :allow-other-keys t args)) (when gem::*x11-server-available* (kr:s-value (kr:g-value gg:error-prompter-gadget :window) :title (format nil "~A:Prompter" *application-long-name*)) (kr:s-value (kr:g-value gg:error-prompter-gadget :window) :icon-title (format nil "~A:Prompter" *application-short-name*)) (kr:s-value (kr:g-value gg:protected-eval-error-gadget :window) :title (format nil "~A:Error-Handler" *application-long-name*)) (kr:s-value (kr:g-value gg:protected-eval-error-gadget :window) :icon-title (format nil "~A:Error" *application-short-name*)) (kr:create-instance 'message-display gg:Motif-Error-Gadget (:modal-p nil) (:window-top (floor gem:*screen-height* 2)) (:window-left (floor gem:*screen-width* 2))) (kr:create-instance 'selector-display gg:motif-query-gadget #-(and)gg:query-gadget (:modal-p nil) (:window-top (floor gem:*screen-height* 2)) (:window-left (floor gem:*screen-width* 2))) (kr:s-value (kr:g-value message-display :window) :title (format nil "~A:Message" *application-long-name*)) (kr:s-value (kr:g-value message-display :window) :icon-title (format nil "~A:Message" *application-short-name*))) (defun call-displayer (message &rest keys &key (stream *standard-output*) (beep t) (wait nil) &allow-other-keys) "A generic display function which sends a display to the specified location. <stream> indicates the stream to which the message is to be sent in the text based version. <beep> is a logical value indicating whether or not the device should make some sort of alert signal. This is meant to be called through call-displayer." (declare (ignore keys stream)) (kr:s-value message-display :beep-p beep) (if wait (gg:display-error-and-wait message-display message) (gg:display-error message-display message))) (when gem::*x11-server-available* (kr:s-value (kr:g-value selector-display :window) :title (format nil "~A:Selection" *application-long-name*)) (kr:s-value (kr:g-value selector-display :window) :icon-title (format nil "~A:Selection" *application-short-name*))) (defun call-selector (message &rest keys &key (stream *query-io*) (in-stream stream) (out-stream stream) (beep t) (option-list '(:yes :no)) &allow-other-keys) "This function offers the user a choice of items from a menu of keywords. The user can either type the keword or select the option by number. <stream> is the stream (default *query-io*) and <option-list> is the list of options (default '(:yes no)). <message> is displayed first on the stream as a prompt." (declare (type String message) (type Stream stream in-stream out-stream) (type List option-list) #-(and)(:returns (type (Member option-list) option))) (declare (ignore keys in-stream out-stream)) (kr:s-value selector-display :beep-p beep) (gg:display-query-and-wait selector-display message option-list))
cb808f2fbc29b5dc2c54395a448d9ff1affef84dab507039e6b0d21489950fe9
ocaml/opam
opamSwitchState.mli
(**************************************************************************) (* *) Copyright 2012 - 2020 OCamlPro Copyright 2012 INRIA (* *) (* All rights reserved. This file is distributed under the terms of the *) GNU Lesser General Public License version 2.1 , with the special (* exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Loading and querying a switch state *) open OpamTypes open OpamStateTypes val load: 'a lock -> 'b global_state -> 'c repos_state -> switch -> 'a switch_state (** Loads the switch state and calls the given function on it, releasing the lock afterwards. The repository state is automatically loaded if not provided. The switch is selected, if not set, using [OpamStateConfig.get_switch] -- which can fail if no switch is configured. Additionally, in case of a write lock, a backup is saved and a message is printed on restoring if [f] raised an exception and there were changes. *) val with_: 'a lock -> ?rt:([< unlocked ] repos_state) -> ?switch:switch -> [< unlocked ] global_state -> ('a switch_state -> 'b) -> 'b (** Creates a virtual state with nothing installed. Availability is computed just from the global state, and [avail_default] (default [true]) controls the result when the availability can't be computed due to undefined variables. Useful for querying and simulating actions when no switch is yet configured, or querying packages directly from the repos *) val load_virtual: ?repos_list: repository_name list -> ?avail_default: bool -> 'a global_state -> 'b repos_state -> unlocked switch_state (** Load the switch's state file, without constructing the package maps: much faster than loading the full switch state *) val load_selections: ?lock_kind: 'a lock -> 'b global_state -> switch -> switch_selections (** Raw function to compute the availability of all packages, in [opams], given the switch configuration and the set of pinned packages. (The result is precomputed in global_state.available_packages once the state is loaded) *) val compute_available_packages: 'a global_state -> switch -> OpamFile.Switch_config.t -> pinned:package_set -> opams:OpamFile.OPAM.t package_map -> package_set (** Raw function to compute the conflicts for all packages, given the set of available packages and the corresponding opam files. This is useful to populate the `u_conflicts` field when building a universe manually. *) val get_conflicts_t: (package -> OpamFilter.env) -> package_set -> OpamFile.OPAM.t package_map -> formula package_map * Infer a switch invariant from a switch state with compiler_packages and roots set , using some heuristics . Useful for migration from pre-2.1 opam roots set, using some heuristics. Useful for migration from pre-2.1 opam *) val infer_switch_invariant: 'a switch_state -> OpamFormula.t (** Releases any locks on the given switch_state *) val unlock: 'a switch_state -> unlocked switch_state (** Releases any locks on the given switch state and then ignores it. Using [drop st] is equivalent to [ignore (unlock st)], and safer than other uses of [ignore] where it is not enforced by the type-system that the value is unlocked before it is lost. *) val drop: 'a switch_state -> unit (** Calls the provided function, ensuring a temporary write lock on the given switch state *) val with_write_lock: ?dontblock:bool -> 'a switch_state -> (rw switch_state -> 'b * rw switch_state) -> 'b * 'a switch_state * { 2 Helpers to access state data } * Returns the repositories configured in the current switch or , if none , the globally set default . highest priority first . globally set default. highest priority first. *) val repos_list: 'a switch_state -> repository_name list val selections: 'a switch_state -> switch_selections (** Return the OPAM file for the given package. @raise Not_found when appropriate *) val opam: 'a switch_state -> package -> OpamFile.OPAM.t * Return the OPAM file , including URL and descr , for the given package , if any any *) val opam_opt: 'a switch_state -> package -> OpamFile.OPAM.t option (** Return the URL field for the given package *) val url: 'a switch_state -> package -> OpamFile.URL.t option (** Returns the primary URL from the URL field of the given package *) val primary_url: 'a switch_state -> package -> url option val primary_url_with_subpath: 'a switch_state -> package -> url option (** Return the descr field for the given package (or an empty descr if none) *) val descr: 'a switch_state -> package -> OpamFile.Descr.t (** Return the descr field for the given package *) val descr_opt: 'a switch_state -> package -> OpamFile.Descr.t option * Returns the full paths of overlay files under the files/ directory val files: 'a switch_state -> package -> filename list (** Return the installed package's local configuration *) val package_config: 'a switch_state -> name -> OpamFile.Dot_config.t (** Check whether a package name is installed *) val is_name_installed: 'a switch_state -> name -> bool (** Return the installed package with the right name @raise Not_found when appropriate *) val find_installed_package_by_name: 'a switch_state -> name -> package (** Return all packages satisfying one of the given atoms from a state *) val packages_of_atoms: 'a switch_state -> atom list -> package_set * Gets the current version of package [ name ] : pinned version , installed version , available version or max existing version , tried in this order . @raise Not_found only if there is no package by this name version, max available version or max existing version, tried in this order. @raise Not_found only if there is no package by this name *) val get_package: 'a switch_state -> name -> package (** "dev packages" are any package with an upstream that isn't the usual HTTP, and without an archive checksum. These need to be updated from upstream independently when installed. It's generally only the case of source-pinned packages, but no rule enforces it in opam itself. *) val is_dev_package: 'a switch_state -> package -> bool (** Checks if the given package name is pinned *) val is_pinned: 'a switch_state -> name -> bool (** Checks if the given package is version-pinned, i.e. pinned without overlay metadata, and relying on the repo's data *) val is_version_pinned: 'a switch_state -> name -> bool (** The set of all "dev packages" (see [is_dev_package] for a definition) *) val dev_packages: 'a switch_state -> package_set (** Returns the local source mirror for the given package ([OpamPath.Switch.sources] or [OpamPath.Switch.pinned_package], depending on wether it's pinned). *) val source_dir: 'a switch_state -> package -> dirname (** Returns the set of active external dependencies for the package, computed from the values of the system-specific variables *) val depexts: 'a switch_state -> package -> OpamSysPkg.Set.t { 2 } Helpers to retrieve computed data (** Return the transitive dependency closures of a collection of packages. [depopts]: include optional dependencies (depopts: foo) [build]: include build dependencies (depends: foo {build}) [post]: include post dependencies (depends: foo {post}) [installed]: only consider already-installed packages [unavaiable]: also consider unavailable packages *) val dependencies: 'a switch_state -> build:bool -> post:bool -> depopts:bool -> installed:bool -> ?unavailable:bool -> universe -> package_set -> package_set (** Same as [dependencies] but for reverse dependencies. *) val reverse_dependencies: 'a switch_state -> build:bool -> post:bool -> depopts:bool -> installed:bool -> ?unavailable:bool -> universe -> package_set -> package_set (** Returns required system packages of each of the given packages (elements are not added to the map if they don't have system dependencies) *) val depexts_status_of_packages: 'a switch_state -> package_set -> OpamSysPkg.status package_map (** Returns not found depexts for the package *) val depexts_unavailable: 'a switch_state -> package -> OpamSysPkg.Set.t option * [ conflicts_with st subset pkgs ] returns all packages declared in conflict with at least one element of [ subset ] within [ pkgs ] , through forward or backward conflict definition or common conflict - class . Packages in [ subset ] ( all their versions ) are excluded from the result . with at least one element of [subset] within [pkgs], through forward or backward conflict definition or common conflict-class. Packages in [subset] (all their versions) are excluded from the result. *) val conflicts_with: 'a switch_state -> package_set -> package_set -> package_set * Put the package data in a form suitable for the solver , pre - computing some maps and sets . Packages in the [ requested ] set are the ones that will get affected by the global [ build_test ] and [ build_doc ] flags . [ test ] and [ doc ] , if unspecified , are taken from [ OpamStateConfig.r ] . [ reinstall ] marks package not considered current in the universe , and that should therefore be reinstalled . If unspecified , it is the packages marked in [ switch_state.reinstall ] that are present in [ requested ] . maps and sets. Packages in the [requested] set are the ones that will get affected by the global [build_test] and [build_doc] flags. [test] and [doc], if unspecified, are taken from [OpamStateConfig.r]. [reinstall] marks package not considered current in the universe, and that should therefore be reinstalled. If unspecified, it is the packages marked in [switch_state.reinstall] that are present in [requested]. *) val universe: 'a switch_state -> ?test:bool -> ?doc:bool -> ?dev_setup:bool -> ?force_dev_deps:bool -> ?reinstall:package_set -> requested:package_set -> user_action -> universe * Dumps the current switch state in PEF format , for interaction with Dose tools tools *) val dump_pef_state: 'a switch_state -> out_channel -> unit * { 2 Updating } (** Sets the given opam file for the given package, updating the other related fields along the way *) val update_package_metadata: package -> OpamFile.OPAM.t -> 'a switch_state -> 'a switch_state (** Removes the metadata associated to the given package, also updating the packages and available sets. *) val remove_package_metadata: package -> 'a switch_state -> 'a switch_state (** Like [update_package_metadata], but also ensures the package is pinned to the given version. The version specified in the opam file, if any, takes precedence over the version of [package]. Also marks it for reinstall if changed. *) val update_pin: package -> OpamFile.OPAM.t -> 'a switch_state -> 'a switch_state (** Updates the selected repositories in the given switch (does not load the full switch state, but takes a transient write lock on the switch, so make sure not to hold other locks to avoid deadlocks). Sets the switch repositories in any case, even if unchanged from the defaults. *) val update_repositories: 'a global_state -> (repository_name list -> repository_name list) -> switch -> unit * { 2 User interaction and reporting } * Returns [ true ] if the switch of the state is the one set in [ $ OPAMROOT / config ] , [ false ] otherwise . This does n't imply that the switch is current w.r.t . either the process or the shell , for that you need to check [ OpamStateConfig.(!r.switch_from ) ] [$OPAMROOT/config], [false] otherwise. This doesn't imply that the switch is current w.r.t. either the process or the shell, for that you need to check [OpamStateConfig.(!r.switch_from)] *) val is_switch_globally_set: 'a switch_state -> bool (** Returns a message about a package or version that couldn't be found *) val not_found_message: 'a switch_state -> atom -> string val unavailable_reason_raw: 'a switch_state -> name * OpamFormula.version_formula -> [ `UnknownVersion | `UnknownPackage | `NoDefinition | `Pinned of OpamPackage.t | `Unavailable of string | `ConflictsBase | `ConflictsInvariant of string | `MissingDepexts of string list | `Default ] (** Returns a printable explanation why a package is not currently available (pinned to an incompatible version, unmet [available:] constraints...). [default] is returned if no reason why it wouldn't be available was found (empty string if unspecified). *) val unavailable_reason: 'a switch_state -> ?default:string -> name * OpamFormula.version_formula -> string (** Returns [true] when the package has the [avoid-version] flag and there isn't already a version with that flag installed (which disables the constraint) *) val avoid_version : 'a switch_state -> package -> bool (** Handle a cache of the opam files of installed packages *) module Installed_cache: sig type t = OpamFile.OPAM.t OpamPackage.Map.t val save: OpamFilename.t -> t -> unit val remove: OpamFilename.t -> unit end
null
https://raw.githubusercontent.com/ocaml/opam/c9ab85dec017d0392bffaf7fb238bad8fa8c1285/src/state/opamSwitchState.mli
ocaml
************************************************************************ All rights reserved. This file is distributed under the terms of the exception on linking described in the file LICENSE. ************************************************************************ * Loading and querying a switch state * Loads the switch state and calls the given function on it, releasing the lock afterwards. The repository state is automatically loaded if not provided. The switch is selected, if not set, using [OpamStateConfig.get_switch] -- which can fail if no switch is configured. Additionally, in case of a write lock, a backup is saved and a message is printed on restoring if [f] raised an exception and there were changes. * Creates a virtual state with nothing installed. Availability is computed just from the global state, and [avail_default] (default [true]) controls the result when the availability can't be computed due to undefined variables. Useful for querying and simulating actions when no switch is yet configured, or querying packages directly from the repos * Load the switch's state file, without constructing the package maps: much faster than loading the full switch state * Raw function to compute the availability of all packages, in [opams], given the switch configuration and the set of pinned packages. (The result is precomputed in global_state.available_packages once the state is loaded) * Raw function to compute the conflicts for all packages, given the set of available packages and the corresponding opam files. This is useful to populate the `u_conflicts` field when building a universe manually. * Releases any locks on the given switch_state * Releases any locks on the given switch state and then ignores it. Using [drop st] is equivalent to [ignore (unlock st)], and safer than other uses of [ignore] where it is not enforced by the type-system that the value is unlocked before it is lost. * Calls the provided function, ensuring a temporary write lock on the given switch state * Return the OPAM file for the given package. @raise Not_found when appropriate * Return the URL field for the given package * Returns the primary URL from the URL field of the given package * Return the descr field for the given package (or an empty descr if none) * Return the descr field for the given package * Return the installed package's local configuration * Check whether a package name is installed * Return the installed package with the right name @raise Not_found when appropriate * Return all packages satisfying one of the given atoms from a state * "dev packages" are any package with an upstream that isn't the usual HTTP, and without an archive checksum. These need to be updated from upstream independently when installed. It's generally only the case of source-pinned packages, but no rule enforces it in opam itself. * Checks if the given package name is pinned * Checks if the given package is version-pinned, i.e. pinned without overlay metadata, and relying on the repo's data * The set of all "dev packages" (see [is_dev_package] for a definition) * Returns the local source mirror for the given package ([OpamPath.Switch.sources] or [OpamPath.Switch.pinned_package], depending on wether it's pinned). * Returns the set of active external dependencies for the package, computed from the values of the system-specific variables * Return the transitive dependency closures of a collection of packages. [depopts]: include optional dependencies (depopts: foo) [build]: include build dependencies (depends: foo {build}) [post]: include post dependencies (depends: foo {post}) [installed]: only consider already-installed packages [unavaiable]: also consider unavailable packages * Same as [dependencies] but for reverse dependencies. * Returns required system packages of each of the given packages (elements are not added to the map if they don't have system dependencies) * Returns not found depexts for the package * Sets the given opam file for the given package, updating the other related fields along the way * Removes the metadata associated to the given package, also updating the packages and available sets. * Like [update_package_metadata], but also ensures the package is pinned to the given version. The version specified in the opam file, if any, takes precedence over the version of [package]. Also marks it for reinstall if changed. * Updates the selected repositories in the given switch (does not load the full switch state, but takes a transient write lock on the switch, so make sure not to hold other locks to avoid deadlocks). Sets the switch repositories in any case, even if unchanged from the defaults. * Returns a message about a package or version that couldn't be found * Returns a printable explanation why a package is not currently available (pinned to an incompatible version, unmet [available:] constraints...). [default] is returned if no reason why it wouldn't be available was found (empty string if unspecified). * Returns [true] when the package has the [avoid-version] flag and there isn't already a version with that flag installed (which disables the constraint) * Handle a cache of the opam files of installed packages
Copyright 2012 - 2020 OCamlPro Copyright 2012 INRIA GNU Lesser General Public License version 2.1 , with the special open OpamTypes open OpamStateTypes val load: 'a lock -> 'b global_state -> 'c repos_state -> switch -> 'a switch_state val with_: 'a lock -> ?rt:([< unlocked ] repos_state) -> ?switch:switch -> [< unlocked ] global_state -> ('a switch_state -> 'b) -> 'b val load_virtual: ?repos_list: repository_name list -> ?avail_default: bool -> 'a global_state -> 'b repos_state -> unlocked switch_state val load_selections: ?lock_kind: 'a lock -> 'b global_state -> switch -> switch_selections val compute_available_packages: 'a global_state -> switch -> OpamFile.Switch_config.t -> pinned:package_set -> opams:OpamFile.OPAM.t package_map -> package_set val get_conflicts_t: (package -> OpamFilter.env) -> package_set -> OpamFile.OPAM.t package_map -> formula package_map * Infer a switch invariant from a switch state with compiler_packages and roots set , using some heuristics . Useful for migration from pre-2.1 opam roots set, using some heuristics. Useful for migration from pre-2.1 opam *) val infer_switch_invariant: 'a switch_state -> OpamFormula.t val unlock: 'a switch_state -> unlocked switch_state val drop: 'a switch_state -> unit val with_write_lock: ?dontblock:bool -> 'a switch_state -> (rw switch_state -> 'b * rw switch_state) -> 'b * 'a switch_state * { 2 Helpers to access state data } * Returns the repositories configured in the current switch or , if none , the globally set default . highest priority first . globally set default. highest priority first. *) val repos_list: 'a switch_state -> repository_name list val selections: 'a switch_state -> switch_selections val opam: 'a switch_state -> package -> OpamFile.OPAM.t * Return the OPAM file , including URL and descr , for the given package , if any any *) val opam_opt: 'a switch_state -> package -> OpamFile.OPAM.t option val url: 'a switch_state -> package -> OpamFile.URL.t option val primary_url: 'a switch_state -> package -> url option val primary_url_with_subpath: 'a switch_state -> package -> url option val descr: 'a switch_state -> package -> OpamFile.Descr.t val descr_opt: 'a switch_state -> package -> OpamFile.Descr.t option * Returns the full paths of overlay files under the files/ directory val files: 'a switch_state -> package -> filename list val package_config: 'a switch_state -> name -> OpamFile.Dot_config.t val is_name_installed: 'a switch_state -> name -> bool val find_installed_package_by_name: 'a switch_state -> name -> package val packages_of_atoms: 'a switch_state -> atom list -> package_set * Gets the current version of package [ name ] : pinned version , installed version , available version or max existing version , tried in this order . @raise Not_found only if there is no package by this name version, max available version or max existing version, tried in this order. @raise Not_found only if there is no package by this name *) val get_package: 'a switch_state -> name -> package val is_dev_package: 'a switch_state -> package -> bool val is_pinned: 'a switch_state -> name -> bool val is_version_pinned: 'a switch_state -> name -> bool val dev_packages: 'a switch_state -> package_set val source_dir: 'a switch_state -> package -> dirname val depexts: 'a switch_state -> package -> OpamSysPkg.Set.t { 2 } Helpers to retrieve computed data val dependencies: 'a switch_state -> build:bool -> post:bool -> depopts:bool -> installed:bool -> ?unavailable:bool -> universe -> package_set -> package_set val reverse_dependencies: 'a switch_state -> build:bool -> post:bool -> depopts:bool -> installed:bool -> ?unavailable:bool -> universe -> package_set -> package_set val depexts_status_of_packages: 'a switch_state -> package_set -> OpamSysPkg.status package_map val depexts_unavailable: 'a switch_state -> package -> OpamSysPkg.Set.t option * [ conflicts_with st subset pkgs ] returns all packages declared in conflict with at least one element of [ subset ] within [ pkgs ] , through forward or backward conflict definition or common conflict - class . Packages in [ subset ] ( all their versions ) are excluded from the result . with at least one element of [subset] within [pkgs], through forward or backward conflict definition or common conflict-class. Packages in [subset] (all their versions) are excluded from the result. *) val conflicts_with: 'a switch_state -> package_set -> package_set -> package_set * Put the package data in a form suitable for the solver , pre - computing some maps and sets . Packages in the [ requested ] set are the ones that will get affected by the global [ build_test ] and [ build_doc ] flags . [ test ] and [ doc ] , if unspecified , are taken from [ OpamStateConfig.r ] . [ reinstall ] marks package not considered current in the universe , and that should therefore be reinstalled . If unspecified , it is the packages marked in [ switch_state.reinstall ] that are present in [ requested ] . maps and sets. Packages in the [requested] set are the ones that will get affected by the global [build_test] and [build_doc] flags. [test] and [doc], if unspecified, are taken from [OpamStateConfig.r]. [reinstall] marks package not considered current in the universe, and that should therefore be reinstalled. If unspecified, it is the packages marked in [switch_state.reinstall] that are present in [requested]. *) val universe: 'a switch_state -> ?test:bool -> ?doc:bool -> ?dev_setup:bool -> ?force_dev_deps:bool -> ?reinstall:package_set -> requested:package_set -> user_action -> universe * Dumps the current switch state in PEF format , for interaction with Dose tools tools *) val dump_pef_state: 'a switch_state -> out_channel -> unit * { 2 Updating } val update_package_metadata: package -> OpamFile.OPAM.t -> 'a switch_state -> 'a switch_state val remove_package_metadata: package -> 'a switch_state -> 'a switch_state val update_pin: package -> OpamFile.OPAM.t -> 'a switch_state -> 'a switch_state val update_repositories: 'a global_state -> (repository_name list -> repository_name list) -> switch -> unit * { 2 User interaction and reporting } * Returns [ true ] if the switch of the state is the one set in [ $ OPAMROOT / config ] , [ false ] otherwise . This does n't imply that the switch is current w.r.t . either the process or the shell , for that you need to check [ OpamStateConfig.(!r.switch_from ) ] [$OPAMROOT/config], [false] otherwise. This doesn't imply that the switch is current w.r.t. either the process or the shell, for that you need to check [OpamStateConfig.(!r.switch_from)] *) val is_switch_globally_set: 'a switch_state -> bool val not_found_message: 'a switch_state -> atom -> string val unavailable_reason_raw: 'a switch_state -> name * OpamFormula.version_formula -> [ `UnknownVersion | `UnknownPackage | `NoDefinition | `Pinned of OpamPackage.t | `Unavailable of string | `ConflictsBase | `ConflictsInvariant of string | `MissingDepexts of string list | `Default ] val unavailable_reason: 'a switch_state -> ?default:string -> name * OpamFormula.version_formula -> string val avoid_version : 'a switch_state -> package -> bool module Installed_cache: sig type t = OpamFile.OPAM.t OpamPackage.Map.t val save: OpamFilename.t -> t -> unit val remove: OpamFilename.t -> unit end
39581806ec8205e214db673399c0bd66eadc5882a833c30a2fd872abbf86c963
nuprl/gradual-typing-performance
lang.rkt
#lang racket/base (require scribble/doclang scribble/base) (provide (all-from-out scribble/doclang scribble/base))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/scribble-lib/scribble/base/lang.rkt
racket
#lang racket/base (require scribble/doclang scribble/base) (provide (all-from-out scribble/doclang scribble/base))
0f9b8680d8e2081cff9d657fdf03c2691382b7d957336f859480dc97b1eaa118
AdRoll/rebar3_format
types.erl
-module(types). -type my_int() :: undefined | integer(). -type person() :: #{name := binary() | string(), age := my_int()}. -type team() :: #{members := [person()], leader := person()}. -type big_team() :: #{members := [team()], office_address => my_int}.
null
https://raw.githubusercontent.com/AdRoll/rebar3_format/5ffb11341796173317ae094d4e165b85fad6aa19/test_app/after/src/otp_samples/types.erl
erlang
-module(types). -type my_int() :: undefined | integer(). -type person() :: #{name := binary() | string(), age := my_int()}. -type team() :: #{members := [person()], leader := person()}. -type big_team() :: #{members := [team()], office_address => my_int}.
afd5613046792e69511d7864cc5839bc3393178fd4874275129864711e024b50
takikawa/racket-ppa
error.rkt
#lang racket/base (require "../host/rktio.rkt" "../host/error.rkt" "../error/message.rkt") (provide raise-network-error raise-network-arguments-error raise-network-option-error) (define (raise-network-error who orig-err base-msg) (define err (remap-rktio-error orig-err)) (define msg (format-rktio-message who err base-msg)) (raise (cond [(not (eq? (rktio-errkind err) RKTIO_ERROR_KIND_RACKET)) (exn:fail:network:errno msg (current-continuation-marks) (cons (rktio-errno err) (let ([kind (rktio-errkind err)]) (cond [(eqv? kind RKTIO_ERROR_KIND_POSIX) 'posix] [(eqv? kind RKTIO_ERROR_KIND_WINDOWS) 'windows] [(eqv? kind RKTIO_ERROR_KIND_GAI) 'gai] [else (error 'raise-network-error "confused about rktio error")]))))] [else (exn:fail:network msg (current-continuation-marks))]))) (define (raise-network-arguments-error who msg socket-str u) (unless (equal? socket-str "socket") (raise-argument-error 'raise-network-arguments-error "\"socket\"" socket-str)) (raise (exn:fail:network (error-message->string who (string-append msg "\n socket: " ((error-value->string-handler) u (error-print-width)))) (current-continuation-marks)))) (define (raise-network-option-error who mode v) (raise-network-error who v (string-append mode "sockopt failed")))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/caff086a1cd48208815cec2a22645a3091c11d4c/src/io/network/error.rkt
racket
#lang racket/base (require "../host/rktio.rkt" "../host/error.rkt" "../error/message.rkt") (provide raise-network-error raise-network-arguments-error raise-network-option-error) (define (raise-network-error who orig-err base-msg) (define err (remap-rktio-error orig-err)) (define msg (format-rktio-message who err base-msg)) (raise (cond [(not (eq? (rktio-errkind err) RKTIO_ERROR_KIND_RACKET)) (exn:fail:network:errno msg (current-continuation-marks) (cons (rktio-errno err) (let ([kind (rktio-errkind err)]) (cond [(eqv? kind RKTIO_ERROR_KIND_POSIX) 'posix] [(eqv? kind RKTIO_ERROR_KIND_WINDOWS) 'windows] [(eqv? kind RKTIO_ERROR_KIND_GAI) 'gai] [else (error 'raise-network-error "confused about rktio error")]))))] [else (exn:fail:network msg (current-continuation-marks))]))) (define (raise-network-arguments-error who msg socket-str u) (unless (equal? socket-str "socket") (raise-argument-error 'raise-network-arguments-error "\"socket\"" socket-str)) (raise (exn:fail:network (error-message->string who (string-append msg "\n socket: " ((error-value->string-handler) u (error-print-width)))) (current-continuation-marks)))) (define (raise-network-option-error who mode v) (raise-network-error who v (string-append mode "sockopt failed")))
77283080f239b66c957f45b2a90a905f0c919186af13b51b6382b21f2f791f68
BranchTaken/Hemlock
test_cmp.ml
open! Basis.Rudiments open! Basis open String let test () = let strs = [ ""; "a"; "aa"; "ab"; "aa"; "a"; ""; ] in let rec fn s strs = begin match strs with | [] -> () | hd :: tl -> begin let () = List.iter strs ~f:(fun s2 -> File.Fmt.stdout |> Basis.Fmt.fmt "cmp " |> pp s |> Basis.Fmt.fmt " " |> pp s2 |> Basis.Fmt.fmt " -> " |> Cmp.pp (cmp s s2) |> Basis.Fmt.fmt "\n" |> ignore ) in fn hd tl end end in let hd, tl = match strs with | hd :: tl -> hd, tl | [] -> not_reached () in fn hd tl let _ = test ()
null
https://raw.githubusercontent.com/BranchTaken/Hemlock/f3604ceda4f75cf18b6ee2b1c2f3c5759ad495a5/bootstrap/test/basis/string/test_cmp.ml
ocaml
open! Basis.Rudiments open! Basis open String let test () = let strs = [ ""; "a"; "aa"; "ab"; "aa"; "a"; ""; ] in let rec fn s strs = begin match strs with | [] -> () | hd :: tl -> begin let () = List.iter strs ~f:(fun s2 -> File.Fmt.stdout |> Basis.Fmt.fmt "cmp " |> pp s |> Basis.Fmt.fmt " " |> pp s2 |> Basis.Fmt.fmt " -> " |> Cmp.pp (cmp s s2) |> Basis.Fmt.fmt "\n" |> ignore ) in fn hd tl end end in let hd, tl = match strs with | hd :: tl -> hd, tl | [] -> not_reached () in fn hd tl let _ = test ()
32383feff71aefff688b43323148d7385f78150b3e63cbb4243846545c654efc
statebox/cql
Instance.hs
SPDX - License - Identifier : AGPL-3.0 - only This file is part of ` statebox / cql ` , the categorical query language . Copyright ( C ) 2019 < 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 < / > . SPDX-License-Identifier: AGPL-3.0-only This file is part of `statebox/cql`, the categorical query language. Copyright (C) 2019 Stichting Statebox <> 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 </>. -} # LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE DataKinds #-} # LANGUAGE DuplicateRecordFields # {-# LANGUAGE ExplicitForAll #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE KindSignatures # {-# LANGUAGE LiberalTypeSynonyms #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} # LANGUAGE TupleSections # {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeSynonymInstances #-} # LANGUAGE UndecidableInstances # module Language.CQL.Instance where import Control.DeepSeq import Control.Monad import Data.List as List hiding (intercalate) import Data.Map.Strict (Map, member, unionWith, (!)) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Typeable hiding (typeOf) import Data.Void import Language.CQL.Collage (Collage(..), assembleGens, attsFrom, fksFrom, typeOf) import Language.CQL.Common (elem', fromListAccum, section, toMapSafely, Deps(..), Err, Kind(INSTANCE), MultiTyMap, TyMap, type (+)) import Language.CQL.Instance.Algebra (Algebra(..), aAtt, Carrier, down1, evalSchTerm, evalSchTerm', nf, nf'', repr'', TalgGen(..)) import qualified Language.CQL.Instance.Algebra as A (simplify) import Language.CQL.Instance.Presentation (Presentation(..)) import qualified Language.CQL.Instance.Presentation as IP (toCollage, typecheck, Presentation(eqs)) import Language.CQL.Mapping as Mapping import Language.CQL.Options import Language.CQL.Prover import Language.CQL.Query import Language.CQL.Schema as Schema import Language.CQL.Term as Term import Language.CQL.Typeside as Typeside import Prelude hiding (EQ) -- | A database instance on a schema. Contains a presentation, an algebra, and a decision procedure. data Instance var ty sym en fk att gen sk x y = Instance { schema :: Schema var ty sym en fk att , pres :: Presentation var ty sym en fk att gen sk , dp :: EQ Void ty sym en fk att gen sk -> Bool , algebra :: Algebra var ty sym en fk att gen sk x y } -- | True if the type algebra is empty, which approximates it being free, -- which approximates it being conservative over the typeside. freeTalg :: Instance var ty sym en fk att gen sk x y -> Bool freeTalg (Instance _ _ _ (Algebra _ _ _ _ _ _ _ _ teqs)) = Prelude.null teqs -- | Just syntactic equality of the theory for now. instance TyMap Eq '[var, ty, sym, en, fk, att, gen, sk, x, y] => Eq (Instance var ty sym en fk att gen sk x y) where (==) (Instance schema' (Presentation gens' sks' eqs' ) _ _) (Instance schema'' (Presentation gens'' sks'' eqs'') _ _) = (schema' == schema'') && (gens' == gens'') && (sks' == sks'') && (eqs' == eqs'') instance TyMap NFData '[var, ty, sym, en, fk, att, gen, sk, x, y] => NFData (Instance var ty sym en fk att gen sk x y) where rnf (Instance s0 p0 dp0 a0) = deepseq s0 $ deepseq p0 $ deepseq dp0 $ rnf a0 -- | A dynamically typed instance. data InstanceEx :: * where InstanceEx :: forall var ty sym en fk att gen sk x y . (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att, gen, sk, x, y]) => Instance var ty sym en fk att gen sk x y -> InstanceEx | Converts an algebra into a presentation : adds one equation per fact in the algebra , and one generator per element . Presentations in this form are called saturated because they are maximally large without being redundant . @I(fk.x ) = I(fk)(I(x))@ algebraToPresentation :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk], Ord y, Ord x) => Algebra var ty sym en fk att gen sk x y -> Presentation var ty sym en fk att x y algebraToPresentation alg@(Algebra sch en' _ _ _ ty' _ _ _) = Presentation gens' sks' eqs' where gens' = Map.fromList $ reify en' $ Schema.ens sch sks' = Map.fromList $ reify ty' $ Typeside.tys $ Schema.typeside sch eqs1 = concatMap fksToEqs reified eqs2 = concatMap attsToEqs reified eqs' = Set.fromList $ eqs1 ++ eqs2 reified = reify en' $ Schema.ens sch fksToEqs (x, e) = (\(fk , _) -> fkToEq x fk ) <$> fksFrom' sch e attsToEqs (x, e) = (\(att, _) -> attToEq x att) <$> attsFrom' sch e fkToEq x fk = EQ (Fk fk (Gen x), Gen $ aFk alg fk x) attToEq x att = EQ (Att att (Gen x), upp $ aAtt alg att x) reify :: (Ord x, Ord en) => (en -> Set x) -> Set en -> [(x, en)] reify f s = concat $ Set.toList $ Set.map (\en'-> Set.toList $ Set.map (, en') $ f en') s -- | Checks that an 'Instance' satisfies its 'Schema'. satisfiesSchema :: (MultiTyMap '[Show] '[var, ty, sym, en, fk, att, gen, sk, x, y], Eq x) => Instance var ty sym en fk att gen sk x y -> Err () satisfiesSchema (Instance sch pres' dp' alg) = do mapM_ (\( EQ (l, r)) -> if hasTypeType l then report (show l) (show r) (instEqT l r) else report (show l) (show r) (instEqE l r)) $ Set.toList $ IP.eqs pres' mapM_ (\(en'', EQ (l, r)) -> report (show l) (show r) (schEqT l r en'')) $ Set.toList $ obs_eqs sch mapM_ (\(en'', EQ (l, r)) -> report (show l) (show r) (schEqE l r en'')) $ Set.toList $ path_eqs sch where Morally , we should create a new dp ( decision procedure ) for the talg , but that 's computationally intractable , and this check still helps . instEqE l r = nf alg (down1 l) == nf alg (down1 r) instEqT l r = dp' $ EQ ((repr'' alg (nf'' alg l)), (repr'' alg (nf'' alg r))) report _ _ True = return () report l r False = Left $ "Not satisfied: " ++ l ++ " = " ++ r schEqE l r e = foldr (\x b -> (evalSchTerm' alg x l == evalSchTerm' alg x r) && b) True (en alg e) schEqT l r e = foldr (\x b -> dp' (EQ (repr'' alg (evalSchTerm alg x l), repr'' alg (evalSchTerm alg x r))) && b) True (en alg e) -- | Constructs an algebra from a saturated theory with a free type algebra. -- Needs to have satisfaction checked. saturatedInstance :: forall var ty sym en fk att gen sk . (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Schema var ty sym en fk att -> Presentation var ty sym en fk att gen sk -> Err (Instance var ty sym en fk att gen sk gen (Either sk (gen, att))) saturatedInstance sch (Presentation gens sks eqs) = do (fks, atts) <- foldM procEq (Map.empty, Map.empty) eqs checkTotality fks _ <- if Set.null (Typeside.eqs $ typeside sch) then return () else Left "Typeside must be free" let alg = Algebra sch (Set.fromList . gens') (nf1 fks) (nf2 fks) Gen (Set.fromList . sks' atts) (nf' atts) repr' Set.empty pure $ Instance sch (Presentation gens sks eqs) (\(EQ (l, r)) -> l == r) alg where checkTotality :: Map (gen, fk) gen -> Err () checkTotality fks = mapM_ (\en -> if List.null (fksMissing en fks) then pure () else Left $ "Missing equation for " ++ show en) $ Schema.ens sch fksMissing en fks = [ gen | gen <- gens' en, (fk, _) <- fksFrom' sch en, not $ member (gen, fk ) fks ] gens' en = [ gen | (gen, en') <- Map.toList gens, en == en' ] sks' atts ty = [ Left sk | (sk , ty') <- Map.toList sks , ty == ty' ] ++ [ Right (gen, att) | enX :: en <- Set.toList (Schema.ens sch), gen <- gens' enX, (att, t) <- attsFrom' sch (enX :: en), not (member (gen, att) atts), t == ty ] diff = sks '' en ty \\ repr' (Left g) = Sk g repr' (Right (x, att)) = Att att $ Gen x procEq (fks, atts) (EQ (Fk fk (Gen gen), Gen gen')) = case Map.lookup (gen, fk) fks of Nothing -> pure (Map.insert (gen, fk) gen' fks, atts) Just gen'' -> Left $ "Duplicate binding: " ++ show gen ++ " and " ++ show gen'' procEq (fks, atts) (EQ (Att att (Gen gen), w)) | isJust p = case Map.lookup (gen, att) atts of Nothing -> pure (fks, Map.insert (gen, att) (fromJust p) atts) Just gen'' -> Left $ "Duplicate binding: " ++ show gen ++ " and " ++ show gen'' where p = case w of Sk s -> Just $ Sk $ Left s Sym s [] -> Just $ Sym s [] _ -> Nothing procEq _ (EQ (l, r)) = Left $ "Bad eq: " ++ show l ++ " = " ++ show r nf1 _ g = g nf2 fks f a = fks ! (a, f) nf' _ (Left sk) = Sk $ Left sk nf' atts (Right x ) = Map.findWithDefault (Sk (Right x)) x atts --------------------------------------------------------------------------------------------------------------- -- Initial algebras -- | Computes an initial instance (minimal model of a presentation). -- Actually, computes the cannonical term model, where the underlying elements -- of the carriers are equivalence class of terms modulo provable equality in the presentation ( differs from CQL java , which uses fresh IDs ) . -- The term model is constructed by repeatedly adding news terms to the empty model -- until a fixedpoint is reached. initialInstance :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Presentation var ty sym en fk att gen sk -> (EQ (() + var) ty sym en fk att gen sk -> Bool) -> Schema var ty sym en fk att -> Instance var ty sym en fk att gen sk (Carrier en fk gen) (TalgGen en fk att gen sk) initialInstance p dp' sch = Instance sch p dp'' $ initialAlgebra where dp'' (EQ (lhs, rhs)) = dp' $ EQ (upp lhs, upp rhs) initialAlgebra = A.simplify this this = Algebra sch en' nf''' nf'''2 id ty' nf'''' repr'''' teqs' col = IP.toCollage sch p ens' = assembleGens col (close col dp') en' k = ens' ! k nf''' e = nf'''_old $ Gen e nf'''2 f e = nf'''_old $ Fk f e nf'''_old e = let t = typeOf col e f [] = error "impossible, please report" f (a:b) = if dp' (EQ (upp a, upp e)) then a else f b in f $ Set.toList $ ens' ! t tys' = assembleSks col ens' ty' y = tys' ! y nf'''' (Left g) = Sk $ MkTalgGen $ Left g nf'''' (Right (gt, att)) = Sk $ MkTalgGen $ Right (gt, att) repr'''' :: TalgGen en fk att gen sk -> Term Void ty sym en fk att gen sk repr'''' (MkTalgGen (Left g)) = Sk g repr'''' (MkTalgGen (Right (x, att))) = Att att $ upp x teqs'' = concatMap (\(e, EQ (lhs,rhs)) -> fmap (\x -> EQ (nf'' this $ subst' lhs x, nf'' this $ subst' rhs x)) (Set.toList $ en' e)) $ Set.toList $ obs_eqs sch teqs' = Set.union (Set.fromList teqs'') (Set.map (\(EQ (lhs,rhs)) -> EQ (nf'' this lhs, nf'' this rhs)) (Set.filter hasTypeType' $ IP.eqs p)) -- | Assemble Skolem terms (labeled nulls). assembleSks :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> Map en (Set (Carrier en fk gen)) -> Map ty (Set (TalgGen en fk att gen sk)) assembleSks col ens' = unionWith Set.union sks' $ fromListAccum gens' where gens' = concatMap (\(en',set) -> concatMap (\term -> concatMap (\(att,ty') -> [(ty',(MkTalgGen . Right) (term,att))]) $ attsFrom col en') $ Set.toList set) (Map.toList ens') sks' = foldr (\(sk,t) m -> Map.insert t (Set.insert (MkTalgGen . Left $ sk) (m ! t)) m) ret $ Map.toList $ csks col ret = Map.fromSet (const Set.empty) $ ctys col instance NFData InstanceEx where rnf (InstanceEx x) = rnf x TODO move to Collage ? Algebra ? TODO move to Collage ? Algebra ? TODO move to Collage ? Algebra ? close :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> (EQ var ty sym en fk att gen sk -> Bool) -> [Carrier en fk gen] close col dp' = y (close1m dp' col) $ fmap Gen $ Map.keys $ cgens col where y f x = let z = f x in if x == z then x else y f z close1m :: (Foldable t, MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => (EQ var ty sym en fk att gen sk -> Bool) -> Collage var ty sym en fk att gen sk -> t (Term Void Void Void en fk Void gen Void) -> [Carrier en fk gen] close1m dp' col = dedup dp' . concatMap (close1 col dp') dedup :: (EQ var ty sym en fk att gen sk -> Bool) -> [Carrier en fk gen] -> [Carrier en fk gen] dedup dp' = nubBy (\x y -> dp' (EQ (upp x, upp y))) close1 :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> (EQ var ty sym en fk att gen sk -> Bool) -> Carrier en fk gen -> [Carrier en fk gen] close1 col _ e = e:(fmap (\(x,_) -> Fk x e) l) where t = typeOf col e l = fksFrom col t -------------------------------------------------------------------------------------------------------- -- Instance syntax data InstanceExp where InstanceVar :: String -> InstanceExp InstanceInitial :: SchemaExp -> InstanceExp InstanceDelta :: MappingExp -> InstanceExp -> [(String, String)] -> InstanceExp InstanceSigma :: MappingExp -> InstanceExp -> [(String, String)] -> InstanceExp InstancePi :: MappingExp -> InstanceExp -> InstanceExp InstanceEval :: QueryExp -> InstanceExp -> InstanceExp InstanceCoEval :: MappingExp -> InstanceExp -> InstanceExp InstanceRaw :: InstExpRaw' -> InstanceExp InstancePivot :: InstanceExp -> InstanceExp deriving (Eq, Show) instance Deps InstanceExp where deps x = case x of InstanceVar v -> [(v, INSTANCE)] InstanceInitial t -> deps t InstancePivot i -> deps i InstanceDelta f i _ -> (deps f) ++ (deps i) InstanceSigma f i _ -> (deps f) ++ (deps i) InstancePi f i -> (deps f) ++ (deps i) InstanceEval q i -> (deps q) ++ (deps i) InstanceCoEval q i -> (deps q) ++ (deps i) InstanceRaw (InstExpRaw' s _ _ _ i) -> (deps s) ++ (concatMap deps i) getOptionsInstance :: InstanceExp -> [(String, String)] getOptionsInstance x = case x of InstanceVar _ -> [] InstanceInitial _ -> [] InstancePivot _ -> [] InstanceDelta _ _ o -> o InstanceSigma _ _ o -> o InstancePi _ _ -> undefined InstanceEval _ _ -> undefined InstanceCoEval _ _ -> undefined InstanceRaw (InstExpRaw' _ _ _ o _) -> o ---------------------------------------------------------------------------------------------------------------------- -- Literal instances data InstExpRaw' = InstExpRaw' { instraw_schema :: SchemaExp , instraw_gens :: [(String, String)] , instraw_sks : : [ ( String , String ) ] this should maybe change in cql grammar , instraw_oeqs :: [(RawTerm, RawTerm)] , instraw_options :: [(String, String)] , instraw_imports :: [InstanceExp] } deriving (Eq, Show) type Gen = String type Sk = String conv' :: (Typeable ty,Show ty) => [(String, String)] -> Err [(String, ty)] conv' [] = pure [] conv' ((att,ty'):tl) = case cast ty' of Just ty'' -> do x <- conv' tl return $ (att, ty''):x Nothing -> Left $ "Not in schema/typeside: " ++ show ty' split'' :: (Typeable en, Typeable ty, Eq ty, Eq en) => [en] -> [ty] -> [(a, String)] -> Err ([(a, en)], [(a, ty)]) split'' _ _ [] = return ([], []) split'' ens2 tys2 ((w, ei):tl) = do (a,b) <- split'' ens2 tys2 tl if elem' ei ens2 then return ((w, fromJust $ cast ei):a, b) else if elem' ei tys2 then return (a, (w, fromJust $ cast ei):b) else Left $ "Not an entity or type: " ++ show ei evalInstanceRaw' :: forall var ty sym en fk att . (MultiTyMap '[Ord, Typeable] '[ty, sym, en, fk, att]) => Schema var ty sym en fk att -> InstExpRaw' -> [Presentation var ty sym en fk att Gen Sk] -> Err (Presentation var ty sym en fk att Gen Sk) evalInstanceRaw' sch (InstExpRaw' _ gens0 eqs' _ _) is = do (gens', sks') <- split'' (Set.toList $ Schema.ens sch) (Set.toList $ tys $ typeside sch) gens0 gens'' <- toMapSafely gens' gens''' <- return $ Map.toList gens'' sks'' <- toMapSafely sks' sks''' <- return $ Map.toList sks'' let gensX = concatMap (Map.toList . gens) is ++ gens''' sksX = concatMap (Map.toList . sks ) is ++ sks''' eqs'' <- transEq gensX sksX eqs' pure $ Presentation (Map.fromList gensX) (Map.fromList sksX) $ Set.fromList $ (concatMap (Set.toList . IP.eqs) is) ++ (Set.toList eqs'') where keys' = map fst transEq _ _ [] = pure Set.empty transEq gens' sks' ((lhs, rhs):eqs'') = do lhs' <- transTerm (keys' gens') (keys' sks') lhs rhs' <- transTerm (keys' gens') (keys' sks') rhs rest <- transEq gens' sks' eqs'' pure $ Set.insert (EQ (lhs', rhs')) rest transPath :: forall var' ty' sym' en' att'. [String] -> RawTerm -> Err (Term var' ty' sym' en' fk att' String Sk) transPath gens' (RawApp x []) | elem x gens' = pure $ Gen x transPath gens' (RawApp x [a]) | elem' x (Map.keys $ sch_fks sch) = Fk (fromJust $ cast x) <$> transPath gens' a transPath _ x = Left $ "cannot type " ++ show x transTerm :: [String] -> [String] -> RawTerm -> Err (Term Void ty sym en fk att Gen Sk) transTerm gens' _ (RawApp x []) | elem x gens' = pure $ Gen x transTerm _ sks' (RawApp x []) | elem x sks' = pure $ Sk x transTerm gens' _ (RawApp x [a]) | elem' x (Map.keys $ sch_fks sch) = Fk (fromJust $ cast x) <$> transPath gens' a transTerm gens' _ (RawApp x [a]) | elem' x (Map.keys $ sch_atts sch) = Att (fromJust $ cast x) <$> transPath gens' a transTerm gens' sks' (RawApp v l) = case cast v :: Maybe sym of Just x -> Sym x <$> mapM (transTerm gens' sks') l Nothing -> Left $ "Cannot type: " ++ v evalInstanceRaw :: (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att]) => Options -> Schema var ty sym en fk att -> InstExpRaw' -> [InstanceEx] -> Err InstanceEx evalInstanceRaw ops ty' t is = do (i :: [Presentation var ty sym en fk att Gen Sk]) <- doImports is r <- evalInstanceRaw' ty' t i _ <- IP.typecheck ty' r l <- toOptions ops $ instraw_options t if bOps l Interpret_As_Algebra then do j <- saturatedInstance ty' r pure $ InstanceEx j else do p <- createProver (IP.toCollage ty' r) l pure $ InstanceEx $ initialInstance r (prv p) ty' where prv p (EQ (l,r)) = prove p (Map.fromList []) (EQ (l, r)) doImports [] = return [] doImports (InstanceEx ts : r) = case cast (pres ts) of Nothing -> Left "Bad import" Just ts' -> do { r' <- doImports r ; return $ ts' : r' } --------------------------------------------------------------------------------------------------------------- -- Basic instances -- | The empty instance on a schema has no data, so the types of its generators and carriers are 'Void'. emptyInstance :: Schema var ty sym en fk att -> Instance var ty sym en fk att Void Void Void Void emptyInstance ts'' = Instance ts'' (Presentation Map.empty Map.empty Set.empty) (const undefined) (Algebra ts'' (const Set.empty) (const undefined) (const undefined) (const undefined) (const Set.empty) (const undefined) (const undefined) Set.empty) -- | Pivot an instance. The returned schema will not have strings as fks etc, so it will be impossible to write a literal on it, at least for now. ( Java CQL hacks around this by landing on . ) pivot :: forall var ty sym en fk att gen sk x y . (MultiTyMap '[Show, Ord, Typeable] '[var, ty, sym, en, fk, att, gen, sk, x, y]) => Instance var ty sym en fk att gen sk x y -> ( Schema var ty sym (x, en) (x, fk) (x, att) , Instance var ty sym (x, en) (x, fk) (x, att) (x, en) y (x, en) y , Mapping var ty sym (x, en) (x, fk) (x, att) en fk att ) pivot (Instance sch _ idp (Algebra _ ens _ fk fn tys nnf rep2'' teqs)) = (sch', inst, mapp) where sch'_ens = Set.fromList [ (x, en) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en)] sch'_fks = Map.fromList [ ((x, fk0 ), ((x, en), (fk fk0 x, en'))) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en), (fk0, en') <- fksFrom' sch en ] sch'_atts = Map.fromList [ ((x, att0), ((x, en), ty' )) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en), (att0, ty') <- attsFrom' sch en ] sch'_peqs = Set.empty sch'_oeqs = Set.empty dp' :: EQ Void ty sym (x, en) (x, fk) (x, att) (x, en) y -> Bool dp' (EQ (l, r)) = idp $ EQ (instToInst l, instToInst r) ens' = Set.singleton gen' = id fk' (x, f) (x', _) | x == x' = (fk f x', snd $ Schema.sch_fks sch ! f) | otherwise = error "anomaly, please report" rep' = Gen nnf' (Left sk) = Sk sk nnf' (Right ((x, _), (x', att))) | x == x' = nnf $ Right (x', att) | otherwise = error "anomaly, please report" rep2' = Sk gens' = Map.fromList [ ((x, en), (x, en)) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en) ] sks' = Map.fromList [ ( y, ty) | ty <- Set.toList (Typeside.tys $ typeside sch), y <- Set.toList (tys ty) ] eqs' = Set.map (\(EQ (x, y)) -> EQ (repr'' alg' x, repr'' alg' y)) teqs es' = teqs tys' = tys em = Map.fromList [ ((x, en) , en) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en) ] fm = Map.fromList [ ((x, fk ) , Fk fk $ Var ()) | (x, fk ) <- Map.keys sch'_fks ] am = Map.fromList [ ((x, att) , Att att $ Var ()) | (x, att) <- Map.keys sch'_atts ] dp2 :: (x, en) -> EQ () ty sym (x, en) (x, fk) (x, att) Void Void -> Bool dp2 (x, _) (EQ (l, r)) = idp $ EQ (schToInst' x l, schToInst' x r) sch' = Schema (typeside sch) sch'_ens sch'_fks sch'_atts sch'_peqs sch'_oeqs dp2 alg' = Algebra sch' ens' gen' fk' rep' tys' nnf' rep2' es' inst = Instance sch' (Presentation gens' sks' eqs') dp' alg' mapp = Mapping sch' sch em fm am schToInst' :: x -> Term () ty sym (x, en) (x, fk) (x, att) Void Void -> Term Void ty sym en fk att gen sk schToInst' x z = case z of Sym f as -> Sym f $ fmap (schToInst' x) as Att (_, f) a -> Att f $ schToInst' x a Sk x0 -> absurd x0 Var () -> upp $ fn x Fk (_, f) a -> Fk f $ schToInst' x a Gen x0 -> absurd x0 instToInst :: Term Void ty sym (x, en) (x, fk) (x, att) (x, en) y -> Term Void ty sym en fk att gen sk instToInst z = case z of Sym f as -> Sym f $ fmap instToInst as Att (_, f) a -> Att f $ instToInst a Sk y -> rep2'' y Var x -> absurd x Fk (_, f) a -> Fk f $ instToInst a Gen (x, _) -> upp $ fn x --------------------------------------------------------------------------------------------------------------- Functorial data migration subs :: (MultiTyMap '[Ord] '[ty, sym, en, fk, att, en', fk', att', gen, sk]) => Mapping var ty sym en fk att en' fk' att' -> Presentation var ty sym en fk att gen sk -> Presentation var ty sym en' fk' att' gen sk subs (Mapping _ _ ens' fks' atts') (Presentation gens' sks' eqs') = Presentation gens'' sks' eqs'' where gens'' = Map.map (\k -> ens' ! k) gens' eqs'' = Set.map (\(EQ (l, r)) -> EQ (changeEn fks' atts' l, changeEn fks' atts' r)) eqs' changeEn :: (Ord k1, Ord k2, Eq var) => Map k1 (Term () Void Void en1 fk Void Void Void) -> Map k2 (Term () ty1 sym en1 fk att Void Void) -> Term Void ty2 sym en2 k1 k2 gen sk -> Term var ty1 sym en1 fk att gen sk changeEn fks' atts' t = case t of Var v -> absurd v Sym h as -> Sym h $ changeEn fks' atts' <$> as Sk k -> Sk k Gen g -> Gen g Fk h a -> subst (upp $ fks' ! h) $ changeEn fks' atts' a Att h a -> subst (upp $ atts' ! h) $ changeEn fks' atts' a changeEn' :: (Ord k, Eq var) => Map k (Term () Void Void en1 fk Void Void Void) -> t -> Term Void ty1 Void en2 k Void gen Void -> Term var ty2 sym en1 fk att gen sk changeEn' fks' atts' t = case t of Var v -> absurd v Sym h _ -> absurd h Sk k -> absurd k Gen g -> Gen g Fk h a -> subst (upp $ fks' ! h) $ changeEn' fks' atts' a Att h _ -> absurd h evalSigmaInst :: (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att, en', fk', att', gen, sk]) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en fk att gen sk x y -> Options -> Err (Instance var ty sym en' fk' att' gen sk (Carrier en' fk' gen) (TalgGen en' fk' att' gen sk)) evalSigmaInst f i o = do d <- createProver (IP.toCollage s p) o return $ initialInstance p (\(EQ (l, r)) -> prove d Map.empty (EQ (l, r))) s where p = subs f $ pres i s = dst f mapGen :: (t1 -> t2) -> Term var ty sym en (t2 -> t2) att t1 sk -> t2 mapGen f (Gen g) = f g mapGen f (Fk fk a) = fk $ mapGen f a mapGen _ _ = error "please report, error on mapGen" evalDeltaAlgebra :: forall var ty sym en fk att gen sk x y en' fk' att' . (Ord en, Ord fk, Ord att, Ord x) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en' fk' att' gen sk x y -> Algebra var ty sym en fk att (en, x) y (en, x) y evalDeltaAlgebra (Mapping src' _ ens' fks0 atts0) (Instance _ _ _ alg@(Algebra _ en' _ _ repr''' ty' _ _ teqs')) = Algebra src' en'' nf''x1 nf''x2 Gen ty' nf'''' Sk teqs' where en'' e = Set.map (\x -> (e,x)) $ en' $ ens' ! e nf''x1 g = g nf''x2 f a = (snd $ Schema.fks src' ! f, nf alg $ subst (upp $ fks0 ! f) (repr''' $ snd a)) nf'''' :: y + ((en,x), att) -> Term Void ty sym Void Void Void Void y nf'''' (Left y) = Sk y nf'''' (Right ((_, x), att)) = nf'' alg $ subst (upp $ atts0 ! att) (upp $ repr''' x) evalDeltaInst :: forall var ty sym en fk att gen sk x y en' fk' att' . (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, x, y]) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en' fk' att' gen sk x y -> Options -> Err (Instance var ty sym en fk att (en,x) y (en,x) y) evalDeltaInst m i _ = pure $ Instance (src m) (algebraToPresentation alg) eq' alg where alg = evalDeltaAlgebra m i eq' (EQ (l, r)) = dp i $ EQ (translateTerm l, translateTerm r) translateTerm :: Term Void ty sym en fk att (en, x) y -> Term Void ty sym en' fk' att' gen sk translateTerm t = case t of Var v -> absurd v Sym s' as -> Sym s' $ translateTerm <$> as Fk fk a -> subst (upp $ Mapping.fks m ! fk ) $ translateTerm a Att att a -> subst (upp $ Mapping.atts m ! att) $ translateTerm a Gen (_, x) -> upp $ repr (algebra i) x Sk y -> repr' (algebra i) y ------------------------------------------------------------------------------------------------------------------- -- Printing InstanceEx is an implementation detail , so hide its presence instance (Show InstanceEx) where show (InstanceEx i) = show i instance (TyMap Show '[var, ty, sym, en, fk, att, gen, sk, x, y], Eq en, Eq fk, Eq att) => Show (Instance var ty sym en fk att gen sk x y) where show (Instance _ p _ alg) = section "instance" $ unlines [ section "presentation" $ show p , section "algebra" $ show alg ]
null
https://raw.githubusercontent.com/statebox/cql/b155e737ef4977ec753e44790f236686ff6a4558/src/Language/CQL/Instance.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE ExplicitForAll # # LANGUAGE FlexibleContexts # # LANGUAGE LiberalTypeSynonyms # # LANGUAGE RankNTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeOperators # # LANGUAGE TypeSynonymInstances # | A database instance on a schema. Contains a presentation, an algebra, and a decision procedure. | True if the type algebra is empty, which approximates it being free, which approximates it being conservative over the typeside. | Just syntactic equality of the theory for now. | A dynamically typed instance. | Checks that an 'Instance' satisfies its 'Schema'. | Constructs an algebra from a saturated theory with a free type algebra. Needs to have satisfaction checked. ------------------------------------------------------------------------------------------------------------- Initial algebras | Computes an initial instance (minimal model of a presentation). Actually, computes the cannonical term model, where the underlying elements of the carriers are equivalence class of terms modulo provable equality The term model is constructed by repeatedly adding news terms to the empty model until a fixedpoint is reached. | Assemble Skolem terms (labeled nulls). ------------------------------------------------------------------------------------------------------ Instance syntax -------------------------------------------------------------------------------------------------------------------- Literal instances ------------------------------------------------------------------------------------------------------------- Basic instances | The empty instance on a schema has no data, so the types of its generators and carriers are 'Void'. | Pivot an instance. The returned schema will not have strings as fks etc, so it will be impossible to write a literal on it, at least for now. ------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- Printing
SPDX - License - Identifier : AGPL-3.0 - only This file is part of ` statebox / cql ` , the categorical query language . Copyright ( C ) 2019 < 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 < / > . SPDX-License-Identifier: AGPL-3.0-only This file is part of `statebox/cql`, the categorical query language. Copyright (C) 2019 Stichting Statebox <> 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 </>. -} # LANGUAGE AllowAmbiguousTypes # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleInstances # # LANGUAGE GADTs # # LANGUAGE KindSignatures # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TupleSections # # LANGUAGE UndecidableInstances # module Language.CQL.Instance where import Control.DeepSeq import Control.Monad import Data.List as List hiding (intercalate) import Data.Map.Strict (Map, member, unionWith, (!)) import qualified Data.Map.Strict as Map import Data.Maybe import Data.Set (Set) import qualified Data.Set as Set import Data.Typeable hiding (typeOf) import Data.Void import Language.CQL.Collage (Collage(..), assembleGens, attsFrom, fksFrom, typeOf) import Language.CQL.Common (elem', fromListAccum, section, toMapSafely, Deps(..), Err, Kind(INSTANCE), MultiTyMap, TyMap, type (+)) import Language.CQL.Instance.Algebra (Algebra(..), aAtt, Carrier, down1, evalSchTerm, evalSchTerm', nf, nf'', repr'', TalgGen(..)) import qualified Language.CQL.Instance.Algebra as A (simplify) import Language.CQL.Instance.Presentation (Presentation(..)) import qualified Language.CQL.Instance.Presentation as IP (toCollage, typecheck, Presentation(eqs)) import Language.CQL.Mapping as Mapping import Language.CQL.Options import Language.CQL.Prover import Language.CQL.Query import Language.CQL.Schema as Schema import Language.CQL.Term as Term import Language.CQL.Typeside as Typeside import Prelude hiding (EQ) data Instance var ty sym en fk att gen sk x y = Instance { schema :: Schema var ty sym en fk att , pres :: Presentation var ty sym en fk att gen sk , dp :: EQ Void ty sym en fk att gen sk -> Bool , algebra :: Algebra var ty sym en fk att gen sk x y } freeTalg :: Instance var ty sym en fk att gen sk x y -> Bool freeTalg (Instance _ _ _ (Algebra _ _ _ _ _ _ _ _ teqs)) = Prelude.null teqs instance TyMap Eq '[var, ty, sym, en, fk, att, gen, sk, x, y] => Eq (Instance var ty sym en fk att gen sk x y) where (==) (Instance schema' (Presentation gens' sks' eqs' ) _ _) (Instance schema'' (Presentation gens'' sks'' eqs'') _ _) = (schema' == schema'') && (gens' == gens'') && (sks' == sks'') && (eqs' == eqs'') instance TyMap NFData '[var, ty, sym, en, fk, att, gen, sk, x, y] => NFData (Instance var ty sym en fk att gen sk x y) where rnf (Instance s0 p0 dp0 a0) = deepseq s0 $ deepseq p0 $ deepseq dp0 $ rnf a0 data InstanceEx :: * where InstanceEx :: forall var ty sym en fk att gen sk x y . (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att, gen, sk, x, y]) => Instance var ty sym en fk att gen sk x y -> InstanceEx | Converts an algebra into a presentation : adds one equation per fact in the algebra , and one generator per element . Presentations in this form are called saturated because they are maximally large without being redundant . @I(fk.x ) = I(fk)(I(x))@ algebraToPresentation :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk], Ord y, Ord x) => Algebra var ty sym en fk att gen sk x y -> Presentation var ty sym en fk att x y algebraToPresentation alg@(Algebra sch en' _ _ _ ty' _ _ _) = Presentation gens' sks' eqs' where gens' = Map.fromList $ reify en' $ Schema.ens sch sks' = Map.fromList $ reify ty' $ Typeside.tys $ Schema.typeside sch eqs1 = concatMap fksToEqs reified eqs2 = concatMap attsToEqs reified eqs' = Set.fromList $ eqs1 ++ eqs2 reified = reify en' $ Schema.ens sch fksToEqs (x, e) = (\(fk , _) -> fkToEq x fk ) <$> fksFrom' sch e attsToEqs (x, e) = (\(att, _) -> attToEq x att) <$> attsFrom' sch e fkToEq x fk = EQ (Fk fk (Gen x), Gen $ aFk alg fk x) attToEq x att = EQ (Att att (Gen x), upp $ aAtt alg att x) reify :: (Ord x, Ord en) => (en -> Set x) -> Set en -> [(x, en)] reify f s = concat $ Set.toList $ Set.map (\en'-> Set.toList $ Set.map (, en') $ f en') s satisfiesSchema :: (MultiTyMap '[Show] '[var, ty, sym, en, fk, att, gen, sk, x, y], Eq x) => Instance var ty sym en fk att gen sk x y -> Err () satisfiesSchema (Instance sch pres' dp' alg) = do mapM_ (\( EQ (l, r)) -> if hasTypeType l then report (show l) (show r) (instEqT l r) else report (show l) (show r) (instEqE l r)) $ Set.toList $ IP.eqs pres' mapM_ (\(en'', EQ (l, r)) -> report (show l) (show r) (schEqT l r en'')) $ Set.toList $ obs_eqs sch mapM_ (\(en'', EQ (l, r)) -> report (show l) (show r) (schEqE l r en'')) $ Set.toList $ path_eqs sch where Morally , we should create a new dp ( decision procedure ) for the talg , but that 's computationally intractable , and this check still helps . instEqE l r = nf alg (down1 l) == nf alg (down1 r) instEqT l r = dp' $ EQ ((repr'' alg (nf'' alg l)), (repr'' alg (nf'' alg r))) report _ _ True = return () report l r False = Left $ "Not satisfied: " ++ l ++ " = " ++ r schEqE l r e = foldr (\x b -> (evalSchTerm' alg x l == evalSchTerm' alg x r) && b) True (en alg e) schEqT l r e = foldr (\x b -> dp' (EQ (repr'' alg (evalSchTerm alg x l), repr'' alg (evalSchTerm alg x r))) && b) True (en alg e) saturatedInstance :: forall var ty sym en fk att gen sk . (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Schema var ty sym en fk att -> Presentation var ty sym en fk att gen sk -> Err (Instance var ty sym en fk att gen sk gen (Either sk (gen, att))) saturatedInstance sch (Presentation gens sks eqs) = do (fks, atts) <- foldM procEq (Map.empty, Map.empty) eqs checkTotality fks _ <- if Set.null (Typeside.eqs $ typeside sch) then return () else Left "Typeside must be free" let alg = Algebra sch (Set.fromList . gens') (nf1 fks) (nf2 fks) Gen (Set.fromList . sks' atts) (nf' atts) repr' Set.empty pure $ Instance sch (Presentation gens sks eqs) (\(EQ (l, r)) -> l == r) alg where checkTotality :: Map (gen, fk) gen -> Err () checkTotality fks = mapM_ (\en -> if List.null (fksMissing en fks) then pure () else Left $ "Missing equation for " ++ show en) $ Schema.ens sch fksMissing en fks = [ gen | gen <- gens' en, (fk, _) <- fksFrom' sch en, not $ member (gen, fk ) fks ] gens' en = [ gen | (gen, en') <- Map.toList gens, en == en' ] sks' atts ty = [ Left sk | (sk , ty') <- Map.toList sks , ty == ty' ] ++ [ Right (gen, att) | enX :: en <- Set.toList (Schema.ens sch), gen <- gens' enX, (att, t) <- attsFrom' sch (enX :: en), not (member (gen, att) atts), t == ty ] diff = sks '' en ty \\ repr' (Left g) = Sk g repr' (Right (x, att)) = Att att $ Gen x procEq (fks, atts) (EQ (Fk fk (Gen gen), Gen gen')) = case Map.lookup (gen, fk) fks of Nothing -> pure (Map.insert (gen, fk) gen' fks, atts) Just gen'' -> Left $ "Duplicate binding: " ++ show gen ++ " and " ++ show gen'' procEq (fks, atts) (EQ (Att att (Gen gen), w)) | isJust p = case Map.lookup (gen, att) atts of Nothing -> pure (fks, Map.insert (gen, att) (fromJust p) atts) Just gen'' -> Left $ "Duplicate binding: " ++ show gen ++ " and " ++ show gen'' where p = case w of Sk s -> Just $ Sk $ Left s Sym s [] -> Just $ Sym s [] _ -> Nothing procEq _ (EQ (l, r)) = Left $ "Bad eq: " ++ show l ++ " = " ++ show r nf1 _ g = g nf2 fks f a = fks ! (a, f) nf' _ (Left sk) = Sk $ Left sk nf' atts (Right x ) = Map.findWithDefault (Sk (Right x)) x atts in the presentation ( differs from CQL java , which uses fresh IDs ) . initialInstance :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Presentation var ty sym en fk att gen sk -> (EQ (() + var) ty sym en fk att gen sk -> Bool) -> Schema var ty sym en fk att -> Instance var ty sym en fk att gen sk (Carrier en fk gen) (TalgGen en fk att gen sk) initialInstance p dp' sch = Instance sch p dp'' $ initialAlgebra where dp'' (EQ (lhs, rhs)) = dp' $ EQ (upp lhs, upp rhs) initialAlgebra = A.simplify this this = Algebra sch en' nf''' nf'''2 id ty' nf'''' repr'''' teqs' col = IP.toCollage sch p ens' = assembleGens col (close col dp') en' k = ens' ! k nf''' e = nf'''_old $ Gen e nf'''2 f e = nf'''_old $ Fk f e nf'''_old e = let t = typeOf col e f [] = error "impossible, please report" f (a:b) = if dp' (EQ (upp a, upp e)) then a else f b in f $ Set.toList $ ens' ! t tys' = assembleSks col ens' ty' y = tys' ! y nf'''' (Left g) = Sk $ MkTalgGen $ Left g nf'''' (Right (gt, att)) = Sk $ MkTalgGen $ Right (gt, att) repr'''' :: TalgGen en fk att gen sk -> Term Void ty sym en fk att gen sk repr'''' (MkTalgGen (Left g)) = Sk g repr'''' (MkTalgGen (Right (x, att))) = Att att $ upp x teqs'' = concatMap (\(e, EQ (lhs,rhs)) -> fmap (\x -> EQ (nf'' this $ subst' lhs x, nf'' this $ subst' rhs x)) (Set.toList $ en' e)) $ Set.toList $ obs_eqs sch teqs' = Set.union (Set.fromList teqs'') (Set.map (\(EQ (lhs,rhs)) -> EQ (nf'' this lhs, nf'' this rhs)) (Set.filter hasTypeType' $ IP.eqs p)) assembleSks :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> Map en (Set (Carrier en fk gen)) -> Map ty (Set (TalgGen en fk att gen sk)) assembleSks col ens' = unionWith Set.union sks' $ fromListAccum gens' where gens' = concatMap (\(en',set) -> concatMap (\term -> concatMap (\(att,ty') -> [(ty',(MkTalgGen . Right) (term,att))]) $ attsFrom col en') $ Set.toList set) (Map.toList ens') sks' = foldr (\(sk,t) m -> Map.insert t (Set.insert (MkTalgGen . Left $ sk) (m ! t)) m) ret $ Map.toList $ csks col ret = Map.fromSet (const Set.empty) $ ctys col instance NFData InstanceEx where rnf (InstanceEx x) = rnf x TODO move to Collage ? Algebra ? TODO move to Collage ? Algebra ? TODO move to Collage ? Algebra ? close :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> (EQ var ty sym en fk att gen sk -> Bool) -> [Carrier en fk gen] close col dp' = y (close1m dp' col) $ fmap Gen $ Map.keys $ cgens col where y f x = let z = f x in if x == z then x else y f z close1m :: (Foldable t, MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => (EQ var ty sym en fk att gen sk -> Bool) -> Collage var ty sym en fk att gen sk -> t (Term Void Void Void en fk Void gen Void) -> [Carrier en fk gen] close1m dp' col = dedup dp' . concatMap (close1 col dp') dedup :: (EQ var ty sym en fk att gen sk -> Bool) -> [Carrier en fk gen] -> [Carrier en fk gen] dedup dp' = nubBy (\x y -> dp' (EQ (upp x, upp y))) close1 :: (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, gen, sk]) => Collage var ty sym en fk att gen sk -> (EQ var ty sym en fk att gen sk -> Bool) -> Carrier en fk gen -> [Carrier en fk gen] close1 col _ e = e:(fmap (\(x,_) -> Fk x e) l) where t = typeOf col e l = fksFrom col t data InstanceExp where InstanceVar :: String -> InstanceExp InstanceInitial :: SchemaExp -> InstanceExp InstanceDelta :: MappingExp -> InstanceExp -> [(String, String)] -> InstanceExp InstanceSigma :: MappingExp -> InstanceExp -> [(String, String)] -> InstanceExp InstancePi :: MappingExp -> InstanceExp -> InstanceExp InstanceEval :: QueryExp -> InstanceExp -> InstanceExp InstanceCoEval :: MappingExp -> InstanceExp -> InstanceExp InstanceRaw :: InstExpRaw' -> InstanceExp InstancePivot :: InstanceExp -> InstanceExp deriving (Eq, Show) instance Deps InstanceExp where deps x = case x of InstanceVar v -> [(v, INSTANCE)] InstanceInitial t -> deps t InstancePivot i -> deps i InstanceDelta f i _ -> (deps f) ++ (deps i) InstanceSigma f i _ -> (deps f) ++ (deps i) InstancePi f i -> (deps f) ++ (deps i) InstanceEval q i -> (deps q) ++ (deps i) InstanceCoEval q i -> (deps q) ++ (deps i) InstanceRaw (InstExpRaw' s _ _ _ i) -> (deps s) ++ (concatMap deps i) getOptionsInstance :: InstanceExp -> [(String, String)] getOptionsInstance x = case x of InstanceVar _ -> [] InstanceInitial _ -> [] InstancePivot _ -> [] InstanceDelta _ _ o -> o InstanceSigma _ _ o -> o InstancePi _ _ -> undefined InstanceEval _ _ -> undefined InstanceCoEval _ _ -> undefined InstanceRaw (InstExpRaw' _ _ _ o _) -> o data InstExpRaw' = InstExpRaw' { instraw_schema :: SchemaExp , instraw_gens :: [(String, String)] , instraw_sks : : [ ( String , String ) ] this should maybe change in cql grammar , instraw_oeqs :: [(RawTerm, RawTerm)] , instraw_options :: [(String, String)] , instraw_imports :: [InstanceExp] } deriving (Eq, Show) type Gen = String type Sk = String conv' :: (Typeable ty,Show ty) => [(String, String)] -> Err [(String, ty)] conv' [] = pure [] conv' ((att,ty'):tl) = case cast ty' of Just ty'' -> do x <- conv' tl return $ (att, ty''):x Nothing -> Left $ "Not in schema/typeside: " ++ show ty' split'' :: (Typeable en, Typeable ty, Eq ty, Eq en) => [en] -> [ty] -> [(a, String)] -> Err ([(a, en)], [(a, ty)]) split'' _ _ [] = return ([], []) split'' ens2 tys2 ((w, ei):tl) = do (a,b) <- split'' ens2 tys2 tl if elem' ei ens2 then return ((w, fromJust $ cast ei):a, b) else if elem' ei tys2 then return (a, (w, fromJust $ cast ei):b) else Left $ "Not an entity or type: " ++ show ei evalInstanceRaw' :: forall var ty sym en fk att . (MultiTyMap '[Ord, Typeable] '[ty, sym, en, fk, att]) => Schema var ty sym en fk att -> InstExpRaw' -> [Presentation var ty sym en fk att Gen Sk] -> Err (Presentation var ty sym en fk att Gen Sk) evalInstanceRaw' sch (InstExpRaw' _ gens0 eqs' _ _) is = do (gens', sks') <- split'' (Set.toList $ Schema.ens sch) (Set.toList $ tys $ typeside sch) gens0 gens'' <- toMapSafely gens' gens''' <- return $ Map.toList gens'' sks'' <- toMapSafely sks' sks''' <- return $ Map.toList sks'' let gensX = concatMap (Map.toList . gens) is ++ gens''' sksX = concatMap (Map.toList . sks ) is ++ sks''' eqs'' <- transEq gensX sksX eqs' pure $ Presentation (Map.fromList gensX) (Map.fromList sksX) $ Set.fromList $ (concatMap (Set.toList . IP.eqs) is) ++ (Set.toList eqs'') where keys' = map fst transEq _ _ [] = pure Set.empty transEq gens' sks' ((lhs, rhs):eqs'') = do lhs' <- transTerm (keys' gens') (keys' sks') lhs rhs' <- transTerm (keys' gens') (keys' sks') rhs rest <- transEq gens' sks' eqs'' pure $ Set.insert (EQ (lhs', rhs')) rest transPath :: forall var' ty' sym' en' att'. [String] -> RawTerm -> Err (Term var' ty' sym' en' fk att' String Sk) transPath gens' (RawApp x []) | elem x gens' = pure $ Gen x transPath gens' (RawApp x [a]) | elem' x (Map.keys $ sch_fks sch) = Fk (fromJust $ cast x) <$> transPath gens' a transPath _ x = Left $ "cannot type " ++ show x transTerm :: [String] -> [String] -> RawTerm -> Err (Term Void ty sym en fk att Gen Sk) transTerm gens' _ (RawApp x []) | elem x gens' = pure $ Gen x transTerm _ sks' (RawApp x []) | elem x sks' = pure $ Sk x transTerm gens' _ (RawApp x [a]) | elem' x (Map.keys $ sch_fks sch) = Fk (fromJust $ cast x) <$> transPath gens' a transTerm gens' _ (RawApp x [a]) | elem' x (Map.keys $ sch_atts sch) = Att (fromJust $ cast x) <$> transPath gens' a transTerm gens' sks' (RawApp v l) = case cast v :: Maybe sym of Just x -> Sym x <$> mapM (transTerm gens' sks') l Nothing -> Left $ "Cannot type: " ++ v evalInstanceRaw :: (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att]) => Options -> Schema var ty sym en fk att -> InstExpRaw' -> [InstanceEx] -> Err InstanceEx evalInstanceRaw ops ty' t is = do (i :: [Presentation var ty sym en fk att Gen Sk]) <- doImports is r <- evalInstanceRaw' ty' t i _ <- IP.typecheck ty' r l <- toOptions ops $ instraw_options t if bOps l Interpret_As_Algebra then do j <- saturatedInstance ty' r pure $ InstanceEx j else do p <- createProver (IP.toCollage ty' r) l pure $ InstanceEx $ initialInstance r (prv p) ty' where prv p (EQ (l,r)) = prove p (Map.fromList []) (EQ (l, r)) doImports [] = return [] doImports (InstanceEx ts : r) = case cast (pres ts) of Nothing -> Left "Bad import" Just ts' -> do { r' <- doImports r ; return $ ts' : r' } emptyInstance :: Schema var ty sym en fk att -> Instance var ty sym en fk att Void Void Void Void emptyInstance ts'' = Instance ts'' (Presentation Map.empty Map.empty Set.empty) (const undefined) (Algebra ts'' (const Set.empty) (const undefined) (const undefined) (const undefined) (const Set.empty) (const undefined) (const undefined) Set.empty) ( Java CQL hacks around this by landing on . ) pivot :: forall var ty sym en fk att gen sk x y . (MultiTyMap '[Show, Ord, Typeable] '[var, ty, sym, en, fk, att, gen, sk, x, y]) => Instance var ty sym en fk att gen sk x y -> ( Schema var ty sym (x, en) (x, fk) (x, att) , Instance var ty sym (x, en) (x, fk) (x, att) (x, en) y (x, en) y , Mapping var ty sym (x, en) (x, fk) (x, att) en fk att ) pivot (Instance sch _ idp (Algebra _ ens _ fk fn tys nnf rep2'' teqs)) = (sch', inst, mapp) where sch'_ens = Set.fromList [ (x, en) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en)] sch'_fks = Map.fromList [ ((x, fk0 ), ((x, en), (fk fk0 x, en'))) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en), (fk0, en') <- fksFrom' sch en ] sch'_atts = Map.fromList [ ((x, att0), ((x, en), ty' )) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en), (att0, ty') <- attsFrom' sch en ] sch'_peqs = Set.empty sch'_oeqs = Set.empty dp' :: EQ Void ty sym (x, en) (x, fk) (x, att) (x, en) y -> Bool dp' (EQ (l, r)) = idp $ EQ (instToInst l, instToInst r) ens' = Set.singleton gen' = id fk' (x, f) (x', _) | x == x' = (fk f x', snd $ Schema.sch_fks sch ! f) | otherwise = error "anomaly, please report" rep' = Gen nnf' (Left sk) = Sk sk nnf' (Right ((x, _), (x', att))) | x == x' = nnf $ Right (x', att) | otherwise = error "anomaly, please report" rep2' = Sk gens' = Map.fromList [ ((x, en), (x, en)) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en) ] sks' = Map.fromList [ ( y, ty) | ty <- Set.toList (Typeside.tys $ typeside sch), y <- Set.toList (tys ty) ] eqs' = Set.map (\(EQ (x, y)) -> EQ (repr'' alg' x, repr'' alg' y)) teqs es' = teqs tys' = tys em = Map.fromList [ ((x, en) , en) | en <- Set.toList (Schema.ens sch), x <- Set.toList (ens en) ] fm = Map.fromList [ ((x, fk ) , Fk fk $ Var ()) | (x, fk ) <- Map.keys sch'_fks ] am = Map.fromList [ ((x, att) , Att att $ Var ()) | (x, att) <- Map.keys sch'_atts ] dp2 :: (x, en) -> EQ () ty sym (x, en) (x, fk) (x, att) Void Void -> Bool dp2 (x, _) (EQ (l, r)) = idp $ EQ (schToInst' x l, schToInst' x r) sch' = Schema (typeside sch) sch'_ens sch'_fks sch'_atts sch'_peqs sch'_oeqs dp2 alg' = Algebra sch' ens' gen' fk' rep' tys' nnf' rep2' es' inst = Instance sch' (Presentation gens' sks' eqs') dp' alg' mapp = Mapping sch' sch em fm am schToInst' :: x -> Term () ty sym (x, en) (x, fk) (x, att) Void Void -> Term Void ty sym en fk att gen sk schToInst' x z = case z of Sym f as -> Sym f $ fmap (schToInst' x) as Att (_, f) a -> Att f $ schToInst' x a Sk x0 -> absurd x0 Var () -> upp $ fn x Fk (_, f) a -> Fk f $ schToInst' x a Gen x0 -> absurd x0 instToInst :: Term Void ty sym (x, en) (x, fk) (x, att) (x, en) y -> Term Void ty sym en fk att gen sk instToInst z = case z of Sym f as -> Sym f $ fmap instToInst as Att (_, f) a -> Att f $ instToInst a Sk y -> rep2'' y Var x -> absurd x Fk (_, f) a -> Fk f $ instToInst a Gen (x, _) -> upp $ fn x Functorial data migration subs :: (MultiTyMap '[Ord] '[ty, sym, en, fk, att, en', fk', att', gen, sk]) => Mapping var ty sym en fk att en' fk' att' -> Presentation var ty sym en fk att gen sk -> Presentation var ty sym en' fk' att' gen sk subs (Mapping _ _ ens' fks' atts') (Presentation gens' sks' eqs') = Presentation gens'' sks' eqs'' where gens'' = Map.map (\k -> ens' ! k) gens' eqs'' = Set.map (\(EQ (l, r)) -> EQ (changeEn fks' atts' l, changeEn fks' atts' r)) eqs' changeEn :: (Ord k1, Ord k2, Eq var) => Map k1 (Term () Void Void en1 fk Void Void Void) -> Map k2 (Term () ty1 sym en1 fk att Void Void) -> Term Void ty2 sym en2 k1 k2 gen sk -> Term var ty1 sym en1 fk att gen sk changeEn fks' atts' t = case t of Var v -> absurd v Sym h as -> Sym h $ changeEn fks' atts' <$> as Sk k -> Sk k Gen g -> Gen g Fk h a -> subst (upp $ fks' ! h) $ changeEn fks' atts' a Att h a -> subst (upp $ atts' ! h) $ changeEn fks' atts' a changeEn' :: (Ord k, Eq var) => Map k (Term () Void Void en1 fk Void Void Void) -> t -> Term Void ty1 Void en2 k Void gen Void -> Term var ty2 sym en1 fk att gen sk changeEn' fks' atts' t = case t of Var v -> absurd v Sym h _ -> absurd h Sk k -> absurd k Gen g -> Gen g Fk h a -> subst (upp $ fks' ! h) $ changeEn' fks' atts' a Att h _ -> absurd h evalSigmaInst :: (MultiTyMap '[Show, Ord, Typeable, NFData] '[var, ty, sym, en, fk, att, en', fk', att', gen, sk]) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en fk att gen sk x y -> Options -> Err (Instance var ty sym en' fk' att' gen sk (Carrier en' fk' gen) (TalgGen en' fk' att' gen sk)) evalSigmaInst f i o = do d <- createProver (IP.toCollage s p) o return $ initialInstance p (\(EQ (l, r)) -> prove d Map.empty (EQ (l, r))) s where p = subs f $ pres i s = dst f mapGen :: (t1 -> t2) -> Term var ty sym en (t2 -> t2) att t1 sk -> t2 mapGen f (Gen g) = f g mapGen f (Fk fk a) = fk $ mapGen f a mapGen _ _ = error "please report, error on mapGen" evalDeltaAlgebra :: forall var ty sym en fk att gen sk x y en' fk' att' . (Ord en, Ord fk, Ord att, Ord x) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en' fk' att' gen sk x y -> Algebra var ty sym en fk att (en, x) y (en, x) y evalDeltaAlgebra (Mapping src' _ ens' fks0 atts0) (Instance _ _ _ alg@(Algebra _ en' _ _ repr''' ty' _ _ teqs')) = Algebra src' en'' nf''x1 nf''x2 Gen ty' nf'''' Sk teqs' where en'' e = Set.map (\x -> (e,x)) $ en' $ ens' ! e nf''x1 g = g nf''x2 f a = (snd $ Schema.fks src' ! f, nf alg $ subst (upp $ fks0 ! f) (repr''' $ snd a)) nf'''' :: y + ((en,x), att) -> Term Void ty sym Void Void Void Void y nf'''' (Left y) = Sk y nf'''' (Right ((_, x), att)) = nf'' alg $ subst (upp $ atts0 ! att) (upp $ repr''' x) evalDeltaInst :: forall var ty sym en fk att gen sk x y en' fk' att' . (MultiTyMap '[Show, Ord, NFData] '[var, ty, sym, en, fk, att, x, y]) => Mapping var ty sym en fk att en' fk' att' -> Instance var ty sym en' fk' att' gen sk x y -> Options -> Err (Instance var ty sym en fk att (en,x) y (en,x) y) evalDeltaInst m i _ = pure $ Instance (src m) (algebraToPresentation alg) eq' alg where alg = evalDeltaAlgebra m i eq' (EQ (l, r)) = dp i $ EQ (translateTerm l, translateTerm r) translateTerm :: Term Void ty sym en fk att (en, x) y -> Term Void ty sym en' fk' att' gen sk translateTerm t = case t of Var v -> absurd v Sym s' as -> Sym s' $ translateTerm <$> as Fk fk a -> subst (upp $ Mapping.fks m ! fk ) $ translateTerm a Att att a -> subst (upp $ Mapping.atts m ! att) $ translateTerm a Gen (_, x) -> upp $ repr (algebra i) x Sk y -> repr' (algebra i) y InstanceEx is an implementation detail , so hide its presence instance (Show InstanceEx) where show (InstanceEx i) = show i instance (TyMap Show '[var, ty, sym, en, fk, att, gen, sk, x, y], Eq en, Eq fk, Eq att) => Show (Instance var ty sym en fk att gen sk x y) where show (Instance _ p _ alg) = section "instance" $ unlines [ section "presentation" $ show p , section "algebra" $ show alg ]
46e2e67699ad2f8851ea3f6fe9a90ee565bd3efc9928c7fd9ad968d0847bdcc4
faylang/fay
CompileError.hs
module Fay.Types.CompileError (CompileError (..)) where import qualified Fay.Exts as F import qualified Fay.Exts.NoAnnotation as N import qualified Fay.Exts.Scoped as S import Language.Haskell.Exts -- | Error type. data CompileError = Couldn'tFindImport N.ModuleName [FilePath] | EmptyDoBlock | FfiFormatBadChars SrcSpanInfo String | FfiFormatIncompleteArg SrcSpanInfo | FfiFormatInvalidJavaScript SrcSpanInfo String String | FfiFormatNoSuchArg SrcSpanInfo Int | FfiNeedsTypeSig S.Exp | GHCError String | InvalidDoBlock | ParseError S.SrcLoc String | ShouldBeDesugared String | UnableResolveQualified N.QName | UnsupportedDeclaration S.Decl | UnsupportedEnum N.Exp | UnsupportedExportSpec N.ExportSpec | UnsupportedExpression S.Exp | UnsupportedFieldPattern S.PatField | UnsupportedImport F.ImportDecl | UnsupportedLet | UnsupportedLetBinding S.Decl | UnsupportedLiteral S.Literal | UnsupportedModuleSyntax String F.Module | UnsupportedPattern S.Pat | UnsupportedQualStmt S.QualStmt | UnsupportedRecursiveDo | UnsupportedRhs S.Rhs | UnsupportedWhereInAlt S.Alt | UnsupportedWhereInMatch S.Match deriving (Show) {-# ANN module "HLint: ignore Use camelCase" #-}
null
https://raw.githubusercontent.com/faylang/fay/8455d975f9f0db2ecc922410e43e484fbd134699/src/Fay/Types/CompileError.hs
haskell
| Error type. # ANN module "HLint: ignore Use camelCase" #
module Fay.Types.CompileError (CompileError (..)) where import qualified Fay.Exts as F import qualified Fay.Exts.NoAnnotation as N import qualified Fay.Exts.Scoped as S import Language.Haskell.Exts data CompileError = Couldn'tFindImport N.ModuleName [FilePath] | EmptyDoBlock | FfiFormatBadChars SrcSpanInfo String | FfiFormatIncompleteArg SrcSpanInfo | FfiFormatInvalidJavaScript SrcSpanInfo String String | FfiFormatNoSuchArg SrcSpanInfo Int | FfiNeedsTypeSig S.Exp | GHCError String | InvalidDoBlock | ParseError S.SrcLoc String | ShouldBeDesugared String | UnableResolveQualified N.QName | UnsupportedDeclaration S.Decl | UnsupportedEnum N.Exp | UnsupportedExportSpec N.ExportSpec | UnsupportedExpression S.Exp | UnsupportedFieldPattern S.PatField | UnsupportedImport F.ImportDecl | UnsupportedLet | UnsupportedLetBinding S.Decl | UnsupportedLiteral S.Literal | UnsupportedModuleSyntax String F.Module | UnsupportedPattern S.Pat | UnsupportedQualStmt S.QualStmt | UnsupportedRecursiveDo | UnsupportedRhs S.Rhs | UnsupportedWhereInAlt S.Alt | UnsupportedWhereInMatch S.Match deriving (Show)
a2f4242718ebd0e99060a629632821ea4b713589b9f3789c6e547aade2b9707a
ku-fpg/hermit
ShellEffect.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE FlexibleContexts # {-# LANGUAGE GADTs #-} # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module HERMIT.Shell.ShellEffect ( ShellEffect(..) , ShellEffectBox(..) , performShellEffect , dumpT , dump ) where import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Reader (ask) import Control.Monad.State (MonadState(..), gets) import Data.Typeable import HERMIT.External import HERMIT.Kure import HERMIT.PrettyPrinter.Common import HERMIT.Plugin.Renderer import HERMIT.Plugin.Types import HERMIT.Shell.Types import System.IO ---------------------------------------------------------------------------------- data ShellEffect :: * -> * where Abort :: ShellEffect () CLSModify :: CLT IO a -> ShellEffect a PluginComp :: PluginM () -> ShellEffect () Continue :: ShellEffect () Resume :: ShellEffect () FmapShellEffect :: (a -> b) -> ShellEffect a -> ShellEffect b instance Functor ShellEffect where fmap = FmapShellEffect data ShellEffectBox where ShellEffectBox :: Typeable a => ShellEffect a -> ShellEffectBox instance Typeable a => Extern (ShellEffect a) where type Box (ShellEffect _a) = ShellEffectBox box = ShellEffectBox unbox (ShellEffectBox i) = case cast i of Just res -> res Nothing -> error "Extern -- unbox: casting of shell effect failed." ---------------------------------------------------------------------------------- performShellEffect :: (MonadCatch m, CLMonad m) => ShellEffect a -> m a performShellEffect Abort = abort performShellEffect Resume = announceUnprovens >> gets cl_cursor >>= resume performShellEffect Continue = announceUnprovens >> get >>= continue performShellEffect (CLSModify m) = clm2clt m performShellEffect (PluginComp m) = pluginM m performShellEffect (FmapShellEffect f s) = fmap f (performShellEffect s) dumpT :: FilePath -> PrettyPrinter -> String -> Int -> TransformH DocH () dumpT fileName pp renderer width = do case lookup renderer shellRenderers of Just r -> do doc <- idR liftIO $ do h <- openFile fileName WriteMode r h ((pOptions pp) { po_width = width }) (Right doc) hClose h _ -> fail "dump: bad renderer option" dump :: FilePath -> PrettyPrinter -> String -> Int -> CLT IO () dump fileName pp renderer width = do st <- get env <- ask let st' = setPrettyOpts (setPretty st pp) $ (cl_pretty_opts st) { po_width = width } (er, _st'') <- runCLT env st' $ do pluginM (changeRenderer renderer) h <- liftIO $ openFile fileName WriteMode printWindowAlways (Just h) liftIO $ hClose h either throwError return er
null
https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/src/HERMIT/Shell/ShellEffect.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE GADTs # -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
# LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE KindSignatures # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeFamilies # module HERMIT.Shell.ShellEffect ( ShellEffect(..) , ShellEffectBox(..) , performShellEffect , dumpT , dump ) where import Control.Monad.Error.Class (MonadError(..)) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Reader (ask) import Control.Monad.State (MonadState(..), gets) import Data.Typeable import HERMIT.External import HERMIT.Kure import HERMIT.PrettyPrinter.Common import HERMIT.Plugin.Renderer import HERMIT.Plugin.Types import HERMIT.Shell.Types import System.IO data ShellEffect :: * -> * where Abort :: ShellEffect () CLSModify :: CLT IO a -> ShellEffect a PluginComp :: PluginM () -> ShellEffect () Continue :: ShellEffect () Resume :: ShellEffect () FmapShellEffect :: (a -> b) -> ShellEffect a -> ShellEffect b instance Functor ShellEffect where fmap = FmapShellEffect data ShellEffectBox where ShellEffectBox :: Typeable a => ShellEffect a -> ShellEffectBox instance Typeable a => Extern (ShellEffect a) where type Box (ShellEffect _a) = ShellEffectBox box = ShellEffectBox unbox (ShellEffectBox i) = case cast i of Just res -> res Nothing -> error "Extern -- unbox: casting of shell effect failed." performShellEffect :: (MonadCatch m, CLMonad m) => ShellEffect a -> m a performShellEffect Abort = abort performShellEffect Resume = announceUnprovens >> gets cl_cursor >>= resume performShellEffect Continue = announceUnprovens >> get >>= continue performShellEffect (CLSModify m) = clm2clt m performShellEffect (PluginComp m) = pluginM m performShellEffect (FmapShellEffect f s) = fmap f (performShellEffect s) dumpT :: FilePath -> PrettyPrinter -> String -> Int -> TransformH DocH () dumpT fileName pp renderer width = do case lookup renderer shellRenderers of Just r -> do doc <- idR liftIO $ do h <- openFile fileName WriteMode r h ((pOptions pp) { po_width = width }) (Right doc) hClose h _ -> fail "dump: bad renderer option" dump :: FilePath -> PrettyPrinter -> String -> Int -> CLT IO () dump fileName pp renderer width = do st <- get env <- ask let st' = setPrettyOpts (setPretty st pp) $ (cl_pretty_opts st) { po_width = width } (er, _st'') <- runCLT env st' $ do pluginM (changeRenderer renderer) h <- liftIO $ openFile fileName WriteMode printWindowAlways (Just h) liftIO $ hClose h either throwError return er
d588e1f5bf74b5f7b45a9656cac64e4e839e1faac9b8fce8d101a56d7bfd77e9
UBTECH-Walker/WalkerSimulationFor2020WAIC
_package_EcatSetZero.lisp
(cl:in-package servo_ctrl-srv) (cl:export '(SERVO-VAL SERVO RESULT-VAL RESULT ))
null
https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_18.04_v1.2_20200616/walker_install/share/common-lisp/ros/servo_ctrl/srv/_package_EcatSetZero.lisp
lisp
(cl:in-package servo_ctrl-srv) (cl:export '(SERVO-VAL SERVO RESULT-VAL RESULT ))