_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
38a1f348549e8c1b7afbb588ff24438e35a1663c7bf6d60bfebb48d428f760d2
ghc/packages-Cabal
Types.hs
# LANGUAGE DeriveGeneric # ----------------------------------------------------------------------------- -- | Module : Distribution . Client . Init . Types Copyright : ( c ) , 2009 -- License : BSD-like -- -- Maintainer : -- Stability : provisional -- Portability : portable -- -- Some types used by the 'cabal init' command. -- ----------------------------------------------------------------------------- module Distribution.Client.Init.Types where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Simple.Setup (Flag(..), toFlag ) import Distribution.Types.Dependency as P import Distribution.Version import Distribution.Verbosity import qualified Distribution.Package as P import Distribution.SPDX.License (License) import Distribution.ModuleName import Distribution.CabalSpecVersion import Language.Haskell.Extension ( Language(..), Extension ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Compat.CharParsing as P import qualified Data.Map as Map | InitFlags is really just a simple type to represent certain -- portions of a .cabal file. Rather than have a flag for EVERY -- possible field, we just have one for each field that the user is -- likely to want and/or that we are likely to be able to -- intelligently guess. data InitFlags = InitFlags { interactive :: Flag Bool , quiet :: Flag Bool , packageDir :: Flag FilePath , noComments :: Flag Bool , minimal :: Flag Bool , simpleProject :: Flag Bool , packageName :: Flag P.PackageName , version :: Flag Version , cabalVersion :: Flag CabalSpecVersion , license :: Flag License , author :: Flag String , email :: Flag String , homepage :: Flag String , synopsis :: Flag String , category :: Flag (Either String Category) , extraSrc :: Maybe [String] , packageType :: Flag PackageType , mainIs :: Flag FilePath , language :: Flag Language , exposedModules :: Maybe [ModuleName] , otherModules :: Maybe [ModuleName] , otherExts :: Maybe [Extension] , dependencies :: Maybe [P.Dependency] , applicationDirs :: Maybe [String] , sourceDirs :: Maybe [String] , buildTools :: Maybe [String] , initializeTestSuite :: Flag Bool , testDirs :: Maybe [String] , initHcPath :: Flag FilePath , initVerbosity :: Flag Verbosity , overwrite :: Flag Bool } deriving (Show, Generic) -- the Monoid instance for Flag has later values override earlier -- ones, which is why we want Maybe [foo] for collecting foo values, -- not Flag [foo]. data BuildType = LibBuild | ExecBuild deriving Eq -- The type of package to initialize. data PackageType = Library | Executable | LibraryAndExecutable deriving (Show, Read, Eq) displayPackageType :: PackageType -> String displayPackageType LibraryAndExecutable = "Library and Executable" displayPackageType pkgtype = show pkgtype instance Monoid InitFlags where mempty = gmempty mappend = (<>) instance Semigroup InitFlags where (<>) = gmappend defaultInitFlags :: InitFlags defaultInitFlags = mempty { initVerbosity = toFlag normal } -- | Some common package categories (non-exhaustive list). data Category = Codec | Concurrency | Control | Data | Database | Development | Distribution | Game | Graphics | Language | Math | Network | Sound | System | Testing | Text | Web deriving (Read, Show, Eq, Ord, Bounded, Enum) instance Pretty Category where pretty = Disp.text . show instance Parsec Category where parsec = do name <- P.munch1 isAlpha case Map.lookup name names of Just cat -> pure cat _ -> P.unexpected $ "Category: " ++ name where names = Map.fromList [ (show cat, cat) | cat <- [ minBound .. maxBound ] ]
null
https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/cabal-install/Distribution/Client/Init/Types.hs
haskell
--------------------------------------------------------------------------- | License : BSD-like Maintainer : Stability : provisional Portability : portable Some types used by the 'cabal init' command. --------------------------------------------------------------------------- portions of a .cabal file. Rather than have a flag for EVERY possible field, we just have one for each field that the user is likely to want and/or that we are likely to be able to intelligently guess. the Monoid instance for Flag has later values override earlier ones, which is why we want Maybe [foo] for collecting foo values, not Flag [foo]. The type of package to initialize. | Some common package categories (non-exhaustive list).
# LANGUAGE DeriveGeneric # Module : Distribution . Client . Init . Types Copyright : ( c ) , 2009 module Distribution.Client.Init.Types where import Distribution.Client.Compat.Prelude import Prelude () import Distribution.Simple.Setup (Flag(..), toFlag ) import Distribution.Types.Dependency as P import Distribution.Version import Distribution.Verbosity import qualified Distribution.Package as P import Distribution.SPDX.License (License) import Distribution.ModuleName import Distribution.CabalSpecVersion import Language.Haskell.Extension ( Language(..), Extension ) import qualified Text.PrettyPrint as Disp import qualified Distribution.Compat.CharParsing as P import qualified Data.Map as Map | InitFlags is really just a simple type to represent certain data InitFlags = InitFlags { interactive :: Flag Bool , quiet :: Flag Bool , packageDir :: Flag FilePath , noComments :: Flag Bool , minimal :: Flag Bool , simpleProject :: Flag Bool , packageName :: Flag P.PackageName , version :: Flag Version , cabalVersion :: Flag CabalSpecVersion , license :: Flag License , author :: Flag String , email :: Flag String , homepage :: Flag String , synopsis :: Flag String , category :: Flag (Either String Category) , extraSrc :: Maybe [String] , packageType :: Flag PackageType , mainIs :: Flag FilePath , language :: Flag Language , exposedModules :: Maybe [ModuleName] , otherModules :: Maybe [ModuleName] , otherExts :: Maybe [Extension] , dependencies :: Maybe [P.Dependency] , applicationDirs :: Maybe [String] , sourceDirs :: Maybe [String] , buildTools :: Maybe [String] , initializeTestSuite :: Flag Bool , testDirs :: Maybe [String] , initHcPath :: Flag FilePath , initVerbosity :: Flag Verbosity , overwrite :: Flag Bool } deriving (Show, Generic) data BuildType = LibBuild | ExecBuild deriving Eq data PackageType = Library | Executable | LibraryAndExecutable deriving (Show, Read, Eq) displayPackageType :: PackageType -> String displayPackageType LibraryAndExecutable = "Library and Executable" displayPackageType pkgtype = show pkgtype instance Monoid InitFlags where mempty = gmempty mappend = (<>) instance Semigroup InitFlags where (<>) = gmappend defaultInitFlags :: InitFlags defaultInitFlags = mempty { initVerbosity = toFlag normal } data Category = Codec | Concurrency | Control | Data | Database | Development | Distribution | Game | Graphics | Language | Math | Network | Sound | System | Testing | Text | Web deriving (Read, Show, Eq, Ord, Bounded, Enum) instance Pretty Category where pretty = Disp.text . show instance Parsec Category where parsec = do name <- P.munch1 isAlpha case Map.lookup name names of Just cat -> pure cat _ -> P.unexpected $ "Category: " ++ name where names = Map.fromList [ (show cat, cat) | cat <- [ minBound .. maxBound ] ]
ca0d3e050bf099d761c6f3c20a087095c68f3c2212cde2e55ef68cacc7d7a823
johnlawrenceaspden/hobby-code
macros.clj
Nice macros ;;debugging parts of expressions (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#)) ;; Examples of dbg (println (+ (* 2 3) (dbg (* 8 9)))) (println (dbg (println "yo"))) (defn factorial[n] (if (= n 0) 1 (* n (dbg (factorial (dec n)))))) (factorial 8) (def integers (iterate inc 0)) (def squares (map #(dbg(* % %)) integers)) (def cubes (map #(dbg(* %1 %2)) integers squares)) three armed if with tolerances (defmacro tif [x z p n] `(let [x# ~x] (cond (<= x# -0.0001) ~n (< -0.0001 x# 0.0001) ~z (<= 0.0001 x#) ~p))) (map #(tif % 'roughly-zero (/ 10 %) (/ -10 %)) '(-1 -0.001 -0.00001 0 0.0001 0.001 1)) ;;can we do it without backquote? (defmacro pyth1[a b] (let [a# (gensym) b# (gensym)] (list 'let (vector a# a b# b) (list '+ (list '* a# a#) (list '* b# b#))))) (defmacro pyth2[a b] `(let [a# ~a b# ~b] (+ (* a# a#) (* b# b#)))) (clojure.walk/macroexpand-all '(* (pyth1 2 3) (pyth2 2 3))) (* ;;hand generated version (let* [G__3409 2 G__3410 3] (+ (* G__3409 G__3409) (* G__3410 G__3410))) ;;auto version. note name resolution (let* [a__3360__auto__ 2 b__3361__auto__ 3] (clojure.core/+ (clojure.core/* a__3360__auto__ a__3360__auto__) (clojure.core/* b__3361__auto__ b__3361__auto__)))) (binding [list vector] (list 1 3)) (binding [list +] (list 1 3)) (binding [+ list] (+ 1 3)) (condp = 1 'one 2 'two 'many)
null
https://raw.githubusercontent.com/johnlawrenceaspden/hobby-code/48e2a89d28557994c72299962cd8e3ace6a75b2d/macros.clj
clojure
debugging parts of expressions Examples of dbg can we do it without backquote? hand generated version auto version. note name resolution
Nice macros (defmacro dbg[x] `(let [x# ~x] (println "dbg:" '~x "=" x#) x#)) (println (+ (* 2 3) (dbg (* 8 9)))) (println (dbg (println "yo"))) (defn factorial[n] (if (= n 0) 1 (* n (dbg (factorial (dec n)))))) (factorial 8) (def integers (iterate inc 0)) (def squares (map #(dbg(* % %)) integers)) (def cubes (map #(dbg(* %1 %2)) integers squares)) three armed if with tolerances (defmacro tif [x z p n] `(let [x# ~x] (cond (<= x# -0.0001) ~n (< -0.0001 x# 0.0001) ~z (<= 0.0001 x#) ~p))) (map #(tif % 'roughly-zero (/ 10 %) (/ -10 %)) '(-1 -0.001 -0.00001 0 0.0001 0.001 1)) (defmacro pyth1[a b] (let [a# (gensym) b# (gensym)] (list 'let (vector a# a b# b) (list '+ (list '* a# a#) (list '* b# b#))))) (defmacro pyth2[a b] `(let [a# ~a b# ~b] (+ (* a# a#) (* b# b#)))) (clojure.walk/macroexpand-all '(* (pyth1 2 3) (pyth2 2 3))) (* (let* [G__3409 2 G__3410 3] (+ (* G__3409 G__3409) (* G__3410 G__3410))) (let* [a__3360__auto__ 2 b__3361__auto__ 3] (clojure.core/+ (clojure.core/* a__3360__auto__ a__3360__auto__) (clojure.core/* b__3361__auto__ b__3361__auto__)))) (binding [list vector] (list 1 3)) (binding [list +] (list 1 3)) (binding [+ list] (+ 1 3)) (condp = 1 'one 2 'two 'many)
a504d0bb8bec061cf05405b365638271451c48068cba0588b19e83e147f139ce
ninjudd/cake
dependency.clj
by , / December 1 , 2010 Copyright ( c ) , 2010 . 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. copied from lazytest.dependency (ns bake.dependency "Bidirectional graphs of dependencies and dependent objects." (:use [clojure.set :only (union)])) (defn graph "Returns a new, empty, dependency graph." [] {:dependencies {} :dependents {}}) (defn- transitive "Recursively expands the set of dependency relationships starting at (get m x)" [m x] (reduce (fn [s k] (union s (transitive m k))) (get m x) (get m x))) (defn dependencies "Returns the set of all things x depends on, directly or transitively." [graph x] (transitive (:dependencies graph) x)) (defn dependents "Returns the set of all things which depend upon x, directly or transitively." [graph x] (transitive (:dependents graph) x)) (defn depends? "True if x is directly or transitively dependent on y." [graph x y] (contains? (dependencies graph x) y)) (defn dependent "True if y is a dependent of x." [graph x y] (contains? (dependents graph x) y)) (defn- add-relationship [graph key x y] (update-in graph [key x] union #{y})) (defn depend "Adds to the dependency graph that x depends on deps. Forbids circular dependencies." ([graph x] graph) ([graph x dep] {:pre [(not (depends? graph dep x))]} (-> graph (add-relationship :dependencies x dep) (add-relationship :dependents dep x))) ([graph x dep & more] (reduce (fn [g d] (depend g x d)) graph (cons dep more)))) (defn- remove-from-map [amap x] (reduce (fn [m [k vs]] (assoc m k (disj vs x))) {} (dissoc amap x))) (defn remove-all "Removes all references to x in the dependency graph." ([graph] graph) ([graph x] (assoc graph :dependencies (remove-from-map (:dependencies graph) x) :dependents (remove-from-map (:dependents graph) x))) ([graph x & more] (reduce remove-all graph (cons x more)))) (defn remove-key "Removes the key x from the dependency graph without removing x as a depedency of other keys." ([graph] graph) ([graph x] (assoc graph :dependencies (dissoc (:dependencies graph) x))) ([graph x & more] (reduce remove-key graph (cons x more))))
null
https://raw.githubusercontent.com/ninjudd/cake/3a1627120b74e425ab21aa4d1b263be09e945cfd/dev/bake/dependency.clj
clojure
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.
by , / December 1 , 2010 Copyright ( c ) , 2010 . All rights reserved . The use and distribution terms for this software are covered by the Eclipse copied from lazytest.dependency (ns bake.dependency "Bidirectional graphs of dependencies and dependent objects." (:use [clojure.set :only (union)])) (defn graph "Returns a new, empty, dependency graph." [] {:dependencies {} :dependents {}}) (defn- transitive "Recursively expands the set of dependency relationships starting at (get m x)" [m x] (reduce (fn [s k] (union s (transitive m k))) (get m x) (get m x))) (defn dependencies "Returns the set of all things x depends on, directly or transitively." [graph x] (transitive (:dependencies graph) x)) (defn dependents "Returns the set of all things which depend upon x, directly or transitively." [graph x] (transitive (:dependents graph) x)) (defn depends? "True if x is directly or transitively dependent on y." [graph x y] (contains? (dependencies graph x) y)) (defn dependent "True if y is a dependent of x." [graph x y] (contains? (dependents graph x) y)) (defn- add-relationship [graph key x y] (update-in graph [key x] union #{y})) (defn depend "Adds to the dependency graph that x depends on deps. Forbids circular dependencies." ([graph x] graph) ([graph x dep] {:pre [(not (depends? graph dep x))]} (-> graph (add-relationship :dependencies x dep) (add-relationship :dependents dep x))) ([graph x dep & more] (reduce (fn [g d] (depend g x d)) graph (cons dep more)))) (defn- remove-from-map [amap x] (reduce (fn [m [k vs]] (assoc m k (disj vs x))) {} (dissoc amap x))) (defn remove-all "Removes all references to x in the dependency graph." ([graph] graph) ([graph x] (assoc graph :dependencies (remove-from-map (:dependencies graph) x) :dependents (remove-from-map (:dependents graph) x))) ([graph x & more] (reduce remove-all graph (cons x more)))) (defn remove-key "Removes the key x from the dependency graph without removing x as a depedency of other keys." ([graph] graph) ([graph x] (assoc graph :dependencies (dissoc (:dependencies graph) x))) ([graph x & more] (reduce remove-key graph (cons x more))))
5ff27e03cb069fc0cce0cfd11182c4a990cfe75be33915442ddd229df1fe7a0f
soegaard/remacs
osx-keyboard.rkt
#lang racket/base (provide key-translate make-initial-dead-key-state copy-dead-key-state char->main-char-key+modifiers) (require (for-syntax syntax/parse racket/syntax racket/base)) (require ffi/unsafe ffi/unsafe/objc ffi/unsafe/define mred/private/wx/cocoa/types) ; _NSString ;;; Bit operations (define (<< x y) (arithmetic-shift x y)) (define (>> x y) (arithmetic-shift x (- y))) ;;; Libraries used (define quartz-lib (ffi-lib "/System/Library/Frameworks/Quartz.framework/Versions/Current/Quartz")) (define carbon-lib (ffi-lib "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")) (define carbon-core-lib (ffi-lib (string-append "/System/Library/Frameworks/CoreServices.framework/" "Frameworks/CarbonCore.framework/Versions/Current/CarbonCore"))) (define cf-lib (ffi-lib "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")) (define-ffi-definer define-quartz quartz-lib) (define-ffi-definer define-carbon-core carbon-core-lib) (define-ffi-definer define-carbon carbon-lib) (define-ffi-definer define-cf cf-lib #:default-make-fail make-not-available) CORE FOUNDATION (import-class NSString) (define _CFStringRef _NSString) ( define _ OSStatus _ sint32 ) ; already imported (define-cpointer-type _CFDataRef) ;;; Unicode Characters ;;; Types from MacTypes.h (define _UniChar _uint16) (define _UniCharCount _ulong) (define _UniCharPointer (_ptr io _UniChar)) (define _UniCharCountPointer (_ptr io _UniCharCount)) (define _OptionBits _uint32) ;;; TEXT INPUT SOURCES ; Most text input sources are keyboards. (define _TISInputSourceRef (_cpointer 'TISInputSourceRef)) ; Each physical key on a keyboard sends a keycode. Example : the key label labelled A on a US keyboard sends kVK_ANSI_A=0 . ; A keyboard layout determines which character corresponds to a physical key. To get a layout , one must first get a reference to the input source : (define-carbon TISCopyCurrentKeyboardLayoutInputSource (_fun -> _TISInputSourceRef)) (define-carbon TISCopyCurrentASCIICapableKeyboardLayoutInputSource (_fun -> _TISInputSourceRef)) Note : These days TISCopyCurrentKeyboardLayoutInputSource ought to work for all keyboards . The input source has several properties , one of is : (define-carbon kTISPropertyUnicodeKeyLayoutData _NSString) ; Getting the property is done by: (define-carbon TISGetInputSourceProperty (_fun (_inputSource : _TISInputSourceRef) (_propertyKey : _CFStringRef) -> (_or-null _CFDataRef))) The value returned by TISGetInputSourceProperty is a CFDataRef , so one mus call CFDataGetBytePtr to get the actual layout . (define-cf CFDataGetBytePtr (_fun _CFDataRef -> _pointer)) ; The return value can be cast to: (define _UCKeyboardLayout (_cpointer 'UCKeyboardLayout)) ; Before translating key codes to characters, one must option ; the physical type of keyboard. (define-carbon LMGetKbdType (_fun -> _uint8)) ; Given a layout and a keyboard type, one can translate ; keycodes to characters using UCKeyTranslate. (define-carbon UCKeyTranslate (_fun (keyboardLayoutPtr : _UCKeyboardLayout) (virtualKeyCode : _uint16) (keyAction : _uint16) (modifierKeyState : _uint32) (keyboardType : _uint32) uint32 (deadKeyState : (_box _uint32)) (maxStringLength : _UniCharCount) ( actualStringLength : _ ) (actualStringLength : (_box _UniCharCount)) (unicodeString : _pointer) -> _OSStatus)) ; Meaning of parameters: ; keyAction what happened to the key? - usually kUCKeyActionDown ; modifierKeyState which modifier keys are down? - shift, alt, ctrl, cmd or combinations ; keyTranslateOptions is previous input handled? - used to disable/enable dead keys deadKeyState integer encoding of prev keys - none is encoded as 0 ; unicodeString array into which the result is stored ; actualStringLength how many characters were stored in unicodeString ; See key-translate below for a more convenient interface for UCKeyTranslate. ;;; ;;; Constants and there symbolic representation. ;;; ; In order to define a lot of constants and keep their symbols ; around it is convenient a little help. SYNTAX ( define - name / value - definer category ) Defines two hash - tables ; category-name-to-value-ht from symbolic name to value ; category-value-to-name-ht from value to symbolic name ; It also defines SYNTAX ( define - category name ) which defines name as , provides val ; and store the pairing in the hashtables. ; Example: See key actions below. (define-syntax (define-name/value-definer stx) (syntax-parse stx [(_ prefix) (with-syntax ([prefix-name-to-value-ht (format-id stx "~a-name-to-value-ht" #'prefix)] [prefix-value-to-name-ht (format-id stx "~a-value-to-name-ht" #'prefix)] [prefix-name (format-id stx "~a-name" #'prefix)] [prefix-value (format-id stx "~a-value" #'prefix)] [define-prefix (format-id stx "define-~a" #'prefix)]) #'(begin (define prefix-name-to-value-ht (make-hash)) (define prefix-value-to-name-ht (make-hash)) (define (prefix-name value) (hash-ref prefix-value-to-name-ht value #f)) (define (prefix-value name) (hash-ref prefix-name-to-value-ht name #f)) (provide prefix-name-to-value-ht prefix-value-to-name-ht prefix-name prefix-value) (define-syntax (define-prefix stx) (syntax-parse stx [(_ name expr) #'(begin (provide name ) (define name expr) (hash-set! prefix-name-to-value-ht 'name name) (hash-set! prefix-value-to-name-ht name 'name))]))))])) ;;; ;;; Key Actions ;;; (define-name/value-definer key-action) (define-key-action kUCKeyActionDown 0) ; /* key is going down*/ / * key is going up*/ (define-key-action kUCKeyActionAutoKey 2) ; /* auto-key down*/ / * get information for key display ( as in Key Caps ) * / ;;; ;;; Key Translate Options ;;; There is only one option . Should dead keys have an effect or not ? (define kUCKeyTranslateNoDeadKeysBit 0) ; /* Prevents setting any new dead-key states*/ (define kUCKeyTranslateNoDeadKeysFlag 1) (define kUCKeyTranslateNoDeadKeysMask 1) ;;; EventModifiers ( UInt16 ) ;;; (define-name/value-definer event-modifier-bits) (define-name/value-definer event-modifier-flag) ; The constants are "event modifiers". Some of them ; are traditional key modiers, such as a modifier-shift-key-bit. From ( file dates 2008 ): ; /System/Library/Frameworks/Carbon.framework/Versions/A/ ; Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h ; The definitions indicate which bit controls what. (define-event-modifier-bits modifier-active-flag-bit 0) ; activeFlagBit = 0, /* activate window? ; (activateEvt and mouseDown) btnStateBit = 7 , state of mouse ! button ? (define-event-modifier-bits modifier-cmd-key-bit 8) ; /* command key down?*/ shiftKeyBit = 9 , / * shift key down?*/ alphaLockBit = 10 , / * alpha lock down?*/ optionKeyBit = 11 , / * option key down?*/ controlKeyBit = 12 , / * control key down?*/ NOTE : The following 3 modifiers are not supported on OS X (define-event-modifier-bits modifier-right-shift-key-bit 13) ; /* right shift key down? */ (define-event-modifier-bits modifier-right-option-key-bit 14) ; /* right Option key down? */ (define-event-modifier-bits modifier-right-control-key-bit 15) ; /* right Control key down? */ ; In actual use, we use the flags: (define-event-modifier-flag modifier-active-flag (<< 1 0)) (define-event-modifier-flag modifier-btn-state (<< 1 7)) (define-event-modifier-flag modifier-cmd-key (<< 1 8)) (define-event-modifier-flag modifier-shift-key (<< 1 9)) (define-event-modifier-flag modifier-alpha-lock (<< 1 10)) (define-event-modifier-flag modifier-option-key (<< 1 11)) (define-event-modifier-flag modifier-control-key (<< 1 12)) NOTE : The following 3 modifiers are not supported on OS X (define-event-modifier-flag modifier-right-shift-key (<< 1 13)) (define-event-modifier-flag modifier-right-option-key (<< 1 14)) (define-event-modifier-flag modifier-right-control-key (<< 1 15)) ;;; Virtual Keycodes ;;; ;/* ; * Summary: ; * Virtual keycodes ; * ; * Discussion: ; * These constants are the virtual keycodes defined originally in ; * Inside Mac Volume V, pg. V-191. They identify physical keys on a ; * keyboard. Those constants with "ANSI" in the name are labeled * according to the key position on an ANSI - standard US keyboard . ; * For example, kVK_ANSI_A indicates the virtual keycode for the key * with the letter ' A ' in the US keyboard layout . Other keyboard ; * layouts may have the 'A' key label on a different physical key; ; * in this case, pressing 'A' will generate a different virtual ; * keycode. ; */ (define-name/value-definer virtual-key-code) (define-virtual-key-code kVK_ANSI_A #x00) (define-virtual-key-code kVK_ANSI_S #x01) (define-virtual-key-code kVK_ANSI_D #x02) (define-virtual-key-code kVK_ANSI_F #x03) (define-virtual-key-code kVK_ANSI_H #x04) (define-virtual-key-code kVK_ANSI_G #x05) (define-virtual-key-code kVK_ANSI_Z #x06) (define-virtual-key-code kVK_ANSI_X #x07) (define-virtual-key-code kVK_ANSI_C #x08) (define-virtual-key-code kVK_ANSI_V #x09) (define-virtual-key-code kVK_ANSI_B #x0B) (define-virtual-key-code kVK_ANSI_Q #x0C) (define-virtual-key-code kVK_ANSI_W #x0D) (define-virtual-key-code kVK_ANSI_E #x0E) (define-virtual-key-code kVK_ANSI_R #x0F) (define-virtual-key-code kVK_ANSI_Y #x10) (define-virtual-key-code kVK_ANSI_T #x11) (define-virtual-key-code kVK_ANSI_1 #x12) (define-virtual-key-code kVK_ANSI_2 #x13) (define-virtual-key-code kVK_ANSI_3 #x14) (define-virtual-key-code kVK_ANSI_4 #x15) (define-virtual-key-code kVK_ANSI_6 #x16) (define-virtual-key-code kVK_ANSI_5 #x17) (define-virtual-key-code kVK_ANSI_Equal #x18) (define-virtual-key-code kVK_ANSI_9 #x19) (define-virtual-key-code kVK_ANSI_7 #x1A) (define-virtual-key-code kVK_ANSI_Minus #x1B) (define-virtual-key-code kVK_ANSI_8 #x1C) (define-virtual-key-code kVK_ANSI_0 #x1D) (define-virtual-key-code kVK_ANSI_RightBracket #x1E) (define-virtual-key-code kVK_ANSI_O #x1F) (define-virtual-key-code kVK_ANSI_U #x20) (define-virtual-key-code kVK_ANSI_LeftBracket #x21) (define-virtual-key-code kVK_ANSI_I #x22) (define-virtual-key-code kVK_ANSI_P #x23) (define-virtual-key-code kVK_ANSI_L #x25) (define-virtual-key-code kVK_ANSI_J #x26) (define-virtual-key-code kVK_ANSI_Quote #x27) (define-virtual-key-code kVK_ANSI_K #x28) (define-virtual-key-code kVK_ANSI_Semicolon #x29) (define-virtual-key-code kVK_ANSI_Backslash #x2A) (define-virtual-key-code kVK_ANSI_Comma #x2B) (define-virtual-key-code kVK_ANSI_Slash #x2C) (define-virtual-key-code kVK_ANSI_N #x2D) (define-virtual-key-code kVK_ANSI_M #x2E) (define-virtual-key-code kVK_ANSI_Period #x2F) (define-virtual-key-code kVK_ANSI_Grave #x32) (define-virtual-key-code kVK_ANSI_KeypadDecimal #x41) (define-virtual-key-code kVK_ANSI_KeypadMultiply #x43) (define-virtual-key-code kVK_ANSI_KeypadPlus #x45) (define-virtual-key-code kVK_ANSI_KeypadClear #x47) (define-virtual-key-code kVK_ANSI_KeypadDivide #x4B) (define-virtual-key-code kVK_ANSI_KeypadEnter #x4C) (define-virtual-key-code kVK_ANSI_KeypadMinus #x4E) (define-virtual-key-code kVK_ANSI_KeypadEquals #x51) (define-virtual-key-code kVK_ANSI_Keypad0 #x52) (define-virtual-key-code kVK_ANSI_Keypad1 #x53) (define-virtual-key-code kVK_ANSI_Keypad2 #x54) (define-virtual-key-code kVK_ANSI_Keypad3 #x55) (define-virtual-key-code kVK_ANSI_Keypad4 #x56) (define-virtual-key-code kVK_ANSI_Keypad5 #x57) (define-virtual-key-code kVK_ANSI_Keypad6 #x58) (define-virtual-key-code kVK_ANSI_Keypad7 #x59) (define-virtual-key-code kVK_ANSI_Keypad8 #x5B) (define-virtual-key-code kVK_ANSI_Keypad9 #x5C) / * keycodes for keys that are independent of keyboard layout*/ (define-virtual-key-code kVK_Return #x24) (define-virtual-key-code kVK_Tab #x30) (define-virtual-key-code kVK_Space #x31) (define-virtual-key-code kVK_Delete #x33) (define-virtual-key-code kVK_Escape #x35) (define-virtual-key-code kVK_Command #x37) (define-virtual-key-code kVK_Shift #x38) (define-virtual-key-code kVK_CapsLock #x39) (define-virtual-key-code kVK_Option #x3A) (define-virtual-key-code kVK_Control #x3B) (define-virtual-key-code kVK_RightShift #x3C) (define-virtual-key-code kVK_RightOption #x3D) (define-virtual-key-code kVK_RightControl #x3E) (define-virtual-key-code kVK_Function #x3F) (define-virtual-key-code kVK_F17 #x40) (define-virtual-key-code kVK_VolumeUp #x48) (define-virtual-key-code kVK_VolumeDown #x49) (define-virtual-key-code kVK_Mute #x4A) (define-virtual-key-code kVK_F18 #x4F) (define-virtual-key-code kVK_F19 #x50) (define-virtual-key-code kVK_F20 #x5A) (define-virtual-key-code kVK_F5 #x60) (define-virtual-key-code kVK_F6 #x61) (define-virtual-key-code kVK_F7 #x62) (define-virtual-key-code kVK_F3 #x63) (define-virtual-key-code kVK_F8 #x64) (define-virtual-key-code kVK_F9 #x65) (define-virtual-key-code kVK_F11 #x67) (define-virtual-key-code kVK_F13 #x69) (define-virtual-key-code kVK_F16 #x6A) (define-virtual-key-code kVK_F14 #x6B) (define-virtual-key-code kVK_F10 #x6D) (define-virtual-key-code kVK_F12 #x6F) (define-virtual-key-code kVK_F15 #x71) (define-virtual-key-code kVK_Help #x72) (define-virtual-key-code kVK_Home #x73) (define-virtual-key-code kVK_PageUp #x74) (define-virtual-key-code kVK_ForwardDelete #x75) (define-virtual-key-code kVK_F4 #x76) (define-virtual-key-code kVK_End #x77) (define-virtual-key-code kVK_F2 #x78) (define-virtual-key-code kVK_PageDown #x79) (define-virtual-key-code kVK_F1 #x7A) (define-virtual-key-code kVK_LeftArrow #x7B) (define-virtual-key-code kVK_RightArrow #x7C) (define-virtual-key-code kVK_DownArrow #x7D) (define-virtual-key-code kVK_UpArrow #x7E) ; /* ISO keyboards only*/ (define-virtual-key-code kVK_ISO_Section #x0A) ; /* JIS keyboards only*/ (define-virtual-key-code kVK_JIS_Yen #x5D) (define-virtual-key-code kVK_JIS_Underscore #x5E) (define-virtual-key-code kVK_JIS_KeypadComma #x5F) (define-virtual-key-code kVK_JIS_Eisu #x66) (define-virtual-key-code kVK_JIS_Kana #x68) ;;; MacRoman character codes ;;; ; The following may or may not be useful at another time. (define-name/value-definer mac-roman) (define-mac-roman kNullCharCode 0) (define-mac-roman kHomeCharCode 1) (define-mac-roman kEnterCharCode 3) (define-mac-roman kEndCharCode 4) (define-mac-roman kHelpCharCode 5) (define-mac-roman kBellCharCode 7) (define-mac-roman kBackspaceCharCode 8) (define-mac-roman kTabCharCode 9) (define-mac-roman kLineFeedCharCode 10) (define-mac-roman kVerticalTabCharCode 11) (define-mac-roman kPageUpCharCode 11) (define-mac-roman kFormFeedCharCode 12) (define-mac-roman kPageDownCharCode 12) (define-mac-roman kReturnCharCode 13) (define-mac-roman kFunctionKeyCharCode 16) (define-mac-roman kCommandCharCode 17) ; /* glyph available only in system fonts*/ (define-mac-roman kCheckCharCode 18) ; /* glyph available only in system fonts*/ (define-mac-roman kDiamondCharCode 19) ; /* glyph available only in system fonts*/ (define-mac-roman kAppleLogoCharCode 20) ; /* glyph available only in system fonts*/ (define-mac-roman kEscapeCharCode 27) (define-mac-roman kClearCharCode 27) (define-mac-roman kLeftArrowCharCode 28) (define-mac-roman kRightArrowCharCode 29) (define-mac-roman kUpArrowCharCode 30) (define-mac-roman kDownArrowCharCode 31) (define-mac-roman kSpaceCharCode 32) (define-mac-roman kDeleteCharCode 127) (define-mac-roman kBulletCharCode 165) (define-mac-roman kNonBreakingSpaceCharCode 202) ;;; ;;; Useful Unicode key points ;;; (define-name/value-definer unicode-key) (define-unicode-key kShiftUnicode #x21E7) ;/* Unicode UPWARDS WHITE ARROW*/ (define-unicode-key kControlUnicode #x2303) ;/* Unicode UP ARROWHEAD*/ / * Unicode OPTION / * Unicode PLACE OF INTEREST SIGN*/ (define-unicode-key kPencilUnicode #x270E) ;/* Unicode LOWER RIGHT PENCIL; actually pointed left until (define-unicode-key kPencilLeftUnicode #xF802) ;/* Unicode LOWER LEFT PENCIL; available in Mac OS X 10.3 and later*/ / * Unicode CHECK MARK*/ (define-unicode-key kDiamondUnicode #x25C6) ;/* Unicode BLACK DIAMOND*/ (define-unicode-key kBulletUnicode #x2022) ;/* Unicode BULLET*/ (define-unicode-key kAppleLogoUnicode #xF8FF) ;/* Unicode APPLE LOGO*/ ;;; ;;; Racket interface to UCKeyTranslate ;;; ;; The physical keyboard typed is cached. (define cached-keyboard-layout #f) (define (get-current-keyboard-layout) (define keyboard (TISCopyCurrentKeyboardLayoutInputSource)) (define layout-data (TISGetInputSourceProperty keyboard kTISPropertyUnicodeKeyLayoutData)) (define layout (CFDataGetBytePtr layout-data)) (cpointer-push-tag! layout 'UCKeyboardLayout) ; cast layout) ;; The strings used to store output from UCKeyTranslate is only allocated once: (define max-string-length 255) (define output-chars (malloc _UniChar max-string-length)) ;; Dead key state A pointer to an unsigned 32 - bit value , initialized to zero . ; The UCKeyTranslate function uses this value to store private ; information about the current dead key state. (define (make-initial-dead-key-state) (box 0)) (define (copy-dead-key-state dks) (box (unbox dks))) ; key-translate : integer [<extra options>] -> string ; Translates a virtual keycode into a string. ; The default key action is kUCKeyActionDown. ; The default dead key state is none. ; The default translate options are to ignore dead keys, ; unless a dead key state was provided, if so ; dead keys are activated. ; The keyboard layout is the one returned by get-current-keyboard-layout; ; the default is to use a cached value. Override by ; passing #f which means to refresh the cache, or ; pass a layout to use. (define (key-translate virtual-key-code #:key-action [key-action kUCKeyActionDown] #:modifier-key-state [modifier-key-state 0] ; no modifier #:keyboard-type [keyboard-type (LMGetKbdType)] #:key-translate-options [key-translate-options #f] #:dead-key-state [dead-key-state #f] ; no prev state #:keyboard-layout [layout-in 'cached]) ; use cached (define actual-string-length (box 0)) (set! key-translate-options (or key-translate-options ; use user settings if provided (if dead-key-state ; otherwise if user has set dead-key-state, 0 ; then take dead-keys into account kUCKeyTranslateNoDeadKeysFlag))) ; else ignore dead keys (set! dead-key-state (or dead-key-state (make-initial-dead-key-state))) (define layout (case layout-in ; use cached [(cached) (cond [cached-keyboard-layout => values] [else (set! cached-keyboard-layout (get-current-keyboard-layout)) cached-keyboard-layout])] ; refresh cache [(#f) (set! cached-keyboard-layout (get-current-keyboard-layout)) cached-keyboard-layout] ; use provided [else layout-in])) (UCKeyTranslate layout virtual-key-code key-action (bitwise-and (>> modifier-key-state 8) #xFF) keyboard-type key-translate-options dead-key-state max-string-length actual-string-length output-chars) ; get the number of characters returned, and convert to string (define n (max 0 (min max-string-length (unbox actual-string-length)))) (list->string (for/list ([i (in-range n)]) (integer->char (ptr-ref output-chars _UniChar i))))) ;;; ;;; Conversions back and forth between characters and key codes. ;;; ; Given a char it is useful to know which key and modifiers must ; be pressed to produce that character. Here a table is ; made storing all characters that can be produced without ; using dead keys. (define char-to-osx-key-code-ht (make-hash)) (define osx-key-code-to-char-ht (make-hash)) (define char-without-shift-ht (make-hash)) ;; All possible values for modifier combinations 16 in all (let () (define no-modifier '(())) (define one-modifier " simplest " modifier first (cmd) (control) (alt))) (define two-modifiers '((cmd shift) (control shift) (alt shift) (cmd control) (cmd option) (control option))) (define four-modifiers (list (apply append one-modifier))) (define three-modifiers (for/list ([m (reverse one-modifier)]) (remove m (car four-modifiers)))) (append no-modifier one-modifier two-modifiers three-modifiers four-modifiers))) ;; symbolic modifier to numeric value (define modifier-ht (make-hash)) (hash-set! modifier-ht 'cmd modifier-cmd-key) (hash-set! modifier-ht 'control modifier-control-key) (hash-set! modifier-ht 'alt modifier-option-key) (hash-set! modifier-ht 'shift modifier-shift-key) ; combine list of modifiers to a single integer (define (modifier-symbol-list->integer ms) (for/sum ([m (in-list ms)]) (hash-ref modifier-ht m 0))) ;; The "main char key" is the character produced when no modifier is pressed. ;; Example If #\> is produced by <shift>+<period> then the main char key of both > and <period> is #\. (define char-to-main-char-key-ht (make-hash)) ; char -> char char - > ( list ( list ) int ) (define osx-keycode-to-main-char-key-ht (make-hash)) ; int -> char ; hash-set-new! : hash-table key value -> void ; only sets if key has no previous value (define (hash-set-new! ht k v) (unless (hash-ref ht k #f) (hash-set! ht k v))) ;; fill in hash tables (for* ([modsyms all-modifier-combinations] ; go through all physical key [(kvc n) virtual-key-code-name-to-value-ht]) ; and modifier combinations (define modks (modifier-symbol-list->integer modsyms)) (define s (key-translate n #:modifier-key-state modks)) ; translate to a char (unless (string=? s "") ; unless key is dead (define c (string-ref s 0)) (hash-set-new! char-to-osx-keycode+modifiers-ht c ; store where char is from (list kvc n modsyms modks)) ; (simplest is kept) (cond [(null? modsyms) ; also, if it is a main char (hash-set! char-to-main-char-key-ht c c) ; store it as such (hash-set! osx-keycode-to-main-char-key-ht n c)] ; [else (define mck (hash-ref osx-keycode-to-main-char-key-ht n #f)) ; otherwise find (when mck (hash-set-new! char-to-main-char-key-ht c mck))]))) ; and store main char key (define (char->main-char-key+modifiers c) (define mck (hash-ref char-to-main-char-key-ht c #f)) (if mck (let () (define k+ms (hash-ref char-to-osx-keycode+modifiers-ht c #f)) (define mods (if (list? k+ms) (cadddr k+ms) #f)) (values mck mods)) (values #f #f))) ;;; ;;; RACKET KEY-CODE TO VIRTUAL KEYCODE ;;; ;;; ;;; WARNING - CODE BELOW IS NOT DONE ;;; (require mred/private/wx/cocoa/keycode) (define racket-keycode-symbol-to-osx-numeric-key-code-ht (make-hash)) (for ([c (in-range 256)]) (define r (map-key-code c)) (hash-set! racket-keycode-symbol-to-osx-numeric-key-code-ht r c)) (define unicode-to-racket-key-symbol-ht (make-hash)) (define (unicode->racket-key-symbol u) (hash-ref unicode-to-racket-key-symbol-ht u #f)) (define racket-key-symbol->unicode key-symbol-to-menu-key) ; Some keys such as functions keys are received as unicode characters ; 'escape 0 kVK_Escape ; 'snapshot 0 ' numpad0 0 ' 0 ; 'numpad2 0 ; 'numpad3 0 ' 0 ; 'numpad5 0 ' 0 ' 0 ; 'numpad8 0 ; 'numpad9 0 ; 'numpad-enter 0 ' multiply 0 ' add 0 ; 'separator 0 ' subtract 0 ' decimal 0 ; 'divide 0 (define symbols-with-unicode '(start cancel clear menu pause prior next end home left up right down select print execute insert help f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 scroll)) ; invert table (for ([s symbols-with-unicode]) (hash-set! unicode-to-racket-key-symbol-ht (racket-key-symbol->unicode s) s)) #;(define unicode-symbols-to-osx-keycode-ht (hasheq 'escape kVK_Escape ' start NSResetFunctionKey ' cancel NSStopFunctionKey 'clear kVK_ANSI_KeypadClear ' menu NSMenuFunctionKey 'pause NSPauseFunctionKey ;'prior NSPrevFunctionKey ;'next NSNextFunctionKey ;'end NSEndFunctionKey ;'home NSHomeFunctionKey 'left kVK_LeftArrow 'up kVK_UpArrow 'right kVK_RightArrow 'down kVK_DownArrow ;'select NSSelectFunctionKey 'print NSPrintFunctionKey 'execute NSExecuteFunctionKey 'snapshot 0 'insert NSInsertFunctionKey 'help NSHelpFunctionKey 'numpad0 kVK_ANSI_Keypad0 'numpad1 kVK_ANSI_Keypad1 'numpad2 kVK_ANSI_Keypad2 'numpad3 kVK_ANSI_Keypad3 'numpad4 kVK_ANSI_Keypad4 'numpad5 kVK_ANSI_Keypad5 'numpad6 kVK_ANSI_Keypad6 'numpad7 kVK_ANSI_Keypad7 'numpad8 kVK_ANSI_Keypad8 'numpad9 kVK_ANSI_Keypad9 'numpad-enter kVK_ANSI_KeypadEnter 'multiply kVK_ANSI_KeypadMultiply 'add kVK_ANSI_KeypadPlus ; 'separator ; ? 'subtract kVK_ANSI_KeypadMinus 'decimal kVK_ANSI_KeypadDecimal 'divide kVK_ANSI_KeypadDivide 'f1 kVK_F1 'f2 kVK_F2 'f3 kVK_F3 'f4 kVK_F4 'f5 kVK_F5 'f6 kVK_F6 'f7 kVK_F7 'f8 kVK_F8 'f9 kVK_F9 'f10 kVK_F10 'f11 kVK_F11 'f12 kVK_F12 'f13 kVK_F13 'f14 kVK_F14 'f15 kVK_F15 'f16 kVK_F16 'f17 kVK_F17 'f18 kVK_F18 'f19 kVK_F19 'f20 kVK_F20 'f21 kVK_F21 'f22 kVK_F22 'f23 kVK_F23 'f24 kVK_F24 ' scroll NSScrollLockFunctionKey )) (define (racket-key-symbol-to-osx-key-code k) (cond [(symbol? k) (define n (hash-ref racket-keycode-symbol-to-osx-numeric-key-code-ht k #f)) (define s (hash-ref virtual-key-code-value-to-name-ht n #f)) (and (or n s) (list n s))] [(char? k) (or (hash-ref char-to-osx-keycode+modifiers-ht k #f) (unicode->racket-key-symbol k))] [else #f])) ;(module+ test ; (check-equal? (racket-to-osx-key-code 'subtract) 'kVK_ANSI_KeypadMinus)
null
https://raw.githubusercontent.com/soegaard/remacs/8681b3acfe93335e2bc2133c6f144af9e0a1289e/old/osx-keyboard.rkt
racket
_NSString Bit operations Libraries used already imported Unicode Characters Types from MacTypes.h TEXT INPUT SOURCES Most text input sources are keyboards. Each physical key on a keyboard sends a keycode. A keyboard layout determines which character corresponds to a physical key. Getting the property is done by: The return value can be cast to: Before translating key codes to characters, one must option the physical type of keyboard. Given a layout and a keyboard type, one can translate keycodes to characters using UCKeyTranslate. Meaning of parameters: keyAction what happened to the key? - usually kUCKeyActionDown modifierKeyState which modifier keys are down? - shift, alt, ctrl, cmd or combinations keyTranslateOptions is previous input handled? - used to disable/enable dead keys unicodeString array into which the result is stored actualStringLength how many characters were stored in unicodeString See key-translate below for a more convenient interface for UCKeyTranslate. Constants and there symbolic representation. In order to define a lot of constants and keep their symbols around it is convenient a little help. category-name-to-value-ht from symbolic name to value category-value-to-name-ht from value to symbolic name It also defines and store the pairing in the hashtables. Example: See key actions below. Key Actions /* key is going down*/ /* auto-key down*/ Key Translate Options /* Prevents setting any new dead-key states*/ The constants are "event modifiers". Some of them are traditional key modiers, such as a modifier-shift-key-bit. /System/Library/Frameworks/Carbon.framework/Versions/A/ Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h The definitions indicate which bit controls what. activeFlagBit = 0, /* activate window? (activateEvt and mouseDown) /* command key down?*/ /* right shift key down? */ /* right Option key down? */ /* right Control key down? */ In actual use, we use the flags: /* * Summary: * Virtual keycodes * * Discussion: * These constants are the virtual keycodes defined originally in * Inside Mac Volume V, pg. V-191. They identify physical keys on a * keyboard. Those constants with "ANSI" in the name are labeled * For example, kVK_ANSI_A indicates the virtual keycode for the key * layouts may have the 'A' key label on a different physical key; * in this case, pressing 'A' will generate a different virtual * keycode. */ /* ISO keyboards only*/ /* JIS keyboards only*/ The following may or may not be useful at another time. /* glyph available only in system fonts*/ /* glyph available only in system fonts*/ /* glyph available only in system fonts*/ /* glyph available only in system fonts*/ Useful Unicode key points /* Unicode UPWARDS WHITE ARROW*/ /* Unicode UP ARROWHEAD*/ /* Unicode LOWER RIGHT PENCIL; /* Unicode LOWER LEFT PENCIL; /* Unicode BLACK DIAMOND*/ /* Unicode BULLET*/ /* Unicode APPLE LOGO*/ Racket interface to UCKeyTranslate The physical keyboard typed is cached. cast The strings used to store output from UCKeyTranslate is only allocated once: Dead key state The UCKeyTranslate function uses this value to store private information about the current dead key state. key-translate : integer [<extra options>] -> string Translates a virtual keycode into a string. The default key action is kUCKeyActionDown. The default dead key state is none. The default translate options are to ignore dead keys, unless a dead key state was provided, if so dead keys are activated. The keyboard layout is the one returned by get-current-keyboard-layout; the default is to use a cached value. Override by passing #f which means to refresh the cache, or pass a layout to use. no modifier no prev state use cached use user settings if provided otherwise if user has set dead-key-state, then take dead-keys into account else ignore dead keys use cached refresh cache use provided get the number of characters returned, and convert to string Conversions back and forth between characters and key codes. Given a char it is useful to know which key and modifiers must be pressed to produce that character. Here a table is made storing all characters that can be produced without using dead keys. All possible values for modifier combinations symbolic modifier to numeric value combine list of modifiers to a single integer The "main char key" is the character produced when no modifier is pressed. Example If #\> is produced by <shift>+<period> then the main char key of both > and <period> is #\. char -> char int -> char hash-set-new! : hash-table key value -> void only sets if key has no previous value fill in hash tables go through all physical key and modifier combinations translate to a char unless key is dead store where char is from (simplest is kept) also, if it is a main char store it as such otherwise find and store main char key RACKET KEY-CODE TO VIRTUAL KEYCODE WARNING - CODE BELOW IS NOT DONE Some keys such as functions keys are received as unicode characters 'escape 0 kVK_Escape 'snapshot 0 'numpad2 0 'numpad3 0 'numpad5 0 'numpad8 0 'numpad9 0 'numpad-enter 0 'separator 0 'divide 0 invert table (define unicode-symbols-to-osx-keycode-ht 'prior NSPrevFunctionKey 'next NSNextFunctionKey 'end NSEndFunctionKey 'home NSHomeFunctionKey 'select NSSelectFunctionKey 'separator ; ? (module+ test (check-equal? (racket-to-osx-key-code 'subtract) 'kVK_ANSI_KeypadMinus)
#lang racket/base (provide key-translate make-initial-dead-key-state copy-dead-key-state char->main-char-key+modifiers) (require (for-syntax syntax/parse racket/syntax racket/base)) (require ffi/unsafe ffi/unsafe/objc ffi/unsafe/define (define (<< x y) (arithmetic-shift x y)) (define (>> x y) (arithmetic-shift x (- y))) (define quartz-lib (ffi-lib "/System/Library/Frameworks/Quartz.framework/Versions/Current/Quartz")) (define carbon-lib (ffi-lib "/System/Library/Frameworks/Carbon.framework/Versions/Current/Carbon")) (define carbon-core-lib (ffi-lib (string-append "/System/Library/Frameworks/CoreServices.framework/" "Frameworks/CarbonCore.framework/Versions/Current/CarbonCore"))) (define cf-lib (ffi-lib "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")) (define-ffi-definer define-quartz quartz-lib) (define-ffi-definer define-carbon-core carbon-core-lib) (define-ffi-definer define-carbon carbon-lib) (define-ffi-definer define-cf cf-lib #:default-make-fail make-not-available) CORE FOUNDATION (import-class NSString) (define _CFStringRef _NSString) (define-cpointer-type _CFDataRef) (define _UniChar _uint16) (define _UniCharCount _ulong) (define _UniCharPointer (_ptr io _UniChar)) (define _UniCharCountPointer (_ptr io _UniCharCount)) (define _OptionBits _uint32) (define _TISInputSourceRef (_cpointer 'TISInputSourceRef)) Example : the key label labelled A on a US keyboard sends kVK_ANSI_A=0 . To get a layout , one must first get a reference to the input source : (define-carbon TISCopyCurrentKeyboardLayoutInputSource (_fun -> _TISInputSourceRef)) (define-carbon TISCopyCurrentASCIICapableKeyboardLayoutInputSource (_fun -> _TISInputSourceRef)) Note : These days TISCopyCurrentKeyboardLayoutInputSource ought to work for all keyboards . The input source has several properties , one of is : (define-carbon kTISPropertyUnicodeKeyLayoutData _NSString) (define-carbon TISGetInputSourceProperty (_fun (_inputSource : _TISInputSourceRef) (_propertyKey : _CFStringRef) -> (_or-null _CFDataRef))) The value returned by TISGetInputSourceProperty is a CFDataRef , so one mus call CFDataGetBytePtr to get the actual layout . (define-cf CFDataGetBytePtr (_fun _CFDataRef -> _pointer)) (define _UCKeyboardLayout (_cpointer 'UCKeyboardLayout)) (define-carbon LMGetKbdType (_fun -> _uint8)) (define-carbon UCKeyTranslate (_fun (keyboardLayoutPtr : _UCKeyboardLayout) (virtualKeyCode : _uint16) (keyAction : _uint16) (modifierKeyState : _uint32) (keyboardType : _uint32) uint32 (deadKeyState : (_box _uint32)) (maxStringLength : _UniCharCount) ( actualStringLength : _ ) (actualStringLength : (_box _UniCharCount)) (unicodeString : _pointer) -> _OSStatus)) deadKeyState integer encoding of prev keys - none is encoded as 0 SYNTAX ( define - name / value - definer category ) Defines two hash - tables SYNTAX ( define - category name ) which defines name as , provides val (define-syntax (define-name/value-definer stx) (syntax-parse stx [(_ prefix) (with-syntax ([prefix-name-to-value-ht (format-id stx "~a-name-to-value-ht" #'prefix)] [prefix-value-to-name-ht (format-id stx "~a-value-to-name-ht" #'prefix)] [prefix-name (format-id stx "~a-name" #'prefix)] [prefix-value (format-id stx "~a-value" #'prefix)] [define-prefix (format-id stx "define-~a" #'prefix)]) #'(begin (define prefix-name-to-value-ht (make-hash)) (define prefix-value-to-name-ht (make-hash)) (define (prefix-name value) (hash-ref prefix-value-to-name-ht value #f)) (define (prefix-value name) (hash-ref prefix-name-to-value-ht name #f)) (provide prefix-name-to-value-ht prefix-value-to-name-ht prefix-name prefix-value) (define-syntax (define-prefix stx) (syntax-parse stx [(_ name expr) #'(begin (provide name ) (define name expr) (hash-set! prefix-name-to-value-ht 'name name) (hash-set! prefix-value-to-name-ht name 'name))]))))])) (define-name/value-definer key-action) / * key is going up*/ / * get information for key display ( as in Key Caps ) * / There is only one option . Should dead keys have an effect or not ? (define kUCKeyTranslateNoDeadKeysFlag 1) (define kUCKeyTranslateNoDeadKeysMask 1) EventModifiers ( UInt16 ) (define-name/value-definer event-modifier-bits) (define-name/value-definer event-modifier-flag) From ( file dates 2008 ): btnStateBit = 7 , state of mouse ! button ? shiftKeyBit = 9 , / * shift key down?*/ alphaLockBit = 10 , / * alpha lock down?*/ optionKeyBit = 11 , / * option key down?*/ controlKeyBit = 12 , / * control key down?*/ NOTE : The following 3 modifiers are not supported on OS X (define-event-modifier-flag modifier-active-flag (<< 1 0)) (define-event-modifier-flag modifier-btn-state (<< 1 7)) (define-event-modifier-flag modifier-cmd-key (<< 1 8)) (define-event-modifier-flag modifier-shift-key (<< 1 9)) (define-event-modifier-flag modifier-alpha-lock (<< 1 10)) (define-event-modifier-flag modifier-option-key (<< 1 11)) (define-event-modifier-flag modifier-control-key (<< 1 12)) NOTE : The following 3 modifiers are not supported on OS X (define-event-modifier-flag modifier-right-shift-key (<< 1 13)) (define-event-modifier-flag modifier-right-option-key (<< 1 14)) (define-event-modifier-flag modifier-right-control-key (<< 1 15)) Virtual Keycodes * according to the key position on an ANSI - standard US keyboard . * with the letter ' A ' in the US keyboard layout . Other keyboard (define-name/value-definer virtual-key-code) (define-virtual-key-code kVK_ANSI_A #x00) (define-virtual-key-code kVK_ANSI_S #x01) (define-virtual-key-code kVK_ANSI_D #x02) (define-virtual-key-code kVK_ANSI_F #x03) (define-virtual-key-code kVK_ANSI_H #x04) (define-virtual-key-code kVK_ANSI_G #x05) (define-virtual-key-code kVK_ANSI_Z #x06) (define-virtual-key-code kVK_ANSI_X #x07) (define-virtual-key-code kVK_ANSI_C #x08) (define-virtual-key-code kVK_ANSI_V #x09) (define-virtual-key-code kVK_ANSI_B #x0B) (define-virtual-key-code kVK_ANSI_Q #x0C) (define-virtual-key-code kVK_ANSI_W #x0D) (define-virtual-key-code kVK_ANSI_E #x0E) (define-virtual-key-code kVK_ANSI_R #x0F) (define-virtual-key-code kVK_ANSI_Y #x10) (define-virtual-key-code kVK_ANSI_T #x11) (define-virtual-key-code kVK_ANSI_1 #x12) (define-virtual-key-code kVK_ANSI_2 #x13) (define-virtual-key-code kVK_ANSI_3 #x14) (define-virtual-key-code kVK_ANSI_4 #x15) (define-virtual-key-code kVK_ANSI_6 #x16) (define-virtual-key-code kVK_ANSI_5 #x17) (define-virtual-key-code kVK_ANSI_Equal #x18) (define-virtual-key-code kVK_ANSI_9 #x19) (define-virtual-key-code kVK_ANSI_7 #x1A) (define-virtual-key-code kVK_ANSI_Minus #x1B) (define-virtual-key-code kVK_ANSI_8 #x1C) (define-virtual-key-code kVK_ANSI_0 #x1D) (define-virtual-key-code kVK_ANSI_RightBracket #x1E) (define-virtual-key-code kVK_ANSI_O #x1F) (define-virtual-key-code kVK_ANSI_U #x20) (define-virtual-key-code kVK_ANSI_LeftBracket #x21) (define-virtual-key-code kVK_ANSI_I #x22) (define-virtual-key-code kVK_ANSI_P #x23) (define-virtual-key-code kVK_ANSI_L #x25) (define-virtual-key-code kVK_ANSI_J #x26) (define-virtual-key-code kVK_ANSI_Quote #x27) (define-virtual-key-code kVK_ANSI_K #x28) (define-virtual-key-code kVK_ANSI_Semicolon #x29) (define-virtual-key-code kVK_ANSI_Backslash #x2A) (define-virtual-key-code kVK_ANSI_Comma #x2B) (define-virtual-key-code kVK_ANSI_Slash #x2C) (define-virtual-key-code kVK_ANSI_N #x2D) (define-virtual-key-code kVK_ANSI_M #x2E) (define-virtual-key-code kVK_ANSI_Period #x2F) (define-virtual-key-code kVK_ANSI_Grave #x32) (define-virtual-key-code kVK_ANSI_KeypadDecimal #x41) (define-virtual-key-code kVK_ANSI_KeypadMultiply #x43) (define-virtual-key-code kVK_ANSI_KeypadPlus #x45) (define-virtual-key-code kVK_ANSI_KeypadClear #x47) (define-virtual-key-code kVK_ANSI_KeypadDivide #x4B) (define-virtual-key-code kVK_ANSI_KeypadEnter #x4C) (define-virtual-key-code kVK_ANSI_KeypadMinus #x4E) (define-virtual-key-code kVK_ANSI_KeypadEquals #x51) (define-virtual-key-code kVK_ANSI_Keypad0 #x52) (define-virtual-key-code kVK_ANSI_Keypad1 #x53) (define-virtual-key-code kVK_ANSI_Keypad2 #x54) (define-virtual-key-code kVK_ANSI_Keypad3 #x55) (define-virtual-key-code kVK_ANSI_Keypad4 #x56) (define-virtual-key-code kVK_ANSI_Keypad5 #x57) (define-virtual-key-code kVK_ANSI_Keypad6 #x58) (define-virtual-key-code kVK_ANSI_Keypad7 #x59) (define-virtual-key-code kVK_ANSI_Keypad8 #x5B) (define-virtual-key-code kVK_ANSI_Keypad9 #x5C) / * keycodes for keys that are independent of keyboard layout*/ (define-virtual-key-code kVK_Return #x24) (define-virtual-key-code kVK_Tab #x30) (define-virtual-key-code kVK_Space #x31) (define-virtual-key-code kVK_Delete #x33) (define-virtual-key-code kVK_Escape #x35) (define-virtual-key-code kVK_Command #x37) (define-virtual-key-code kVK_Shift #x38) (define-virtual-key-code kVK_CapsLock #x39) (define-virtual-key-code kVK_Option #x3A) (define-virtual-key-code kVK_Control #x3B) (define-virtual-key-code kVK_RightShift #x3C) (define-virtual-key-code kVK_RightOption #x3D) (define-virtual-key-code kVK_RightControl #x3E) (define-virtual-key-code kVK_Function #x3F) (define-virtual-key-code kVK_F17 #x40) (define-virtual-key-code kVK_VolumeUp #x48) (define-virtual-key-code kVK_VolumeDown #x49) (define-virtual-key-code kVK_Mute #x4A) (define-virtual-key-code kVK_F18 #x4F) (define-virtual-key-code kVK_F19 #x50) (define-virtual-key-code kVK_F20 #x5A) (define-virtual-key-code kVK_F5 #x60) (define-virtual-key-code kVK_F6 #x61) (define-virtual-key-code kVK_F7 #x62) (define-virtual-key-code kVK_F3 #x63) (define-virtual-key-code kVK_F8 #x64) (define-virtual-key-code kVK_F9 #x65) (define-virtual-key-code kVK_F11 #x67) (define-virtual-key-code kVK_F13 #x69) (define-virtual-key-code kVK_F16 #x6A) (define-virtual-key-code kVK_F14 #x6B) (define-virtual-key-code kVK_F10 #x6D) (define-virtual-key-code kVK_F12 #x6F) (define-virtual-key-code kVK_F15 #x71) (define-virtual-key-code kVK_Help #x72) (define-virtual-key-code kVK_Home #x73) (define-virtual-key-code kVK_PageUp #x74) (define-virtual-key-code kVK_ForwardDelete #x75) (define-virtual-key-code kVK_F4 #x76) (define-virtual-key-code kVK_End #x77) (define-virtual-key-code kVK_F2 #x78) (define-virtual-key-code kVK_PageDown #x79) (define-virtual-key-code kVK_F1 #x7A) (define-virtual-key-code kVK_LeftArrow #x7B) (define-virtual-key-code kVK_RightArrow #x7C) (define-virtual-key-code kVK_DownArrow #x7D) (define-virtual-key-code kVK_UpArrow #x7E) (define-virtual-key-code kVK_ISO_Section #x0A) (define-virtual-key-code kVK_JIS_Yen #x5D) (define-virtual-key-code kVK_JIS_Underscore #x5E) (define-virtual-key-code kVK_JIS_KeypadComma #x5F) (define-virtual-key-code kVK_JIS_Eisu #x66) (define-virtual-key-code kVK_JIS_Kana #x68) MacRoman character codes (define-name/value-definer mac-roman) (define-mac-roman kNullCharCode 0) (define-mac-roman kHomeCharCode 1) (define-mac-roman kEnterCharCode 3) (define-mac-roman kEndCharCode 4) (define-mac-roman kHelpCharCode 5) (define-mac-roman kBellCharCode 7) (define-mac-roman kBackspaceCharCode 8) (define-mac-roman kTabCharCode 9) (define-mac-roman kLineFeedCharCode 10) (define-mac-roman kVerticalTabCharCode 11) (define-mac-roman kPageUpCharCode 11) (define-mac-roman kFormFeedCharCode 12) (define-mac-roman kPageDownCharCode 12) (define-mac-roman kReturnCharCode 13) (define-mac-roman kFunctionKeyCharCode 16) (define-mac-roman kEscapeCharCode 27) (define-mac-roman kClearCharCode 27) (define-mac-roman kLeftArrowCharCode 28) (define-mac-roman kRightArrowCharCode 29) (define-mac-roman kUpArrowCharCode 30) (define-mac-roman kDownArrowCharCode 31) (define-mac-roman kSpaceCharCode 32) (define-mac-roman kDeleteCharCode 127) (define-mac-roman kBulletCharCode 165) (define-mac-roman kNonBreakingSpaceCharCode 202) (define-name/value-definer unicode-key) / * Unicode OPTION / * Unicode PLACE OF INTEREST SIGN*/ actually pointed left until available in Mac OS X 10.3 and later*/ / * Unicode CHECK MARK*/ (define cached-keyboard-layout #f) (define (get-current-keyboard-layout) (define keyboard (TISCopyCurrentKeyboardLayoutInputSource)) (define layout-data (TISGetInputSourceProperty keyboard kTISPropertyUnicodeKeyLayoutData)) (define layout (CFDataGetBytePtr layout-data)) layout) (define max-string-length 255) (define output-chars (malloc _UniChar max-string-length)) A pointer to an unsigned 32 - bit value , initialized to zero . (define (make-initial-dead-key-state) (box 0)) (define (copy-dead-key-state dks) (box (unbox dks))) (define (key-translate virtual-key-code #:key-action [key-action kUCKeyActionDown] #:keyboard-type [keyboard-type (LMGetKbdType)] #:key-translate-options [key-translate-options #f] (define actual-string-length (box 0)) (set! key-translate-options (set! dead-key-state (or dead-key-state (make-initial-dead-key-state))) (define layout (case layout-in [(cached) (cond [cached-keyboard-layout => values] [else (set! cached-keyboard-layout (get-current-keyboard-layout)) cached-keyboard-layout])] [(#f) (set! cached-keyboard-layout (get-current-keyboard-layout)) cached-keyboard-layout] [else layout-in])) (UCKeyTranslate layout virtual-key-code key-action (bitwise-and (>> modifier-key-state 8) #xFF) keyboard-type key-translate-options dead-key-state max-string-length actual-string-length output-chars) (define n (max 0 (min max-string-length (unbox actual-string-length)))) (list->string (for/list ([i (in-range n)]) (integer->char (ptr-ref output-chars _UniChar i))))) (define char-to-osx-key-code-ht (make-hash)) (define osx-key-code-to-char-ht (make-hash)) (define char-without-shift-ht (make-hash)) 16 in all (let () (define no-modifier '(())) (define one-modifier " simplest " modifier first (cmd) (control) (alt))) (define two-modifiers '((cmd shift) (control shift) (alt shift) (cmd control) (cmd option) (control option))) (define four-modifiers (list (apply append one-modifier))) (define three-modifiers (for/list ([m (reverse one-modifier)]) (remove m (car four-modifiers)))) (append no-modifier one-modifier two-modifiers three-modifiers four-modifiers))) (define modifier-ht (make-hash)) (hash-set! modifier-ht 'cmd modifier-cmd-key) (hash-set! modifier-ht 'control modifier-control-key) (hash-set! modifier-ht 'alt modifier-option-key) (hash-set! modifier-ht 'shift modifier-shift-key) (define (modifier-symbol-list->integer ms) (for/sum ([m (in-list ms)]) (hash-ref modifier-ht m 0))) char - > ( list ( list ) int ) (define (hash-set-new! ht k v) (unless (hash-ref ht k #f) (hash-set! ht k v))) (define modks (modifier-symbol-list->integer modsyms)) (define c (string-ref s 0)) (cond [else (define (char->main-char-key+modifiers c) (define mck (hash-ref char-to-main-char-key-ht c #f)) (if mck (let () (define k+ms (hash-ref char-to-osx-keycode+modifiers-ht c #f)) (define mods (if (list? k+ms) (cadddr k+ms) #f)) (values mck mods)) (values #f #f))) (require mred/private/wx/cocoa/keycode) (define racket-keycode-symbol-to-osx-numeric-key-code-ht (make-hash)) (for ([c (in-range 256)]) (define r (map-key-code c)) (hash-set! racket-keycode-symbol-to-osx-numeric-key-code-ht r c)) (define unicode-to-racket-key-symbol-ht (make-hash)) (define (unicode->racket-key-symbol u) (hash-ref unicode-to-racket-key-symbol-ht u #f)) (define racket-key-symbol->unicode key-symbol-to-menu-key) ' numpad0 0 ' 0 ' 0 ' 0 ' 0 ' multiply 0 ' add 0 ' subtract 0 ' decimal 0 (define symbols-with-unicode '(start cancel clear menu pause prior next end home left up right down select print execute insert help f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 f12 f13 f14 f15 f16 f17 f18 f19 f20 f21 f22 f23 f24 scroll)) (for ([s symbols-with-unicode]) (hash-set! unicode-to-racket-key-symbol-ht (racket-key-symbol->unicode s) s)) (hasheq 'escape kVK_Escape ' start NSResetFunctionKey ' cancel NSStopFunctionKey 'clear kVK_ANSI_KeypadClear ' menu NSMenuFunctionKey 'pause NSPauseFunctionKey 'left kVK_LeftArrow 'up kVK_UpArrow 'right kVK_RightArrow 'down kVK_DownArrow 'print NSPrintFunctionKey 'execute NSExecuteFunctionKey 'snapshot 0 'insert NSInsertFunctionKey 'help NSHelpFunctionKey 'numpad0 kVK_ANSI_Keypad0 'numpad1 kVK_ANSI_Keypad1 'numpad2 kVK_ANSI_Keypad2 'numpad3 kVK_ANSI_Keypad3 'numpad4 kVK_ANSI_Keypad4 'numpad5 kVK_ANSI_Keypad5 'numpad6 kVK_ANSI_Keypad6 'numpad7 kVK_ANSI_Keypad7 'numpad8 kVK_ANSI_Keypad8 'numpad9 kVK_ANSI_Keypad9 'numpad-enter kVK_ANSI_KeypadEnter 'multiply kVK_ANSI_KeypadMultiply 'add kVK_ANSI_KeypadPlus 'subtract kVK_ANSI_KeypadMinus 'decimal kVK_ANSI_KeypadDecimal 'divide kVK_ANSI_KeypadDivide 'f1 kVK_F1 'f2 kVK_F2 'f3 kVK_F3 'f4 kVK_F4 'f5 kVK_F5 'f6 kVK_F6 'f7 kVK_F7 'f8 kVK_F8 'f9 kVK_F9 'f10 kVK_F10 'f11 kVK_F11 'f12 kVK_F12 'f13 kVK_F13 'f14 kVK_F14 'f15 kVK_F15 'f16 kVK_F16 'f17 kVK_F17 'f18 kVK_F18 'f19 kVK_F19 'f20 kVK_F20 'f21 kVK_F21 'f22 kVK_F22 'f23 kVK_F23 'f24 kVK_F24 ' scroll NSScrollLockFunctionKey )) (define (racket-key-symbol-to-osx-key-code k) (cond [(symbol? k) (define n (hash-ref racket-keycode-symbol-to-osx-numeric-key-code-ht k #f)) (define s (hash-ref virtual-key-code-value-to-name-ht n #f)) (and (or n s) (list n s))] [(char? k) (or (hash-ref char-to-osx-keycode+modifiers-ht k #f) (unicode->racket-key-symbol k))] [else #f]))
554234c3f74700912c8097188f6bc78ef74df1955f1a49e33d57b0085ab5112e
spurious/sagittarius-scheme-mirror
gzip.scm
-*- mode : scheme ; coding : utf-8 -*- ;;; gzip.scm - RFC1952 zlib library ;;; Copyright ( c ) 2010 - 2013 < > ;;; ;;; Redistribution and use in source and binary forms, with or without ;;; modification, are permitted provided that the following conditions ;;; are met: ;;; ;;; 1. Redistributions of source code must retain the above copyright ;;; notice, this list of conditions and the following disclaimer. ;;; ;;; 2. Redistributions in binary form must reproduce the above copyright ;;; notice, this list of conditions and the following disclaimer in the ;;; documentation and/or other materials provided with the distribution. ;;; ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;; ;; This library ignores FTEXT and OS and always treats data as binary. ;; The "extra" data in the header is also ignored. Only DEFLATEd data ;; is supported. (library (rfc gzip) (export open-gzip-output-port open-gzip-input-port get-gzip-header (rename (make-gzip make-gzip-header)) make-gzip-header-from-file ;; header accessor gzip-text? gzip-mtime gzip-extra-data gzip-filename gzip-comment gzip-method gzip-os ;; OS fat-filesystem amiga vms unix vm/cms atari-tos hpfs-filesystem macintosh z-system cp/m tops-20 ntfs-filesystem qdos acorn-riscos unknown) (import (rnrs) (sagittarius) (srfi :19 time) (rfc zlib) (binary pack)) ;;; From industria start -*- mode : scheme ; coding : utf-8 -*- Copyright © 2010 < > SPDX - License - Identifier : MIT ;; 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. (define-record-type gzip (fields text? mtime extra-data filename comment method os)) (define (flg-ftext? x) (fxbit-set? x 0)) (define (flg-fhcrc? x) (fxbit-set? x 1)) (define (flg-fextra? x) (fxbit-set? x 2)) (define (flg-fname? x) (fxbit-set? x 3)) (define (flg-fcomment? x) (fxbit-set? x 4)) (define (flg-reserved? x) (not (fxzero? (fxbit-field x 6 8)))) (define-constant gzip-magic #vu8(#x1f #x8b)) ;;; OS (define-constant fat-filesystem 0) (define-constant amiga 1) (define-constant vms 2) (define-constant unix 3) (define-constant vm/cms 4) (define-constant atari-tos 5) (define-constant hpfs-filesystem 6) (define-constant macintosh 7) (define-constant z-system 8) (define-constant cp/m 9) (define-constant tops-20 10) (define-constant ntfs-filesystem 11) (define-constant qdos 12) (define-constant acorn-riscos 13) (define-constant unknown 255) (define-constant compression-method-deflate 8) (define (get-asciiz p) (call-with-string-output-port (lambda (r) (let lp () (let ((b (get-u8 p))) (unless (fxzero? b) (put-char r (integer->char b)) (lp))))))) (define (get-gzip-header* p who) (let*-values (((cm flg mtime xfl os) (get-unpack p "<uCCLCC")) ((extra) (if (flg-fextra? flg) (get-bytevector-n p (get-unpack p "<S")) #vu8())) ((fname) (and (flg-fname? flg) (get-asciiz p))) ((fcomment) (and (flg-fcomment? flg) (get-asciiz p))) ((crc16) (and (flg-fhcrc? flg) (get-unpack p "<S")))) (unless (= cm compression-method-deflate) (error who "invalid compression method" cm)) (when (flg-reserved? flg) (error who "reserved flags set" flg)) (make-gzip (flg-ftext? flg) (and (not (zero? mtime)) (time-monotonic->date (make-time 'time-monotonic 0 mtime))) extra fname fcomment (if (= xfl 2) 'slowest (if (= xfl 4) 'fastest xfl)) os))) (define get-gzip-header (case-lambda ((p) (get-gzip-header p 'get-gzip-header)) ((p who) ;; check magic (unless (eqv? (lookahead-u8 p) #x1f) (error who "not GZIP data" p)) (get-u8 p) (unless (eqv? (lookahead-u8 p) #x8b) (error who "not GZIP data" p)) (get-u8 p) (get-gzip-header* p who)))) (define (get-crc in bv*) ;; The bv* is taken from the bit-reader state for the inflater. (let ((len (- (format-size "<L") (bytevector-length bv*)))) (unpack "<L" (bytevector-append bv* (get-bytevector-n in len))))) ;; always treat as binary... FIXME (define (make-gzip-header-from-file file :key (comment "")) (make-gzip #f (time-monotonic->date (make-time 'time-monotonic 0 (div (file-stat-mtime file) 1000000000))) #vu8() file comment 'fastest unknown)) (define (gzip-header->bytevector header) (unless (gzip? header) (assertion-violation 'gzip-header->bytevector "not a GZIP header" header)) (call-with-bytevector-output-port (lambda (out) (define (construct-flag header) (let ((f 0)) (when (gzip-text? header) (set! f #x01)) (unless (zero? (bytevector-length (gzip-extra-data header))) (set! f (fxior f #x04))) (when (gzip-filename header) (set! f (fxior f #x08))) (when (gzip-comment header) (set! f (fxior f #x10))) f)) (define (date->mtime date) (let ((t (if (eqv? date 0) date (time-nanosecond (date->time-monotonic date))))) (pack "<uL" t))) (define (zero-terminated-string s) (when s (put-bytevector out (string->utf8 s)) (put-u8 out 0))) (put-bytevector out gzip-magic) (put-u8 out compression-method-deflate) (put-u8 out (construct-flag header)) (put-bytevector out (date->mtime (gzip-mtime header))) (let ((m (gzip-method header))) (if (symbol? m) (case m ((slowest) (put-u8 out 2)) ((fastest) (put-u8 out 4))) (put-u8 out m))) (put-u8 out (gzip-os header)) (let ((extra (gzip-extra-data header))) (unless (zero? (bytevector-length extra)) (put-bytevector out (pack "<S" (bytevector-length extra))) (put-bytevector out extra))) (zero-terminated-string (gzip-filename header)) (zero-terminated-string (gzip-comment header)) ;; we don't put CRC16... FIXME ))) ;;; end ;; only supports deflating ... (define (open-gzip-output-port sink :key (header #f) (owner? #f)) (define (make-wrapped-deflating-output-port) (define dout (open-deflating-output-port sink :window-bits -15)) (define crc 0) (define size 0) (define (write! bv start count) (set! crc (crc32 (bytevector-copy bv start (- count start)) crc)) (set! size (+ size count)) (put-bytevector dout bv start count) count) (define (close) (close-output-port dout) ;; put crc32 (put-bytevector sink (pack "<L" crc)) ;; put ISIZE (put-bytevector sink (pack "<L" size)) (when owner? (close-output-port sink))) (make-custom-binary-output-port "gzip-port" write! #f #f close)) (if header ;; put header to sink and make deflating port with window-bits -15 (let ((bv (gzip-header->bytevector header))) (put-bytevector sink bv) (make-wrapped-deflating-output-port)) ;; make empty header (open-deflating-output-port sink :window-bits 31 :owner? owner?))) ;;; decompress (define (open-gzip-input-port source :key (owner? #f)) ;; for now we don't care the header information... (open-inflating-input-port source :owner? owner? :window-bits 31)) )
null
https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/sitelib/rfc/gzip.scm
scheme
coding : utf-8 -*- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This library ignores FTEXT and OS and always treats data as binary. The "extra" data in the header is also ignored. Only DEFLATEd data is supported. header accessor OS From industria start coding : utf-8 -*- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), the rights to use, copy, modify, merge, publish, distribute, sublicense, Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. OS check magic The bv* is taken from the bit-reader state for the inflater. always treat as binary... we don't put CRC16... FIXME end only supports deflating ... put crc32 put ISIZE put header to sink and make deflating port with window-bits -15 make empty header decompress for now we don't care the header information...
gzip.scm - RFC1952 zlib library Copyright ( c ) 2010 - 2013 < > " AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING (library (rfc gzip) (export open-gzip-output-port open-gzip-input-port get-gzip-header (rename (make-gzip make-gzip-header)) make-gzip-header-from-file gzip-text? gzip-mtime gzip-extra-data gzip-filename gzip-comment gzip-method gzip-os fat-filesystem amiga vms unix vm/cms atari-tos hpfs-filesystem macintosh z-system cp/m tops-20 ntfs-filesystem qdos acorn-riscos unknown) (import (rnrs) (sagittarius) (srfi :19 time) (rfc zlib) (binary pack)) Copyright © 2010 < > SPDX - License - Identifier : MIT to deal in the Software without restriction , including without limitation and/or sell copies of the Software , and to permit persons to whom the all copies or substantial portions of the Software . THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING (define-record-type gzip (fields text? mtime extra-data filename comment method os)) (define (flg-ftext? x) (fxbit-set? x 0)) (define (flg-fhcrc? x) (fxbit-set? x 1)) (define (flg-fextra? x) (fxbit-set? x 2)) (define (flg-fname? x) (fxbit-set? x 3)) (define (flg-fcomment? x) (fxbit-set? x 4)) (define (flg-reserved? x) (not (fxzero? (fxbit-field x 6 8)))) (define-constant gzip-magic #vu8(#x1f #x8b)) (define-constant fat-filesystem 0) (define-constant amiga 1) (define-constant vms 2) (define-constant unix 3) (define-constant vm/cms 4) (define-constant atari-tos 5) (define-constant hpfs-filesystem 6) (define-constant macintosh 7) (define-constant z-system 8) (define-constant cp/m 9) (define-constant tops-20 10) (define-constant ntfs-filesystem 11) (define-constant qdos 12) (define-constant acorn-riscos 13) (define-constant unknown 255) (define-constant compression-method-deflate 8) (define (get-asciiz p) (call-with-string-output-port (lambda (r) (let lp () (let ((b (get-u8 p))) (unless (fxzero? b) (put-char r (integer->char b)) (lp))))))) (define (get-gzip-header* p who) (let*-values (((cm flg mtime xfl os) (get-unpack p "<uCCLCC")) ((extra) (if (flg-fextra? flg) (get-bytevector-n p (get-unpack p "<S")) #vu8())) ((fname) (and (flg-fname? flg) (get-asciiz p))) ((fcomment) (and (flg-fcomment? flg) (get-asciiz p))) ((crc16) (and (flg-fhcrc? flg) (get-unpack p "<S")))) (unless (= cm compression-method-deflate) (error who "invalid compression method" cm)) (when (flg-reserved? flg) (error who "reserved flags set" flg)) (make-gzip (flg-ftext? flg) (and (not (zero? mtime)) (time-monotonic->date (make-time 'time-monotonic 0 mtime))) extra fname fcomment (if (= xfl 2) 'slowest (if (= xfl 4) 'fastest xfl)) os))) (define get-gzip-header (case-lambda ((p) (get-gzip-header p 'get-gzip-header)) ((p who) (unless (eqv? (lookahead-u8 p) #x1f) (error who "not GZIP data" p)) (get-u8 p) (unless (eqv? (lookahead-u8 p) #x8b) (error who "not GZIP data" p)) (get-u8 p) (get-gzip-header* p who)))) (define (get-crc in bv*) (let ((len (- (format-size "<L") (bytevector-length bv*)))) (unpack "<L" (bytevector-append bv* (get-bytevector-n in len))))) FIXME (define (make-gzip-header-from-file file :key (comment "")) (make-gzip #f (time-monotonic->date (make-time 'time-monotonic 0 (div (file-stat-mtime file) 1000000000))) #vu8() file comment 'fastest unknown)) (define (gzip-header->bytevector header) (unless (gzip? header) (assertion-violation 'gzip-header->bytevector "not a GZIP header" header)) (call-with-bytevector-output-port (lambda (out) (define (construct-flag header) (let ((f 0)) (when (gzip-text? header) (set! f #x01)) (unless (zero? (bytevector-length (gzip-extra-data header))) (set! f (fxior f #x04))) (when (gzip-filename header) (set! f (fxior f #x08))) (when (gzip-comment header) (set! f (fxior f #x10))) f)) (define (date->mtime date) (let ((t (if (eqv? date 0) date (time-nanosecond (date->time-monotonic date))))) (pack "<uL" t))) (define (zero-terminated-string s) (when s (put-bytevector out (string->utf8 s)) (put-u8 out 0))) (put-bytevector out gzip-magic) (put-u8 out compression-method-deflate) (put-u8 out (construct-flag header)) (put-bytevector out (date->mtime (gzip-mtime header))) (let ((m (gzip-method header))) (if (symbol? m) (case m ((slowest) (put-u8 out 2)) ((fastest) (put-u8 out 4))) (put-u8 out m))) (put-u8 out (gzip-os header)) (let ((extra (gzip-extra-data header))) (unless (zero? (bytevector-length extra)) (put-bytevector out (pack "<S" (bytevector-length extra))) (put-bytevector out extra))) (zero-terminated-string (gzip-filename header)) (zero-terminated-string (gzip-comment header)) ))) (define (open-gzip-output-port sink :key (header #f) (owner? #f)) (define (make-wrapped-deflating-output-port) (define dout (open-deflating-output-port sink :window-bits -15)) (define crc 0) (define size 0) (define (write! bv start count) (set! crc (crc32 (bytevector-copy bv start (- count start)) crc)) (set! size (+ size count)) (put-bytevector dout bv start count) count) (define (close) (close-output-port dout) (put-bytevector sink (pack "<L" crc)) (put-bytevector sink (pack "<L" size)) (when owner? (close-output-port sink))) (make-custom-binary-output-port "gzip-port" write! #f #f close)) (if header (let ((bv (gzip-header->bytevector header))) (put-bytevector sink bv) (make-wrapped-deflating-output-port)) (open-deflating-output-port sink :window-bits 31 :owner? owner?))) (define (open-gzip-input-port source :key (owner? #f)) (open-inflating-input-port source :owner? owner? :window-bits 31)) )
09952278e822dd0d87cb62338516a68a08c0f3beb99ef6d86b88b244a84857c8
takano-akio/fast-builder
map.hs
import Control.Concurrent import Criterion.Main import qualified Data.IntMap as IM import Data.Monoid import qualified Data.ByteString.Builder as Bstr import qualified Data.ByteString.FastBuilder as Fast main :: IO () main = runInUnboundThread $ do let size sz m = bgroup sz [ bench "lazy/fast" $ nf (Fast.toLazyByteString . fastMap) m , bench "lazy/bstr" $ nf (Bstr.toLazyByteString . bstrMap) m ] map10 `seq` map100 `seq` map1000 `seq` map10000 `seq` defaultMain [ size "10" map10 , size "100" map100 , size "1000" map1000 , size "10000" map10000 ] type Map = IM.IntMap Int fastMap :: Map -> Fast.Builder fastMap = Fast.rebuild . IM.foldMapWithKey f where f key val = Fast.int32LE (fromIntegral key) <> Fast.int32LE (fromIntegral val) bstrMap :: Map -> Bstr.Builder bstrMap = IM.foldMapWithKey f where f key val = Bstr.int32LE (fromIntegral key) <> Bstr.int32LE (fromIntegral val) map10 :: Map map10 = makeItems 10 map100 :: Map map100 = makeItems 100 map1000 :: Map map1000 = makeItems 1000 map10000 :: Map map10000 = makeItems 10000 makeItems :: Int -> Map makeItems n = IM.fromList $ do i <- [0..n-1] return (i * 3, i)
null
https://raw.githubusercontent.com/takano-akio/fast-builder/d499ffb338300c1df5479e3d8918d986803a7243/benchmarks/map.hs
haskell
import Control.Concurrent import Criterion.Main import qualified Data.IntMap as IM import Data.Monoid import qualified Data.ByteString.Builder as Bstr import qualified Data.ByteString.FastBuilder as Fast main :: IO () main = runInUnboundThread $ do let size sz m = bgroup sz [ bench "lazy/fast" $ nf (Fast.toLazyByteString . fastMap) m , bench "lazy/bstr" $ nf (Bstr.toLazyByteString . bstrMap) m ] map10 `seq` map100 `seq` map1000 `seq` map10000 `seq` defaultMain [ size "10" map10 , size "100" map100 , size "1000" map1000 , size "10000" map10000 ] type Map = IM.IntMap Int fastMap :: Map -> Fast.Builder fastMap = Fast.rebuild . IM.foldMapWithKey f where f key val = Fast.int32LE (fromIntegral key) <> Fast.int32LE (fromIntegral val) bstrMap :: Map -> Bstr.Builder bstrMap = IM.foldMapWithKey f where f key val = Bstr.int32LE (fromIntegral key) <> Bstr.int32LE (fromIntegral val) map10 :: Map map10 = makeItems 10 map100 :: Map map100 = makeItems 100 map1000 :: Map map1000 = makeItems 1000 map10000 :: Map map10000 = makeItems 10000 makeItems :: Int -> Map makeItems n = IM.fromList $ do i <- [0..n-1] return (i * 3, i)
19750de3cc4b3d011baf9afd2815f72ee522fcd3840cf3e2c1e392fb86a49934
ahungry/pseudo
macros.lisp
;; Pseudo - A pseudo 3d multiplayer roguelike Copyright ( C ) 2013 ;; ;; 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 </>. MACRO Definitions (in-package #:pseudo) (defmacro class-to-json (name slots &body body) "Send a class data set to json" `(with-slots ,slots ,name (new-js ,@body))) (defmacro thing-to-json (fn-name name &rest varlist) "Create a function such as card-to-json to pull out a card from a place object passed in and serialize as json" `(defun ,fn-name (,name) (class-to-json ,name (,@varlist) ,@(nreverse (loop for var in varlist collect `((string-downcase (string ',var)) ,var)))))) (defmacro things-to-json (fn-name helper name place) `(defun ,fn-name () (loop for ,name in ,place collect (,helper ,name)))) (defmacro mad-adder (fn-name name place &rest varlist) "Create an (add-classname function for fast adding of new class instances to the main place object" `(defun ,fn-name (obj) (let ((,name (make-instance ',name))) (with-slots (,@varlist) ,name ,@(loop for var in varlist collect `(setf ,var (if obj (pop obj) 0))) (push ,name ,place))))) ;; Lifted from -with-defclass (defun build-var (classname var) "Helper function for defobject" (list var :initform nil :accessor (intern (concatenate 'string (string classname) "-" (string var))) :initarg (intern (string var) :keyword))) (defun build-varlist (classname varlist) "Helper function for defobject" (loop for var in varlist collect (build-var classname var))) (defmacro defobject (name &rest varlist) "Define a class with a set of behaviors, Variables are accessed by name-varname. (defobject classname v1 v2 v3)" `(defclass ,name () ,(build-varlist name varlist))) (defmacro json-response (emit-action emit-data broadcast-action broadcast-data) "Standard output format for the game's json responses, it sends out as emit and broadcast for local and global scope on the user's receiving end" `(to-json (new-js ("emit" (new-js ("event" ,emit-action) ("data" ,emit-data))) ("broadcast" (new-js ("event" ,broadcast-action) ("data" ,broadcast-data)))))) (defun no-json-response () (json-response "nil" "nil" "nil" "nil")) (defmacro game-dataset (name &rest fields) `(progn (defparameter ,(intern (concatenate 'string "*" (string name) "S*")) nil) (defobject ,name ,@fields) (mad-adder ,(intern (concatenate 'string "ADD-" (string name))) ,name ,(intern (concatenate 'string "*" (string name) "S*")) ,@fields) (thing-to-json ,(intern (concatenate 'string (string name) "-TO-JSON")) ,name ,@fields) (things-to-json ,(intern (concatenate 'string (string name) "S-TO-JSON")) ,(intern (concatenate 'string (string name) "-TO-JSON")) ,name ,(intern (concatenate 'string "*" (string name) "S*"))))) (defmacro pretty-json (json-object) `(cl-ppcre:regex-replace-all ",|}" (string ,json-object) (string #\Newline)))
null
https://raw.githubusercontent.com/ahungry/pseudo/a3e6329313e334941f211a991e5853bbe6d247f1/macros.lisp
lisp
Pseudo - A pseudo 3d multiplayer roguelike This program is free software: you can redistribute it and/or modify (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. along with this program. If not, see </>. Lifted from -with-defclass
Copyright ( C ) 2013 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 You should have received a copy of the GNU Affero General Public License MACRO Definitions (in-package #:pseudo) (defmacro class-to-json (name slots &body body) "Send a class data set to json" `(with-slots ,slots ,name (new-js ,@body))) (defmacro thing-to-json (fn-name name &rest varlist) "Create a function such as card-to-json to pull out a card from a place object passed in and serialize as json" `(defun ,fn-name (,name) (class-to-json ,name (,@varlist) ,@(nreverse (loop for var in varlist collect `((string-downcase (string ',var)) ,var)))))) (defmacro things-to-json (fn-name helper name place) `(defun ,fn-name () (loop for ,name in ,place collect (,helper ,name)))) (defmacro mad-adder (fn-name name place &rest varlist) "Create an (add-classname function for fast adding of new class instances to the main place object" `(defun ,fn-name (obj) (let ((,name (make-instance ',name))) (with-slots (,@varlist) ,name ,@(loop for var in varlist collect `(setf ,var (if obj (pop obj) 0))) (push ,name ,place))))) (defun build-var (classname var) "Helper function for defobject" (list var :initform nil :accessor (intern (concatenate 'string (string classname) "-" (string var))) :initarg (intern (string var) :keyword))) (defun build-varlist (classname varlist) "Helper function for defobject" (loop for var in varlist collect (build-var classname var))) (defmacro defobject (name &rest varlist) "Define a class with a set of behaviors, Variables are accessed by name-varname. (defobject classname v1 v2 v3)" `(defclass ,name () ,(build-varlist name varlist))) (defmacro json-response (emit-action emit-data broadcast-action broadcast-data) "Standard output format for the game's json responses, it sends out as emit and broadcast for local and global scope on the user's receiving end" `(to-json (new-js ("emit" (new-js ("event" ,emit-action) ("data" ,emit-data))) ("broadcast" (new-js ("event" ,broadcast-action) ("data" ,broadcast-data)))))) (defun no-json-response () (json-response "nil" "nil" "nil" "nil")) (defmacro game-dataset (name &rest fields) `(progn (defparameter ,(intern (concatenate 'string "*" (string name) "S*")) nil) (defobject ,name ,@fields) (mad-adder ,(intern (concatenate 'string "ADD-" (string name))) ,name ,(intern (concatenate 'string "*" (string name) "S*")) ,@fields) (thing-to-json ,(intern (concatenate 'string (string name) "-TO-JSON")) ,name ,@fields) (things-to-json ,(intern (concatenate 'string (string name) "S-TO-JSON")) ,(intern (concatenate 'string (string name) "-TO-JSON")) ,name ,(intern (concatenate 'string "*" (string name) "S*"))))) (defmacro pretty-json (json-object) `(cl-ppcre:regex-replace-all ",|}" (string ,json-object) (string #\Newline)))
b80292ae1312f954d3df30fe278dd83260430e9ae35cb8189066d699586a6d1f
melange-re/melange
lam_pass_count.ml
(************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (************************************) Adapted for Javascript backend : , (*A naive dead code elimination *) type used_info = { mutable times : int; mutable captured : bool; captured in functon or loop , inline in such cases should be careful 1 . can not inline mutable values 2 . avoid re - computation inline in such cases should be careful 1. can not inline mutable values 2. avoid re-computation *) } type occ_tbl = used_info Hash_ident.t First pass : count the occurrences of all let - bound identifiers type local_tbl = used_info Map_ident.t let dummy_info () = { times = 0; captured = false } (* y is untouched *) let absorb_info (x : used_info) (y : used_info) = match (x, y) with | { times = x0 }, { times = y0; captured } -> x.times <- x0 + y0; if captured then x.captured <- true let pp_info fmt (x : used_info) = Format.fprintf fmt "(<captured:%b>:%d)" x.captured x.times let pp_occ_tbl fmt tbl = Hash_ident.iter tbl (fun k v -> Format.fprintf fmt "@[%a@ %a@]@." Ident.print k pp_info v) (* The global table [occ] associates to each let-bound identifier the number of its uses (as a reference): - 0 if never used - 1 if used exactly once in and not under a lambda or within a loop - when under a lambda, - it's probably a closure - within a loop - update reference, niether is good for inlining - > 1 if used several times or under a lambda or within a loop. The local table [bv] associates to each locally-let-bound variable its reference count, as above. [bv] is enriched at let bindings but emptied when crossing lambdas and loops. *) let collect_occurs lam : occ_tbl = let occ : occ_tbl = Hash_ident.create 83 in (* Current use count of a variable. *) let used v = match Hash_ident.find_opt occ v with | None -> false | Some { times; _ } -> times > 0 in (* Entering a [let]. Returns updated [bv]. *) let bind_var bv ident = let r = dummy_info () in Hash_ident.add occ ident r; Map_ident.add bv ident r in (* Record a use of a variable *) let add_one_use bv ident = match Map_ident.find_opt bv ident with | Some r -> r.times <- r.times + 1 | None -> ( ident is not locally bound , therefore this is a use under a lambda or within a loop . Increase use count by 2 -- enough so that single - use optimizations will not apply . or within a loop. Increase use count by 2 -- enough so that single-use optimizations will not apply. *) match Hash_ident.find_opt occ ident with | Some r -> absorb_info r { times = 1; captured = true } | None -> (* Not a let-bound variable, ignore *) ()) in let inherit_use bv ident bid = let n = match Hash_ident.find_opt occ bid with | None -> dummy_info () | Some v -> v in match Map_ident.find_opt bv ident with | Some r -> absorb_info r n | None -> ( ident is not locally bound , therefore this is a use under a lambda or within a loop . Increase use count by 2 -- enough so that single - use optimizations will not apply . or within a loop. Increase use count by 2 -- enough so that single-use optimizations will not apply. *) match Hash_ident.find_opt occ ident with | Some r -> absorb_info r { n with captured = true } | None -> (* Not a let-bound variable, ignore *) ()) in let rec count (bv : local_tbl) (lam : Lam.t) = match lam with | Lfunction { body = l } -> count Map_ident.empty l (* when entering a function local [bv] is cleaned up, so that all closure variables will not be carried over, since the parameters are never rebound, so it is fine to kep it empty *) | Lfor (_, l1, l2, _dir, l3) -> count bv l1; count bv l2; count Map_ident.empty l3 | Lwhile (l1, l2) -> count Map_ident.empty l1; count Map_ident.empty l2 | Lvar v | Lmutvar v -> add_one_use bv v | Llet (_, v, Lvar w, l2) -> (* v will be replaced by w in l2, so each occurrence of v in l2 increases w's refcount *) count (bind_var bv v) l2; inherit_use bv w v | Llet (kind, v, l1, l2) -> count (bind_var bv v) l2; count [ l2 ] first , If v is unused , l1 will be removed , so do n't count its variables If v is unused, l1 will be removed, so don't count its variables *) if kind = Strict || used v then count bv l1 | Lmutlet (_, l1, l2) -> count bv l1; count bv l2 | Lassign (_, l) -> Lalias - bound variables are never assigned , so do n't increase this ident 's refcount this ident's refcount *) count bv l | Lglobal_module _ -> () | Lprim { args; _ } -> List.iter (count bv) args | Lletrec (bindings, body) -> List.iter (fun (_v, l) -> count bv l) bindings; count bv body (* Note there is a difference here when do beta reduction for *) | Lapply { ap_func = Lfunction { params; body }; ap_args = args; _ } when Ext_list.same_length params args -> count bv (Lam_beta_reduce.no_names_beta_reduce params body args) (* | Lapply{fn = Lfunction{function_kind = Tupled; params; body}; *) (* args = [Lprim {primitive = Pmakeblock _; args; _}]; _} *) when Ext_list.same_length params args - > (* count bv (Lam_beta_reduce.beta_reduce params body args) *) | Lapply { ap_func = l1; ap_args = ll; _ } -> count bv l1; List.iter (count bv) ll | Lconst _cst -> () | Lswitch (l, sw) -> count_default bv sw; count bv l; List.iter (fun (_, l) -> count bv l) sw.sw_consts; List.iter (fun (_, l) -> count bv l) sw.sw_blocks | Lstringswitch (l, sw, d) -> ( count bv l; List.iter (fun (_, l) -> count bv l) sw; match d with Some d -> count bv d | None -> ()) (* x2 for native backend *) (* begin match sw with *) (* | []|[_] -> count bv d *) (* | _ -> count bv d ; count bv d *) (* end *) | Lstaticraise (_i, ls) -> List.iter (count bv) ls | Lstaticcatch (l1, (_i, _), l2) -> count bv l1; count bv l2 | Ltrywith (l1, _v, l2) -> count bv l1; count bv l2 | Lifthenelse (l1, l2, l3) -> count bv l1; count bv l2; count bv l3 | Lsequence (l1, l2) -> count bv l1; count bv l2 | Lsend (_, m, o, ll, _) -> count bv m; count bv o; List.iter (count bv) ll and count_default bv sw = match sw.sw_failaction with | None -> () | Some al -> if (not sw.sw_consts_full) && not sw.sw_blocks_full then ( (* default action will occur twice in native code *) count bv al; count bv al) else ( (* default action will occur once *) assert ((not sw.sw_consts_full) || not sw.sw_blocks_full); count bv al) in count Map_ident.empty lam; occ
null
https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/core/lam_pass_count.ml
ocaml
********************************** OCaml ********************************** A naive dead code elimination y is untouched The global table [occ] associates to each let-bound identifier the number of its uses (as a reference): - 0 if never used - 1 if used exactly once in and not under a lambda or within a loop - when under a lambda, - it's probably a closure - within a loop - update reference, niether is good for inlining - > 1 if used several times or under a lambda or within a loop. The local table [bv] associates to each locally-let-bound variable its reference count, as above. [bv] is enriched at let bindings but emptied when crossing lambdas and loops. Current use count of a variable. Entering a [let]. Returns updated [bv]. Record a use of a variable Not a let-bound variable, ignore Not a let-bound variable, ignore when entering a function local [bv] is cleaned up, so that all closure variables will not be carried over, since the parameters are never rebound, so it is fine to kep it empty v will be replaced by w in l2, so each occurrence of v in l2 increases w's refcount Note there is a difference here when do beta reduction for | Lapply{fn = Lfunction{function_kind = Tupled; params; body}; args = [Lprim {primitive = Pmakeblock _; args; _}]; _} count bv (Lam_beta_reduce.beta_reduce params body args) x2 for native backend begin match sw with | []|[_] -> count bv d | _ -> count bv d ; count bv d end default action will occur twice in native code default action will occur once
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . Adapted for Javascript backend : , type used_info = { mutable times : int; mutable captured : bool; captured in functon or loop , inline in such cases should be careful 1 . can not inline mutable values 2 . avoid re - computation inline in such cases should be careful 1. can not inline mutable values 2. avoid re-computation *) } type occ_tbl = used_info Hash_ident.t First pass : count the occurrences of all let - bound identifiers type local_tbl = used_info Map_ident.t let dummy_info () = { times = 0; captured = false } let absorb_info (x : used_info) (y : used_info) = match (x, y) with | { times = x0 }, { times = y0; captured } -> x.times <- x0 + y0; if captured then x.captured <- true let pp_info fmt (x : used_info) = Format.fprintf fmt "(<captured:%b>:%d)" x.captured x.times let pp_occ_tbl fmt tbl = Hash_ident.iter tbl (fun k v -> Format.fprintf fmt "@[%a@ %a@]@." Ident.print k pp_info v) let collect_occurs lam : occ_tbl = let occ : occ_tbl = Hash_ident.create 83 in let used v = match Hash_ident.find_opt occ v with | None -> false | Some { times; _ } -> times > 0 in let bind_var bv ident = let r = dummy_info () in Hash_ident.add occ ident r; Map_ident.add bv ident r in let add_one_use bv ident = match Map_ident.find_opt bv ident with | Some r -> r.times <- r.times + 1 | None -> ( ident is not locally bound , therefore this is a use under a lambda or within a loop . Increase use count by 2 -- enough so that single - use optimizations will not apply . or within a loop. Increase use count by 2 -- enough so that single-use optimizations will not apply. *) match Hash_ident.find_opt occ ident with | Some r -> absorb_info r { times = 1; captured = true } | None -> ()) in let inherit_use bv ident bid = let n = match Hash_ident.find_opt occ bid with | None -> dummy_info () | Some v -> v in match Map_ident.find_opt bv ident with | Some r -> absorb_info r n | None -> ( ident is not locally bound , therefore this is a use under a lambda or within a loop . Increase use count by 2 -- enough so that single - use optimizations will not apply . or within a loop. Increase use count by 2 -- enough so that single-use optimizations will not apply. *) match Hash_ident.find_opt occ ident with | Some r -> absorb_info r { n with captured = true } | None -> ()) in let rec count (bv : local_tbl) (lam : Lam.t) = match lam with | Lfunction { body = l } -> count Map_ident.empty l | Lfor (_, l1, l2, _dir, l3) -> count bv l1; count bv l2; count Map_ident.empty l3 | Lwhile (l1, l2) -> count Map_ident.empty l1; count Map_ident.empty l2 | Lvar v | Lmutvar v -> add_one_use bv v | Llet (_, v, Lvar w, l2) -> count (bind_var bv v) l2; inherit_use bv w v | Llet (kind, v, l1, l2) -> count (bind_var bv v) l2; count [ l2 ] first , If v is unused , l1 will be removed , so do n't count its variables If v is unused, l1 will be removed, so don't count its variables *) if kind = Strict || used v then count bv l1 | Lmutlet (_, l1, l2) -> count bv l1; count bv l2 | Lassign (_, l) -> Lalias - bound variables are never assigned , so do n't increase this ident 's refcount this ident's refcount *) count bv l | Lglobal_module _ -> () | Lprim { args; _ } -> List.iter (count bv) args | Lletrec (bindings, body) -> List.iter (fun (_v, l) -> count bv l) bindings; count bv body | Lapply { ap_func = Lfunction { params; body }; ap_args = args; _ } when Ext_list.same_length params args -> count bv (Lam_beta_reduce.no_names_beta_reduce params body args) when Ext_list.same_length params args - > | Lapply { ap_func = l1; ap_args = ll; _ } -> count bv l1; List.iter (count bv) ll | Lconst _cst -> () | Lswitch (l, sw) -> count_default bv sw; count bv l; List.iter (fun (_, l) -> count bv l) sw.sw_consts; List.iter (fun (_, l) -> count bv l) sw.sw_blocks | Lstringswitch (l, sw, d) -> ( count bv l; List.iter (fun (_, l) -> count bv l) sw; match d with Some d -> count bv d | None -> ()) | Lstaticraise (_i, ls) -> List.iter (count bv) ls | Lstaticcatch (l1, (_i, _), l2) -> count bv l1; count bv l2 | Ltrywith (l1, _v, l2) -> count bv l1; count bv l2 | Lifthenelse (l1, l2, l3) -> count bv l1; count bv l2; count bv l3 | Lsequence (l1, l2) -> count bv l1; count bv l2 | Lsend (_, m, o, ll, _) -> count bv m; count bv o; List.iter (count bv) ll and count_default bv sw = match sw.sw_failaction with | None -> () | Some al -> if (not sw.sw_consts_full) && not sw.sw_blocks_full then ( count bv al; count bv al) else ( assert ((not sw.sw_consts_full) || not sw.sw_blocks_full); count bv al) in count Map_ident.empty lam; occ
e1c54815d6e8a81c116c66222d9031ce92eaa474b8c4b1c43d87ca757de0ff55
puppetlabs/puppetdb
server.clj
(ns puppetlabs.puppetdb.http.server "REST server Consolidates our disparate REST endpoints into a single Ring application." (:require [puppetlabs.puppetdb.http :as http] [puppetlabs.puppetdb.middleware :refer [wrap-with-globals wrap-with-metrics wrap-with-illegal-argument-catch wrap-with-exception-handling verify-accepts-json verify-content-type make-pdb-handler verify-sync-version]] [puppetlabs.comidi :as cmdi] [puppetlabs.puppetdb.http.handlers :as handlers] [puppetlabs.i18n.core :refer [tru]])) (defn- refuse-retired-api [version] (constantly (http/error-response (tru "The {0} API has been retired; please use v4" version) 404))) (defn retired-api-route [version] (cmdi/context (str "/" version) (cmdi/routes [true (refuse-retired-api version)]))) (def routes (cmdi/routes (retired-api-route "v1") (retired-api-route "v2") (retired-api-route "v3") (apply cmdi/context "/v4" (map (fn [[route-str handler]] (cmdi/context route-str (handler :v4))) {"" handlers/root-routes "/facts" handlers/facts-routes "/edges" handlers/edge-routes "/factsets" handlers/factset-routes "/inventory" handlers/inventory-routes "/package-inventory" handlers/package-inventory-routes "/packages" handlers/packages-routes "/fact-names" handlers/fact-names-routes "/fact-contents" handlers/fact-contents-routes "/fact-paths" handlers/fact-path-routes "/nodes" handlers/node-routes "/environments" handlers/environments-routes "/producers" handlers/producers-routes "/resources" handlers/resources-routes "/catalogs" handlers/catalog-routes "/catalog-input-contents" handlers/catalog-input-contents-routes "/catalog-inputs" handlers/catalog-inputs-routes "/events" handlers/events-routes "/event-counts" handlers/event-counts-routes "/aggregate-event-counts" handlers/agg-event-counts-routes "/reports" handlers/reports-routes})))) (defn build-app "Generates a Ring application that handles PuppetDB requests. If get-authorizer is nil or false, all requests will be accepted. Otherwise it must accept no arguments and return an authorize function that accepts a request. The request will be allowed only if authorize returns :authorized. Otherwise, the return value should be a message describing the reason that access was denied." [get-shared-globals] (fn [req] (let [handler (-> (make-pdb-handler routes identity) wrap-with-illegal-argument-catch verify-accepts-json (verify-content-type ["application/json"]) verify-sync-version (wrap-with-metrics (atom {}) http/leading-uris) (wrap-with-globals get-shared-globals) wrap-with-exception-handling)] (handler req))))
null
https://raw.githubusercontent.com/puppetlabs/puppetdb/b3d6d10555561657150fa70b6d1e609fba9c0eda/src/puppetlabs/puppetdb/http/server.clj
clojure
(ns puppetlabs.puppetdb.http.server "REST server Consolidates our disparate REST endpoints into a single Ring application." (:require [puppetlabs.puppetdb.http :as http] [puppetlabs.puppetdb.middleware :refer [wrap-with-globals wrap-with-metrics wrap-with-illegal-argument-catch wrap-with-exception-handling verify-accepts-json verify-content-type make-pdb-handler verify-sync-version]] [puppetlabs.comidi :as cmdi] [puppetlabs.puppetdb.http.handlers :as handlers] [puppetlabs.i18n.core :refer [tru]])) (defn- refuse-retired-api [version] (constantly (http/error-response (tru "The {0} API has been retired; please use v4" version) 404))) (defn retired-api-route [version] (cmdi/context (str "/" version) (cmdi/routes [true (refuse-retired-api version)]))) (def routes (cmdi/routes (retired-api-route "v1") (retired-api-route "v2") (retired-api-route "v3") (apply cmdi/context "/v4" (map (fn [[route-str handler]] (cmdi/context route-str (handler :v4))) {"" handlers/root-routes "/facts" handlers/facts-routes "/edges" handlers/edge-routes "/factsets" handlers/factset-routes "/inventory" handlers/inventory-routes "/package-inventory" handlers/package-inventory-routes "/packages" handlers/packages-routes "/fact-names" handlers/fact-names-routes "/fact-contents" handlers/fact-contents-routes "/fact-paths" handlers/fact-path-routes "/nodes" handlers/node-routes "/environments" handlers/environments-routes "/producers" handlers/producers-routes "/resources" handlers/resources-routes "/catalogs" handlers/catalog-routes "/catalog-input-contents" handlers/catalog-input-contents-routes "/catalog-inputs" handlers/catalog-inputs-routes "/events" handlers/events-routes "/event-counts" handlers/event-counts-routes "/aggregate-event-counts" handlers/agg-event-counts-routes "/reports" handlers/reports-routes})))) (defn build-app "Generates a Ring application that handles PuppetDB requests. If get-authorizer is nil or false, all requests will be accepted. Otherwise it must accept no arguments and return an authorize function that accepts a request. The request will be allowed only if authorize returns :authorized. Otherwise, the return value should be a message describing the reason that access was denied." [get-shared-globals] (fn [req] (let [handler (-> (make-pdb-handler routes identity) wrap-with-illegal-argument-catch verify-accepts-json (verify-content-type ["application/json"]) verify-sync-version (wrap-with-metrics (atom {}) http/leading-uris) (wrap-with-globals get-shared-globals) wrap-with-exception-handling)] (handler req))))
ce60ff5d43efd4184ee04329a36c0e166c7f5130a031575604e430d541894d26
syntax-objects/syntax-parse-example
3.rkt
#lang racket/base (provide try catch finally try-with try-with*) (require racket/match (for-syntax syntax/parse racket/base)) (begin-for-syntax (define ((invalid-expr name) stx) (raise-syntax-error name "invalid in expression context" stx))) (define-syntax catch (invalid-expr 'catch)) (define-syntax finally (invalid-expr 'finally)) (begin-for-syntax (define-syntax-class catch-clause #:description "catch clause" #:literals [catch] (pattern (catch binding:expr body:expr ...+))) (define-syntax-class finally-clause #:description "finally clause" #:literals [finally] (pattern (finally body:expr ...+))) (define-syntax-class body-expr #:literals [catch finally] (pattern (~and :expr (~not (~or (finally . _) (catch . _))))))) (define-syntax (try stx) (syntax-parse stx [(_ body:body-expr ...+) #'(let () body ...)] [(_ body:body-expr ...+ catch:catch-clause ... finally:finally-clause) #'(call-with-continuation-barrier (lambda () (dynamic-wind void (lambda () (try body ... catch ...)) (lambda () finally.body ...))))] [(_ body:body-expr ...+ catch:catch-clause ...) #'(with-handlers ([void (lambda (e) (match e [catch.binding catch.body ...] ... [_ (raise e)]))]) body ...)])) (define-syntax (try-with stx) (syntax-parse stx [(_ ([name:id val:expr] ...) body:body-expr ...+) #'(let ([cust (make-custodian)]) (try (define-values (name ...) (parameterize ([current-custodian cust]) (values val ...))) body ... (finally (custodian-shutdown-all cust))))])) (define-syntax (try-with* stx) (syntax-parse stx [(_ ([name:id val:expr] ...) body:body-expr ...+) #'(let ([cust (make-custodian)]) (try (define-values (name ...) (parameterize ([current-custodian cust]) (define name val) ... (values name ...))) body ... (finally (custodian-shutdown-all cust))))]))
null
https://raw.githubusercontent.com/syntax-objects/syntax-parse-example/0675ce0717369afcde284202ec7df661d7af35aa/try-catch-finally/3.rkt
racket
#lang racket/base (provide try catch finally try-with try-with*) (require racket/match (for-syntax syntax/parse racket/base)) (begin-for-syntax (define ((invalid-expr name) stx) (raise-syntax-error name "invalid in expression context" stx))) (define-syntax catch (invalid-expr 'catch)) (define-syntax finally (invalid-expr 'finally)) (begin-for-syntax (define-syntax-class catch-clause #:description "catch clause" #:literals [catch] (pattern (catch binding:expr body:expr ...+))) (define-syntax-class finally-clause #:description "finally clause" #:literals [finally] (pattern (finally body:expr ...+))) (define-syntax-class body-expr #:literals [catch finally] (pattern (~and :expr (~not (~or (finally . _) (catch . _))))))) (define-syntax (try stx) (syntax-parse stx [(_ body:body-expr ...+) #'(let () body ...)] [(_ body:body-expr ...+ catch:catch-clause ... finally:finally-clause) #'(call-with-continuation-barrier (lambda () (dynamic-wind void (lambda () (try body ... catch ...)) (lambda () finally.body ...))))] [(_ body:body-expr ...+ catch:catch-clause ...) #'(with-handlers ([void (lambda (e) (match e [catch.binding catch.body ...] ... [_ (raise e)]))]) body ...)])) (define-syntax (try-with stx) (syntax-parse stx [(_ ([name:id val:expr] ...) body:body-expr ...+) #'(let ([cust (make-custodian)]) (try (define-values (name ...) (parameterize ([current-custodian cust]) (values val ...))) body ... (finally (custodian-shutdown-all cust))))])) (define-syntax (try-with* stx) (syntax-parse stx [(_ ([name:id val:expr] ...) body:body-expr ...+) #'(let ([cust (make-custodian)]) (try (define-values (name ...) (parameterize ([current-custodian cust]) (define name val) ... (values name ...))) body ... (finally (custodian-shutdown-all cust))))]))
e20a92e6b05976f7f53c628b223a13d704958fa5fa4f8f77f28c7d5c7c6c02df
hasktorch/hasktorch
TensorFactories.hs
# LANGUAGE FlexibleContexts # module Torch.TensorFactories where import Foreign.ForeignPtr import System.IO.Unsafe import Torch.Dimname import Torch.Internal.Cast import Torch.Internal.Class (Castable (..)) import qualified Torch.Internal.Const as ATen import qualified Torch.Internal.Managed.Autograd as LibTorch import Torch.Internal.Managed.Cast import qualified Torch.Internal.Managed.Native as ATen import qualified Torch.Internal.Managed.TensorFactories as LibTorch import qualified Torch.Internal.Managed.Type.Tensor as ATen import qualified Torch.Internal.Managed.Type.TensorOptions as ATen import qualified Torch.Internal.Type as ATen import Torch.Scalar import Torch.Tensor import Torch.TensorOptions -- XXX: We use the torch:: constructors, not at:: constructures, because otherwise we can not use libtorch 's AD . type FactoryType = ForeignPtr ATen.IntArray -> ForeignPtr ATen.TensorOptions -> IO (ForeignPtr ATen.Tensor) type FactoryTypeWithDimnames = ForeignPtr ATen.IntArray -> ForeignPtr ATen.DimnameList -> ForeignPtr ATen.TensorOptions -> IO (ForeignPtr ATen.Tensor) mkFactory :: -- | aten_impl FactoryType -> -- | shape [Int] -> -- | opts TensorOptions -> -- | output IO Tensor mkFactory = cast2 mkFactoryUnsafe :: FactoryType -> [Int] -> TensorOptions -> Tensor mkFactoryUnsafe f shape opts = unsafePerformIO $ mkFactory f shape opts mkFactoryWithDimnames :: FactoryTypeWithDimnames -> [(Int, Dimname)] -> TensorOptions -> IO Tensor mkFactoryWithDimnames aten_impl shape = cast3 aten_impl (map fst shape) (map snd shape) mkFactoryUnsafeWithDimnames :: FactoryTypeWithDimnames -> [(Int, Dimname)] -> TensorOptions -> Tensor mkFactoryUnsafeWithDimnames f shape opts = unsafePerformIO $ mkFactoryWithDimnames f shape opts mkDefaultFactory :: ([Int] -> TensorOptions -> a) -> [Int] -> a mkDefaultFactory non_default shape = non_default shape defaultOpts mkDefaultFactoryWithDimnames :: ([(Int, Dimname)] -> TensorOptions -> a) -> [(Int, Dimname)] -> a mkDefaultFactoryWithDimnames non_default shape = non_default shape defaultOpts -------------------- Factories -------------------- | Returns a tensor filled with the scalar value 1 , with the shape defined by the variable argument size . ones :: -- | sequence of integers defining the shape of the output tensor. [Int] -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor ones = mkFactoryUnsafe LibTorch.ones_lo TODO - ones_like from Native.hs is redundant with this | Returns a tensor filled with the scalar value 1 , with the same size as input tensor onesLike :: -- | input Tensor -> -- | output Tensor onesLike self = unsafePerformIO $ cast1 ATen.ones_like_t self -- | Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. zeros :: -- | sequence of integers defining the shape of the output tensor. [Int] -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor zeros = mkFactoryUnsafe LibTorch.zeros_lo -- | Returns a tensor filled with the scalar value 0, with the same size as input tensor zerosLike :: -- | input Tensor -> -- | output Tensor zerosLike self = unsafePerformIO $ cast1 ATen.zeros_like_t self | Returns a tensor filled with random numbers from a uniform distribution on the interval [ 0,1 ) randIO :: -- | sequence of integers defining the shape of the output tensor. [Int] -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output IO Tensor randIO = mkFactory LibTorch.rand_lo -- | Returns a tensor filled with random numbers from a standard normal distribution. randnIO :: -- | sequence of integers defining the shape of the output tensor. [Int] -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output IO Tensor randnIO = mkFactory LibTorch.randn_lo -- | Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive). randintIO :: -- | lowest integer to be drawn from the distribution. Default: 0. Int -> -- | one above the highest integer to be drawn from the distribution. Int -> -- | the shape of the output tensor. [Int] -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output IO Tensor randintIO low high = mkFactory (LibTorch.randint_lllo (fromIntegral low) (fromIntegral high)) -- | Returns a tensor with the same size as input that is filled with random numbers from standard normal distribution. randnLikeIO :: -- | input Tensor -> -- | output IO Tensor randnLikeIO = cast1 ATen.randn_like_t | Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [ 0,1 ) . randLikeIO :: -- | input Tensor -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output IO Tensor randLikeIO = cast2 LibTorch.rand_like_to fullLike :: -- | input Tensor -> -- | _fill_value Float -> -- | opt TensorOptions -> -- | output IO Tensor fullLike = cast3 LibTorch.full_like_tso onesWithDimnames :: [(Int, Dimname)] -> TensorOptions -> Tensor onesWithDimnames = mkFactoryUnsafeWithDimnames LibTorch.ones_lNo zerosWithDimnames :: [(Int, Dimname)] -> TensorOptions -> Tensor zerosWithDimnames = mkFactoryUnsafeWithDimnames LibTorch.zeros_lNo randWithDimnames :: [(Int, Dimname)] -> TensorOptions -> IO Tensor randWithDimnames = mkFactoryWithDimnames LibTorch.rand_lNo randnWithDimnames :: [(Int, Dimname)] -> TensorOptions -> IO Tensor randnWithDimnames = mkFactoryWithDimnames LibTorch.randn_lNo | Returns a one - dimensional tensor of steps equally spaced points between start and end . linspace :: (Scalar a, Scalar b) => -- | @start@ a -> | @end@ b -> -- | @steps@ Int -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor linspace start end steps opts = unsafePerformIO $ cast4 LibTorch.linspace_sslo start end steps opts logspace :: (Scalar a, Scalar b) => a -> b -> Int -> Double -> TensorOptions -> Tensor logspace start end steps base opts = unsafePerformIO $ cast5 LibTorch.logspace_ssldo start end steps base opts -- -experimental/pull/57#discussion_r301062033 -- empty :: [Int] -> TensorOptions -> Tensor -- empty = mkFactoryUnsafe LibTorch.empty_lo eyeSquare :: -- | dim Int -> -- | opts TensorOptions -> -- | output Tensor eyeSquare dim = unsafePerformIO . cast2 LibTorch.eye_lo dim | Returns a 2 - D tensor with ones on the diagonal and zeros elsewhere . eye :: -- | the number of rows Int -> -- | the number of columns Int -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor eye nrows ncols opts = unsafePerformIO $ cast3 LibTorch.eye_llo nrows ncols opts -- | Returns a tensor of given size filled with fill_value. full :: Scalar a => -- | the shape of the output tensor. [Int] -> -- | the number to fill the output tensor with a -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor full shape value opts = unsafePerformIO $ cast3 LibTorch.full_lso shape value opts | Constructs a sparse tensors in COO(rdinate ) format with non - zero elements at the given indices with the given values . sparseCooTensor :: -- | The indices are the coordinates of the non-zero values in the matrix Tensor -> -- | Initial values for the tensor. Tensor -> -- | the shape of the output tensor. [Int] -> -- | TensorOptions -> -- | output Tensor sparseCooTensor indices values size opts = unsafePerformIO $ cast4 sparse_coo_tensor_ttlo indices values size opts where sparse_coo_tensor_ttlo indices' values' size' opts' = do i' <- LibTorch.dropVariable indices' v' <- LibTorch.dropVariable values' LibTorch.sparse_coo_tensor_ttlo i' v' size' opts' -------------------- Factories with default type -------------------- ones' :: [Int] -> Tensor ones' = mkDefaultFactory ones zeros' :: [Int] -> Tensor zeros' = mkDefaultFactory zeros randIO' :: [Int] -> IO Tensor randIO' = mkDefaultFactory randIO randnIO' :: [Int] -> IO Tensor randnIO' = mkDefaultFactory randnIO randintIO' :: Int -> Int -> [Int] -> IO Tensor randintIO' low high = mkDefaultFactory (randintIO low high) randLikeIO' :: Tensor -> IO Tensor randLikeIO' t = randLikeIO t defaultOpts bernoulliIO' :: -- | t Tensor -> -- | output IO Tensor bernoulliIO' = cast1 ATen.bernoulli_t bernoulliIO :: -- | t Tensor -> -- | p Double -> -- | output IO Tensor bernoulliIO = cast2 ATen.bernoulli_td poissonIO :: -- | t Tensor -> -- | output IO Tensor poissonIO = cast1 ATen.poisson_t multinomialIO' :: -- | t Tensor -> -- | num_samples Int -> -- | output IO Tensor multinomialIO' = cast2 ATen.multinomial_tl multinomialIO :: -- | t Tensor -> -- | num_samples Int -> -- | replacement Bool -> -- | output IO Tensor multinomialIO = cast3 ATen.multinomial_tlb normalIO' :: -- | _mean Tensor -> -- | output IO Tensor normalIO' = cast1 ATen.normal_t normalIO :: -- | _mean Tensor -> -- | _std Tensor -> -- | output IO Tensor normalIO = cast2 ATen.normal_tt normalScalarIO :: -- | _mean Tensor -> -- | _std Double -> -- | output IO Tensor normalScalarIO = cast2 ATen.normal_td normalScalarIO' :: -- | _mean Double -> -- | _std Tensor -> -- | output IO Tensor normalScalarIO' = cast2 ATen.normal_dt normalWithSizeIO :: -- | _mean Double -> -- | _std Double -> -- | _size Int -> -- | output IO Tensor normalWithSizeIO = cast3 ATen.normal_ddl rreluIO''' :: -- | t Tensor -> -- | output IO Tensor rreluIO''' = cast1 ATen.rrelu_t rreluIO'' :: Scalar a => -- | t Tensor -> -- | upper a -> -- | output IO Tensor rreluIO'' = cast2 ATen.rrelu_ts rreluIO' :: Scalar a => -- | t Tensor -> -- | lower a -> -- | upper a -> -- | output IO Tensor rreluIO' = cast3 ATen.rrelu_tss rreluIO :: Scalar a => -- | t Tensor -> -- | lower a -> -- | upper a -> -- | training Bool -> -- | output IO Tensor rreluIO = cast4 ATen.rrelu_tssb rreluWithNoiseIO''' :: -- | t Tensor -> -- | noise Tensor -> -- | output IO Tensor rreluWithNoiseIO''' = cast2 ATen.rrelu_with_noise_tt rreluWithNoiseIO'' :: Scalar a => -- | t Tensor -> -- | noise Tensor -> -- | upper a -> -- | output IO Tensor rreluWithNoiseIO'' = cast3 ATen.rrelu_with_noise_tts rreluWithNoiseIO' :: Scalar a => -- | t Tensor -> -- | noise Tensor -> -- | lower a -> -- | upper a -> -- | output IO Tensor rreluWithNoiseIO' = cast4 ATen.rrelu_with_noise_ttss rreluWithNoiseIO :: Scalar a => -- | t Tensor -> -- | noise Tensor -> -- | lower a -> -- | upper a -> -- | training Bool -> -- | output IO Tensor rreluWithNoiseIO = cast5 ATen.rrelu_with_noise_ttssb onesWithDimnames' :: [(Int, Dimname)] -> Tensor onesWithDimnames' = mkDefaultFactoryWithDimnames onesWithDimnames zerosWithDimnames' :: [(Int, Dimname)] -> Tensor zerosWithDimnames' = mkDefaultFactoryWithDimnames zerosWithDimnames randWithDimnames' :: [(Int, Dimname)] -> IO Tensor randWithDimnames' = mkDefaultFactoryWithDimnames randWithDimnames randnWithDimnames' :: [(Int, Dimname)] -> IO Tensor randnWithDimnames' = mkDefaultFactoryWithDimnames randnWithDimnames linspace' :: (Scalar a, Scalar b) => a -> b -> Int -> Tensor linspace' start end steps = linspace start end steps defaultOpts logspace' :: (Scalar a, Scalar b) => a -> b -> Int -> Double -> Tensor logspace' start end steps base = logspace start end steps base defaultOpts eyeSquare' :: Int -> Tensor eyeSquare' dim = eyeSquare dim defaultOpts eye' :: Int -> Int -> Tensor eye' nrows ncols = eye nrows ncols defaultOpts full' :: Scalar a => [Int] -> a -> Tensor full' shape value = full shape value defaultOpts sparseCooTensor' :: Tensor -> Tensor -> [Int] -> Tensor sparseCooTensor' indices values size = sparseCooTensor indices values size defaultOpts | Returns a 1 - D tensor with values from the interval [ start , end ) taken with common difference step beginning from start . arange :: -- | start Int -> | end Int -> -- | step Int -> -- | configures the data type, device, layout and other properties of the resulting tensor. TensorOptions -> -- | output Tensor arange s e ss o = unsafePerformIO $ (cast4 ATen.arange_ssso) s e ss o | Returns a 1 - D tensor with values from the interval [ start , end ) taken with common difference step beginning from start . arange' :: -- | start Int -> | end Int -> -- | step Int -> -- | output Tensor arange' s e ss = arange s e ss defaultOpts
null
https://raw.githubusercontent.com/hasktorch/hasktorch/4e846fdcd89df5c7c6991cb9d6142007a6bb0a58/hasktorch/src/Torch/TensorFactories.hs
haskell
XXX: We use the torch:: constructors, not at:: constructures, because | aten_impl | shape | opts | output ------------------ Factories -------------------- | sequence of integers defining the shape of the output tensor. | configures the data type, device, layout and other properties of the resulting tensor. | output | input | output | Returns a tensor filled with the scalar value 0, with the shape defined by the variable argument size. | sequence of integers defining the shape of the output tensor. | configures the data type, device, layout and other properties of the resulting tensor. | output | Returns a tensor filled with the scalar value 0, with the same size as input tensor | input | output | sequence of integers defining the shape of the output tensor. | configures the data type, device, layout and other properties of the resulting tensor. | output | Returns a tensor filled with random numbers from a standard normal distribution. | sequence of integers defining the shape of the output tensor. | configures the data type, device, layout and other properties of the resulting tensor. | output | Returns a tensor filled with random integers generated uniformly between low (inclusive) and high (exclusive). | lowest integer to be drawn from the distribution. Default: 0. | one above the highest integer to be drawn from the distribution. | the shape of the output tensor. | configures the data type, device, layout and other properties of the resulting tensor. | output | Returns a tensor with the same size as input that is filled with random numbers from standard normal distribution. | input | output | input | configures the data type, device, layout and other properties of the resulting tensor. | output | input | _fill_value | opt | output | @start@ | @steps@ | configures the data type, device, layout and other properties of the resulting tensor. | output -experimental/pull/57#discussion_r301062033 empty :: [Int] -> TensorOptions -> Tensor empty = mkFactoryUnsafe LibTorch.empty_lo | dim | opts | output | the number of rows | the number of columns | configures the data type, device, layout and other properties of the resulting tensor. | output | Returns a tensor of given size filled with fill_value. | the shape of the output tensor. | the number to fill the output tensor with | configures the data type, device, layout and other properties of the resulting tensor. | output | The indices are the coordinates of the non-zero values in the matrix | Initial values for the tensor. | the shape of the output tensor. | | output ------------------ Factories with default type -------------------- | t | output | t | p | output | t | output | t | num_samples | output | t | num_samples | replacement | output | _mean | output | _mean | _std | output | _mean | _std | output | _mean | _std | output | _mean | _std | _size | output | t | output | t | upper | output | t | lower | upper | output | t | lower | upper | training | output | t | noise | output | t | noise | upper | output | t | noise | lower | upper | output | t | noise | lower | upper | training | output | start | step | configures the data type, device, layout and other properties of the resulting tensor. | output | start | step | output
# LANGUAGE FlexibleContexts # module Torch.TensorFactories where import Foreign.ForeignPtr import System.IO.Unsafe import Torch.Dimname import Torch.Internal.Cast import Torch.Internal.Class (Castable (..)) import qualified Torch.Internal.Const as ATen import qualified Torch.Internal.Managed.Autograd as LibTorch import Torch.Internal.Managed.Cast import qualified Torch.Internal.Managed.Native as ATen import qualified Torch.Internal.Managed.TensorFactories as LibTorch import qualified Torch.Internal.Managed.Type.Tensor as ATen import qualified Torch.Internal.Managed.Type.TensorOptions as ATen import qualified Torch.Internal.Type as ATen import Torch.Scalar import Torch.Tensor import Torch.TensorOptions otherwise we can not use libtorch 's AD . type FactoryType = ForeignPtr ATen.IntArray -> ForeignPtr ATen.TensorOptions -> IO (ForeignPtr ATen.Tensor) type FactoryTypeWithDimnames = ForeignPtr ATen.IntArray -> ForeignPtr ATen.DimnameList -> ForeignPtr ATen.TensorOptions -> IO (ForeignPtr ATen.Tensor) mkFactory :: FactoryType -> [Int] -> TensorOptions -> IO Tensor mkFactory = cast2 mkFactoryUnsafe :: FactoryType -> [Int] -> TensorOptions -> Tensor mkFactoryUnsafe f shape opts = unsafePerformIO $ mkFactory f shape opts mkFactoryWithDimnames :: FactoryTypeWithDimnames -> [(Int, Dimname)] -> TensorOptions -> IO Tensor mkFactoryWithDimnames aten_impl shape = cast3 aten_impl (map fst shape) (map snd shape) mkFactoryUnsafeWithDimnames :: FactoryTypeWithDimnames -> [(Int, Dimname)] -> TensorOptions -> Tensor mkFactoryUnsafeWithDimnames f shape opts = unsafePerformIO $ mkFactoryWithDimnames f shape opts mkDefaultFactory :: ([Int] -> TensorOptions -> a) -> [Int] -> a mkDefaultFactory non_default shape = non_default shape defaultOpts mkDefaultFactoryWithDimnames :: ([(Int, Dimname)] -> TensorOptions -> a) -> [(Int, Dimname)] -> a mkDefaultFactoryWithDimnames non_default shape = non_default shape defaultOpts | Returns a tensor filled with the scalar value 1 , with the shape defined by the variable argument size . ones :: [Int] -> TensorOptions -> Tensor ones = mkFactoryUnsafe LibTorch.ones_lo TODO - ones_like from Native.hs is redundant with this | Returns a tensor filled with the scalar value 1 , with the same size as input tensor onesLike :: Tensor -> Tensor onesLike self = unsafePerformIO $ cast1 ATen.ones_like_t self zeros :: [Int] -> TensorOptions -> Tensor zeros = mkFactoryUnsafe LibTorch.zeros_lo zerosLike :: Tensor -> Tensor zerosLike self = unsafePerformIO $ cast1 ATen.zeros_like_t self | Returns a tensor filled with random numbers from a uniform distribution on the interval [ 0,1 ) randIO :: [Int] -> TensorOptions -> IO Tensor randIO = mkFactory LibTorch.rand_lo randnIO :: [Int] -> TensorOptions -> IO Tensor randnIO = mkFactory LibTorch.randn_lo randintIO :: Int -> Int -> [Int] -> TensorOptions -> IO Tensor randintIO low high = mkFactory (LibTorch.randint_lllo (fromIntegral low) (fromIntegral high)) randnLikeIO :: Tensor -> IO Tensor randnLikeIO = cast1 ATen.randn_like_t | Returns a tensor with the same size as input that is filled with random numbers from a uniform distribution on the interval [ 0,1 ) . randLikeIO :: Tensor -> TensorOptions -> IO Tensor randLikeIO = cast2 LibTorch.rand_like_to fullLike :: Tensor -> Float -> TensorOptions -> IO Tensor fullLike = cast3 LibTorch.full_like_tso onesWithDimnames :: [(Int, Dimname)] -> TensorOptions -> Tensor onesWithDimnames = mkFactoryUnsafeWithDimnames LibTorch.ones_lNo zerosWithDimnames :: [(Int, Dimname)] -> TensorOptions -> Tensor zerosWithDimnames = mkFactoryUnsafeWithDimnames LibTorch.zeros_lNo randWithDimnames :: [(Int, Dimname)] -> TensorOptions -> IO Tensor randWithDimnames = mkFactoryWithDimnames LibTorch.rand_lNo randnWithDimnames :: [(Int, Dimname)] -> TensorOptions -> IO Tensor randnWithDimnames = mkFactoryWithDimnames LibTorch.randn_lNo | Returns a one - dimensional tensor of steps equally spaced points between start and end . linspace :: (Scalar a, Scalar b) => a -> | @end@ b -> Int -> TensorOptions -> Tensor linspace start end steps opts = unsafePerformIO $ cast4 LibTorch.linspace_sslo start end steps opts logspace :: (Scalar a, Scalar b) => a -> b -> Int -> Double -> TensorOptions -> Tensor logspace start end steps base opts = unsafePerformIO $ cast5 LibTorch.logspace_ssldo start end steps base opts eyeSquare :: Int -> TensorOptions -> Tensor eyeSquare dim = unsafePerformIO . cast2 LibTorch.eye_lo dim | Returns a 2 - D tensor with ones on the diagonal and zeros elsewhere . eye :: Int -> Int -> TensorOptions -> Tensor eye nrows ncols opts = unsafePerformIO $ cast3 LibTorch.eye_llo nrows ncols opts full :: Scalar a => [Int] -> a -> TensorOptions -> Tensor full shape value opts = unsafePerformIO $ cast3 LibTorch.full_lso shape value opts | Constructs a sparse tensors in COO(rdinate ) format with non - zero elements at the given indices with the given values . sparseCooTensor :: Tensor -> Tensor -> [Int] -> TensorOptions -> Tensor sparseCooTensor indices values size opts = unsafePerformIO $ cast4 sparse_coo_tensor_ttlo indices values size opts where sparse_coo_tensor_ttlo indices' values' size' opts' = do i' <- LibTorch.dropVariable indices' v' <- LibTorch.dropVariable values' LibTorch.sparse_coo_tensor_ttlo i' v' size' opts' ones' :: [Int] -> Tensor ones' = mkDefaultFactory ones zeros' :: [Int] -> Tensor zeros' = mkDefaultFactory zeros randIO' :: [Int] -> IO Tensor randIO' = mkDefaultFactory randIO randnIO' :: [Int] -> IO Tensor randnIO' = mkDefaultFactory randnIO randintIO' :: Int -> Int -> [Int] -> IO Tensor randintIO' low high = mkDefaultFactory (randintIO low high) randLikeIO' :: Tensor -> IO Tensor randLikeIO' t = randLikeIO t defaultOpts bernoulliIO' :: Tensor -> IO Tensor bernoulliIO' = cast1 ATen.bernoulli_t bernoulliIO :: Tensor -> Double -> IO Tensor bernoulliIO = cast2 ATen.bernoulli_td poissonIO :: Tensor -> IO Tensor poissonIO = cast1 ATen.poisson_t multinomialIO' :: Tensor -> Int -> IO Tensor multinomialIO' = cast2 ATen.multinomial_tl multinomialIO :: Tensor -> Int -> Bool -> IO Tensor multinomialIO = cast3 ATen.multinomial_tlb normalIO' :: Tensor -> IO Tensor normalIO' = cast1 ATen.normal_t normalIO :: Tensor -> Tensor -> IO Tensor normalIO = cast2 ATen.normal_tt normalScalarIO :: Tensor -> Double -> IO Tensor normalScalarIO = cast2 ATen.normal_td normalScalarIO' :: Double -> Tensor -> IO Tensor normalScalarIO' = cast2 ATen.normal_dt normalWithSizeIO :: Double -> Double -> Int -> IO Tensor normalWithSizeIO = cast3 ATen.normal_ddl rreluIO''' :: Tensor -> IO Tensor rreluIO''' = cast1 ATen.rrelu_t rreluIO'' :: Scalar a => Tensor -> a -> IO Tensor rreluIO'' = cast2 ATen.rrelu_ts rreluIO' :: Scalar a => Tensor -> a -> a -> IO Tensor rreluIO' = cast3 ATen.rrelu_tss rreluIO :: Scalar a => Tensor -> a -> a -> Bool -> IO Tensor rreluIO = cast4 ATen.rrelu_tssb rreluWithNoiseIO''' :: Tensor -> Tensor -> IO Tensor rreluWithNoiseIO''' = cast2 ATen.rrelu_with_noise_tt rreluWithNoiseIO'' :: Scalar a => Tensor -> Tensor -> a -> IO Tensor rreluWithNoiseIO'' = cast3 ATen.rrelu_with_noise_tts rreluWithNoiseIO' :: Scalar a => Tensor -> Tensor -> a -> a -> IO Tensor rreluWithNoiseIO' = cast4 ATen.rrelu_with_noise_ttss rreluWithNoiseIO :: Scalar a => Tensor -> Tensor -> a -> a -> Bool -> IO Tensor rreluWithNoiseIO = cast5 ATen.rrelu_with_noise_ttssb onesWithDimnames' :: [(Int, Dimname)] -> Tensor onesWithDimnames' = mkDefaultFactoryWithDimnames onesWithDimnames zerosWithDimnames' :: [(Int, Dimname)] -> Tensor zerosWithDimnames' = mkDefaultFactoryWithDimnames zerosWithDimnames randWithDimnames' :: [(Int, Dimname)] -> IO Tensor randWithDimnames' = mkDefaultFactoryWithDimnames randWithDimnames randnWithDimnames' :: [(Int, Dimname)] -> IO Tensor randnWithDimnames' = mkDefaultFactoryWithDimnames randnWithDimnames linspace' :: (Scalar a, Scalar b) => a -> b -> Int -> Tensor linspace' start end steps = linspace start end steps defaultOpts logspace' :: (Scalar a, Scalar b) => a -> b -> Int -> Double -> Tensor logspace' start end steps base = logspace start end steps base defaultOpts eyeSquare' :: Int -> Tensor eyeSquare' dim = eyeSquare dim defaultOpts eye' :: Int -> Int -> Tensor eye' nrows ncols = eye nrows ncols defaultOpts full' :: Scalar a => [Int] -> a -> Tensor full' shape value = full shape value defaultOpts sparseCooTensor' :: Tensor -> Tensor -> [Int] -> Tensor sparseCooTensor' indices values size = sparseCooTensor indices values size defaultOpts | Returns a 1 - D tensor with values from the interval [ start , end ) taken with common difference step beginning from start . arange :: Int -> | end Int -> Int -> TensorOptions -> Tensor arange s e ss o = unsafePerformIO $ (cast4 ATen.arange_ssso) s e ss o | Returns a 1 - D tensor with values from the interval [ start , end ) taken with common difference step beginning from start . arange' :: Int -> | end Int -> Int -> Tensor arange' s e ss = arange s e ss defaultOpts
b0c2a239eb9db5b8d71141eedcd8d96e933756f7ed0490179f03ff3a1ba7b7bc
lisp/de.setf.resource
vocabulary.lisp
-*- Mode : lisp ; Syntax : ansi - common - lisp ; Base : 10 ; Package : common - lisp - user ; -*- 20100513T131615Z00 ;;; from #<doc-node -schema/rdfs-namespace.xml #x26BA2DE6> (in-package :common-lisp-user) (defpackage "-schema#" (:use ) (:nicknames "rdfs") (:export "Class" "comment" "Container" "ContainerMembershipProperty" "Datatype" "domain" "isDefinedBy" "label" "Literal" "member" "range" "Resource" "seeAlso" "subClassOf" "subPropertyOf")) (in-package "-schema#") (rdfs:defvocabulary "rdf" :uri "-schema#" :package "-schema#" :definitions ( (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Alt| (|Container|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Bag| (|Container|) ()) (de.setf.resource.schema:defclass |Class| (|Resource|) ((|subClassOf| :type |Class|))) (de.setf.resource.schema:defclass |Container| (|Resource|) ()) (de.setf.resource.schema:defclass |ContainerMembershipProperty| (|-rdf-syntax-ns#|:|Property|) ()) (de.setf.resource.schema:defclass |Datatype| (|Class|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|List| (|Resource|) ((|-rdf-syntax-ns#|:|first| :type |Resource|) (|-rdf-syntax-ns#|:|rest| :type |-rdf-syntax-ns#|:|List|))) (de.setf.resource.schema:defclass |Literal| (|Resource|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Property| (|Resource|) ((|subPropertyOf| :type |-rdf-syntax-ns#|:|Property|) (|domain| :type |Class|) (|range| :type |Class|))) (de.setf.resource.schema:defclass |Resource| () ((|-rdf-syntax-ns#|:|type| :type |Class|) (|comment| :type |Literal|) (|label| :type |Literal|) (|seeAlso| :type |Resource|) (|isDefinedBy| :type |Resource|) (|member| :type |Resource|) (|-rdf-syntax-ns#|:|value| :type |Resource|))) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Seq| (|Container|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Statement| (|Resource|) ((|-rdf-syntax-ns#|:|subject| :type |Resource|) (|-rdf-syntax-ns#|:|predicate| :type |Resource|) (|-rdf-syntax-ns#|:|object| :type |Resource|)))))
null
https://raw.githubusercontent.com/lisp/de.setf.resource/27bf6dfb3b3ca99cfd5a6feaa5839d99bfb4d29e/namespaces/www-w3-org/2000/01/rdf-schema/vocabulary.lisp
lisp
Syntax : ansi - common - lisp ; Base : 10 ; Package : common - lisp - user ; -*- from #<doc-node -schema/rdfs-namespace.xml #x26BA2DE6>
20100513T131615Z00 (in-package :common-lisp-user) (defpackage "-schema#" (:use ) (:nicknames "rdfs") (:export "Class" "comment" "Container" "ContainerMembershipProperty" "Datatype" "domain" "isDefinedBy" "label" "Literal" "member" "range" "Resource" "seeAlso" "subClassOf" "subPropertyOf")) (in-package "-schema#") (rdfs:defvocabulary "rdf" :uri "-schema#" :package "-schema#" :definitions ( (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Alt| (|Container|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Bag| (|Container|) ()) (de.setf.resource.schema:defclass |Class| (|Resource|) ((|subClassOf| :type |Class|))) (de.setf.resource.schema:defclass |Container| (|Resource|) ()) (de.setf.resource.schema:defclass |ContainerMembershipProperty| (|-rdf-syntax-ns#|:|Property|) ()) (de.setf.resource.schema:defclass |Datatype| (|Class|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|List| (|Resource|) ((|-rdf-syntax-ns#|:|first| :type |Resource|) (|-rdf-syntax-ns#|:|rest| :type |-rdf-syntax-ns#|:|List|))) (de.setf.resource.schema:defclass |Literal| (|Resource|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Property| (|Resource|) ((|subPropertyOf| :type |-rdf-syntax-ns#|:|Property|) (|domain| :type |Class|) (|range| :type |Class|))) (de.setf.resource.schema:defclass |Resource| () ((|-rdf-syntax-ns#|:|type| :type |Class|) (|comment| :type |Literal|) (|label| :type |Literal|) (|seeAlso| :type |Resource|) (|isDefinedBy| :type |Resource|) (|member| :type |Resource|) (|-rdf-syntax-ns#|:|value| :type |Resource|))) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Seq| (|Container|) ()) (de.setf.resource.schema:defclass |-rdf-syntax-ns#|:|Statement| (|Resource|) ((|-rdf-syntax-ns#|:|subject| :type |Resource|) (|-rdf-syntax-ns#|:|predicate| :type |Resource|) (|-rdf-syntax-ns#|:|object| :type |Resource|)))))
dc5800789956e3279d4ca7e315c379389bafc6c616489297622727a75857de64
SamB/coq
typeclasses.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (*i $Id$ i*) (*i*) open Names open Libnames open Decl_kinds open Term open Sign open Evd open Environ open Nametab open Mod_subst open Topconstr open Util (*i*) (* This module defines type-classes *) type typeclass = { The class implementation : a record parameterized by the context with in it or a definition if the class is a singleton . This acts as the classe 's global identifier . the class is a singleton. This acts as the classe's global identifier. *) cl_impl : global_reference; Context in which the definitions are typed . Includes both typeclass parameters and superclasses . The boolean indicates if the argument is a direct superclass . The boolean indicates if the typeclass argument is a direct superclass. *) cl_context : ((global_reference * bool) option * rel_declaration) list; cl_params : int; (* This is the length of the suffix of the context which should be considered explicit parameters. *) Context of definitions and properties on defs , will not be shared cl_props : rel_context; (* The methods implementations of the typeclass as projections. *) cl_projs : (identifier * constant) list; } type instance val instances : global_reference -> instance list val typeclasses : unit -> typeclass list val add_class : typeclass -> unit val new_instance : typeclass -> int option -> bool -> constant -> instance val add_instance : instance -> unit raises a UserError if not a class val class_of_constr : constr -> typeclass option raises a UserError if not a class val instance_impl : instance -> constant val is_class : global_reference -> bool val is_instance : global_reference -> bool val is_method : constant -> bool val is_implicit_arg : hole_kind -> bool (* Returns the term and type for the given instance of the parameters and fields of the type class. *) val instance_constructor : typeclass -> constr list -> constr * types (* Use evar_extra for marking resolvable evars. *) val bool_in : bool -> Dyn.t val bool_out : Dyn.t -> bool val is_resolvable : evar_info -> bool val mark_unresolvable : evar_info -> evar_info val mark_unresolvables : evar_map -> evar_map val resolve_typeclasses : ?onlyargs:bool -> ?split:bool -> ?fail:bool -> env -> evar_defs -> evar_defs val register_add_instance_hint : (constant -> int option -> unit) -> unit val add_instance_hint : constant -> int option -> unit val solve_instanciations_problem : (env -> evar_defs -> bool -> bool -> bool -> evar_defs) ref
null
https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/pretyping/typeclasses.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** i $Id$ i i i This module defines type-classes This is the length of the suffix of the context which should be considered explicit parameters. The methods implementations of the typeclass as projections. Returns the term and type for the given instance of the parameters and fields of the type class. Use evar_extra for marking resolvable evars.
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * open Names open Libnames open Decl_kinds open Term open Sign open Evd open Environ open Nametab open Mod_subst open Topconstr open Util type typeclass = { The class implementation : a record parameterized by the context with in it or a definition if the class is a singleton . This acts as the classe 's global identifier . the class is a singleton. This acts as the classe's global identifier. *) cl_impl : global_reference; Context in which the definitions are typed . Includes both typeclass parameters and superclasses . The boolean indicates if the argument is a direct superclass . The boolean indicates if the typeclass argument is a direct superclass. *) cl_context : ((global_reference * bool) option * rel_declaration) list; Context of definitions and properties on defs , will not be shared cl_props : rel_context; cl_projs : (identifier * constant) list; } type instance val instances : global_reference -> instance list val typeclasses : unit -> typeclass list val add_class : typeclass -> unit val new_instance : typeclass -> int option -> bool -> constant -> instance val add_instance : instance -> unit raises a UserError if not a class val class_of_constr : constr -> typeclass option raises a UserError if not a class val instance_impl : instance -> constant val is_class : global_reference -> bool val is_instance : global_reference -> bool val is_method : constant -> bool val is_implicit_arg : hole_kind -> bool val instance_constructor : typeclass -> constr list -> constr * types val bool_in : bool -> Dyn.t val bool_out : Dyn.t -> bool val is_resolvable : evar_info -> bool val mark_unresolvable : evar_info -> evar_info val mark_unresolvables : evar_map -> evar_map val resolve_typeclasses : ?onlyargs:bool -> ?split:bool -> ?fail:bool -> env -> evar_defs -> evar_defs val register_add_instance_hint : (constant -> int option -> unit) -> unit val add_instance_hint : constant -> int option -> unit val solve_instanciations_problem : (env -> evar_defs -> bool -> bool -> bool -> evar_defs) ref
22d876604b8db23ff4f4a2f692fe233ec7cf1655390f4ec12ca688f89dc9f59e
PrincetonUniversity/lucid
Cid.ml
(* Compound Identifiers *) type id = Id.t type t = | Id of id | Compound of id * t We represent " Array.create " as Compound("Array " , I d " create " ) ) (* Constructors *) let rec create ss = match ss with I d ( Id.create " " ) | [s] -> Id (Id.create s) | s :: ss -> Compound (Id.create s, create ss) ;; let rec create_ids ids = match ids with | [] -> failwith "Cannot create an empty cid!" I d ( Id.create " " ) | [id] -> Id id | id :: ids -> Compound (id, create_ids ids) ;; let create_ids_rev ids = create_ids (List.rev ids) let rec fresh ss = match ss with | [] -> Id (Id.fresh "") | [s] -> Id (Id.fresh s) | s :: ss -> Compound (Id.create s, fresh ss) ;; let rec freshen_last cid = match cid with | Id id -> Id (Id.freshen id) | Compound (id, cid) -> Compound (id, freshen_last cid) ;; let str_cons str cid : t = match cid with | Id id -> Compound (Id.fresh str, Id id) | Compound (id, cid) -> Compound (Id.fresh str, Compound (id, cid)) ;; let id id = Id id let compound id cid = Compound (id, cid) let rec concat cid1 cid2 = match cid1 with | Id id -> compound id cid2 | Compound (id, cid1) -> compound id (concat cid1 cid2) ;; let from_string str = BatString.split_on_char '.' str |> create (* Destructors *) let rec to_string cid = match cid with | Id id -> Id.to_string id | Compound (id, cid) -> Id.to_string id ^ "." ^ to_string cid ;; let rec to_string_delim d cid = match cid with | Id id -> Id.to_string_delim d id | Compound (id, cid) -> Id.to_string_delim d id ^ "." ^ to_string_delim d cid ;; let to_id d = match d with | Id evid -> evid | _ -> failwith "attempted to convert cid with multiple parts into id" ;; let rec to_ids d = match d with | Id id -> [id] | Compound (id, cid) -> id :: to_ids cid ;; let rec to_ids_prefix d = match d with | Id id -> id, [] | Compound (id, cid) -> let base, rest = to_ids_prefix cid in base, id :: rest ;; let rec first_id d = match d with | Id id -> id | Compound (id, _) -> id ;; let rec last_id d = match d with | Id id -> id | Compound (_, cid) -> last_id cid ;; let rec names cid = match cid with | Id id -> [Id.name id] | Compound (id, cid) -> Id.name id :: names cid ;; Operations let rec compare cid1 cid2 = match cid1, cid2 with | Id i1, Id i2 -> Id.compare i1 i2 | Compound (id1, cid1), Compound (id2, cid2) -> let i = Id.compare id1 id2 in if i = 0 then compare cid1 cid2 else i | Id _, Compound _ -> -1 | Compound _, Id _ -> 1 ;; let equal cid1 cid2 = compare cid1 cid2 = 0 let equals = equal let rec equal_names cid1 cid2 = match cid1, cid2 with | Id i1, Id i2 -> Id.equal_names i1 i2 | Compound (id1, cid1), Compound (id2, cid2) -> Id.equal_names id1 id2 && equal_names cid1 cid2 | _ -> false ;; let lookup_opt tuples key = Core.List.Assoc.find ~equal:equals tuples key let lookup tuples key = match lookup_opt tuples key with | Some v -> v | None -> let err_str = "error looking up " ^ to_string key in failwith err_str ;; let exists tuples key = match lookup_opt tuples key with | Some _ -> true | None -> false ;; let rec replace tuples key new_val = match tuples with | [] -> [] | (k, v) :: tuples -> if equals k key then (k, new_val) :: tuples else (k, v) :: replace tuples key new_val ;; let rec remove tuples key = match tuples with | [] -> [] | (k, v) :: tl -> if equals k key then remove tl key else (k, v) :: remove tl key ;; let rec modify_tail f t = match t with | Id id -> Id (f id) | Compound (id, cid) -> Compound (id, modify_tail f cid) ;;
null
https://raw.githubusercontent.com/PrincetonUniversity/lucid/3a8f1638858b180e009a914735e474b7cf01845f/src/lib/frontend/datastructures/Cid.ml
ocaml
Compound Identifiers Constructors Destructors
type id = Id.t type t = | Id of id | Compound of id * t We represent " Array.create " as Compound("Array " , I d " create " ) ) let rec create ss = match ss with I d ( Id.create " " ) | [s] -> Id (Id.create s) | s :: ss -> Compound (Id.create s, create ss) ;; let rec create_ids ids = match ids with | [] -> failwith "Cannot create an empty cid!" I d ( Id.create " " ) | [id] -> Id id | id :: ids -> Compound (id, create_ids ids) ;; let create_ids_rev ids = create_ids (List.rev ids) let rec fresh ss = match ss with | [] -> Id (Id.fresh "") | [s] -> Id (Id.fresh s) | s :: ss -> Compound (Id.create s, fresh ss) ;; let rec freshen_last cid = match cid with | Id id -> Id (Id.freshen id) | Compound (id, cid) -> Compound (id, freshen_last cid) ;; let str_cons str cid : t = match cid with | Id id -> Compound (Id.fresh str, Id id) | Compound (id, cid) -> Compound (Id.fresh str, Compound (id, cid)) ;; let id id = Id id let compound id cid = Compound (id, cid) let rec concat cid1 cid2 = match cid1 with | Id id -> compound id cid2 | Compound (id, cid1) -> compound id (concat cid1 cid2) ;; let from_string str = BatString.split_on_char '.' str |> create let rec to_string cid = match cid with | Id id -> Id.to_string id | Compound (id, cid) -> Id.to_string id ^ "." ^ to_string cid ;; let rec to_string_delim d cid = match cid with | Id id -> Id.to_string_delim d id | Compound (id, cid) -> Id.to_string_delim d id ^ "." ^ to_string_delim d cid ;; let to_id d = match d with | Id evid -> evid | _ -> failwith "attempted to convert cid with multiple parts into id" ;; let rec to_ids d = match d with | Id id -> [id] | Compound (id, cid) -> id :: to_ids cid ;; let rec to_ids_prefix d = match d with | Id id -> id, [] | Compound (id, cid) -> let base, rest = to_ids_prefix cid in base, id :: rest ;; let rec first_id d = match d with | Id id -> id | Compound (id, _) -> id ;; let rec last_id d = match d with | Id id -> id | Compound (_, cid) -> last_id cid ;; let rec names cid = match cid with | Id id -> [Id.name id] | Compound (id, cid) -> Id.name id :: names cid ;; Operations let rec compare cid1 cid2 = match cid1, cid2 with | Id i1, Id i2 -> Id.compare i1 i2 | Compound (id1, cid1), Compound (id2, cid2) -> let i = Id.compare id1 id2 in if i = 0 then compare cid1 cid2 else i | Id _, Compound _ -> -1 | Compound _, Id _ -> 1 ;; let equal cid1 cid2 = compare cid1 cid2 = 0 let equals = equal let rec equal_names cid1 cid2 = match cid1, cid2 with | Id i1, Id i2 -> Id.equal_names i1 i2 | Compound (id1, cid1), Compound (id2, cid2) -> Id.equal_names id1 id2 && equal_names cid1 cid2 | _ -> false ;; let lookup_opt tuples key = Core.List.Assoc.find ~equal:equals tuples key let lookup tuples key = match lookup_opt tuples key with | Some v -> v | None -> let err_str = "error looking up " ^ to_string key in failwith err_str ;; let exists tuples key = match lookup_opt tuples key with | Some _ -> true | None -> false ;; let rec replace tuples key new_val = match tuples with | [] -> [] | (k, v) :: tuples -> if equals k key then (k, new_val) :: tuples else (k, v) :: replace tuples key new_val ;; let rec remove tuples key = match tuples with | [] -> [] | (k, v) :: tl -> if equals k key then remove tl key else (k, v) :: remove tl key ;; let rec modify_tail f t = match t with | Id id -> Id (f id) | Compound (id, cid) -> Compound (id, modify_tail f cid) ;;
f4087c1acac7a1ffe4524fb3c0c66b81e0da9b58d9470857887a22dcbbbfb1a6
tilk/yieldfsm
MakeLocalVars.hs
| Copyright : ( C ) 2022 : BSD2 ( see the file LICENSE ) Maintainer : < > This module defines a transformation which ensures that all references to mutable variables are local . Copyright : (C) 2022 Marek Materzok License : BSD2 (see the file LICENSE) Maintainer : Marek Materzok <> This module defines a transformation which ensures that all references to mutable variables are local. -} # LANGUAGE FlexibleContexts # module FSM.Process.MakeLocalVars(makeLocalVars) where import Prelude import FSM.Lang import FSM.FreeVars import Control.Lens import Control.Monad.Reader import Data.Maybe import qualified Data.Set as S import qualified Data.Map.Strict as M import qualified Language.Haskell.TH as TH import Data.Key(forWithKeyM) import FSM.Util.MonadRefresh import FSM.Process.ReturningFuns data LVData = LVData { _lvDataReturning :: Bool, _lvDataRetFuns :: S.Set TH.Name, _lvDataMutVars :: [TH.Name], _lvDataEnvVars :: [TH.Name], _lvDataFunVars :: M.Map TH.Name [TH.Name] } $(makeLenses ''LVData) | Makes all references to mutable variables local - i.e. the mutable variable is defined in the same function where it 's used . To achieve that , it creates local copies of non - local variables . They are initialized from new function arguments , and their final values are returned in a tuple . Example : > var n = 0 > fun loop ( ): > fun f ( ): > n = n + 1 > ret ( ) > let _ = call f ( ) > yield n > ret call loop ( ) > ret call loop ( ) Is translated to : > var n = 0 > fun loop ( ( ) , n_init ): > var n = n_init > fun f ( ( ) , n_init ): > var n = n_init > n = n + 1 > ret ( ( ) , n ) > let rt = call f ( ( ) , n ) > case > | ( _ , ): > n = n_new > yield n > ret call loop ( ( ) , n ) > ret call loop ( ( ) , n ) Makes all references to mutable variables local - i.e. the mutable variable is defined in the same function where it's used. To achieve that, it creates local copies of non-local variables. They are initialized from new function arguments, and their final values are returned in a tuple. Example: > var n = 0 > fun loop (): > fun f (): > n = n + 1 > ret () > let _ = call f () > yield n > ret call loop () > ret call loop () Is translated to: > var n = 0 > fun loop ((), n_init): > var n = n_init > fun f ((), n_init): > var n = n_init > n = n + 1 > ret ((), n) > let rt = call f ((), n) > case rt > | (_, n_new): > n = n_new > yield n > ret call loop ((), n) > ret call loop ((), n) -} makeLocalVars :: (IsDesugared l, WithAssign l, MonadRefresh m) => Prog l -> m (Prog l) makeLocalVars prog = do s' <- flip runReaderT (LVData False (returningFuns $ progBody prog) [] [] M.empty) $ makeLocalVarsStmt $ progBody prog return $ prog { progBody = s' } makeLocalVarsStmt :: (IsDesugared l, WithAssign l, MonadRefresh m, MonadReader LVData m) => Stmt l -> m (Stmt l) makeLocalVarsStmt SNop = return SNop makeLocalVarsStmt (SYield e) = return $ SYield e makeLocalVarsStmt (SBlock ss) = SBlock <$> mapM makeLocalVarsStmt ss makeLocalVarsStmt (SIf e st sf) = SIf e <$> makeLocalVarsStmt st <*> makeLocalVarsStmt sf makeLocalVarsStmt (SCase e cs) = SCase e <$> mapM (\(p, s) -> (p,) <$> makeLocalVarsStmt s) cs makeLocalVarsStmt (SLet VarLet n vs s) = makeLocalVarsVStmt vs $ \e -> SLet VarLet n (VExp e) <$> makeLocalVarsStmt s makeLocalVarsStmt (SLet VarMut n vs s) = makeLocalVarsVStmt vs $ \e -> do n' <- refreshName n SLet VarMut n' (VExp e) <$> locally lvDataMutVars (n':) (makeLocalVarsStmt $ renameSingle n n' s) makeLocalVarsStmt (SAssign n e) = return $ SAssign n e makeLocalVarsStmt (SRet vs) = do mvs <- view lvDataEnvVars mvs' <- mvsOf vs r <- view lvDataReturning if not r || mvs == mvs' then SRet <$> makeLocalVarsVStmtRet vs else makeLocalVarsVStmt vs (return . SRet . VExp . tupE . (:map TH.VarE mvs)) where mvsOf (VExp _) = return [] mvsOf (VCall f _) = views lvDataFunVars $ fromJust . M.lookup f makeLocalVarsStmt (SFun fs s) = do TODO deduce actual variable usage locally lvDataFunVars (M.map (const mvs0) fs `M.union`) $ do fs' <- forWithKeyM fs $ \f (p, s') -> do r <- views lvDataRetFuns $ S.member f mvs <- views lvDataFunVars $ fromJust . M.lookup f vns <- replicateM (length mvs) $ makeName "v" let lets = foldr (.) id (zipWith (\mv vn -> SLet VarMut mv (VExp $ TH.VarE vn)) mvs vns) locally lvDataEnvVars (const mvs) $ locally lvDataReturning (const r) $ (tupP $ p:map TH.VarP vns,) . lets <$> makeLocalVarsStmt s' SFun fs' <$> makeLocalVarsStmt s makeLocalVarsVStmtRet :: (MonadRefresh m, MonadReader LVData m) => VStmt -> m VStmt makeLocalVarsVStmtRet (VExp e) = return $ VExp e makeLocalVarsVStmtRet (VCall f e) = do mvs <- views lvDataFunVars $ fromJust . M.lookup f return $ VCall f $ tupE $ e:map TH.VarE mvs makeLocalVarsVStmt :: (IsDesugared l, WithAssign l, MonadRefresh m, MonadReader LVData m) => VStmt -> (TH.Exp -> m (Stmt l)) -> m (Stmt l) makeLocalVarsVStmt (VExp e) c = c e makeLocalVarsVStmt (VCall f e) c = do n <- makeName "rt" rn <- makeName "r" mvs <- views lvDataFunVars $ fromJust . M.lookup f vns <- replicateM (length mvs) $ makeName "v" s <- c $ TH.VarE rn return $ SLet VarLet n (VCall f $ tupE $ e:map TH.VarE mvs) $ SCase (TH.VarE n) [(tupP $ map TH.VarP $ rn:vns, sBlockS $ zipWith SAssign mvs (map TH.VarE vns) ++ [s])]
null
https://raw.githubusercontent.com/tilk/yieldfsm/bf86708eab22faec90c63cb15b0ac94c7005724b/src/FSM/Process/MakeLocalVars.hs
haskell
| Copyright : ( C ) 2022 : BSD2 ( see the file LICENSE ) Maintainer : < > This module defines a transformation which ensures that all references to mutable variables are local . Copyright : (C) 2022 Marek Materzok License : BSD2 (see the file LICENSE) Maintainer : Marek Materzok <> This module defines a transformation which ensures that all references to mutable variables are local. -} # LANGUAGE FlexibleContexts # module FSM.Process.MakeLocalVars(makeLocalVars) where import Prelude import FSM.Lang import FSM.FreeVars import Control.Lens import Control.Monad.Reader import Data.Maybe import qualified Data.Set as S import qualified Data.Map.Strict as M import qualified Language.Haskell.TH as TH import Data.Key(forWithKeyM) import FSM.Util.MonadRefresh import FSM.Process.ReturningFuns data LVData = LVData { _lvDataReturning :: Bool, _lvDataRetFuns :: S.Set TH.Name, _lvDataMutVars :: [TH.Name], _lvDataEnvVars :: [TH.Name], _lvDataFunVars :: M.Map TH.Name [TH.Name] } $(makeLenses ''LVData) | Makes all references to mutable variables local - i.e. the mutable variable is defined in the same function where it 's used . To achieve that , it creates local copies of non - local variables . They are initialized from new function arguments , and their final values are returned in a tuple . Example : > var n = 0 > fun loop ( ): > fun f ( ): > n = n + 1 > ret ( ) > let _ = call f ( ) > yield n > ret call loop ( ) > ret call loop ( ) Is translated to : > var n = 0 > fun loop ( ( ) , n_init ): > var n = n_init > fun f ( ( ) , n_init ): > var n = n_init > n = n + 1 > ret ( ( ) , n ) > let rt = call f ( ( ) , n ) > case > | ( _ , ): > n = n_new > yield n > ret call loop ( ( ) , n ) > ret call loop ( ( ) , n ) Makes all references to mutable variables local - i.e. the mutable variable is defined in the same function where it's used. To achieve that, it creates local copies of non-local variables. They are initialized from new function arguments, and their final values are returned in a tuple. Example: > var n = 0 > fun loop (): > fun f (): > n = n + 1 > ret () > let _ = call f () > yield n > ret call loop () > ret call loop () Is translated to: > var n = 0 > fun loop ((), n_init): > var n = n_init > fun f ((), n_init): > var n = n_init > n = n + 1 > ret ((), n) > let rt = call f ((), n) > case rt > | (_, n_new): > n = n_new > yield n > ret call loop ((), n) > ret call loop ((), n) -} makeLocalVars :: (IsDesugared l, WithAssign l, MonadRefresh m) => Prog l -> m (Prog l) makeLocalVars prog = do s' <- flip runReaderT (LVData False (returningFuns $ progBody prog) [] [] M.empty) $ makeLocalVarsStmt $ progBody prog return $ prog { progBody = s' } makeLocalVarsStmt :: (IsDesugared l, WithAssign l, MonadRefresh m, MonadReader LVData m) => Stmt l -> m (Stmt l) makeLocalVarsStmt SNop = return SNop makeLocalVarsStmt (SYield e) = return $ SYield e makeLocalVarsStmt (SBlock ss) = SBlock <$> mapM makeLocalVarsStmt ss makeLocalVarsStmt (SIf e st sf) = SIf e <$> makeLocalVarsStmt st <*> makeLocalVarsStmt sf makeLocalVarsStmt (SCase e cs) = SCase e <$> mapM (\(p, s) -> (p,) <$> makeLocalVarsStmt s) cs makeLocalVarsStmt (SLet VarLet n vs s) = makeLocalVarsVStmt vs $ \e -> SLet VarLet n (VExp e) <$> makeLocalVarsStmt s makeLocalVarsStmt (SLet VarMut n vs s) = makeLocalVarsVStmt vs $ \e -> do n' <- refreshName n SLet VarMut n' (VExp e) <$> locally lvDataMutVars (n':) (makeLocalVarsStmt $ renameSingle n n' s) makeLocalVarsStmt (SAssign n e) = return $ SAssign n e makeLocalVarsStmt (SRet vs) = do mvs <- view lvDataEnvVars mvs' <- mvsOf vs r <- view lvDataReturning if not r || mvs == mvs' then SRet <$> makeLocalVarsVStmtRet vs else makeLocalVarsVStmt vs (return . SRet . VExp . tupE . (:map TH.VarE mvs)) where mvsOf (VExp _) = return [] mvsOf (VCall f _) = views lvDataFunVars $ fromJust . M.lookup f makeLocalVarsStmt (SFun fs s) = do TODO deduce actual variable usage locally lvDataFunVars (M.map (const mvs0) fs `M.union`) $ do fs' <- forWithKeyM fs $ \f (p, s') -> do r <- views lvDataRetFuns $ S.member f mvs <- views lvDataFunVars $ fromJust . M.lookup f vns <- replicateM (length mvs) $ makeName "v" let lets = foldr (.) id (zipWith (\mv vn -> SLet VarMut mv (VExp $ TH.VarE vn)) mvs vns) locally lvDataEnvVars (const mvs) $ locally lvDataReturning (const r) $ (tupP $ p:map TH.VarP vns,) . lets <$> makeLocalVarsStmt s' SFun fs' <$> makeLocalVarsStmt s makeLocalVarsVStmtRet :: (MonadRefresh m, MonadReader LVData m) => VStmt -> m VStmt makeLocalVarsVStmtRet (VExp e) = return $ VExp e makeLocalVarsVStmtRet (VCall f e) = do mvs <- views lvDataFunVars $ fromJust . M.lookup f return $ VCall f $ tupE $ e:map TH.VarE mvs makeLocalVarsVStmt :: (IsDesugared l, WithAssign l, MonadRefresh m, MonadReader LVData m) => VStmt -> (TH.Exp -> m (Stmt l)) -> m (Stmt l) makeLocalVarsVStmt (VExp e) c = c e makeLocalVarsVStmt (VCall f e) c = do n <- makeName "rt" rn <- makeName "r" mvs <- views lvDataFunVars $ fromJust . M.lookup f vns <- replicateM (length mvs) $ makeName "v" s <- c $ TH.VarE rn return $ SLet VarLet n (VCall f $ tupE $ e:map TH.VarE mvs) $ SCase (TH.VarE n) [(tupP $ map TH.VarP $ rn:vns, sBlockS $ zipWith SAssign mvs (map TH.VarE vns) ++ [s])]
51d69fe67cea847ee8160cec3718903da7ecc1055fba3d2575b6a166cb6b3462
aengelberg/instagenerate
project.clj
(defproject instagenerate "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [instaparse "1.3.4"] [org.clojure/core.logic "0.8.7"]])
null
https://raw.githubusercontent.com/aengelberg/instagenerate/a04f639c203f8491a6d413b55862cb55226ae455/project.clj
clojure
(defproject instagenerate "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[org.clojure/clojure "1.6.0"] [instaparse "1.3.4"] [org.clojure/core.logic "0.8.7"]])
37366502f84eca9b1e83cdfeb373285da49ad7052455da057ad16501612b33df
shortishly/pgec
pgec_telemetry_resp_metrics.erl
Copyright ( c ) 2023 < > %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. -module(pgec_telemetry_resp_metrics). -export([handle/4]). -include_lib("kernel/include/logger.hrl"). handle(EventName, #{bytes := N}, _, _) -> counter(#{name => EventName ++ [bytes], delta => N}); handle(EventName, #{count := N}, _, _) -> counter(#{name => EventName ++ [count], delta => N}); handle(EventName, Measurements, Metadata, Config) -> ?LOG_INFO(#{event_name => EventName, measurements => Measurements, metadata => Metadata, config => Config}). counter(#{name := EventName} = Arg) -> try metrics:counter(Arg#{name := pgec_util:snake_case(EventName)}) catch error:badarg -> ?LOG_NOTICE(Arg#{note => "this observation was dropped"}) end.
null
https://raw.githubusercontent.com/shortishly/pgec/440a0fd7ebd1fe0d5ff4e44723f68fd7ceba88a5/src/pgec_telemetry_resp_metrics.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright ( c ) 2023 < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(pgec_telemetry_resp_metrics). -export([handle/4]). -include_lib("kernel/include/logger.hrl"). handle(EventName, #{bytes := N}, _, _) -> counter(#{name => EventName ++ [bytes], delta => N}); handle(EventName, #{count := N}, _, _) -> counter(#{name => EventName ++ [count], delta => N}); handle(EventName, Measurements, Metadata, Config) -> ?LOG_INFO(#{event_name => EventName, measurements => Measurements, metadata => Metadata, config => Config}). counter(#{name := EventName} = Arg) -> try metrics:counter(Arg#{name := pgec_util:snake_case(EventName)}) catch error:badarg -> ?LOG_NOTICE(Arg#{note => "this observation was dropped"}) end.
415a7a82230be52f351e45f72a96a80f6688cb0a74cb751eabffd7029142f151
bmeurer/ocaml-arm
camlinternalOO.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with (* the special exception on linking described in file ../LICENSE. *) (* *) (***********************************************************************) $ Id$ (** Run-time support for objects and classes. All functions in this module are for system use only, not for the casual user. *) (** {6 Classes} *) type tag type label type table type meth type t type obj type closure val public_method_label : string -> tag val new_method : table -> label val new_variable : table -> string -> int val new_methods_variables : table -> string array -> string array -> label array val get_variable : table -> string -> int val get_variables : table -> string array -> int array val get_method_label : table -> string -> label val get_method_labels : table -> string array -> label array val get_method : table -> label -> meth val set_method : table -> label -> meth -> unit val set_methods : table -> label array -> unit val narrow : table -> string array -> string array -> string array -> unit val widen : table -> unit val add_initializer : table -> (obj -> unit) -> unit val dummy_table : table val create_table : string array -> table val init_class : table -> unit val inherits : table -> string array -> string array -> string array -> (t * (table -> obj -> Obj.t) * t * obj) -> bool -> Obj.t array val make_class : string array -> (table -> Obj.t -> t) -> (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t) type init_table val make_class_store : string array -> (table -> t) -> init_table -> unit val dummy_class : string * int * int -> (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t) * { 6 Objects } val copy : (< .. > as 'a) -> 'a val create_object : table -> obj val create_object_opt : obj -> table -> obj val run_initializers : obj -> table -> unit val run_initializers_opt : obj -> obj -> table -> obj val create_object_and_run_initializers : obj -> table -> obj external send : obj -> tag -> t = "%send" external sendcache : obj -> tag -> t -> int -> t = "%sendcache" external sendself : obj -> label -> t = "%sendself" external get_public_method : obj -> tag -> closure = "caml_get_public_method" "noalloc" * { 6 Table cache } type tables val lookup_tables : tables -> closure array -> tables * { 6 Builtins to reduce code size } val get_const : t - > closure int - > closure val get_env : int - > int - > closure : label - > closure val set_var : int - > closure val app_const : ( t - > t ) - > t - > closure val app_var : ( t - > t ) - > int - > closure val app_env : ( t - > t ) - > int - > int - > closure : ( t - > t ) - > label - > closure val app_const_const : ( t - > t - > t ) - > t - > t - > closure app_const_var : ( t - > t - > t ) - > t - > int - > closure val app_const_env : ( t - > t - > t ) - > t - > int - > int - > closure val app_const_meth : ( t - > t - > t ) - > t - > label - > closure app_var_const : ( t - > t - > t ) - > int - > t - > closure val app_env_const : ( t - > t - > t ) - > int - > int - > t - > closure val app_meth_const : ( t - > t - > t ) - > label - > t - > closure val meth_app_const : label - > t - > closure val meth_app_var : label - > int - > closure val meth_app_env : label - > int - > int - > closure : label - > label - > closure val send_const : tag - > obj - > int - > closure val send_var : tag - > int - > int - > closure val send_env : tag - > int - > int - > int - > closure val send_meth : tag - > label - > int - > closure val get_const : t -> closure val get_var : int -> closure val get_env : int -> int -> closure val get_meth : label -> closure val set_var : int -> closure val app_const : (t -> t) -> t -> closure val app_var : (t -> t) -> int -> closure val app_env : (t -> t) -> int -> int -> closure val app_meth : (t -> t) -> label -> closure val app_const_const : (t -> t -> t) -> t -> t -> closure val app_const_var : (t -> t -> t) -> t -> int -> closure val app_const_env : (t -> t -> t) -> t -> int -> int -> closure val app_const_meth : (t -> t -> t) -> t -> label -> closure val app_var_const : (t -> t -> t) -> int -> t -> closure val app_env_const : (t -> t -> t) -> int -> int -> t -> closure val app_meth_const : (t -> t -> t) -> label -> t -> closure val meth_app_const : label -> t -> closure val meth_app_var : label -> int -> closure val meth_app_env : label -> int -> int -> closure val meth_app_meth : label -> label -> closure val send_const : tag -> obj -> int -> closure val send_var : tag -> int -> int -> closure val send_env : tag -> int -> int -> int -> closure val send_meth : tag -> label -> int -> closure *) type impl = GetConst | GetVar | GetEnv | GetMeth | SetVar | AppConst | AppVar | AppEnv | AppMeth | AppConstConst | AppConstVar | AppConstEnv | AppConstMeth | AppVarConst | AppEnvConst | AppMethConst | MethAppConst | MethAppVar | MethAppEnv | MethAppMeth | SendConst | SendVar | SendEnv | SendMeth | Closure of closure (** {6 Parameters} *) (* currently disabled *) type params = { mutable compact_table : bool; mutable copy_parent : bool; mutable clean_when_copying : bool; mutable retry_count : int; mutable bucket_small_size : int } val params : params * { 6 Statistics } type stats = { classes : int; methods : int; inst_vars : int } val stats : unit -> stats
null
https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/stdlib/camlinternalOO.mli
ocaml
********************************************************************* OCaml the special exception on linking described in file ../LICENSE. ********************************************************************* * Run-time support for objects and classes. All functions in this module are for system use only, not for the casual user. * {6 Classes} * {6 Parameters} currently disabled
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the GNU Library General Public License , with $ Id$ type tag type label type table type meth type t type obj type closure val public_method_label : string -> tag val new_method : table -> label val new_variable : table -> string -> int val new_methods_variables : table -> string array -> string array -> label array val get_variable : table -> string -> int val get_variables : table -> string array -> int array val get_method_label : table -> string -> label val get_method_labels : table -> string array -> label array val get_method : table -> label -> meth val set_method : table -> label -> meth -> unit val set_methods : table -> label array -> unit val narrow : table -> string array -> string array -> string array -> unit val widen : table -> unit val add_initializer : table -> (obj -> unit) -> unit val dummy_table : table val create_table : string array -> table val init_class : table -> unit val inherits : table -> string array -> string array -> string array -> (t * (table -> obj -> Obj.t) * t * obj) -> bool -> Obj.t array val make_class : string array -> (table -> Obj.t -> t) -> (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t) type init_table val make_class_store : string array -> (table -> t) -> init_table -> unit val dummy_class : string * int * int -> (t * (table -> Obj.t -> t) * (Obj.t -> t) * Obj.t) * { 6 Objects } val copy : (< .. > as 'a) -> 'a val create_object : table -> obj val create_object_opt : obj -> table -> obj val run_initializers : obj -> table -> unit val run_initializers_opt : obj -> obj -> table -> obj val create_object_and_run_initializers : obj -> table -> obj external send : obj -> tag -> t = "%send" external sendcache : obj -> tag -> t -> int -> t = "%sendcache" external sendself : obj -> label -> t = "%sendself" external get_public_method : obj -> tag -> closure = "caml_get_public_method" "noalloc" * { 6 Table cache } type tables val lookup_tables : tables -> closure array -> tables * { 6 Builtins to reduce code size } val get_const : t - > closure int - > closure val get_env : int - > int - > closure : label - > closure val set_var : int - > closure val app_const : ( t - > t ) - > t - > closure val app_var : ( t - > t ) - > int - > closure val app_env : ( t - > t ) - > int - > int - > closure : ( t - > t ) - > label - > closure val app_const_const : ( t - > t - > t ) - > t - > t - > closure app_const_var : ( t - > t - > t ) - > t - > int - > closure val app_const_env : ( t - > t - > t ) - > t - > int - > int - > closure val app_const_meth : ( t - > t - > t ) - > t - > label - > closure app_var_const : ( t - > t - > t ) - > int - > t - > closure val app_env_const : ( t - > t - > t ) - > int - > int - > t - > closure val app_meth_const : ( t - > t - > t ) - > label - > t - > closure val meth_app_const : label - > t - > closure val meth_app_var : label - > int - > closure val meth_app_env : label - > int - > int - > closure : label - > label - > closure val send_const : tag - > obj - > int - > closure val send_var : tag - > int - > int - > closure val send_env : tag - > int - > int - > int - > closure val send_meth : tag - > label - > int - > closure val get_const : t -> closure val get_var : int -> closure val get_env : int -> int -> closure val get_meth : label -> closure val set_var : int -> closure val app_const : (t -> t) -> t -> closure val app_var : (t -> t) -> int -> closure val app_env : (t -> t) -> int -> int -> closure val app_meth : (t -> t) -> label -> closure val app_const_const : (t -> t -> t) -> t -> t -> closure val app_const_var : (t -> t -> t) -> t -> int -> closure val app_const_env : (t -> t -> t) -> t -> int -> int -> closure val app_const_meth : (t -> t -> t) -> t -> label -> closure val app_var_const : (t -> t -> t) -> int -> t -> closure val app_env_const : (t -> t -> t) -> int -> int -> t -> closure val app_meth_const : (t -> t -> t) -> label -> t -> closure val meth_app_const : label -> t -> closure val meth_app_var : label -> int -> closure val meth_app_env : label -> int -> int -> closure val meth_app_meth : label -> label -> closure val send_const : tag -> obj -> int -> closure val send_var : tag -> int -> int -> closure val send_env : tag -> int -> int -> int -> closure val send_meth : tag -> label -> int -> closure *) type impl = GetConst | GetVar | GetEnv | GetMeth | SetVar | AppConst | AppVar | AppEnv | AppMeth | AppConstConst | AppConstVar | AppConstEnv | AppConstMeth | AppVarConst | AppEnvConst | AppMethConst | MethAppConst | MethAppVar | MethAppEnv | MethAppMeth | SendConst | SendVar | SendEnv | SendMeth | Closure of closure type params = { mutable compact_table : bool; mutable copy_parent : bool; mutable clean_when_copying : bool; mutable retry_count : int; mutable bucket_small_size : int } val params : params * { 6 Statistics } type stats = { classes : int; methods : int; inst_vars : int } val stats : unit -> stats
75b7317310b5b77ea9150fccd2b2d34f6138a7b0f1690d3821b9f3d52de2cf9f
realworldocaml/mdx
mdx_top.mli
* Copyright ( c ) 2017 * Copyright ( c ) 2018 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2017 Frédéric Bour * Copyright (c) 2018 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * Toplevel logic for [ mdx ] . type t (** The type for configuration values. *) type directive = | Directory of string | Load of string (** The type for toplevel directives *) val init : verbose:bool -> silent:bool -> verbose_findlib:bool -> directives:directive list -> packages:string list -> predicates:string list -> unit -> t (** [init ()] is a new configuration value. *) val eval : t -> string list -> (string list, string list) result (** [eval t p] evaluates the toplevel phrase [p] (possibly spawning on mulitple lines) with the configuration value [t]. *) val in_env : Mdx.Ocaml_env.t -> (unit -> 'a) -> 'a
null
https://raw.githubusercontent.com/realworldocaml/mdx/4d8e7e8321faeeabe7091fbe2e901e64ab19dc06/lib/top/mdx_top.mli
ocaml
* The type for configuration values. * The type for toplevel directives * [init ()] is a new configuration value. * [eval t p] evaluates the toplevel phrase [p] (possibly spawning on mulitple lines) with the configuration value [t].
* Copyright ( c ) 2017 * Copyright ( c ) 2018 < > * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2017 Frédéric Bour * Copyright (c) 2018 Thomas Gazagnaire <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * Toplevel logic for [ mdx ] . type t type directive = | Directory of string val init : verbose:bool -> silent:bool -> verbose_findlib:bool -> directives:directive list -> packages:string list -> predicates:string list -> unit -> t val eval : t -> string list -> (string list, string list) result val in_env : Mdx.Ocaml_env.t -> (unit -> 'a) -> 'a
4f9d6abe0ce99aa539a9514fd695b8913424473ea568d8a1017188f2d07efbc8
smimram/funk
sound.ml
sound.ml [ part of the funk project ] [ functional kernel , contents : userland sound functions * copyright : ( C ) 2005 by , * email : , * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This program is free software ; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation ; either version 2 * * of the License , or ( at your option ) any later version . * * * * This program is distributed in the hope that it will be useful , * * but WITHOUT ANY WARRANTY ; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * * GNU General Public License for more details . * * * * You should have received a copy of the GNU General Public License * * along with this program ; if not , write to the Free Software * * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [functional kernel, -lyon.fr/nicolas.guenot/funk/] * contents : userland sound functions * copyright : (C) 2005 by samuel mimram, nicolas guenot * email : , ******************************************************************************* * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * ******************************************************************************) * * Userland sound functions * * @author * * Userland sound functions * * @author Brice Goglin **) (* Speaker and Timer constants *) let clock_tick_rate = 1193182 let timer_data_port = 0x42 let timer_control_port = 0x43 let timer_oscillator_cmd = 0xb6 let speaker_control_port = 0x61 let speaker_timer_driven_enable_cmd = 0x3 let speaker_timer_disable_cmd = 0xff lxor speaker_timer_driven_enable_cmd Put Timer in oscillator mode let oscillator_timer () = ignore (Funk.outb_p timer_control_port timer_oscillator_cmd) (* Set Timer frequency *) let set_timer_frequency freq = let count = clock_tick_rate/freq in ignore (Funk.outb_p timer_data_port (count land 0xff)); ignore (Funk.outb_p timer_data_port ((count lsr 8) land 0xff)) (* Enable/disable the internal speaker in timer driven mode *) let enable_speaker () = let status = Funk.inb_p speaker_control_port in ignore (Funk.outb_p speaker_control_port (status lor speaker_timer_driven_enable_cmd)) let disable_speaker () = let status = Funk.inb_p speaker_control_port in ignore (Funk.outb_p speaker_control_port (status land speaker_timer_disable_cmd)) (* Beep during delay milliseconds with frequency freq Hz *) let beep freq delay = oscillator_timer (); set_timer_frequency freq; enable_speaker (); Funk.usleep (delay*1000); disable_speaker ()
null
https://raw.githubusercontent.com/smimram/funk/88328dd9087c9097b1bfe2cf5394ba99fa631934/src/userland/sound.ml
ocaml
Speaker and Timer constants Set Timer frequency Enable/disable the internal speaker in timer driven mode Beep during delay milliseconds with frequency freq Hz
sound.ml [ part of the funk project ] [ functional kernel , contents : userland sound functions * copyright : ( C ) 2005 by , * email : , * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This program is free software ; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation ; either version 2 * * of the License , or ( at your option ) any later version . * * * * This program is distributed in the hope that it will be useful , * * but WITHOUT ANY WARRANTY ; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * * GNU General Public License for more details . * * * * You should have received a copy of the GNU General Public License * * along with this program ; if not , write to the Free Software * * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * [functional kernel, -lyon.fr/nicolas.guenot/funk/] * contents : userland sound functions * copyright : (C) 2005 by samuel mimram, nicolas guenot * email : , ******************************************************************************* * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License * * as published by the Free Software Foundation; either version 2 * * of the License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * * ******************************************************************************) * * Userland sound functions * * @author * * Userland sound functions * * @author Brice Goglin **) let clock_tick_rate = 1193182 let timer_data_port = 0x42 let timer_control_port = 0x43 let timer_oscillator_cmd = 0xb6 let speaker_control_port = 0x61 let speaker_timer_driven_enable_cmd = 0x3 let speaker_timer_disable_cmd = 0xff lxor speaker_timer_driven_enable_cmd Put Timer in oscillator mode let oscillator_timer () = ignore (Funk.outb_p timer_control_port timer_oscillator_cmd) let set_timer_frequency freq = let count = clock_tick_rate/freq in ignore (Funk.outb_p timer_data_port (count land 0xff)); ignore (Funk.outb_p timer_data_port ((count lsr 8) land 0xff)) let enable_speaker () = let status = Funk.inb_p speaker_control_port in ignore (Funk.outb_p speaker_control_port (status lor speaker_timer_driven_enable_cmd)) let disable_speaker () = let status = Funk.inb_p speaker_control_port in ignore (Funk.outb_p speaker_control_port (status land speaker_timer_disable_cmd)) let beep freq delay = oscillator_timer (); set_timer_frequency freq; enable_speaker (); Funk.usleep (delay*1000); disable_speaker ()
da396ed11f41f7fc51f24289afd44ed699e5825029c68b73b4a7a56e2a2589e6
dalaing/little-languages
Infer.hs
# LANGUAGE TemplateHaskell # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # module Common.Term.Infer ( InferInput(..) , HasInferInput(..) , InferOutput(..) , HasInferOutput(..) , mkInfer , InferStack(..) ) where import Control.Applicative (Alternative) import Control.Monad.Error.Lens (throwing) import Control.Monad.Except (MonadError, Except) import Control.Lens.TH (makeClassy) import Common.Recursion import Common.Type.Error TODO replace with non - empty list -- possibly replace with Validation / AccValidation? newtype InferStack e a = InferStack { runInfer :: Except e a } deriving (Functor, Applicative, Alternative, Monad, MonadError e) data InferInput e ty tm = InferInput { _inferSteps :: [MaybeStep tm (InferStack e ty)] } makeClassy ''InferInput TODO make into a semigroup ? instance Monoid (InferInput e ty tm) where mempty = InferInput [] mappend (InferInput i1) (InferInput i2) = InferInput (mappend i1 i2) data InferOutput e ty tm = InferOutput { _inferRules :: [tm -> Maybe (InferStack e ty)] , _infer :: tm -> InferStack e ty } makeClassy ''InferOutput mkInfer :: ( AsUnknownType e n ) => InferInput e ty tm -> InferOutput e ty tm mkInfer (InferInput is) = let err = throwing _TeUnknownType Nothing in InferOutput (mkMaybeSteps err is) (combineMaybeSteps err is)
null
https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/multityped/nb-modular/src/Common/Term/Infer.hs
haskell
possibly replace with Validation / AccValidation?
# LANGUAGE TemplateHaskell # # LANGUAGE MultiParamTypeClasses # # LANGUAGE FunctionalDependencies # # LANGUAGE FlexibleInstances # # LANGUAGE FlexibleContexts # # LANGUAGE GeneralizedNewtypeDeriving # module Common.Term.Infer ( InferInput(..) , HasInferInput(..) , InferOutput(..) , HasInferOutput(..) , mkInfer , InferStack(..) ) where import Control.Applicative (Alternative) import Control.Monad.Error.Lens (throwing) import Control.Monad.Except (MonadError, Except) import Control.Lens.TH (makeClassy) import Common.Recursion import Common.Type.Error TODO replace with non - empty list newtype InferStack e a = InferStack { runInfer :: Except e a } deriving (Functor, Applicative, Alternative, Monad, MonadError e) data InferInput e ty tm = InferInput { _inferSteps :: [MaybeStep tm (InferStack e ty)] } makeClassy ''InferInput TODO make into a semigroup ? instance Monoid (InferInput e ty tm) where mempty = InferInput [] mappend (InferInput i1) (InferInput i2) = InferInput (mappend i1 i2) data InferOutput e ty tm = InferOutput { _inferRules :: [tm -> Maybe (InferStack e ty)] , _infer :: tm -> InferStack e ty } makeClassy ''InferOutput mkInfer :: ( AsUnknownType e n ) => InferInput e ty tm -> InferOutput e ty tm mkInfer (InferInput is) = let err = throwing _TeUnknownType Nothing in InferOutput (mkMaybeSteps err is) (combineMaybeSteps err is)
49bf93f10c5d4935f1d9cd68d7670c0ec2740b07f9c630f1bf7bf3105604dd61
digitallyinduced/ihp
Lockable.hs
module IHP.AuthSupport.Lockable where import IHP.Prelude lock :: forall user. (?modelContext :: ModelContext, CanUpdate user, UpdateField "lockedAt" user user (Maybe UTCTime) (Maybe UTCTime)) => user -> IO user lock user = do now <- getCurrentTime let currentLockedAt :: Maybe UTCTime = getField @"lockedAt" user let user' :: user = updateField @"lockedAt" (Just now) user updateRecord user' lockDuration :: NominalDiffTime lockDuration = let timeInSecs = 60 * 60 in secondsToNominalDiffTime timeInSecs isLocked :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => user -> IO Bool isLocked user = do now <- getCurrentTime pure (isLocked' now user) isLocked' :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => UTCTime -> user -> Bool isLocked' now user = case getField @"lockedAt" user of Just lockedAt -> let diff = diffUTCTime now lockedAt in diff < lockDuration Nothing -> False
null
https://raw.githubusercontent.com/digitallyinduced/ihp/620482b47e0daf13ed3bdaa83ec2953c55477e6e/IHP/AuthSupport/Lockable.hs
haskell
module IHP.AuthSupport.Lockable where import IHP.Prelude lock :: forall user. (?modelContext :: ModelContext, CanUpdate user, UpdateField "lockedAt" user user (Maybe UTCTime) (Maybe UTCTime)) => user -> IO user lock user = do now <- getCurrentTime let currentLockedAt :: Maybe UTCTime = getField @"lockedAt" user let user' :: user = updateField @"lockedAt" (Just now) user updateRecord user' lockDuration :: NominalDiffTime lockDuration = let timeInSecs = 60 * 60 in secondsToNominalDiffTime timeInSecs isLocked :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => user -> IO Bool isLocked user = do now <- getCurrentTime pure (isLocked' now user) isLocked' :: forall user. (HasField "lockedAt" user (Maybe UTCTime)) => UTCTime -> user -> Bool isLocked' now user = case getField @"lockedAt" user of Just lockedAt -> let diff = diffUTCTime now lockedAt in diff < lockDuration Nothing -> False
440b92155d815f9c9efdeee25dc6aa74382927c9d5ecad5ac7b8fcd9223b73f6
marcoheisig/Typo
upgraded-array-element-ntype.lisp
(in-package #:typo.ntype) (defmethod upgraded-array-element-ntype ((primitive-ntype primitive-ntype)) (primitive-ntype-upgraded-array-element-ntype primitive-ntype)) (defmethod upgraded-array-element-ntype ((ntype ntype)) (primitive-ntype-upgraded-array-element-ntype (ntype-primitive-ntype ntype))) (let ((cache (make-array (list +primitive-ntype-limit+) :element-type '(cons ntype (cons boolean null)) :initial-element (list (universal-ntype) nil)))) (loop for p across *primitive-ntypes* do (setf (aref cache (ntype-index p)) (multiple-value-list (find-primitive-ntype (upgraded-array-element-type (primitive-ntype-type-specifier p)))))) (defun primitive-ntype-upgraded-array-element-ntype (primitive-ntype) (declare (primitive-ntype primitive-ntype)) (values-list (aref cache (ntype-index primitive-ntype)))))
null
https://raw.githubusercontent.com/marcoheisig/Typo/88f2708bbb8f8f8ac2dd19cd153a16c06554a6aa/code/ntype/upgraded-array-element-ntype.lisp
lisp
(in-package #:typo.ntype) (defmethod upgraded-array-element-ntype ((primitive-ntype primitive-ntype)) (primitive-ntype-upgraded-array-element-ntype primitive-ntype)) (defmethod upgraded-array-element-ntype ((ntype ntype)) (primitive-ntype-upgraded-array-element-ntype (ntype-primitive-ntype ntype))) (let ((cache (make-array (list +primitive-ntype-limit+) :element-type '(cons ntype (cons boolean null)) :initial-element (list (universal-ntype) nil)))) (loop for p across *primitive-ntypes* do (setf (aref cache (ntype-index p)) (multiple-value-list (find-primitive-ntype (upgraded-array-element-type (primitive-ntype-type-specifier p)))))) (defun primitive-ntype-upgraded-array-element-ntype (primitive-ntype) (declare (primitive-ntype primitive-ntype)) (values-list (aref cache (ntype-index primitive-ntype)))))
845390db33451da56838ab74306ca3715e1ec98902166848e9b103b42c285cf6
hexlet-codebattle/battle_asserts
simplified_stairway_to_heaven.clj
(ns battle-asserts.issues.simplified-stairway-to-heaven (:require [clojure.test.check.generators :as gen])) (def level :medium) (def tags ["collections"]) (def description {:en "`N` dicks randomly spread out of `M` stairs, there can be as many dicks as you want on one step. We gotta go down these stairs. Every time you step on a stair-step with dicks, the infame number increases by the number of dicks. You can go down one or two steps at a time (You can`t lookup infame number farther than two steps away from you!). Write a function to descend the stairs minimizing the infame number (function must find local minimun at each step!). The function receives an array with the number of dicks on each step and returns the minimized infame number. Powered by Eugene Zaytsev." :ru "`N` членов случайно раскиданы по лестнице из `M` ступенек, на одной ступеньке может быть сколько угодно членов. Нужно спуститься по этой лестнице вниз. Каждый раз наступая на ступеньку с членами, число позора увеличивается по количеству членов. Спускаться можно на одну или две ступеньки за раз (вы не можете обнаружить число позора дальше, чем в двух ступеньках от вас!). Напишите функцию спуска с лестницы минимизирующую коэффициент позора (функция должна находить локальный минимум на каждом шаге!). Функция принимает массив с количеством членов на каждой ступеньке и возвращает минимизированное число позора. При поддержке Евгения Зайцева."}) (def signature {:input [{:argument-name "arr" :type {:name "array" :nested {:name "integer"}}}] :output {:type {:name "integer"}}}) (defn arguments-generator [] (gen/tuple (gen/vector (gen/choose 0 12) 3 12))) (def test-data [{:expected 0 :arguments [[0 1 0 1]]} {:expected 0 :arguments [[1 0 1 0 1]]} {:expected 9 :arguments [[1 0 3 5 10 0 11 1]]} {:expected 20 :arguments [[0 11 6 8 1 4 10 9]]} {:expected 34 :arguments [[9 11 1 5 6 6 5 4 9 12]]}]) (defn iter-step ([steps] (iter-step steps 0)) ([steps acc] (let [len (count steps)] (if (<= len 1) acc (let [first-pol (first steps) second-pol (second steps)] (if (< first-pol second-pol) (iter-step (drop 1 steps) (+ acc first-pol)) (iter-step (drop 2 steps) (+ acc second-pol)))))))) (defn solution [steps-map] (iter-step steps-map))
null
https://raw.githubusercontent.com/hexlet-codebattle/battle_asserts/c6304f492c86472b9ddb4332a84a2c510b61af6d/src/battle_asserts/issues/simplified_stairway_to_heaven.clj
clojure
(ns battle-asserts.issues.simplified-stairway-to-heaven (:require [clojure.test.check.generators :as gen])) (def level :medium) (def tags ["collections"]) (def description {:en "`N` dicks randomly spread out of `M` stairs, there can be as many dicks as you want on one step. We gotta go down these stairs. Every time you step on a stair-step with dicks, the infame number increases by the number of dicks. You can go down one or two steps at a time (You can`t lookup infame number farther than two steps away from you!). Write a function to descend the stairs minimizing the infame number (function must find local minimun at each step!). The function receives an array with the number of dicks on each step and returns the minimized infame number. Powered by Eugene Zaytsev." :ru "`N` членов случайно раскиданы по лестнице из `M` ступенек, на одной ступеньке может быть сколько угодно членов. Нужно спуститься по этой лестнице вниз. Каждый раз наступая на ступеньку с членами, число позора увеличивается по количеству членов. Спускаться можно на одну или две ступеньки за раз (вы не можете обнаружить число позора дальше, чем в двух ступеньках от вас!). Напишите функцию спуска с лестницы минимизирующую коэффициент позора (функция должна находить локальный минимум на каждом шаге!). Функция принимает массив с количеством членов на каждой ступеньке и возвращает минимизированное число позора. При поддержке Евгения Зайцева."}) (def signature {:input [{:argument-name "arr" :type {:name "array" :nested {:name "integer"}}}] :output {:type {:name "integer"}}}) (defn arguments-generator [] (gen/tuple (gen/vector (gen/choose 0 12) 3 12))) (def test-data [{:expected 0 :arguments [[0 1 0 1]]} {:expected 0 :arguments [[1 0 1 0 1]]} {:expected 9 :arguments [[1 0 3 5 10 0 11 1]]} {:expected 20 :arguments [[0 11 6 8 1 4 10 9]]} {:expected 34 :arguments [[9 11 1 5 6 6 5 4 9 12]]}]) (defn iter-step ([steps] (iter-step steps 0)) ([steps acc] (let [len (count steps)] (if (<= len 1) acc (let [first-pol (first steps) second-pol (second steps)] (if (< first-pol second-pol) (iter-step (drop 1 steps) (+ acc first-pol)) (iter-step (drop 2 steps) (+ acc second-pol)))))))) (defn solution [steps-map] (iter-step steps-map))
b182446d4993cf62a870b1439ca50513d8464ffcf2f9faf944651a88ebcc9f27
DanielG/cabal-helper
GHC.hs
cabal - helper : Simple interface to Cabal 's configuration state Copyright ( C ) 2018 < > -- SPDX - License - Identifier : Apache-2.0 -- 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 | Module : CabalHelper . Compiletime . Program . GHC Description : GHC program interface License : Apache-2.0 Module : CabalHelper.Compiletime.Program.GHC Description : GHC program interface License : Apache-2.0 -} module CabalHelper.Compiletime.Program.GHC where import Control.Monad import Control.Monad.Trans.Maybe import Control.Monad.IO.Class import Data.Char import Data.List import Data.Maybe import Data.Version import System.Exit import System.FilePath import System.Directory import CabalHelper.Shared.Common (parseVer, trim, appCacheDir, parsePkgId) import CabalHelper.Compiletime.Types import CabalHelper.Compiletime.Types.Cabal ( ResolvedCabalVersion, showResolvedCabalVersion, UnpackedCabalVersion , unpackedToResolvedCabalVersion, CabalVersion'(..) ) import CabalHelper.Compiletime.Process import CabalHelper.Compiletime.Log data GhcPackageSource = GPSAmbient | GPSPackageDBs ![PackageDbDir] | GPSPackageEnv !PackageEnvFile data GhcInvocation = GhcInvocation { giOutDir :: !FilePath , giOutput :: !FilePath , giCPPOptions :: ![String] , giPackageSource :: !GhcPackageSource , giIncludeDirs :: ![FilePath] , giHideAllPackages :: !Bool , giPackages :: ![String] , giWarningFlags :: ![String] , giInputs :: ![String] } newtype GhcVersion = GhcVersion { unGhcVersion :: Version } deriving (Eq, Ord, Read, Show) showGhcVersion :: GhcVersion -> String showGhcVersion (GhcVersion v) = showVersion v getGhcVersion :: (Verbose, Progs) => IO Version getGhcVersion = parseVer . trim <$> readProcess' (ghcProgram ?progs) ["--numeric-version"] "" ghcLibdir :: (Verbose, Progs) => IO FilePath ghcLibdir = do trim <$> readProcess' (ghcProgram ?progs) ["--print-libdir"] "" getGhcPkgVersion :: (Verbose, Progs) => IO Version getGhcPkgVersion = parseVer . trim . dropWhile (not . isDigit) <$> readProcess' (ghcPkgProgram ?progs) ["--version"] "" createPkgDb :: (Verbose, Progs) => UnpackedCabalVersion -> IO PackageDbDir createPkgDb cabalVer = do db@(PackageDbDir db_path) <- getPrivateCabalPkgDb $ unpackedToResolvedCabalVersion cabalVer exists <- doesDirectoryExist db_path when (not exists) $ callProcessStderr Nothing [] (ghcPkgProgram ?progs) ["init", db_path] return db getPrivateCabalPkgDb :: (Verbose, Progs) => ResolvedCabalVersion -> IO PackageDbDir getPrivateCabalPkgDb cabalVer = do appdir <- appCacheDir ghcVer <- getGhcVersion let db_path = appdir </> "ghc-" ++ showVersion ghcVer ++ ".package-dbs" </> "Cabal-" ++ showResolvedCabalVersion cabalVer return $ PackageDbDir db_path getPrivateCabalPkgEnv :: Verbose => GhcVersion -> ResolvedCabalVersion -> IO PackageEnvFile getPrivateCabalPkgEnv ghcVer cabalVer = do appdir <- appCacheDir let env_path = appdir </> "ghc-" ++ showGhcVersion ghcVer ++ ".package-envs" </> "Cabal-" ++ showResolvedCabalVersion cabalVer ++ ".package-env" return $ PackageEnvFile env_path listCabalVersions :: (Verbose, Progs) => Maybe PackageDbDir -> MaybeT IO [Version] listCabalVersions mdb = do let mdb_path = unPackageDbDir <$> mdb exists <- fromMaybe True <$> traverse (liftIO . doesDirectoryExist) mdb_path case exists of True -> MaybeT $ logIOError "listCabalVersions" $ Just <$> do let mdbopt = ("--package-conf="++) <$> mdb_path args = ["list", "--simple-output", "Cabal"] ++ maybeToList mdbopt catMaybes . map (fmap snd . parsePkgId) . words <$> readProcess' (ghcPkgProgram ?progs) args "" _ -> mzero cabalVersionExistsInPkgDb :: (Verbose, Progs) => CabalVersion' a -> PackageDbDir -> IO Bool cabalVersionExistsInPkgDb cabalVer db@(PackageDbDir db_path) = do fromMaybe False <$> runMaybeT (do vers <- listCabalVersions (Just db) return $ case (cabalVer, vers) of (CabalVersion ver, _) -> ver `elem` vers (CabalHEAD _, []) -> False (CabalHEAD _, [_headver]) -> True (CabalHEAD _, _) -> error $ msg ++ db_path) where msg = "\ \Multiple Cabal versions in a HEAD package-db!\n\ \This shouldn't happen. However you can manually delete the following\n\ \directory to resolve this:\n " invokeGhc :: Env => GhcInvocation -> IO (Either ExitCode FilePath) invokeGhc GhcInvocation {..} = do giOutDirAbs <- makeAbsolute giOutDir giOutputAbs <- makeAbsolute giOutput giIncludeDirsAbs <- mapM makeAbsolute giIncludeDirs giInputsAbs <- mapM makeAbsolute giInputs We unset some interferring envvars here for stack , see : -- -helper/issues/78#issuecomment-557860898 let eos = [("GHC_ENVIRONMENT", EnvUnset), ("GHC_PACKAGE_PATH", EnvUnset)] rv <- callProcessStderr' (Just "/") eos (ghcProgram ?progs) $ concat [ [ "-outputdir", giOutDirAbs , "-o", giOutputAbs ] , map ("-optP"++) giCPPOptions , if giHideAllPackages then ["-hide-all-packages"] else [] , let packageFlags = concatMap (\p -> ["-package", p]) giPackages in case giPackageSource of GPSAmbient -> packageFlags GPSPackageDBs dbs -> concat [ map ("-package-conf="++) $ unPackageDbDir <$> dbs , packageFlags ] GPSPackageEnv env -> [ "-package-env=" ++ unPackageEnvFile env ] , map ("-i"++) $ nub $ "" : giIncludeDirsAbs , giWarningFlags , ["--make"] , giInputsAbs ] return $ case rv of ExitSuccess -> Right giOutput e@(ExitFailure _) -> Left e
null
https://raw.githubusercontent.com/DanielG/cabal-helper/0e9df088226d80669dd0882ed743bca871dce61c/src/CabalHelper/Compiletime/Program/GHC.hs
haskell
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 -helper/issues/78#issuecomment-557860898
cabal - helper : Simple interface to Cabal 's configuration state Copyright ( C ) 2018 < > SPDX - License - Identifier : Apache-2.0 Licensed under the Apache License , Version 2.0 ( the " License " ) ; | Module : CabalHelper . Compiletime . Program . GHC Description : GHC program interface License : Apache-2.0 Module : CabalHelper.Compiletime.Program.GHC Description : GHC program interface License : Apache-2.0 -} module CabalHelper.Compiletime.Program.GHC where import Control.Monad import Control.Monad.Trans.Maybe import Control.Monad.IO.Class import Data.Char import Data.List import Data.Maybe import Data.Version import System.Exit import System.FilePath import System.Directory import CabalHelper.Shared.Common (parseVer, trim, appCacheDir, parsePkgId) import CabalHelper.Compiletime.Types import CabalHelper.Compiletime.Types.Cabal ( ResolvedCabalVersion, showResolvedCabalVersion, UnpackedCabalVersion , unpackedToResolvedCabalVersion, CabalVersion'(..) ) import CabalHelper.Compiletime.Process import CabalHelper.Compiletime.Log data GhcPackageSource = GPSAmbient | GPSPackageDBs ![PackageDbDir] | GPSPackageEnv !PackageEnvFile data GhcInvocation = GhcInvocation { giOutDir :: !FilePath , giOutput :: !FilePath , giCPPOptions :: ![String] , giPackageSource :: !GhcPackageSource , giIncludeDirs :: ![FilePath] , giHideAllPackages :: !Bool , giPackages :: ![String] , giWarningFlags :: ![String] , giInputs :: ![String] } newtype GhcVersion = GhcVersion { unGhcVersion :: Version } deriving (Eq, Ord, Read, Show) showGhcVersion :: GhcVersion -> String showGhcVersion (GhcVersion v) = showVersion v getGhcVersion :: (Verbose, Progs) => IO Version getGhcVersion = parseVer . trim <$> readProcess' (ghcProgram ?progs) ["--numeric-version"] "" ghcLibdir :: (Verbose, Progs) => IO FilePath ghcLibdir = do trim <$> readProcess' (ghcProgram ?progs) ["--print-libdir"] "" getGhcPkgVersion :: (Verbose, Progs) => IO Version getGhcPkgVersion = parseVer . trim . dropWhile (not . isDigit) <$> readProcess' (ghcPkgProgram ?progs) ["--version"] "" createPkgDb :: (Verbose, Progs) => UnpackedCabalVersion -> IO PackageDbDir createPkgDb cabalVer = do db@(PackageDbDir db_path) <- getPrivateCabalPkgDb $ unpackedToResolvedCabalVersion cabalVer exists <- doesDirectoryExist db_path when (not exists) $ callProcessStderr Nothing [] (ghcPkgProgram ?progs) ["init", db_path] return db getPrivateCabalPkgDb :: (Verbose, Progs) => ResolvedCabalVersion -> IO PackageDbDir getPrivateCabalPkgDb cabalVer = do appdir <- appCacheDir ghcVer <- getGhcVersion let db_path = appdir </> "ghc-" ++ showVersion ghcVer ++ ".package-dbs" </> "Cabal-" ++ showResolvedCabalVersion cabalVer return $ PackageDbDir db_path getPrivateCabalPkgEnv :: Verbose => GhcVersion -> ResolvedCabalVersion -> IO PackageEnvFile getPrivateCabalPkgEnv ghcVer cabalVer = do appdir <- appCacheDir let env_path = appdir </> "ghc-" ++ showGhcVersion ghcVer ++ ".package-envs" </> "Cabal-" ++ showResolvedCabalVersion cabalVer ++ ".package-env" return $ PackageEnvFile env_path listCabalVersions :: (Verbose, Progs) => Maybe PackageDbDir -> MaybeT IO [Version] listCabalVersions mdb = do let mdb_path = unPackageDbDir <$> mdb exists <- fromMaybe True <$> traverse (liftIO . doesDirectoryExist) mdb_path case exists of True -> MaybeT $ logIOError "listCabalVersions" $ Just <$> do let mdbopt = ("--package-conf="++) <$> mdb_path args = ["list", "--simple-output", "Cabal"] ++ maybeToList mdbopt catMaybes . map (fmap snd . parsePkgId) . words <$> readProcess' (ghcPkgProgram ?progs) args "" _ -> mzero cabalVersionExistsInPkgDb :: (Verbose, Progs) => CabalVersion' a -> PackageDbDir -> IO Bool cabalVersionExistsInPkgDb cabalVer db@(PackageDbDir db_path) = do fromMaybe False <$> runMaybeT (do vers <- listCabalVersions (Just db) return $ case (cabalVer, vers) of (CabalVersion ver, _) -> ver `elem` vers (CabalHEAD _, []) -> False (CabalHEAD _, [_headver]) -> True (CabalHEAD _, _) -> error $ msg ++ db_path) where msg = "\ \Multiple Cabal versions in a HEAD package-db!\n\ \This shouldn't happen. However you can manually delete the following\n\ \directory to resolve this:\n " invokeGhc :: Env => GhcInvocation -> IO (Either ExitCode FilePath) invokeGhc GhcInvocation {..} = do giOutDirAbs <- makeAbsolute giOutDir giOutputAbs <- makeAbsolute giOutput giIncludeDirsAbs <- mapM makeAbsolute giIncludeDirs giInputsAbs <- mapM makeAbsolute giInputs We unset some interferring envvars here for stack , see : let eos = [("GHC_ENVIRONMENT", EnvUnset), ("GHC_PACKAGE_PATH", EnvUnset)] rv <- callProcessStderr' (Just "/") eos (ghcProgram ?progs) $ concat [ [ "-outputdir", giOutDirAbs , "-o", giOutputAbs ] , map ("-optP"++) giCPPOptions , if giHideAllPackages then ["-hide-all-packages"] else [] , let packageFlags = concatMap (\p -> ["-package", p]) giPackages in case giPackageSource of GPSAmbient -> packageFlags GPSPackageDBs dbs -> concat [ map ("-package-conf="++) $ unPackageDbDir <$> dbs , packageFlags ] GPSPackageEnv env -> [ "-package-env=" ++ unPackageEnvFile env ] , map ("-i"++) $ nub $ "" : giIncludeDirsAbs , giWarningFlags , ["--make"] , giInputsAbs ] return $ case rv of ExitSuccess -> Right giOutput e@(ExitFailure _) -> Left e
4b2d493f0aee177eb84f67eec683465b4654a4414554815403e0b2fe66e8a887
freizl/dive-into-haskell
NatureNum.hs
module NatureNum where data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ s) = 1 + natToInteger s integerToNat :: Integer -> Maybe Nat integerToNat i | i < 0 = Nothing | i == 0 = Just Zero | otherwise = fmap Succ (integerToNat (i - 1)) t1 :: IO () t1 = do print $ natToInteger Zero print $ natToInteger (Succ Zero) print $ natToInteger (Succ (Succ Zero)) print $ integerToNat 0 print $ integerToNat 1 print $ integerToNat 2 print $ integerToNat (-1)
null
https://raw.githubusercontent.com/freizl/dive-into-haskell/b18a6bfe212db6c3a5d707b4a640170b8bcf9330/readings/haskell-book/12/NatureNum.hs
haskell
module NatureNum where data Nat = Zero | Succ Nat deriving (Eq, Show) natToInteger :: Nat -> Integer natToInteger Zero = 0 natToInteger (Succ s) = 1 + natToInteger s integerToNat :: Integer -> Maybe Nat integerToNat i | i < 0 = Nothing | i == 0 = Just Zero | otherwise = fmap Succ (integerToNat (i - 1)) t1 :: IO () t1 = do print $ natToInteger Zero print $ natToInteger (Succ Zero) print $ natToInteger (Succ (Succ Zero)) print $ integerToNat 0 print $ integerToNat 1 print $ integerToNat 2 print $ integerToNat (-1)
e6177141fa7db5248df8db2619d63adaf43002198fb0a4c603a4a57ac002dce9
informatica-unica/lip
fun.ml
open FunLib.Types open FunLib.Prettyprint open FunLib.Main (********************************************************************** trace test : (command, n_steps, location, expected value after n_steps) **********************************************************************) let test_trace = [ ("int x; x:=51", 2, "x", 51); ("int x; x:=0; x:=x+1", 5, "x", 1); ("int x; int y; x:=0; y:=x+1; x:=y+1", 10, "x", 2); ("int x; int y; x:=0; if x=0 then y:=10 else y:=20", 5, "y", 10); ("int x; int y; x:=1; if x=0 then y:=10 else y:=20", 5, "y", 20); ("int x; int y; int r; x:=3; y:=2; r:=0; while 1<=y do ( r:=r+x; y:=y-1 )", 30, "r", 6); ("int x; int y; x:=3; while 0<=x and not 0=x do x:=x-1; x:=5", 50, "x", 5); ("int min; int x; int y; x:=5; y:=3; if x<=y then min:=x else min:=y", 40, "min", 3); ("int min; int x; int y; int z; x:=1; y:=2; z:=3; if x<=y and x<=z then min:=x else ( if y<=z then min:=y else min:=z )", 40, "min", 1); ("int x; fun f(y) { skip; return y+1 }; x := f(10)", 20, "x", 11); ("int x; fun f(y) { skip; return y+1 }; fun g(z) { skip; return f(z)+2 }; x := g(10)", 20, "x", 13); ("int x; int z; fun f(y) { x:=x+1; return x }; x := 10; z := f(0)", 20, "x", 11); ("int x; int z; fun f(y) { x:=x+1; return x }; x := 10; z := f(0)", 20, "z", 11); ("int x; int y; int w; fun f(z) { z:=x; x:=y; y:=z; return 0 }; x := 10; y := 20; w := f(0)", 20, "x", 20); ("int x; int y; int w; fun f(z) { z:=x; x:=y; y:=z; return 0 }; x := 10; y := 20; w := f(0)", 20, "y", 10); ("int x; int y; fun f(x) { x:=20; return 0 }; x := 10; y := f(0); x := x+1", 20, "x", 11); ] let%test _ = print_newline(); print_endline ("*** Testing trace..."); List.fold_left (fun b (ps,n,x,v) -> let p = parse ps in let t = last (trace n p) in (* actual result *) print_string (ps ^ " ->* " ^ string_of_conf (vars_of_prog p) t); let b' = (match t with St st -> apply st x = v | Cmd(_,_) -> failwith "program not terminated") in print_string (" " ^ (if b' then "[OK]" else "[NO : expected " ^ string_of_val v ^ "]")); print_newline(); b && b') true test_trace
null
https://raw.githubusercontent.com/informatica-unica/lip/2ee4e17873a64b04e63ea737a61670ac0766e2d5/imp/fun/test/fun.ml
ocaml
********************************************************************* trace test : (command, n_steps, location, expected value after n_steps) ********************************************************************* actual result
open FunLib.Types open FunLib.Prettyprint open FunLib.Main let test_trace = [ ("int x; x:=51", 2, "x", 51); ("int x; x:=0; x:=x+1", 5, "x", 1); ("int x; int y; x:=0; y:=x+1; x:=y+1", 10, "x", 2); ("int x; int y; x:=0; if x=0 then y:=10 else y:=20", 5, "y", 10); ("int x; int y; x:=1; if x=0 then y:=10 else y:=20", 5, "y", 20); ("int x; int y; int r; x:=3; y:=2; r:=0; while 1<=y do ( r:=r+x; y:=y-1 )", 30, "r", 6); ("int x; int y; x:=3; while 0<=x and not 0=x do x:=x-1; x:=5", 50, "x", 5); ("int min; int x; int y; x:=5; y:=3; if x<=y then min:=x else min:=y", 40, "min", 3); ("int min; int x; int y; int z; x:=1; y:=2; z:=3; if x<=y and x<=z then min:=x else ( if y<=z then min:=y else min:=z )", 40, "min", 1); ("int x; fun f(y) { skip; return y+1 }; x := f(10)", 20, "x", 11); ("int x; fun f(y) { skip; return y+1 }; fun g(z) { skip; return f(z)+2 }; x := g(10)", 20, "x", 13); ("int x; int z; fun f(y) { x:=x+1; return x }; x := 10; z := f(0)", 20, "x", 11); ("int x; int z; fun f(y) { x:=x+1; return x }; x := 10; z := f(0)", 20, "z", 11); ("int x; int y; int w; fun f(z) { z:=x; x:=y; y:=z; return 0 }; x := 10; y := 20; w := f(0)", 20, "x", 20); ("int x; int y; int w; fun f(z) { z:=x; x:=y; y:=z; return 0 }; x := 10; y := 20; w := f(0)", 20, "y", 10); ("int x; int y; fun f(x) { x:=20; return 0 }; x := 10; y := f(0); x := x+1", 20, "x", 11); ] let%test _ = print_newline(); print_endline ("*** Testing trace..."); List.fold_left (fun b (ps,n,x,v) -> let p = parse ps in print_string (ps ^ " ->* " ^ string_of_conf (vars_of_prog p) t); let b' = (match t with St st -> apply st x = v | Cmd(_,_) -> failwith "program not terminated") in print_string (" " ^ (if b' then "[OK]" else "[NO : expected " ^ string_of_val v ^ "]")); print_newline(); b && b') true test_trace
2d067327837b2184e2ddbe3ebb5d98701e2171c9667a118db98327dc0e3f49fc
fourmolu/fourmolu
warning-pragma-list-multiline-four-out.hs
module Test {-# DEPRECATED [ "This module is deprecated." , "Please use OtherModule instead." ] #-} ( foo, bar, baz, ) where
null
https://raw.githubusercontent.com/fourmolu/fourmolu/45256f146648d8006b5a1244446c4ce6d2debafd/data/examples/module-header/warning-pragma-list-multiline-four-out.hs
haskell
# DEPRECATED [ "This module is deprecated." , "Please use OtherModule instead." ] #
module Test foo, bar, baz, ) where
13dac590f62ce4f2d799dfaf185b203079f33a513ef77d3c2f51468e10a769aa
AbstractMachinesLab/caramel
marg.ml
open Std (** {1 Flag parsing utils} *) type 'a t = string list -> 'a -> (string list * 'a) type 'a table = (string, 'a t) Hashtbl.t let unit f : 'a t = fun args acc -> (args, (f acc)) let param ptype f : 'a t = fun args acc -> match args with | [] -> failwith ("expects a " ^ ptype ^ " argument") | arg :: args -> args, f arg acc let unit_ignore : 'a t = fun x -> unit (fun x -> x) x let param_ignore = fun x -> param "string" (fun _ x -> x) x let bool f = param "bool" (function | "yes" | "y" | "Y" | "true" | "True" | "1" -> f true | "no" | "n" | "N" | "false" | "False" | "0" -> f false | str -> failwithf "expecting boolean (%s), got %S." "yes|y|Y|true|1 / no|n|N|false|0" str ) type docstring = string type 'a spec = (string * docstring * 'a t) let rec assoc3 key = function | [] -> raise Not_found | (key', _, value) :: _ when key = key' -> value | _ :: xs -> assoc3 key xs let rec mem_assoc3 key = function | [] -> false | (key', _, _) :: xs -> key = key' || mem_assoc3 key xs let parse_one ~warning global_spec local_spec args global local = match args with | [] -> None | arg :: args -> match Hashtbl.find global_spec arg with | action -> begin match action args global with | (args, global) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> match assoc3 arg local_spec with | action -> begin match action args local with | (args, local) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> None let parse_all ~warning global_spec local_spec = let rec normal_parsing args global local = match parse_one ~warning global_spec local_spec args global local with | Some (args, global, local) -> normal_parsing args global local | None -> match args with | arg :: args -> warning ("unknown flag " ^ arg); resume_parsing args global local | [] -> (global, local) and resume_parsing args global local = let args = match args with | arg :: args when not (Hashtbl.mem global_spec arg || mem_assoc3 arg local_spec) -> args | args -> args in normal_parsing args global local in normal_parsing
null
https://raw.githubusercontent.com/AbstractMachinesLab/caramel/7d4e505d6032e22a630d2e3bd7085b77d0efbb0c/vendor/ocaml-lsp-1.4.0/ocaml-lsp-server/vendor/merlin/src/utils/marg.ml
ocaml
* {1 Flag parsing utils}
open Std type 'a t = string list -> 'a -> (string list * 'a) type 'a table = (string, 'a t) Hashtbl.t let unit f : 'a t = fun args acc -> (args, (f acc)) let param ptype f : 'a t = fun args acc -> match args with | [] -> failwith ("expects a " ^ ptype ^ " argument") | arg :: args -> args, f arg acc let unit_ignore : 'a t = fun x -> unit (fun x -> x) x let param_ignore = fun x -> param "string" (fun _ x -> x) x let bool f = param "bool" (function | "yes" | "y" | "Y" | "true" | "True" | "1" -> f true | "no" | "n" | "N" | "false" | "False" | "0" -> f false | str -> failwithf "expecting boolean (%s), got %S." "yes|y|Y|true|1 / no|n|N|false|0" str ) type docstring = string type 'a spec = (string * docstring * 'a t) let rec assoc3 key = function | [] -> raise Not_found | (key', _, value) :: _ when key = key' -> value | _ :: xs -> assoc3 key xs let rec mem_assoc3 key = function | [] -> false | (key', _, _) :: xs -> key = key' || mem_assoc3 key xs let parse_one ~warning global_spec local_spec args global local = match args with | [] -> None | arg :: args -> match Hashtbl.find global_spec arg with | action -> begin match action args global with | (args, global) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> match assoc3 arg local_spec with | action -> begin match action args local with | (args, local) -> Some (args, global, local) | exception (Failure msg) -> warning ("flag " ^ arg ^ " " ^ msg); Some (args, global, local) | exception exn -> warning ("flag " ^ arg ^ ": error, " ^ Printexc.to_string exn); Some (args, global, local) end | exception Not_found -> None let parse_all ~warning global_spec local_spec = let rec normal_parsing args global local = match parse_one ~warning global_spec local_spec args global local with | Some (args, global, local) -> normal_parsing args global local | None -> match args with | arg :: args -> warning ("unknown flag " ^ arg); resume_parsing args global local | [] -> (global, local) and resume_parsing args global local = let args = match args with | arg :: args when not (Hashtbl.mem global_spec arg || mem_assoc3 arg local_spec) -> args | args -> args in normal_parsing args global local in normal_parsing
d011f8a503b95997cd7e531ac79f0b15096027bc4ecfb4c56aa9697032234719
mfoemmel/erlang-otp
ts_install.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(ts_install). -export([install/2, platform_id/1]). -include("ts.hrl"). install(install_local, Options) -> install(os:type(), Options); install(TargetSystem, Options) -> io:format("Running configure for cross architecture, network target name~n" "~p~n", [TargetSystem]), case autoconf(TargetSystem) of {ok, Vars0} -> OsType = os_type(TargetSystem), Vars1 = ts_erl_config:variables(merge(Vars0,Options),OsType), {Options1, Vars2} = add_vars(Vars1, Options), Vars3 = lists:flatten([Options1|Vars2]), write_terms(?variables, Vars3); {error, Reason} -> {error, Reason} end. os_type({unix,_}=OsType) -> OsType; os_type({win32,_}=OsType) -> OsType; os_type(_Other) -> vxworks. merge(Vars,[]) -> Vars; merge(Vars,[{crossroot,X}| Tail]) -> merge([{crossroot, X} | Vars], Tail); merge(Vars,[_X | Tail]) -> merge(Vars,Tail). Autoconf for various platforms . %% unix uses the configure script win32 uses ts_autoconf_win32 uses ts_autoconf_vxworks . autoconf(TargetSystem) -> case autoconf1(TargetSystem) of ok -> autoconf2(file:read_file("conf_vars")); Error -> Error end. autoconf1({win32, _}) -> ts_autoconf_win32:configure(); autoconf1({unix, _}) -> unix_autoconf(); autoconf1(Other) -> ts_autoconf_vxworks:configure(Other). autoconf2({ok, Bin}) -> get_vars(binary_to_list(Bin), name, [], []); autoconf2(Error) -> Error. get_vars([$:|Rest], name, Current, Result) -> Name = list_to_atom(lists:reverse(Current)), get_vars(Rest, value, [], [Name|Result]); get_vars([$\r|Rest], value, Current, Result) -> get_vars(Rest, value, Current, Result); get_vars([$\n|Rest], value, Current, [Name|Result]) -> Value = lists:reverse(Current), get_vars(Rest, name, [], [{Name, Value}|Result]); get_vars([C|Rest], State, Current, Result) -> get_vars(Rest, State, [C|Current], Result); get_vars([], name, [], Result) -> {ok, Result}; get_vars(_, _, _, _) -> {error, fatal_bad_conf_vars}. unix_autoconf() -> Configure = filename:absname("configure"), Args = case catch erlang:system_info(threads) of false -> ""; _ -> " --enable-shlib-thread-safety" end ++ case catch string:str(erlang:system_info(system_version), "debug") > 0 of false -> ""; _ -> " --enable-debug-mode" end, case filelib:is_file(Configure) of true -> Port = open_port({spawn, Configure ++ Args}, [stream, eof]), ts_lib:print_data(Port); false -> {error, no_configure_script} end. write_terms(Name, Terms) -> case file:open(Name, [write]) of {ok, Fd} -> Result = write_terms1(Fd, Terms), file:close(Fd), Result; {error, Reason} -> {error, Reason} end. write_terms1(Fd, [Term|Rest]) -> ok = io:format(Fd, "~p.\n", [Term]), write_terms1(Fd, Rest); write_terms1(_, []) -> ok. add_vars(Vars0, Opts0) -> {Opts,LongNames} = case lists:keymember(longnames, 1, Opts0) of true -> {lists:keydelete(longnames, 1, Opts0),true}; false -> {Opts0,false} end, {PlatformId, PlatformLabel, PlatformFilename, Version} = platform([{longnames, LongNames}|Vars0]), {Opts, [{longnames, LongNames}, {platform_id, PlatformId}, {platform_filename, PlatformFilename}, {rsh_name, get_rsh_name()}, {platform_label, PlatformLabel}, {erl_flags, []}, {erl_release, Version}, {ts_testcase_callback, get_testcase_callback()} | Vars0]}. get_testcase_callback() -> case os:getenv("TS_TESTCASE_CALLBACK") of ModFunc when is_list(ModFunc), ModFunc /= "" -> case string:tokens(ModFunc, " ") of [_Mod,_Func] -> ModFunc; _ -> "" end; _ -> case init:get_argument(ts_testcase_callback) of {ok,[[Mod,Func]]} -> Mod ++ " " ++ Func; _ -> "" end end. get_rsh_name() -> case os:getenv("ERL_RSH") of false -> case ts_lib:erlang_type() of {clearcase, _} -> "ctrsh"; {_, _} -> "rsh" end; Str -> Str end. platform_id(Vars) -> {Id,_,_,_} = platform(Vars), Id. platform(Vars) -> Hostname = hostname(), {Type,Version} = ts_lib:erlang_type(), Cpu = ts_lib:var('CPU', Vars), Os = ts_lib:var(os, Vars), ErlType = to_upper(atom_to_list(Type)), OsType = ts_lib:initial_capital(Os), CpuType = ts_lib:initial_capital(Cpu), LinuxDist = linux_dist(), ExtraLabel = extra_platform_label(), Schedulers = schedulers(), BindType = bind_type(), KP = kernel_poll(), IOTHR = io_thread(), LC = lock_checking(), MT = modified_timing(), AsyncThreads = async_threads(), HeapType = heap_type_label(), Debug = debug(), CpuBits = word_size(), Common = lists:concat([Hostname,"/",OsType,"/",CpuType,CpuBits,LinuxDist, Schedulers,BindType,KP,IOTHR,LC,MT,AsyncThreads, HeapType,Debug,ExtraLabel]), PlatformId = lists:concat([ErlType, " ", Version, Common]), PlatformLabel = ErlType ++ Common, PlatformFilename = platform_as_filename(PlatformId), {PlatformId, PlatformLabel, PlatformFilename, Version}. platform_as_filename(Label) -> lists:map(fun($ ) -> $_; ($/) -> $_; (C) when $A =< C, C =< $Z -> C - $A + $a; (C) -> C end, Label). to_upper(String) -> lists:map(fun(C) when $a =< C, C =< $z -> C - $a + $A; (C) -> C end, String). word_size() -> case erlang:system_info(wordsize) of 4 -> ""; 8 -> "/64" end. linux_dist() -> case os:type() of {unix,linux} -> linux_dist_1([fun linux_dist_suse/0]); _ -> "" end. linux_dist_1([F|T]) -> case F() of "" -> linux_dist_1(T); Str -> Str end; linux_dist_1([]) -> "". linux_dist_suse() -> case filelib:is_file("/etc/SuSE-release") of false -> ""; true -> Ver0 = os:cmd("awk '/^VERSION/ {print $3}' /etc/SuSE-release"), [_|Ver1] = lists:reverse(Ver0), Ver = lists:reverse(Ver1), "/Suse" ++ Ver end. hostname() -> case catch inet:gethostname() of {ok, Hostname} when is_list(Hostname) -> "/" ++ lists:takewhile(fun (C) -> C /= $. end, Hostname); _ -> "/localhost" end. heap_type_label() -> case catch erlang:system_info(heap_type) of hybrid -> "/Hybrid"; _ -> "" %private end. async_threads() -> case catch erlang:system_info(threads) of true -> "/A"++integer_to_list(erlang:system_info(thread_pool_size)); _ -> "" end. schedulers() -> case catch erlang:system_info(smp_support) of true -> case {erlang:system_info(schedulers), erlang:system_info(schedulers_online)} of {S,S} -> "/S"++integer_to_list(S); {S,O} -> "/S"++integer_to_list(S) ++ ":" ++ integer_to_list(O) end; _ -> "" end. bind_type() -> case catch erlang:system_info(scheduler_bind_type) of thread_no_node_processor_spread -> "/sbttnnps"; no_node_processor_spread -> "/sbtnnps"; no_node_thread_spread -> "/sbtnnts"; processor_spread -> "/sbtps"; thread_spread -> "/sbtts"; no_spread -> "/sbtns"; _ -> "" end. debug() -> case string:str(erlang:system_info(system_version), "debug") of 0 -> ""; _ -> "/Debug" end. lock_checking() -> case catch erlang:system_info(lock_checking) of true -> "/LC"; _ -> "" end. modified_timing() -> case catch erlang:system_info(modified_timing_level) of N when is_integer(N) -> "/T" ++ integer_to_list(N); _ -> "" end. kernel_poll() -> case catch erlang:system_info(kernel_poll) of true -> "/KP"; _ -> "" end. io_thread() -> case catch erlang:system_info(io_thread) of true -> "/IOTHR"; _ -> "" end. extra_platform_label() -> case os:getenv("TS_EXTRA_PLATFORM_LABEL") of [] -> ""; [_|_]=Label -> "/" ++ Label; false -> "" end.
null
https://raw.githubusercontent.com/mfoemmel/erlang-otp/9c6fdd21e4e6573ca6f567053ff3ac454d742bc2/lib/test_server/src/ts_install.erl
erlang
%CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% unix uses the configure script private
Copyright Ericsson AB 1997 - 2009 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " -module(ts_install). -export([install/2, platform_id/1]). -include("ts.hrl"). install(install_local, Options) -> install(os:type(), Options); install(TargetSystem, Options) -> io:format("Running configure for cross architecture, network target name~n" "~p~n", [TargetSystem]), case autoconf(TargetSystem) of {ok, Vars0} -> OsType = os_type(TargetSystem), Vars1 = ts_erl_config:variables(merge(Vars0,Options),OsType), {Options1, Vars2} = add_vars(Vars1, Options), Vars3 = lists:flatten([Options1|Vars2]), write_terms(?variables, Vars3); {error, Reason} -> {error, Reason} end. os_type({unix,_}=OsType) -> OsType; os_type({win32,_}=OsType) -> OsType; os_type(_Other) -> vxworks. merge(Vars,[]) -> Vars; merge(Vars,[{crossroot,X}| Tail]) -> merge([{crossroot, X} | Vars], Tail); merge(Vars,[_X | Tail]) -> merge(Vars,Tail). Autoconf for various platforms . win32 uses ts_autoconf_win32 uses ts_autoconf_vxworks . autoconf(TargetSystem) -> case autoconf1(TargetSystem) of ok -> autoconf2(file:read_file("conf_vars")); Error -> Error end. autoconf1({win32, _}) -> ts_autoconf_win32:configure(); autoconf1({unix, _}) -> unix_autoconf(); autoconf1(Other) -> ts_autoconf_vxworks:configure(Other). autoconf2({ok, Bin}) -> get_vars(binary_to_list(Bin), name, [], []); autoconf2(Error) -> Error. get_vars([$:|Rest], name, Current, Result) -> Name = list_to_atom(lists:reverse(Current)), get_vars(Rest, value, [], [Name|Result]); get_vars([$\r|Rest], value, Current, Result) -> get_vars(Rest, value, Current, Result); get_vars([$\n|Rest], value, Current, [Name|Result]) -> Value = lists:reverse(Current), get_vars(Rest, name, [], [{Name, Value}|Result]); get_vars([C|Rest], State, Current, Result) -> get_vars(Rest, State, [C|Current], Result); get_vars([], name, [], Result) -> {ok, Result}; get_vars(_, _, _, _) -> {error, fatal_bad_conf_vars}. unix_autoconf() -> Configure = filename:absname("configure"), Args = case catch erlang:system_info(threads) of false -> ""; _ -> " --enable-shlib-thread-safety" end ++ case catch string:str(erlang:system_info(system_version), "debug") > 0 of false -> ""; _ -> " --enable-debug-mode" end, case filelib:is_file(Configure) of true -> Port = open_port({spawn, Configure ++ Args}, [stream, eof]), ts_lib:print_data(Port); false -> {error, no_configure_script} end. write_terms(Name, Terms) -> case file:open(Name, [write]) of {ok, Fd} -> Result = write_terms1(Fd, Terms), file:close(Fd), Result; {error, Reason} -> {error, Reason} end. write_terms1(Fd, [Term|Rest]) -> ok = io:format(Fd, "~p.\n", [Term]), write_terms1(Fd, Rest); write_terms1(_, []) -> ok. add_vars(Vars0, Opts0) -> {Opts,LongNames} = case lists:keymember(longnames, 1, Opts0) of true -> {lists:keydelete(longnames, 1, Opts0),true}; false -> {Opts0,false} end, {PlatformId, PlatformLabel, PlatformFilename, Version} = platform([{longnames, LongNames}|Vars0]), {Opts, [{longnames, LongNames}, {platform_id, PlatformId}, {platform_filename, PlatformFilename}, {rsh_name, get_rsh_name()}, {platform_label, PlatformLabel}, {erl_flags, []}, {erl_release, Version}, {ts_testcase_callback, get_testcase_callback()} | Vars0]}. get_testcase_callback() -> case os:getenv("TS_TESTCASE_CALLBACK") of ModFunc when is_list(ModFunc), ModFunc /= "" -> case string:tokens(ModFunc, " ") of [_Mod,_Func] -> ModFunc; _ -> "" end; _ -> case init:get_argument(ts_testcase_callback) of {ok,[[Mod,Func]]} -> Mod ++ " " ++ Func; _ -> "" end end. get_rsh_name() -> case os:getenv("ERL_RSH") of false -> case ts_lib:erlang_type() of {clearcase, _} -> "ctrsh"; {_, _} -> "rsh" end; Str -> Str end. platform_id(Vars) -> {Id,_,_,_} = platform(Vars), Id. platform(Vars) -> Hostname = hostname(), {Type,Version} = ts_lib:erlang_type(), Cpu = ts_lib:var('CPU', Vars), Os = ts_lib:var(os, Vars), ErlType = to_upper(atom_to_list(Type)), OsType = ts_lib:initial_capital(Os), CpuType = ts_lib:initial_capital(Cpu), LinuxDist = linux_dist(), ExtraLabel = extra_platform_label(), Schedulers = schedulers(), BindType = bind_type(), KP = kernel_poll(), IOTHR = io_thread(), LC = lock_checking(), MT = modified_timing(), AsyncThreads = async_threads(), HeapType = heap_type_label(), Debug = debug(), CpuBits = word_size(), Common = lists:concat([Hostname,"/",OsType,"/",CpuType,CpuBits,LinuxDist, Schedulers,BindType,KP,IOTHR,LC,MT,AsyncThreads, HeapType,Debug,ExtraLabel]), PlatformId = lists:concat([ErlType, " ", Version, Common]), PlatformLabel = ErlType ++ Common, PlatformFilename = platform_as_filename(PlatformId), {PlatformId, PlatformLabel, PlatformFilename, Version}. platform_as_filename(Label) -> lists:map(fun($ ) -> $_; ($/) -> $_; (C) when $A =< C, C =< $Z -> C - $A + $a; (C) -> C end, Label). to_upper(String) -> lists:map(fun(C) when $a =< C, C =< $z -> C - $a + $A; (C) -> C end, String). word_size() -> case erlang:system_info(wordsize) of 4 -> ""; 8 -> "/64" end. linux_dist() -> case os:type() of {unix,linux} -> linux_dist_1([fun linux_dist_suse/0]); _ -> "" end. linux_dist_1([F|T]) -> case F() of "" -> linux_dist_1(T); Str -> Str end; linux_dist_1([]) -> "". linux_dist_suse() -> case filelib:is_file("/etc/SuSE-release") of false -> ""; true -> Ver0 = os:cmd("awk '/^VERSION/ {print $3}' /etc/SuSE-release"), [_|Ver1] = lists:reverse(Ver0), Ver = lists:reverse(Ver1), "/Suse" ++ Ver end. hostname() -> case catch inet:gethostname() of {ok, Hostname} when is_list(Hostname) -> "/" ++ lists:takewhile(fun (C) -> C /= $. end, Hostname); _ -> "/localhost" end. heap_type_label() -> case catch erlang:system_info(heap_type) of hybrid -> "/Hybrid"; end. async_threads() -> case catch erlang:system_info(threads) of true -> "/A"++integer_to_list(erlang:system_info(thread_pool_size)); _ -> "" end. schedulers() -> case catch erlang:system_info(smp_support) of true -> case {erlang:system_info(schedulers), erlang:system_info(schedulers_online)} of {S,S} -> "/S"++integer_to_list(S); {S,O} -> "/S"++integer_to_list(S) ++ ":" ++ integer_to_list(O) end; _ -> "" end. bind_type() -> case catch erlang:system_info(scheduler_bind_type) of thread_no_node_processor_spread -> "/sbttnnps"; no_node_processor_spread -> "/sbtnnps"; no_node_thread_spread -> "/sbtnnts"; processor_spread -> "/sbtps"; thread_spread -> "/sbtts"; no_spread -> "/sbtns"; _ -> "" end. debug() -> case string:str(erlang:system_info(system_version), "debug") of 0 -> ""; _ -> "/Debug" end. lock_checking() -> case catch erlang:system_info(lock_checking) of true -> "/LC"; _ -> "" end. modified_timing() -> case catch erlang:system_info(modified_timing_level) of N when is_integer(N) -> "/T" ++ integer_to_list(N); _ -> "" end. kernel_poll() -> case catch erlang:system_info(kernel_poll) of true -> "/KP"; _ -> "" end. io_thread() -> case catch erlang:system_info(io_thread) of true -> "/IOTHR"; _ -> "" end. extra_platform_label() -> case os:getenv("TS_EXTRA_PLATFORM_LABEL") of [] -> ""; [_|_]=Label -> "/" ++ Label; false -> "" end.
0cc3bc2682e056df9e84e2bd880f653da5dee4e3eacc0b4f590b339f3ca5e9ae
Provisdom/defn-spec
core_test.cljc
(ns defn-spec.core-test #?(:cljs (:require-macros [defn-spec.core-test :refer [is-error-thrown is-exception-thrown without-asserts]])) (:require #?(:cljs [cljs.test :refer-macros [deftest is testing]] :clj [clojure.test :refer [deftest is testing]]) [clojure.spec.alpha :as s] [defn-spec.core :as f])) #?(:clj (defn- cljs-env? "Take the &env from a macro, and tell whether we are expanding into cljs." [env] (boolean (:ns env)))) #?(:clj (defmacro is-exception-thrown "(is (thrown-with-msg? ...)) for specified exceptions in Clojure/ClojureScript." [clj-exc-class cljs-exc-class re expr msg] (let [is (if (cljs-env? &env) 'cljs.test/is 'clojure.test/is) exc-class (if (cljs-env? &env) cljs-exc-class clj-exc-class)] `(~is (~'thrown-with-msg? ~exc-class ~re ~expr) ~msg)))) #?(:clj (defmacro is-error-thrown "(is (thrown-with-msg? ...)) for general exceptions in Clojure/ClojureScript." ([re expr] `(is-exception-thrown java.lang.Exception js/Error ~re ~expr nil)) ([re expr msg] `(is-exception-thrown java.lang.Exception js/Error ~re ~expr ~msg)))) (s/check-asserts true) (f/defn-spec arity-1-fn {::f/args (s/cat :x int?) ::f/ret nat-int?} [x] (inc x)) (f/defn-spec n-arity-fn "docstring" {::f/args (s/cat :x int? :y (s/? int?)) ::f/ret nat-int?} ([x] (n-arity-fn x 0)) ([x y] (+ x y))) (deftest test-function-calls (testing "arity 1" (is (arity-1-fn 1)) (is-error-thrown #"did not conform to spec" (arity-1-fn "") "args vec is checked") (is (= -1 (arity-1-fn -2)) "Return value is NOT checked.")) (testing "N arity" (is (= 1 (n-arity-fn 1))) (is (= 3 (n-arity-fn 1 2))) (is (= "docstring" (:doc (meta #'n-arity-fn)))) (is-error-thrown #"did not conform to spec" (n-arity-fn 1 "2")) (is (= -1 (n-arity-fn -1 0))))) ;; These are only expected to pass it orchestra is on the classpath #?(:clj (deftest ^:orchestra test-function-calls-ret-checking (testing "Return value is checked." (is-error-thrown #"did not conform to spec" (arity-1-fn -2))) (is-error-thrown #"did not conform to spec" (n-arity-fn -1 0)))) #?(:clj (defmacro without-asserts [& body] (eval `(binding [s/*compile-asserts* false] (macroexpand-1 (quote ~@body)))))) (without-asserts (f/defn-spec no-asserts {::f/args (s/cat :a number? :b (s/? number?))} ([a] "a") ([a b] "a b"))) (deftest ^:production test-compile-asserts-false (is (no-asserts "1"))) (defn instrumented-fn [x] (inc x)) (f/fdef instrumented-fn :args (s/cat :x number?) :ret number?) (deftest test-fdef (is (instrumented-fn 1)) (is-error-thrown #"did not conform to spec" (instrumented-fn "")))
null
https://raw.githubusercontent.com/Provisdom/defn-spec/aabd8bdd3fb3e2eb5b7988803335f62dc76cdc5f/test/defn_spec/core_test.cljc
clojure
These are only expected to pass it orchestra is on the classpath
(ns defn-spec.core-test #?(:cljs (:require-macros [defn-spec.core-test :refer [is-error-thrown is-exception-thrown without-asserts]])) (:require #?(:cljs [cljs.test :refer-macros [deftest is testing]] :clj [clojure.test :refer [deftest is testing]]) [clojure.spec.alpha :as s] [defn-spec.core :as f])) #?(:clj (defn- cljs-env? "Take the &env from a macro, and tell whether we are expanding into cljs." [env] (boolean (:ns env)))) #?(:clj (defmacro is-exception-thrown "(is (thrown-with-msg? ...)) for specified exceptions in Clojure/ClojureScript." [clj-exc-class cljs-exc-class re expr msg] (let [is (if (cljs-env? &env) 'cljs.test/is 'clojure.test/is) exc-class (if (cljs-env? &env) cljs-exc-class clj-exc-class)] `(~is (~'thrown-with-msg? ~exc-class ~re ~expr) ~msg)))) #?(:clj (defmacro is-error-thrown "(is (thrown-with-msg? ...)) for general exceptions in Clojure/ClojureScript." ([re expr] `(is-exception-thrown java.lang.Exception js/Error ~re ~expr nil)) ([re expr msg] `(is-exception-thrown java.lang.Exception js/Error ~re ~expr ~msg)))) (s/check-asserts true) (f/defn-spec arity-1-fn {::f/args (s/cat :x int?) ::f/ret nat-int?} [x] (inc x)) (f/defn-spec n-arity-fn "docstring" {::f/args (s/cat :x int? :y (s/? int?)) ::f/ret nat-int?} ([x] (n-arity-fn x 0)) ([x y] (+ x y))) (deftest test-function-calls (testing "arity 1" (is (arity-1-fn 1)) (is-error-thrown #"did not conform to spec" (arity-1-fn "") "args vec is checked") (is (= -1 (arity-1-fn -2)) "Return value is NOT checked.")) (testing "N arity" (is (= 1 (n-arity-fn 1))) (is (= 3 (n-arity-fn 1 2))) (is (= "docstring" (:doc (meta #'n-arity-fn)))) (is-error-thrown #"did not conform to spec" (n-arity-fn 1 "2")) (is (= -1 (n-arity-fn -1 0))))) #?(:clj (deftest ^:orchestra test-function-calls-ret-checking (testing "Return value is checked." (is-error-thrown #"did not conform to spec" (arity-1-fn -2))) (is-error-thrown #"did not conform to spec" (n-arity-fn -1 0)))) #?(:clj (defmacro without-asserts [& body] (eval `(binding [s/*compile-asserts* false] (macroexpand-1 (quote ~@body)))))) (without-asserts (f/defn-spec no-asserts {::f/args (s/cat :a number? :b (s/? number?))} ([a] "a") ([a b] "a b"))) (deftest ^:production test-compile-asserts-false (is (no-asserts "1"))) (defn instrumented-fn [x] (inc x)) (f/fdef instrumented-fn :args (s/cat :x number?) :ret number?) (deftest test-fdef (is (instrumented-fn 1)) (is-error-thrown #"did not conform to spec" (instrumented-fn "")))
dc6bbd7ae75a2ff8446b42355136a7aeb00d4424777ec80ab92677b206f6bfee
janestreet/core
test_avltree.ml
open! Core open Expect_test_helpers_core module Int_option = struct type t = int option [@@deriving equal, sexp_of] end let invariant tree = Avltree.invariant tree ~compare; Avltree.iter tree ~f:(fun ~key ~data -> assert (key = data)) ;; let require_is_absent tree int = require [%here] (not (Avltree.mem tree ~compare int)) let require_is_present tree int = require [%here] (Avltree.mem tree ~compare int); require_equal [%here] (module Int_option) (Avltree.find tree ~compare int) (Some int) ;; let require_equivalent_set tree set = let from_iter = ref Int.Set.empty in Avltree.iter tree ~f:(fun ~key:int ~data:_ -> from_iter := Set.add !from_iter int); let from_fold = Avltree.fold tree ~init:Int.Set.empty ~f:(fun ~key:int ~data:_ set -> Set.add set int) in require_sets_are_equal [%here] !from_iter from_fold; require_sets_are_equal [%here] !from_iter set ;; let require_ref_mutated f ~to_:expect = let r = ref (not expect) in let return = f r in require_equal [%here] (module Bool) !r expect; return ;; module Operation = struct type t = | Add | Add_if_not_exists | Remove [@@deriving equal, quickcheck, sexp_of] let perform t int avltree set = let is_present = Avltree.mem avltree ~compare int in let avltree, set = match t with | Add -> let avltree = require_ref_mutated ~to_:(not is_present) (fun added -> Avltree.add avltree ~replace:true ~compare ~added ~key:int ~data:int) in require_is_present avltree int; let set = Set.add set int in avltree, set | Add_if_not_exists -> let avltree = require_ref_mutated ~to_:(not is_present) (fun added -> (* if buggy, this will replace the data with the wrong value *) Avltree.add avltree ~replace:false ~compare ~added ~key:int ~data:(if is_present then int + 1 else int)) in require_is_present avltree int; let set = Set.add set int in avltree, set | Remove -> let avltree = require_ref_mutated ~to_:is_present (fun removed -> Avltree.remove avltree ~removed ~compare int) in require_is_absent avltree int; let set = Set.remove set int in avltree, set in invariant avltree; require_equivalent_set avltree set ;; end let operation_printed_crs = ref false let () = let old = !on_print_cr in on_print_cr := fun cr -> operation_printed_crs := true; old cr ;; module Operation_sequence = struct module Data = struct type t = int [@@deriving equal, quickcheck, sexp_of] let quickcheck_generator = Base_quickcheck.Generator.small_positive_or_zero_int end type t = (Operation.t * Data.t) list [@@deriving equal, quickcheck, sexp_of] end let size = 1000 let data_sorted = List.init size ~f:Fn.id let data_reverse_sorted = data_sorted |> List.rev let add_then_remove_sorted = let%bind.List operation = [ Operation.Add; Remove ] in let%map.List int = data_sorted in operation, int ;; let add_then_remove_reverse_sorted = let%bind.List operation = [ Operation.Add; Remove ] in let%map.List int = data_reverse_sorted in operation, int ;; let%expect_test "random operations" = quickcheck_m [%here] (module Operation_sequence) ~examples:[ add_then_remove_sorted; add_then_remove_reverse_sorted ] ~f:(fun operations -> List.fold_until operations ~init:(Avltree.empty, Int.Set.empty) ~f:(fun (t, s) (operation, int) -> operation_printed_crs := false; Operation.perform operation int t s; if !operation_printed_crs then Stop () else Continue (t, s)) ~finish:(ignore : (int, int) Avltree.t * Int.Set.t -> unit)); [%expect {| |}] ;;
null
https://raw.githubusercontent.com/janestreet/core/4b6635d206f7adcfac8324820d246299d6f572fe/core/test/test_avltree.ml
ocaml
if buggy, this will replace the data with the wrong value
open! Core open Expect_test_helpers_core module Int_option = struct type t = int option [@@deriving equal, sexp_of] end let invariant tree = Avltree.invariant tree ~compare; Avltree.iter tree ~f:(fun ~key ~data -> assert (key = data)) ;; let require_is_absent tree int = require [%here] (not (Avltree.mem tree ~compare int)) let require_is_present tree int = require [%here] (Avltree.mem tree ~compare int); require_equal [%here] (module Int_option) (Avltree.find tree ~compare int) (Some int) ;; let require_equivalent_set tree set = let from_iter = ref Int.Set.empty in Avltree.iter tree ~f:(fun ~key:int ~data:_ -> from_iter := Set.add !from_iter int); let from_fold = Avltree.fold tree ~init:Int.Set.empty ~f:(fun ~key:int ~data:_ set -> Set.add set int) in require_sets_are_equal [%here] !from_iter from_fold; require_sets_are_equal [%here] !from_iter set ;; let require_ref_mutated f ~to_:expect = let r = ref (not expect) in let return = f r in require_equal [%here] (module Bool) !r expect; return ;; module Operation = struct type t = | Add | Add_if_not_exists | Remove [@@deriving equal, quickcheck, sexp_of] let perform t int avltree set = let is_present = Avltree.mem avltree ~compare int in let avltree, set = match t with | Add -> let avltree = require_ref_mutated ~to_:(not is_present) (fun added -> Avltree.add avltree ~replace:true ~compare ~added ~key:int ~data:int) in require_is_present avltree int; let set = Set.add set int in avltree, set | Add_if_not_exists -> let avltree = require_ref_mutated ~to_:(not is_present) (fun added -> Avltree.add avltree ~replace:false ~compare ~added ~key:int ~data:(if is_present then int + 1 else int)) in require_is_present avltree int; let set = Set.add set int in avltree, set | Remove -> let avltree = require_ref_mutated ~to_:is_present (fun removed -> Avltree.remove avltree ~removed ~compare int) in require_is_absent avltree int; let set = Set.remove set int in avltree, set in invariant avltree; require_equivalent_set avltree set ;; end let operation_printed_crs = ref false let () = let old = !on_print_cr in on_print_cr := fun cr -> operation_printed_crs := true; old cr ;; module Operation_sequence = struct module Data = struct type t = int [@@deriving equal, quickcheck, sexp_of] let quickcheck_generator = Base_quickcheck.Generator.small_positive_or_zero_int end type t = (Operation.t * Data.t) list [@@deriving equal, quickcheck, sexp_of] end let size = 1000 let data_sorted = List.init size ~f:Fn.id let data_reverse_sorted = data_sorted |> List.rev let add_then_remove_sorted = let%bind.List operation = [ Operation.Add; Remove ] in let%map.List int = data_sorted in operation, int ;; let add_then_remove_reverse_sorted = let%bind.List operation = [ Operation.Add; Remove ] in let%map.List int = data_reverse_sorted in operation, int ;; let%expect_test "random operations" = quickcheck_m [%here] (module Operation_sequence) ~examples:[ add_then_remove_sorted; add_then_remove_reverse_sorted ] ~f:(fun operations -> List.fold_until operations ~init:(Avltree.empty, Int.Set.empty) ~f:(fun (t, s) (operation, int) -> operation_printed_crs := false; Operation.perform operation int t s; if !operation_printed_crs then Stop () else Continue (t, s)) ~finish:(ignore : (int, int) Avltree.t * Int.Set.t -> unit)); [%expect {| |}] ;;
0c8fb49646f86dae7954e40f49c4bbd2c2a69cdc9f0b80678e554245997f4960
sealchain-project/sealchain
Core.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE GADTs # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Rank2Types #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # {-# LANGUAGE TypeOperators #-} # options_ghc -fno - warn - redundant - constraints # -- | Symbolic evaluation for the functionally pure subset of expressions that are shared by all three languages : ' Term ' , ' Prop ' , and ' Invariant ' . module Pact.Analyze.Eval.Core where import Control.Lens (over) import Data.Foldable (asum) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.SBV (EqSymbolic ((./=), (.==)), OrdSymbolic ((.<), (.<=), (.>), (.>=)), SBV, SymVal, ite, literal, uninterpret, unliteral) import Data.SBV.List ((.:)) import qualified Data.SBV.List as SBVL import qualified Data.SBV.String as SBVS import Data.SBV.Tools.BoundedList (band, bfoldr, bfoldrM, bmapM, breverse, bsort, bzipWith) import Data.SBV.Tuple (tuple, _1, _2) import qualified Data.Text as T import Data.Type.Equality ((:~:) (Refl)) import GHC.Stack import GHC.TypeLits (symbolVal) import Pact.Analyze.Errors import Pact.Analyze.Eval.Numerical import Pact.Analyze.Types import Pact.Analyze.Types.Eval import Pact.Analyze.Util (Boolean (..), vacuousMatch) import qualified Pact.Native as Pact import Pact.Types.Pretty (renderCompactString) -- | Bound on the size of lists we check. This may be user-configurable in the -- future. listBound :: Int listBound = 10 -- Note [Time Representation] -- Pact uses the Thyme library ( UTCTime ) to represent times . Thyme internally uses a 64 - bit count of microseconds since the MJD epoch . So , our symbolic representation is naturally a 64 - bit integer . -- The effect from a Pact - user 's point of view is that we store 6 digits to -- the right of the decimal point in times (even though we don't print -- sub-second precision by default...). -- pact > ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) " 2016 - 07 - 23T13:30:45Z " pact > (= ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.0010021 ) ) -- true pact > (= ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001003 ) ) -- false evalIntAddTime :: Analyzer m => TermOf m 'TyTime -> TermOf m 'TyInteger -> m (S Time) evalIntAddTime timeT secsT = do time <- eval timeT secs <- eval secsT Convert seconds to milliseconds /before/ conversion to Integer ( see note -- [Time Representation]). pure $ time + fromIntegralS (secs * 1000000) evalDecAddTime :: Analyzer m => TermOf m 'TyTime -> TermOf m 'TyDecimal -> m (S Time) evalDecAddTime timeT secsT = do time <- eval timeT secs <- eval secsT if isConcreteS secs Convert seconds to milliseconds /before/ conversion to Integer ( see note -- [Time Representation]). then pure $ time + fromIntegralS (banker'sMethodS (secs * fromInteger' 1000000)) else throwErrorNoLoc $ PossibleRoundoff "A time being added is not concrete, so we can't guarantee that roundoff won't happen when it's converted to an integer." evalComparisonOp :: forall m a. Analyzer m => SingTy a -> ComparisonOp -> TermOf m a -> TermOf m a -> m (S Bool) evalComparisonOp ty op xT yT = withOrd ty $ do x <- withSing ty $ eval xT y <- withSing ty $ eval yT let f :: SymVal (Concrete a) => SBV Bool f = case op of Gt -> x .> y Lt -> x .< y Gte -> x .>= y Lte -> x .<= y Eq -> x .== y Neq -> x ./= y pure $ sansProv $ withSymVal ty f singIte :: forall m a a'. (Analyzer m, a' ~ Concrete a, SingI a) => SingTy a -> SBV Bool -> m (S a') -> m (S a') -> m (S a') singIte ty a b c = withSymVal ty $ withMergeableAnalyzer @m ty $ ite a b c evalLogicalOp :: Analyzer m => LogicalOp -> [TermOf m 'TyBool] -> m (S Bool) evalLogicalOp AndOp [a, b] = do a' <- eval a singIte SBool (_sSbv a') (eval b) (pure sFalse) evalLogicalOp OrOp [a, b] = do a' <- eval a singIte SBool (_sSbv a') (pure sTrue) (eval b) evalLogicalOp NotOp [a] = sNot <$> eval a evalLogicalOp op terms = throwErrorNoLoc $ MalformedLogicalOpExec op $ length terms evalCore :: forall m a. (Analyzer m, SingI a) => Core (TermOf m) a -> m (S (Concrete a)) evalCore (Lit a) = withSymVal (sing :: SingTy a) $ pure $ literalS a evalCore (Sym s) = pure s evalCore (Var vid name) = do mVal <- getVar vid case mVal of Nothing -> throwErrorNoLoc $ VarNotInScope name vid Just (AVal mProv sval) -> pure $ mkS mProv sval Just OpaqueVal -> throwErrorNoLoc OpaqueValEncountered evalCore (Identity _ a) = eval a evalCore (Constantly _ a _) = eval a evalCore (Compose tya tyb _ a (Open vida _nma tmb) (Open vidb _nmb tmc)) = do a' <- withSing tya $ eval a b' <- withVar vida (mkAVal a') $ withSing tyb $ eval tmb withVar vidb (mkAVal b') $ eval tmc evalCore (StrConcat p1 p2) = (.++) <$> eval p1 <*> eval p2 evalCore (StrLength p) = over s2Sbv SBVS.length . coerceS @Str @String <$> eval p evalCore (StrToInt s) = evalStrToInt s evalCore (StrToIntBase b s) = evalStrToIntBase b s evalCore (Numerical a) = evalNumerical a evalCore (IntAddTime time secs) = evalIntAddTime time secs evalCore (DecAddTime time secs) = evalDecAddTime time secs evalCore (Comparison ty op x y) = evalComparisonOp ty op x y evalCore (Logical op props) = evalLogicalOp op props evalCore (ObjAt schema colNameT objT) = evalObjAt schema colNameT objT (sing :: SingTy a) evalCore (LiteralObject SObjectNil (Object SNil)) = pure $ literalS () evalCore (LiteralObject (SObjectCons _ ty tys) (Object (SCons _ (Column _ val) vals))) = do let objTy = SObjectUnsafe tys withSing objTy $ withSymVal ty $ withSymVal objTy $ do S _ val' <- eval val S _ vals' <- evalCore $ LiteralObject objTy $ Object vals pure $ sansProv $ tuple (val', vals') evalCore LiteralObject{} = vacuousMatch "previous two cases cover all literal objects" evalCore (ObjMerge ty1@(SObject schema1) ty2@(SObject schema2) obj1 obj2) = withSing ty1 $ withSing ty2 $ do S _ obj1' <- eval obj1 S _ obj2' <- eval obj2 case sing @a of SObject schema -> pure $ sansProv $ evalObjMerge' (obj1' :< schema1) (obj2' :< schema2) schema _ -> throwErrorNoLoc "this must be an object" evalCore ObjMerge{} = throwErrorNoLoc "both types must be objects" evalCore (ObjContains (SObjectUnsafe schema) key _obj) = hasKey schema <$> eval key evalCore (StrContains needle haystack) = do needle' <- eval needle haystack' <- eval haystack pure $ sansProv $ _sSbv (coerceS @Str @String needle') `SBVS.isInfixOf` _sSbv (coerceS @Str @String haystack') evalCore (ListContains ty needle haystack) = withSymVal ty $ do S _ needle' <- withSing ty $ eval needle S _ haystack' <- withSing ty $ eval haystack pure $ sansProv $ bfoldr listBound (\cell rest -> cell .== needle' .|| rest) sFalse haystack' evalCore (ListEqNeq ty op a b) = withSymVal ty $ do S _ a' <- withSing ty $ eval a S _ b' <- withSing ty $ eval b let sameList = SBVL.length a' .== SBVL.length b' .&& band listBound (bzipWith listBound (.==) a' b') pure $ sansProv $ case op of Eq' -> sameList Neq' -> sNot sameList evalCore (ListAt ty i l) = withSymVal ty $ do S _ i' <- eval i S _ l' <- eval l -- valid range [0..length l - 1] markFailure $ i' .< 0 .|| i' .>= SBVL.length l' -- statically build a list of index comparisons pure $ sansProv $ SBVL.elemAt l' i' evalCore (ListLength ty l) = withSymVal ty $ withSing ty $ do S prov l' <- eval l pure $ S prov $ SBVL.length l' evalCore (LiteralList ty xs) = withSymVal ty $ withSing ty $ do vals <- traverse (fmap _sSbv . eval) xs pure $ sansProv $ SBVL.implode vals evalCore (ListDrop ty n list) = withSymVal ty $ withSing ty $ do S _ n' <- eval n S _ list' <- eval list -- if the index is positive, count from the start of the list, otherwise -- count from the end. pure $ sansProv $ ite (n' .>= 0) (SBVL.drop n' list') (SBVL.take (SBVL.length list' + n') list') evalCore (ListTake ty n list) = withSymVal ty $ withSing ty $ do S _ n' <- eval n S _ list' <- eval list -- if the index is positive, count from the start of the list, otherwise -- count from the end. pure $ sansProv $ ite (n' .>= 0) (SBVL.take n' list') (SBVL.drop (SBVL.length list' + n') list') evalCore (ListConcat ty p1 p2) = withSymVal ty $ withSing ty $ do S _ p1' <- eval p1 S _ p2' <- eval p2 pure $ sansProv $ SBVL.concat p1' p2' evalCore (ListReverse ty l) = withSymVal ty $ withSing ty $ do S prov l' <- eval l pure $ S prov $ breverse listBound l' evalCore (ListSort ty l) = withSymVal ty $ withSing ty $ withOrd ty $ do S prov l' <- eval l pure $ S prov $ bsort listBound l' evalCore (MakeList ty i a) = withSymVal ty $ withSing ty $ do S _ i' <- eval i S _ a' <- eval a case unliteral i' of Just i'' -> pure $ sansProv $ SBVL.implode $ replicate (fromInteger i'') a' Nothing -> throwErrorNoLoc $ UnhandledTerm "make-list currently requires a statically determined length" evalCore (ListMap tya tyb (Open vid _ expr) as) = withSymVal tya $ withSymVal tyb $ withSing tya $ withSing tyb $ withMergeableAnalyzer @m (SList tyb) $ do S _ as' <- eval as bs <- bmapM listBound (\val -> _sSbv <$> withVar vid (mkAVal' val) (eval expr)) as' pure $ sansProv bs evalCore (ListFilter tya (Open vid _ f) as) = withSymVal tya $ withMergeableAnalyzer @m (SList tya) $ do S _ as' <- eval as let bfilterM = bfoldrM listBound (\sbva svblst -> do S _ x' <- withVar vid (mkAVal' sbva) (eval f) pure $ ite x' (sbva .: svblst) svblst) (literal []) sansProv <$> bfilterM as' evalCore (ListFold tya tyb (Open vid1 _ (Open vid2 _ f)) a bs) = withSymVal tya $ withSymVal tyb $ withSing tyb $ withMergeableAnalyzer @m tya $ do S _ a' <- eval a S _ bs' <- eval bs result <- bfoldrM listBound (\sbvb sbva -> fmap _sSbv $ withVar vid1 (mkAVal' sbvb) $ withVar vid2 (mkAVal' sbva) $ eval f) a' bs' pure $ sansProv result evalCore (AndQ tya (Open vid1 _ f) (Open vid2 _ g) a) = do S _ a' <- withSing tya $ eval a fv <- withVar vid1 (mkAVal' a') $ eval f gv <- withVar vid2 (mkAVal' a') $ eval g pure $ fv .&& gv evalCore (OrQ tya (Open vid1 _ f) (Open vid2 _ g) a) = do S _ a' <- withSing tya $ eval a fv <- withVar vid1 (mkAVal' a') $ eval f gv <- withVar vid2 (mkAVal' a') $ eval g pure $ fv .|| gv evalCore (Where schema tya key (Open vid _ f) obj) = withSymVal tya $ do S _ v <- evalObjAt schema key obj tya withVar vid (mkAVal' v) $ eval f -- TODO: we need to be very careful here with non-ground types evalCore (Typeof tya _a) = pure $ literalS $ Str $ renderCompactString tya evalCore (GuardEqNeq op xT yT) = do x <- eval xT y <- eval yT pure $ sansProv $ case op of Eq' -> x .== y Neq' -> x ./= y evalCore (ObjectEqNeq SObjectNil SObjectNil eqNeq _ _) = pure $ case eqNeq of { Eq' -> sTrue; Neq' -> sFalse } evalCore (ObjectEqNeq SObjectNil SObjectCons{} eqNeq _ _) = pure $ case eqNeq of { Eq' -> sFalse; Neq' -> sTrue } evalCore (ObjectEqNeq SObjectCons{} SObjectNil eqNeq _ _) = pure $ case eqNeq of { Eq' -> sFalse; Neq' -> sTrue } evalCore (ObjectEqNeq objTy1@(SObject schema@SCons'{}) objTy2@(SObject SCons'{}) eqNeq obj1 obj2) = case singEq objTy1 objTy2 of Nothing -> pure sFalse Just Refl -> withSing objTy1 $ do S _ obj1' <- eval obj1 S _ obj2' <- eval obj2 let go :: SingList tys -> SBV (Concrete ('TyObject tys)) -> SBV (Concrete ('TyObject tys)) -> SBV Bool go SNil' _ _ = sTrue go (SCons' _ colTy' schema') objA objB = withSymVal colTy' $ withSymVal (SObjectUnsafe schema') $ _1 objA .== _1 objB .&& go schema' (_2 objA) (_2 objB) let objsEq = go schema obj1' obj2' pure $ sansProv $ case eqNeq of { Eq' -> objsEq; Neq' -> sNot objsEq } evalCore (ObjectEqNeq _ _ _ _ _) = vacuousMatch "covered by previous case" evalCore (ObjDrop ty@(SObjectUnsafe schema') _keys obj) = withSing ty $ do S prov obj' <- eval obj case sing @a of SObjectUnsafe schema -> pure $ S prov $ evalDropTake (obj' :< schema') schema evalCore (ObjTake ty@(SObjectUnsafe schema') _keys obj) = withSing ty $ do S prov obj' <- eval obj case sing @a of SObjectUnsafe schema -> pure $ S prov $ evalDropTake (obj' :< schema') schema -- | Implementation for both drop and take. -- We @schema@ -- the type of the object we 're starting with , and @schema'@ -- the type we need to produce . @schema'@ must be a sub - list of -- Therefore, we work through the elements of the object one at a time, keeping -- the ones that go in the resulting object. evalDropTake :: HasCallStack => SBV (ConcreteObj schema) :< SingList schema -> SingList schema' -> SBV (ConcreteObj schema') evalDropTake _ SNil' = literal () evalDropTake (obj :< SingList (SCons k ty ks )) schema'@(SingList (SCons k' ty' ks')) = withHasKind ty $ withSymVal (SObjectUnsafe (SingList ks)) -- Test equality of both the key names and types. If the key matches then the type should as well , but we need to test both to convince ghc $ fromMaybe (evalDropTake (_2 obj :< SingList ks) schema') $ do Refl <- eqSym k k' Refl <- singEq ty ty' withSymVal ty $ withSymVal (SObjectUnsafe (SingList ks')) $ pure $ tuple (_1 obj, evalDropTake (_2 obj :< SingList ks) (SingList ks')) evalDropTake _ _ = error "evalDropTake invariant violation" data SomeObj where SomeObj :: SingList schema -> SBV (ConcreteObj schema) -> SomeObj -- | Shrink the given object to the largest subobject smaller than the search schema . Meaning its first key is > than the search schema 's first key . subObject :: SBV (ConcreteObj schema) :< SingList schema -> SingList searchSchema -> SomeObj subObject (_ :< SNil') _ = SomeObj SNil' (literal ()) subObject _ SNil' = SomeObj SNil' (literal ()) subObject (obj :< schema@(SingList (SCons k v kvs))) searchSchema@(SingList (SCons sk _sv _skvs)) = withHasKind v $ withSymVal (SObjectUnsafe (SingList kvs)) $ case cmpSym k sk of GT -> SomeObj schema obj _ -> subObject (_2 obj :< SingList kvs) searchSchema | Merge two objects , returning one with the requested schema . -- -- We simultaneously shrink each input object, via @subObject@ so that we're -- always examining the smallest objects that could possibly match our -- searched-for schema. -- -- Example: -- obj1 : { x : 1 , y : 2 } obj2 : { y : 4 , z : 5 } -- schema: { y: integer, z: integer } -- -- Note that this example illustrates why we must shrink objects before the first call . If we did n't shrink here then obj2 would match first even though -- obj1 should. -- Step 1 : shrink -- obj1 : { y : 2 } obj2 : { y : 4 , z : 5 } -- schema: { y: integer, z: integer } -- 2 : match -- y = 2 -- 3 : shrink -- obj1 : { } obj2 : { z : 5 } -- schema: { z: integer } -- 3.5 . switch to @evalDropTake@ -- obj2 : { z : 5 } -- schema: { z: integer } -- 4 : match -- z = 5 -- 5 : shrink -- -- obj2: {} -- schema: {} -- 6 : terminate -- result : { y : 2 , z : 5 } evalObjMerge' :: HasCallStack => (SBV (ConcreteObj schema1) :< SingList schema1) -> (SBV (ConcreteObj schema2) :< SingList schema2) -> SingList schema -> SBV (ConcreteObj schema) evalObjMerge' _ _ SNil' = literal () evalObjMerge' (obj1 :< schema1@(SingList (SCons k1 ty1 subSchema1))) (obj2 :< schema2@(SingList (SCons k2 ty2 subSchema2))) schema@(SingList (SCons k ty subSchema )) = withSymVal (SObjectUnsafe (SingList subSchema1)) $ withHasKind ty1 $ withSymVal (SObjectUnsafe (SingList subSchema2)) $ withHasKind ty2 $ withSymVal ty $ withSymVal (SObjectUnsafe (SingList subSchema)) $ fromMaybe (error "evalObjMerge' invariant violation") $ case subObject (obj1 :< schema1) schema of SomeObj schema1' obj1' -> case subObject (obj2 :< schema2) schema of SomeObj schema2' obj2' -> asum object 1 matches ( left - biased ) [ do Refl <- eqSym k1 k Refl <- singEq ty1 ty pure $ tuple ( _1 obj1 , evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') (SingList subSchema) ) object 2 matches , do Refl <- eqSym k2 k Refl <- singEq ty2 ty pure $ tuple (_1 obj2 , evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') (SingList subSchema) ) -- neither object matches , pure $ evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') schema ] evalObjMerge' (obj1 :< schema1@(SingList SCons{})) (_ :< SNil') schema@(SingList SCons{}) = evalDropTake (obj1 :< schema1) schema evalObjMerge' (_ :< SNil') (obj2 :< schema2@(SingList SCons{})) schema@(SingList SCons{}) = evalDropTake (obj2 :< schema2) schema evalObjMerge' (_ :< SNil') (_ :< SNil') (SingList SCons{}) = error "evalObjMerge' invariant violation: both input object exhausted" hasKey :: SingList schema -> S Str -> S Bool hasKey singList (S _ key) = sansProv $ foldrSingList sFalse (\k _ty accum -> (literal (Str (symbolVal k)) .== key) .|| accum) singList evalStrToInt :: Analyzer m => TermOf m 'TyStr -> m (S Integer) evalStrToInt sT = do s' <- _sSbv <$> eval sT let s = coerceSBV @Str @String s' markFailure $ SBVS.null s markFailure $ SBVS.length s .> 128 let nat = SBVS.strToNat s markFailure $ nat .< 0 -- will happen if empty or contains a non-digit pure $ sansProv nat evalStrToIntBase :: (Analyzer m) => TermOf m 'TyInteger -> TermOf m 'TyStr -> m (S Integer) evalStrToIntBase bT sT = do b <- eval bT s' <- eval sT let s = coerceS @Str @String s' markFailure $ SBVS.null $ _sSbv s markFailure $ SBVS.length (_sSbv s) .> 128 case (unliteralS b, unliteralS s) of -- Symbolic base and string: give up; too many possible solutions. (Nothing, Nothing) -> throwErrorNoLoc "Unable to convert string to integer for symbolic base and string" Symbolic base and concrete string : pre - compute all 17 possible outcomes (Nothing, Just conStr) -> let conText = T.pack conStr in foldr (\conBase rest -> singIte SInteger (b .== literalS conBase) (precompute conBase conText) rest) symbolicFailure [2..16] Concrete base and symbolic string : only support base 10 (Just conBase, Nothing) | conBase == 10 -> evalStrToInt $ inject' $ coerceS @String @Str s | otherwise -> throwErrorNoLoc $ FailureMessage $ T.pack $ "Unable to statically determine the string for conversion to integer \ \from base " ++ show conBase -- Concrete base and string: use pact native impl (Just conBase, Just conStr) -> case Pact.baseStrToInt conBase (T.pack conStr) of Left err -> throwErrorNoLoc $ FailureMessage $ "Failed to convert string to integer: " <> err Right res -> pure $ literalS res where symbolicFailure = do markFailure sTrue pure (literalS 0) precompute base conText = case Pact.baseStrToInt base conText of Left _err -> symbolicFailure Right res -> pure (literalS res) evalObjAt :: forall a m schema. (Analyzer m, HasCallStack) => SingTy ('TyObject schema) -> TermOf m 'TyStr -> TermOf m ('TyObject schema) -> SingTy a -> m (S (Concrete a)) evalObjAt objTy@(SObjectUnsafe schema) colNameT obj retType = withSymVal retType $ withSing objTy $ do needColName <- eval colNameT S mObjProv objVal <- eval obj let go :: m (SBV (Concrete a)) go = foldrObject (objVal :< schema) -- if we didn't hit the column we're looking for mark as failure (do markFailure sTrue pure $ uninterpret "notfound") -- look through every column for one with the name we're looking for (\sym col schema' rest -> withMergeableAnalyzer @m retType $ ite (needColName .== literalS (Str (symbolVal sym))) (case singEq schema' retType of Nothing -> throwErrorNoLoc "evalObjAt mismatched field types" Just Refl -> pure col ) rest) mProv :: Maybe Provenance mProv = do FromRow ocMap <- mObjProv -- NOTE: We can only propagate the provenance from the row- to the -- cell-level if we know the column name statically: Str cnStr <- unliteralS needColName FromCell <$> Map.lookup (ColumnName cnStr) ocMap S mProv <$> go evalExistential :: Analyzer m => Existential (TermOf m) -> m (EType, AVal) evalExistential (Some ty prop) = do prop' <- withSing ty $ eval prop pure (EType ty, mkAVal prop')
null
https://raw.githubusercontent.com/sealchain-project/sealchain/e97b4bac865fb147979cb14723a12c716a62e51e/pact/src/Pact/Analyze/Eval/Core.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # # LANGUAGE OverloadedStrings # # LANGUAGE Rank2Types # # LANGUAGE TypeOperators # | Symbolic evaluation for the functionally pure subset of expressions that | Bound on the size of lists we check. This may be user-configurable in the future. Note [Time Representation] the right of the decimal point in times (even though we don't print sub-second precision by default...). true false [Time Representation]). [Time Representation]). valid range [0..length l - 1] statically build a list of index comparisons if the index is positive, count from the start of the list, otherwise count from the end. if the index is positive, count from the start of the list, otherwise count from the end. TODO: we need to be very careful here with non-ground types | Implementation for both drop and take. the type of the object we 're starting with , and @schema'@ -- Therefore, we work through the elements of the object one at a time, keeping the ones that go in the resulting object. Test equality of both the key names and types. If the key matches then the | Shrink the given object to the largest subobject smaller than the search We simultaneously shrink each input object, via @subObject@ so that we're always examining the smallest objects that could possibly match our searched-for schema. Example: schema: { y: integer, z: integer } Note that this example illustrates why we must shrink objects before the obj1 should. schema: { y: integer, z: integer } schema: { z: integer } schema: { z: integer } obj2: {} schema: {} neither object matches will happen if empty or contains a non-digit Symbolic base and string: give up; too many possible solutions. Concrete base and string: use pact native impl if we didn't hit the column we're looking for mark as failure look through every column for one with the name we're looking for NOTE: We can only propagate the provenance from the row- to the cell-level if we know the column name statically:
# LANGUAGE GADTs # # LANGUAGE LambdaCase # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # # options_ghc -fno - warn - redundant - constraints # are shared by all three languages : ' Term ' , ' Prop ' , and ' Invariant ' . module Pact.Analyze.Eval.Core where import Control.Lens (over) import Data.Foldable (asum) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.SBV (EqSymbolic ((./=), (.==)), OrdSymbolic ((.<), (.<=), (.>), (.>=)), SBV, SymVal, ite, literal, uninterpret, unliteral) import Data.SBV.List ((.:)) import qualified Data.SBV.List as SBVL import qualified Data.SBV.String as SBVS import Data.SBV.Tools.BoundedList (band, bfoldr, bfoldrM, bmapM, breverse, bsort, bzipWith) import Data.SBV.Tuple (tuple, _1, _2) import qualified Data.Text as T import Data.Type.Equality ((:~:) (Refl)) import GHC.Stack import GHC.TypeLits (symbolVal) import Pact.Analyze.Errors import Pact.Analyze.Eval.Numerical import Pact.Analyze.Types import Pact.Analyze.Types.Eval import Pact.Analyze.Util (Boolean (..), vacuousMatch) import qualified Pact.Native as Pact import Pact.Types.Pretty (renderCompactString) listBound :: Int listBound = 10 Pact uses the Thyme library ( UTCTime ) to represent times . Thyme internally uses a 64 - bit count of microseconds since the MJD epoch . So , our symbolic representation is naturally a 64 - bit integer . The effect from a Pact - user 's point of view is that we store 6 digits to pact > ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) " 2016 - 07 - 23T13:30:45Z " pact > (= ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.0010021 ) ) pact > (= ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001002 ) ( add - time ( time " 2016 - 07 - 23T13:30:45Z " ) 0.001003 ) ) evalIntAddTime :: Analyzer m => TermOf m 'TyTime -> TermOf m 'TyInteger -> m (S Time) evalIntAddTime timeT secsT = do time <- eval timeT secs <- eval secsT Convert seconds to milliseconds /before/ conversion to Integer ( see note pure $ time + fromIntegralS (secs * 1000000) evalDecAddTime :: Analyzer m => TermOf m 'TyTime -> TermOf m 'TyDecimal -> m (S Time) evalDecAddTime timeT secsT = do time <- eval timeT secs <- eval secsT if isConcreteS secs Convert seconds to milliseconds /before/ conversion to Integer ( see note then pure $ time + fromIntegralS (banker'sMethodS (secs * fromInteger' 1000000)) else throwErrorNoLoc $ PossibleRoundoff "A time being added is not concrete, so we can't guarantee that roundoff won't happen when it's converted to an integer." evalComparisonOp :: forall m a. Analyzer m => SingTy a -> ComparisonOp -> TermOf m a -> TermOf m a -> m (S Bool) evalComparisonOp ty op xT yT = withOrd ty $ do x <- withSing ty $ eval xT y <- withSing ty $ eval yT let f :: SymVal (Concrete a) => SBV Bool f = case op of Gt -> x .> y Lt -> x .< y Gte -> x .>= y Lte -> x .<= y Eq -> x .== y Neq -> x ./= y pure $ sansProv $ withSymVal ty f singIte :: forall m a a'. (Analyzer m, a' ~ Concrete a, SingI a) => SingTy a -> SBV Bool -> m (S a') -> m (S a') -> m (S a') singIte ty a b c = withSymVal ty $ withMergeableAnalyzer @m ty $ ite a b c evalLogicalOp :: Analyzer m => LogicalOp -> [TermOf m 'TyBool] -> m (S Bool) evalLogicalOp AndOp [a, b] = do a' <- eval a singIte SBool (_sSbv a') (eval b) (pure sFalse) evalLogicalOp OrOp [a, b] = do a' <- eval a singIte SBool (_sSbv a') (pure sTrue) (eval b) evalLogicalOp NotOp [a] = sNot <$> eval a evalLogicalOp op terms = throwErrorNoLoc $ MalformedLogicalOpExec op $ length terms evalCore :: forall m a. (Analyzer m, SingI a) => Core (TermOf m) a -> m (S (Concrete a)) evalCore (Lit a) = withSymVal (sing :: SingTy a) $ pure $ literalS a evalCore (Sym s) = pure s evalCore (Var vid name) = do mVal <- getVar vid case mVal of Nothing -> throwErrorNoLoc $ VarNotInScope name vid Just (AVal mProv sval) -> pure $ mkS mProv sval Just OpaqueVal -> throwErrorNoLoc OpaqueValEncountered evalCore (Identity _ a) = eval a evalCore (Constantly _ a _) = eval a evalCore (Compose tya tyb _ a (Open vida _nma tmb) (Open vidb _nmb tmc)) = do a' <- withSing tya $ eval a b' <- withVar vida (mkAVal a') $ withSing tyb $ eval tmb withVar vidb (mkAVal b') $ eval tmc evalCore (StrConcat p1 p2) = (.++) <$> eval p1 <*> eval p2 evalCore (StrLength p) = over s2Sbv SBVS.length . coerceS @Str @String <$> eval p evalCore (StrToInt s) = evalStrToInt s evalCore (StrToIntBase b s) = evalStrToIntBase b s evalCore (Numerical a) = evalNumerical a evalCore (IntAddTime time secs) = evalIntAddTime time secs evalCore (DecAddTime time secs) = evalDecAddTime time secs evalCore (Comparison ty op x y) = evalComparisonOp ty op x y evalCore (Logical op props) = evalLogicalOp op props evalCore (ObjAt schema colNameT objT) = evalObjAt schema colNameT objT (sing :: SingTy a) evalCore (LiteralObject SObjectNil (Object SNil)) = pure $ literalS () evalCore (LiteralObject (SObjectCons _ ty tys) (Object (SCons _ (Column _ val) vals))) = do let objTy = SObjectUnsafe tys withSing objTy $ withSymVal ty $ withSymVal objTy $ do S _ val' <- eval val S _ vals' <- evalCore $ LiteralObject objTy $ Object vals pure $ sansProv $ tuple (val', vals') evalCore LiteralObject{} = vacuousMatch "previous two cases cover all literal objects" evalCore (ObjMerge ty1@(SObject schema1) ty2@(SObject schema2) obj1 obj2) = withSing ty1 $ withSing ty2 $ do S _ obj1' <- eval obj1 S _ obj2' <- eval obj2 case sing @a of SObject schema -> pure $ sansProv $ evalObjMerge' (obj1' :< schema1) (obj2' :< schema2) schema _ -> throwErrorNoLoc "this must be an object" evalCore ObjMerge{} = throwErrorNoLoc "both types must be objects" evalCore (ObjContains (SObjectUnsafe schema) key _obj) = hasKey schema <$> eval key evalCore (StrContains needle haystack) = do needle' <- eval needle haystack' <- eval haystack pure $ sansProv $ _sSbv (coerceS @Str @String needle') `SBVS.isInfixOf` _sSbv (coerceS @Str @String haystack') evalCore (ListContains ty needle haystack) = withSymVal ty $ do S _ needle' <- withSing ty $ eval needle S _ haystack' <- withSing ty $ eval haystack pure $ sansProv $ bfoldr listBound (\cell rest -> cell .== needle' .|| rest) sFalse haystack' evalCore (ListEqNeq ty op a b) = withSymVal ty $ do S _ a' <- withSing ty $ eval a S _ b' <- withSing ty $ eval b let sameList = SBVL.length a' .== SBVL.length b' .&& band listBound (bzipWith listBound (.==) a' b') pure $ sansProv $ case op of Eq' -> sameList Neq' -> sNot sameList evalCore (ListAt ty i l) = withSymVal ty $ do S _ i' <- eval i S _ l' <- eval l markFailure $ i' .< 0 .|| i' .>= SBVL.length l' pure $ sansProv $ SBVL.elemAt l' i' evalCore (ListLength ty l) = withSymVal ty $ withSing ty $ do S prov l' <- eval l pure $ S prov $ SBVL.length l' evalCore (LiteralList ty xs) = withSymVal ty $ withSing ty $ do vals <- traverse (fmap _sSbv . eval) xs pure $ sansProv $ SBVL.implode vals evalCore (ListDrop ty n list) = withSymVal ty $ withSing ty $ do S _ n' <- eval n S _ list' <- eval list pure $ sansProv $ ite (n' .>= 0) (SBVL.drop n' list') (SBVL.take (SBVL.length list' + n') list') evalCore (ListTake ty n list) = withSymVal ty $ withSing ty $ do S _ n' <- eval n S _ list' <- eval list pure $ sansProv $ ite (n' .>= 0) (SBVL.take n' list') (SBVL.drop (SBVL.length list' + n') list') evalCore (ListConcat ty p1 p2) = withSymVal ty $ withSing ty $ do S _ p1' <- eval p1 S _ p2' <- eval p2 pure $ sansProv $ SBVL.concat p1' p2' evalCore (ListReverse ty l) = withSymVal ty $ withSing ty $ do S prov l' <- eval l pure $ S prov $ breverse listBound l' evalCore (ListSort ty l) = withSymVal ty $ withSing ty $ withOrd ty $ do S prov l' <- eval l pure $ S prov $ bsort listBound l' evalCore (MakeList ty i a) = withSymVal ty $ withSing ty $ do S _ i' <- eval i S _ a' <- eval a case unliteral i' of Just i'' -> pure $ sansProv $ SBVL.implode $ replicate (fromInteger i'') a' Nothing -> throwErrorNoLoc $ UnhandledTerm "make-list currently requires a statically determined length" evalCore (ListMap tya tyb (Open vid _ expr) as) = withSymVal tya $ withSymVal tyb $ withSing tya $ withSing tyb $ withMergeableAnalyzer @m (SList tyb) $ do S _ as' <- eval as bs <- bmapM listBound (\val -> _sSbv <$> withVar vid (mkAVal' val) (eval expr)) as' pure $ sansProv bs evalCore (ListFilter tya (Open vid _ f) as) = withSymVal tya $ withMergeableAnalyzer @m (SList tya) $ do S _ as' <- eval as let bfilterM = bfoldrM listBound (\sbva svblst -> do S _ x' <- withVar vid (mkAVal' sbva) (eval f) pure $ ite x' (sbva .: svblst) svblst) (literal []) sansProv <$> bfilterM as' evalCore (ListFold tya tyb (Open vid1 _ (Open vid2 _ f)) a bs) = withSymVal tya $ withSymVal tyb $ withSing tyb $ withMergeableAnalyzer @m tya $ do S _ a' <- eval a S _ bs' <- eval bs result <- bfoldrM listBound (\sbvb sbva -> fmap _sSbv $ withVar vid1 (mkAVal' sbvb) $ withVar vid2 (mkAVal' sbva) $ eval f) a' bs' pure $ sansProv result evalCore (AndQ tya (Open vid1 _ f) (Open vid2 _ g) a) = do S _ a' <- withSing tya $ eval a fv <- withVar vid1 (mkAVal' a') $ eval f gv <- withVar vid2 (mkAVal' a') $ eval g pure $ fv .&& gv evalCore (OrQ tya (Open vid1 _ f) (Open vid2 _ g) a) = do S _ a' <- withSing tya $ eval a fv <- withVar vid1 (mkAVal' a') $ eval f gv <- withVar vid2 (mkAVal' a') $ eval g pure $ fv .|| gv evalCore (Where schema tya key (Open vid _ f) obj) = withSymVal tya $ do S _ v <- evalObjAt schema key obj tya withVar vid (mkAVal' v) $ eval f evalCore (Typeof tya _a) = pure $ literalS $ Str $ renderCompactString tya evalCore (GuardEqNeq op xT yT) = do x <- eval xT y <- eval yT pure $ sansProv $ case op of Eq' -> x .== y Neq' -> x ./= y evalCore (ObjectEqNeq SObjectNil SObjectNil eqNeq _ _) = pure $ case eqNeq of { Eq' -> sTrue; Neq' -> sFalse } evalCore (ObjectEqNeq SObjectNil SObjectCons{} eqNeq _ _) = pure $ case eqNeq of { Eq' -> sFalse; Neq' -> sTrue } evalCore (ObjectEqNeq SObjectCons{} SObjectNil eqNeq _ _) = pure $ case eqNeq of { Eq' -> sFalse; Neq' -> sTrue } evalCore (ObjectEqNeq objTy1@(SObject schema@SCons'{}) objTy2@(SObject SCons'{}) eqNeq obj1 obj2) = case singEq objTy1 objTy2 of Nothing -> pure sFalse Just Refl -> withSing objTy1 $ do S _ obj1' <- eval obj1 S _ obj2' <- eval obj2 let go :: SingList tys -> SBV (Concrete ('TyObject tys)) -> SBV (Concrete ('TyObject tys)) -> SBV Bool go SNil' _ _ = sTrue go (SCons' _ colTy' schema') objA objB = withSymVal colTy' $ withSymVal (SObjectUnsafe schema') $ _1 objA .== _1 objB .&& go schema' (_2 objA) (_2 objB) let objsEq = go schema obj1' obj2' pure $ sansProv $ case eqNeq of { Eq' -> objsEq; Neq' -> sNot objsEq } evalCore (ObjectEqNeq _ _ _ _ _) = vacuousMatch "covered by previous case" evalCore (ObjDrop ty@(SObjectUnsafe schema') _keys obj) = withSing ty $ do S prov obj' <- eval obj case sing @a of SObjectUnsafe schema -> pure $ S prov $ evalDropTake (obj' :< schema') schema evalCore (ObjTake ty@(SObjectUnsafe schema') _keys obj) = withSing ty $ do S prov obj' <- eval obj case sing @a of SObjectUnsafe schema -> pure $ S prov $ evalDropTake (obj' :< schema') schema the type we need to produce . @schema'@ must be a sub - list of evalDropTake :: HasCallStack => SBV (ConcreteObj schema) :< SingList schema -> SingList schema' -> SBV (ConcreteObj schema') evalDropTake _ SNil' = literal () evalDropTake (obj :< SingList (SCons k ty ks )) schema'@(SingList (SCons k' ty' ks')) = withHasKind ty $ withSymVal (SObjectUnsafe (SingList ks)) type should as well , but we need to test both to convince ghc $ fromMaybe (evalDropTake (_2 obj :< SingList ks) schema') $ do Refl <- eqSym k k' Refl <- singEq ty ty' withSymVal ty $ withSymVal (SObjectUnsafe (SingList ks')) $ pure $ tuple (_1 obj, evalDropTake (_2 obj :< SingList ks) (SingList ks')) evalDropTake _ _ = error "evalDropTake invariant violation" data SomeObj where SomeObj :: SingList schema -> SBV (ConcreteObj schema) -> SomeObj schema . Meaning its first key is > than the search schema 's first key . subObject :: SBV (ConcreteObj schema) :< SingList schema -> SingList searchSchema -> SomeObj subObject (_ :< SNil') _ = SomeObj SNil' (literal ()) subObject _ SNil' = SomeObj SNil' (literal ()) subObject (obj :< schema@(SingList (SCons k v kvs))) searchSchema@(SingList (SCons sk _sv _skvs)) = withHasKind v $ withSymVal (SObjectUnsafe (SingList kvs)) $ case cmpSym k sk of GT -> SomeObj schema obj _ -> subObject (_2 obj :< SingList kvs) searchSchema | Merge two objects , returning one with the requested schema . obj1 : { x : 1 , y : 2 } obj2 : { y : 4 , z : 5 } first call . If we did n't shrink here then obj2 would match first even though Step 1 : shrink obj1 : { y : 2 } obj2 : { y : 4 , z : 5 } 2 : match y = 2 3 : shrink obj1 : { } obj2 : { z : 5 } 3.5 . switch to @evalDropTake@ obj2 : { z : 5 } 4 : match z = 5 5 : shrink 6 : terminate result : { y : 2 , z : 5 } evalObjMerge' :: HasCallStack => (SBV (ConcreteObj schema1) :< SingList schema1) -> (SBV (ConcreteObj schema2) :< SingList schema2) -> SingList schema -> SBV (ConcreteObj schema) evalObjMerge' _ _ SNil' = literal () evalObjMerge' (obj1 :< schema1@(SingList (SCons k1 ty1 subSchema1))) (obj2 :< schema2@(SingList (SCons k2 ty2 subSchema2))) schema@(SingList (SCons k ty subSchema )) = withSymVal (SObjectUnsafe (SingList subSchema1)) $ withHasKind ty1 $ withSymVal (SObjectUnsafe (SingList subSchema2)) $ withHasKind ty2 $ withSymVal ty $ withSymVal (SObjectUnsafe (SingList subSchema)) $ fromMaybe (error "evalObjMerge' invariant violation") $ case subObject (obj1 :< schema1) schema of SomeObj schema1' obj1' -> case subObject (obj2 :< schema2) schema of SomeObj schema2' obj2' -> asum object 1 matches ( left - biased ) [ do Refl <- eqSym k1 k Refl <- singEq ty1 ty pure $ tuple ( _1 obj1 , evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') (SingList subSchema) ) object 2 matches , do Refl <- eqSym k2 k Refl <- singEq ty2 ty pure $ tuple (_1 obj2 , evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') (SingList subSchema) ) , pure $ evalObjMerge' (obj1' :< schema1') (obj2' :< schema2') schema ] evalObjMerge' (obj1 :< schema1@(SingList SCons{})) (_ :< SNil') schema@(SingList SCons{}) = evalDropTake (obj1 :< schema1) schema evalObjMerge' (_ :< SNil') (obj2 :< schema2@(SingList SCons{})) schema@(SingList SCons{}) = evalDropTake (obj2 :< schema2) schema evalObjMerge' (_ :< SNil') (_ :< SNil') (SingList SCons{}) = error "evalObjMerge' invariant violation: both input object exhausted" hasKey :: SingList schema -> S Str -> S Bool hasKey singList (S _ key) = sansProv $ foldrSingList sFalse (\k _ty accum -> (literal (Str (symbolVal k)) .== key) .|| accum) singList evalStrToInt :: Analyzer m => TermOf m 'TyStr -> m (S Integer) evalStrToInt sT = do s' <- _sSbv <$> eval sT let s = coerceSBV @Str @String s' markFailure $ SBVS.null s markFailure $ SBVS.length s .> 128 let nat = SBVS.strToNat s pure $ sansProv nat evalStrToIntBase :: (Analyzer m) => TermOf m 'TyInteger -> TermOf m 'TyStr -> m (S Integer) evalStrToIntBase bT sT = do b <- eval bT s' <- eval sT let s = coerceS @Str @String s' markFailure $ SBVS.null $ _sSbv s markFailure $ SBVS.length (_sSbv s) .> 128 case (unliteralS b, unliteralS s) of (Nothing, Nothing) -> throwErrorNoLoc "Unable to convert string to integer for symbolic base and string" Symbolic base and concrete string : pre - compute all 17 possible outcomes (Nothing, Just conStr) -> let conText = T.pack conStr in foldr (\conBase rest -> singIte SInteger (b .== literalS conBase) (precompute conBase conText) rest) symbolicFailure [2..16] Concrete base and symbolic string : only support base 10 (Just conBase, Nothing) | conBase == 10 -> evalStrToInt $ inject' $ coerceS @String @Str s | otherwise -> throwErrorNoLoc $ FailureMessage $ T.pack $ "Unable to statically determine the string for conversion to integer \ \from base " ++ show conBase (Just conBase, Just conStr) -> case Pact.baseStrToInt conBase (T.pack conStr) of Left err -> throwErrorNoLoc $ FailureMessage $ "Failed to convert string to integer: " <> err Right res -> pure $ literalS res where symbolicFailure = do markFailure sTrue pure (literalS 0) precompute base conText = case Pact.baseStrToInt base conText of Left _err -> symbolicFailure Right res -> pure (literalS res) evalObjAt :: forall a m schema. (Analyzer m, HasCallStack) => SingTy ('TyObject schema) -> TermOf m 'TyStr -> TermOf m ('TyObject schema) -> SingTy a -> m (S (Concrete a)) evalObjAt objTy@(SObjectUnsafe schema) colNameT obj retType = withSymVal retType $ withSing objTy $ do needColName <- eval colNameT S mObjProv objVal <- eval obj let go :: m (SBV (Concrete a)) go = foldrObject (objVal :< schema) (do markFailure sTrue pure $ uninterpret "notfound") (\sym col schema' rest -> withMergeableAnalyzer @m retType $ ite (needColName .== literalS (Str (symbolVal sym))) (case singEq schema' retType of Nothing -> throwErrorNoLoc "evalObjAt mismatched field types" Just Refl -> pure col ) rest) mProv :: Maybe Provenance mProv = do FromRow ocMap <- mObjProv Str cnStr <- unliteralS needColName FromCell <$> Map.lookup (ColumnName cnStr) ocMap S mProv <$> go evalExistential :: Analyzer m => Existential (TermOf m) -> m (EType, AVal) evalExistential (Some ty prop) = do prop' <- withSing ty $ eval prop pure (EType ty, mkAVal prop')
601a3c70f36dcd50bc62788e3e53a5c97f28537e9b0e050b381a064748a0604f
TheLortex/mirage-monorepo
mirage_random.ml
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * { 1 Random - related devices } This module define random - related devices for MirageOS . { e Release v3.0.0 } This module define random-related devices for MirageOS. {e Release v3.0.0 } *) (** {1 Operations to generate random numbers} *) module type S = sig type g (** The state of the generator. *) val generate: ?g:g -> int -> Cstruct.t (** [generate ~g n] generates a random buffer of length [n] using [g]. *) end
null
https://raw.githubusercontent.com/TheLortex/mirage-monorepo/b557005dfe5a51fc50f0597d82c450291cfe8a2a/duniverse/mirage-random/src/mirage_random.ml
ocaml
* {1 Operations to generate random numbers} * The state of the generator. * [generate ~g n] generates a random buffer of length [n] using [g].
* Copyright ( c ) 2011 - 2015 Anil Madhavapeddy < > * Copyright ( c ) 2013 - 2015 < > * Copyright ( c ) 2013 Citrix Systems Inc * * Permission to use , copy , modify , and distribute this software for any * purpose with or without fee is hereby granted , provided that the above * copyright notice and this permission notice appear in all copies . * * THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN * ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE . * Copyright (c) 2011-2015 Anil Madhavapeddy <> * Copyright (c) 2013-2015 Thomas Gazagnaire <> * Copyright (c) 2013 Citrix Systems Inc * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) * { 1 Random - related devices } This module define random - related devices for MirageOS . { e Release v3.0.0 } This module define random-related devices for MirageOS. {e Release v3.0.0 } *) module type S = sig type g val generate: ?g:g -> int -> Cstruct.t end
7eff6492bd650fa1245cd0bc0b2f11199a18090b3b47678ba588c44304ade432
coccinelle/coccinelle
interface_tools.mli
module Option : sig type 'a t = 'a option val map : ('a -> 'b) -> 'a option -> 'b option val equal : ('a -> 'b -> bool) -> 'a option -> 'b option -> bool val exists : ('a -> bool) -> 'a option -> bool val some : 'a -> 'a option val iter : ('a -> unit) -> 'a option -> unit val filter : ('a -> bool) -> 'a option -> 'a option end module Version : sig type t = { major : int; minor : int; patch : int; } val mk : int -> int -> int -> t val compare : t -> t -> int val equal : t -> t -> bool val hash : t -> int val of_string : string -> t (* val of_command_line : string -> t *) val to_string : ?sep:string -> ?include_patch:bool -> t -> string end val signature_of_in_channel : ?filename:string -> in_channel -> Parsetree.signature (* module Interpreter : sig type t = { command_line : string; version : Version.t; } val of_command_line : string -> t end *) module Buffer : sig include module type of (struct include Buffer end) val add_channel_no_wait : Buffer.t -> in_channel -> int -> int val add_channel_to_the_end : ?chunk_size:int -> ?continue:(unit -> bool) -> Buffer.t -> in_channel -> unit val suffix_of_length : Buffer.t -> int -> string val has_suffix : Buffer.t -> string -> bool end module String : sig include module type of (struct include String end) val suffix_of_length : string -> int -> string val has_suffix : string -> suffix:string -> bool val prefix_of_length : string -> int -> string val has_prefix : string -> prefix:string -> bool val suffix_from : string -> int -> string end
null
https://raw.githubusercontent.com/coccinelle/coccinelle/5448bb2bd03491ffec356bf7bd6ddcdbf4d36bc9/bundles/stdcompat/stdcompat-current/interface_generator/interface_tools.mli
ocaml
val of_command_line : string -> t module Interpreter : sig type t = { command_line : string; version : Version.t; } val of_command_line : string -> t end
module Option : sig type 'a t = 'a option val map : ('a -> 'b) -> 'a option -> 'b option val equal : ('a -> 'b -> bool) -> 'a option -> 'b option -> bool val exists : ('a -> bool) -> 'a option -> bool val some : 'a -> 'a option val iter : ('a -> unit) -> 'a option -> unit val filter : ('a -> bool) -> 'a option -> 'a option end module Version : sig type t = { major : int; minor : int; patch : int; } val mk : int -> int -> int -> t val compare : t -> t -> int val equal : t -> t -> bool val hash : t -> int val of_string : string -> t val to_string : ?sep:string -> ?include_patch:bool -> t -> string end val signature_of_in_channel : ?filename:string -> in_channel -> Parsetree.signature module Buffer : sig include module type of (struct include Buffer end) val add_channel_no_wait : Buffer.t -> in_channel -> int -> int val add_channel_to_the_end : ?chunk_size:int -> ?continue:(unit -> bool) -> Buffer.t -> in_channel -> unit val suffix_of_length : Buffer.t -> int -> string val has_suffix : Buffer.t -> string -> bool end module String : sig include module type of (struct include String end) val suffix_of_length : string -> int -> string val has_suffix : string -> suffix:string -> bool val prefix_of_length : string -> int -> string val has_prefix : string -> prefix:string -> bool val suffix_from : string -> int -> string end
7760111d818bed397f092ca252b5bc97fe077f09ef87379c168f2f84b99c7d6b
kmi/irs
new.lisp
Mode : Lisp ; Package : File created in WebOnto (in-package "OCML") (in-ontology cashew-ontology)
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/ontologies/domains/cashew-ontology/new.lisp
lisp
Package :
File created in WebOnto (in-package "OCML") (in-ontology cashew-ontology)
5364984484dc1db83e918f04f06764d51652b6d3b77ba7b08b6b3be7d22687e5
quephird/fun-with-quil
gingham.clj
(ns fun-with-quil.sketches.gingham (:use quil.core)) (def ^:constant screen-w 1920) (def ^:constant screen-h 1080) (defn make-gingham-fn [g d] "g controls the granularity of the squares d controls the distortion of the resultant image" (fn [x y] (let [s (/ 3.0 (+ y 99.0))] (+ (* (int (rem (* (+ (* (+ x d) s) (* s y)) g) 2)) 127) (* (int (rem (* (+ (* (- (* d 2) x) s) (* s y)) g) 2)) 127))))) (defn setup [] (smooth) (no-loop) ) (defn draw [] (let [r (make-gingham-fn 0.25 1024) g (make-gingham-fn 3 1024) b (make-gingham-fn 15 1024)] (doseq [x (range screen-w) y (range screen-h)] (stroke (r x y) (g x y) (b x y)) (point x y))) (save "gingham.png") ) (sketch :title "gingham" :setup setup :draw draw :size [screen-w screen-h])
null
https://raw.githubusercontent.com/quephird/fun-with-quil/3b3a6885771f5a1a4cffeb8379f05a28048a1616/src/fun_with_quil/sketches/gingham.clj
clojure
(ns fun-with-quil.sketches.gingham (:use quil.core)) (def ^:constant screen-w 1920) (def ^:constant screen-h 1080) (defn make-gingham-fn [g d] "g controls the granularity of the squares d controls the distortion of the resultant image" (fn [x y] (let [s (/ 3.0 (+ y 99.0))] (+ (* (int (rem (* (+ (* (+ x d) s) (* s y)) g) 2)) 127) (* (int (rem (* (+ (* (- (* d 2) x) s) (* s y)) g) 2)) 127))))) (defn setup [] (smooth) (no-loop) ) (defn draw [] (let [r (make-gingham-fn 0.25 1024) g (make-gingham-fn 3 1024) b (make-gingham-fn 15 1024)] (doseq [x (range screen-w) y (range screen-h)] (stroke (r x y) (g x y) (b x y)) (point x y))) (save "gingham.png") ) (sketch :title "gingham" :setup setup :draw draw :size [screen-w screen-h])
39478a8951490d082c8568c0b8acad97ce9a98a2d58f1df907142c3972400a1a
incoherentsoftware/defect-process
Types.hs
module Player.Gun.All.ShardGun.Data.Types ( ShardGunStAttackDescription(..) , ShardGunStImages(..) , ShardGunData(..) ) where import qualified Data.List.NonEmpty as NE import Attack.Description.Types import Configs.All.PlayerGun.ShardGun import Msg.Types import Util import Window.Graphics data ShardGunStAttackDescription = ShardGunStAttackDescription { _playerBlinkStrikes :: NE.NonEmpty AttackDescription , _shardExplosionAtkDesc :: AttackDescription } data ShardGunStImages = ShardGunStImages { _shardImpale :: Image } data ShardGunData = ShardGunData { _gunMsgId :: MsgId , _aimAngle :: Radians , _blinkStrikePosMsgIds :: [(Pos2, MsgId)] , _blinkStrikePlayerStartPos :: Maybe Pos2 , _attackDescription :: ShardGunStAttackDescription , _images :: ShardGunStImages , _config :: ShardGunConfig }
null
https://raw.githubusercontent.com/incoherentsoftware/defect-process/ae362274cca0e59c0fc0dcaee0f0e208db8ccc46/src/Player/Gun/All/ShardGun/Data/Types.hs
haskell
module Player.Gun.All.ShardGun.Data.Types ( ShardGunStAttackDescription(..) , ShardGunStImages(..) , ShardGunData(..) ) where import qualified Data.List.NonEmpty as NE import Attack.Description.Types import Configs.All.PlayerGun.ShardGun import Msg.Types import Util import Window.Graphics data ShardGunStAttackDescription = ShardGunStAttackDescription { _playerBlinkStrikes :: NE.NonEmpty AttackDescription , _shardExplosionAtkDesc :: AttackDescription } data ShardGunStImages = ShardGunStImages { _shardImpale :: Image } data ShardGunData = ShardGunData { _gunMsgId :: MsgId , _aimAngle :: Radians , _blinkStrikePosMsgIds :: [(Pos2, MsgId)] , _blinkStrikePlayerStartPos :: Maybe Pos2 , _attackDescription :: ShardGunStAttackDescription , _images :: ShardGunStImages , _config :: ShardGunConfig }
a3f6cae8d7d5540a6374cddc0baef19c4c3d6ea34f363c8150030da04f616ff8
janestreet/core
hashtbl_unit_tests_intf.ml
open! Core * A subset of [ Hashtbl_intf . ] . Leaves out definitions that we do not need to test and that some implementations may not provide . and that some implementations may not provide. *) module type Hashtbl_for_testing = sig type ('a, 'b) t [@@deriving sexp_of] include Hashtbl_intf.Creators with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a with type ('a, 'b, 'c) create_options := ('a, 'b, 'c) Hashtbl_intf.create_options_with_first_class_module [ Creators ] gives us a different create than [ Hashtbl_intf . ] does val create : ?growth_allowed:bool -> ?size:int -> 'a Base.Hashtbl.Key.t -> ('a, 'b) t include Hashtbl_intf.Accessors with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a include Hashtbl_intf.Multi with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a val invariant : 'a Invariant.t -> 'b Invariant.t -> ('a, 'b) t Invariant.t end module type Hashtbl_unit_tests = sig module type Hashtbl_for_testing = Hashtbl_for_testing (** Wrap this in a [let%test_module] to ensure the tests get run *) module Make (Hashtbl : Hashtbl_for_testing) : sig end end
null
https://raw.githubusercontent.com/janestreet/core/4b6635d206f7adcfac8324820d246299d6f572fe/core/test/hashtbl_unit_tests_intf.ml
ocaml
* Wrap this in a [let%test_module] to ensure the tests get run
open! Core * A subset of [ Hashtbl_intf . ] . Leaves out definitions that we do not need to test and that some implementations may not provide . and that some implementations may not provide. *) module type Hashtbl_for_testing = sig type ('a, 'b) t [@@deriving sexp_of] include Hashtbl_intf.Creators with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a with type ('a, 'b, 'c) create_options := ('a, 'b, 'c) Hashtbl_intf.create_options_with_first_class_module [ Creators ] gives us a different create than [ Hashtbl_intf . ] does val create : ?growth_allowed:bool -> ?size:int -> 'a Base.Hashtbl.Key.t -> ('a, 'b) t include Hashtbl_intf.Accessors with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a include Hashtbl_intf.Multi with type ('a, 'b) t := ('a, 'b) t with type 'a key := 'a val invariant : 'a Invariant.t -> 'b Invariant.t -> ('a, 'b) t Invariant.t end module type Hashtbl_unit_tests = sig module type Hashtbl_for_testing = Hashtbl_for_testing module Make (Hashtbl : Hashtbl_for_testing) : sig end end
8fd8e3b298d120c528685fcdfbd491c16932bd5d07d8c1d4b5879bb4608118dd
tweag/ormolu
lambda-multi-line2.hs
tricky0 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt tricky1 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt tricky2 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt
null
https://raw.githubusercontent.com/tweag/ormolu/34bdf62429768f24b70d0f8ba7730fc4d8ae73ba/data/examples/declaration/value/function/lambda-multi-line2.hs
haskell
tricky0 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt tricky1 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt tricky2 = flip all (zip ws gs) $ \(wt, gt) -> canUnify poly_given_ok wt gt || go False wt gt
e5af6916ce35f8a3107efa614bc1930952c14271fc527f2287fb89f14571209b
re-ops/re-cog
hostname.clj
(ns re-cog.scripts.hostname (:require [pallet.stevedore :refer (script)])) (defn hostnamectl "sets hostname and hosts file" [hostname fqdn] (script ("sudo" "/usr/bin/hostnamectl" "set-hostname" ~hostname)))
null
https://raw.githubusercontent.com/re-ops/re-cog/316c37fbd9216e722fd5c177a7d729e5518e2427/src/re_cog/scripts/hostname.clj
clojure
(ns re-cog.scripts.hostname (:require [pallet.stevedore :refer (script)])) (defn hostnamectl "sets hostname and hosts file" [hostname fqdn] (script ("sudo" "/usr/bin/hostnamectl" "set-hostname" ~hostname)))
603c29d4c631260ee91f0513a6dc36b8105e9001d474af07554ca261b6857ed9
mokus0/junkbox
proddigits.hs
#!runhaskell - " proddigits.hs " - ( c ) 2007 - - [ 03:05am|mokus > 95657055187 digits in 1e10 ! ( 128.53 TB ) - [ 03:07am|mokus > 90 min cpu time to compute that - [ 03:07am|mokus > ( on my 1.66 GHz G4 ) - - about 1.15657e8 digits in 1e12 ! - about 9.9e101 digits in 10e100 ! - "proddigits.hs" - (c) 2007 James Cook - - [03:05am|mokus> 95657055187 digits in 1e10! (128.53 TB) - [03:07am|mokus> 90 min cpu time to compute that - [03:07am|mokus> (on my 1.66 GHz G4) - - about 1.15657e8 digits in 1e12! - about 9.9e101 digits in 10e100! -} module Math.Main where prodDigits base xs = (prodDigitsE xs) / (log base) prodDigitsE xs = foldl (\x y -> x + log y) 0 xs main = putStrLn (show $ prodDigits 10 [1, 1e90 .. 1e100])
null
https://raw.githubusercontent.com/mokus0/junkbox/151014bbef9db2b9205209df66c418d6d58b0d9e/Haskell/Math/proddigits.hs
haskell
#!runhaskell - " proddigits.hs " - ( c ) 2007 - - [ 03:05am|mokus > 95657055187 digits in 1e10 ! ( 128.53 TB ) - [ 03:07am|mokus > 90 min cpu time to compute that - [ 03:07am|mokus > ( on my 1.66 GHz G4 ) - - about 1.15657e8 digits in 1e12 ! - about 9.9e101 digits in 10e100 ! - "proddigits.hs" - (c) 2007 James Cook - - [03:05am|mokus> 95657055187 digits in 1e10! (128.53 TB) - [03:07am|mokus> 90 min cpu time to compute that - [03:07am|mokus> (on my 1.66 GHz G4) - - about 1.15657e8 digits in 1e12! - about 9.9e101 digits in 10e100! -} module Math.Main where prodDigits base xs = (prodDigitsE xs) / (log base) prodDigitsE xs = foldl (\x y -> x + log y) 0 xs main = putStrLn (show $ prodDigits 10 [1, 1e90 .. 1e100])
09cd4f93555d81b197c9fd42e0e05c06fc17116a27ac38447ace5c5ebe0469da
pink-gorilla/ui-gorilla
sparkline.cljs
(ns demo.notebook.sparkline (:require [ui.spark :as spark])) (defn data [nr] (vec (take nr (repeatedly rand)))) (def data-20 (data 20)) (def data-40 (data 40)) (def data-100 (data 100)) (def data-150 (data 150)) ^:R [:div [spark/line {:data data-20 :limit 20 : width 100 : height 20 : svgWidth 300 : 20 : margin 5 }] [spark/line {:data data-20 :limit 20 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/line {:data data-20 :limit 20 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/line {:data data-40 :limit 40 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/spot {:data data-100 :limit 100 :svgWidth 300 :svgHeight 20 :margin 10}] [spark/bar {:data [50, 10, 5, 20, 10 6 7 88 50 30 60] :limit 10 :svgWidth 300 :svgHeight 20 :margin 10}] [spark/bar {:data data-150 :limit 50 :svgWidth 300 :svgHeight 20 :margin 1}]]
null
https://raw.githubusercontent.com/pink-gorilla/ui-gorilla/3cc408b398d30a8e54c15f863fbabece9f036209/src/demo/notebook/sparkline.cljs
clojure
(ns demo.notebook.sparkline (:require [ui.spark :as spark])) (defn data [nr] (vec (take nr (repeatedly rand)))) (def data-20 (data 20)) (def data-40 (data 40)) (def data-100 (data 100)) (def data-150 (data 150)) ^:R [:div [spark/line {:data data-20 :limit 20 : width 100 : height 20 : svgWidth 300 : 20 : margin 5 }] [spark/line {:data data-20 :limit 20 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/line {:data data-20 :limit 20 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/line {:data data-40 :limit 40 :width 100 :height 20 :svgWidth 300 :svgHeight 20 :margin 5}] [spark/spot {:data data-100 :limit 100 :svgWidth 300 :svgHeight 20 :margin 10}] [spark/bar {:data [50, 10, 5, 20, 10 6 7 88 50 30 60] :limit 10 :svgWidth 300 :svgHeight 20 :margin 10}] [spark/bar {:data data-150 :limit 50 :svgWidth 300 :svgHeight 20 :margin 1}]]
e60a7e35286f8964171ca46b53ec33213a704d1f0b35e1a64bf9e5b966b6e1ad
mzp/coq-ide-for-ios
elim.ml
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) $ I d : elim.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $ open Pp open Util open Names open Term open Termops open Environ open Libnames open Reduction open Inductiveops open Proof_type open Clenv open Hipattern open Tacmach open Tacticals open Tactics open Hiddentac open Genarg open Tacexpr let introElimAssumsThen tac ba = let nassums = List.fold_left (fun acc b -> if b then acc+2 else acc+1) 0 ba.branchsign in let introElimAssums = tclDO nassums intro in (tclTHEN introElimAssums (elim_on_ba tac ba)) let introCaseAssumsThen tac ba = let case_thin_sign = List.flatten (List.map (function b -> if b then [false;true] else [false]) ba.branchsign) in let n1 = List.length case_thin_sign in let n2 = List.length ba.branchnames in let (l1,l2),l3 = if n1 < n2 then list_chop n1 ba.branchnames, [] else (ba.branchnames, []), if n1 > n2 then snd (list_chop n2 case_thin_sign) else [] in let introCaseAssums = tclTHEN (intros_pattern no_move l1) (intros_clearing l3) in (tclTHEN introCaseAssums (case_on_ba (tac l2) ba)) The following tactic Decompose repeatedly applies the elimination(s ) rule(s ) of the types satisfying the predicate ` ` recognizer '' onto a certain hypothesis . For example : Require Elim . Require Le . Goal ( y : nat){x : | ( le O x)/\(le x y)}->{x : | ( le O x ) } . Intros y H. Decompose [ sig and ] H;EAuto . Qed . Another example : Goal ( A , B , C : Prop)(A/\B/\C \/ B/\C \/ C/\A ) - > C. Intros A B C H ; Decompose [ and or ] H ; Assumption . Qed . elimination(s) rule(s) of the types satisfying the predicate ``recognizer'' onto a certain hypothesis. For example : Require Elim. Require Le. Goal (y:nat){x:nat | (le O x)/\(le x y)}->{x:nat | (le O x)}. Intros y H. Decompose [sig and] H;EAuto. Qed. Another example : Goal (A,B,C:Prop)(A/\B/\C \/ B/\C \/ C/\A) -> C. Intros A B C H; Decompose [and or] H; Assumption. Qed. *) let elimHypThen tac id gl = elimination_then tac ([],[]) (mkVar id) gl let rec general_decompose_on_hyp recognizer = ifOnHyp recognizer (general_decompose_aux recognizer) (fun _ -> tclIDTAC) and general_decompose_aux recognizer id = elimHypThen (introElimAssumsThen (fun bas -> tclTHEN (clear [id]) (tclMAP (general_decompose_on_hyp recognizer) (ids_of_named_context bas.assums)))) id Faudrait ajouter un COMPLETE pour que pas si aucune élimination n'est possible pas si aucune élimination n'est possible *) (* Meilleures stratégies mais perte de compatibilité *) let tmphyp_name = id_of_string "_TmpHyp" let up_to_delta = ref false (* true *) let general_decompose recognizer c gl = let typc = pf_type_of gl c in tclTHENSV (cut typc) [| tclTHEN (intro_using tmphyp_name) (onLastHypId (ifOnHyp recognizer (general_decompose_aux recognizer) (fun id -> clear [id]))); exact_no_check c |] gl let head_in gls indl t = try let ity,_ = if !up_to_delta then find_mrectype (pf_env gls) (project gls) t else extract_mrectype t in List.mem ity indl with Not_found -> false let inductive_of = function | IndRef ity -> ity | r -> errorlabstrm "Decompose" (Printer.pr_global r ++ str " is not an inductive type.") let decompose_these c l gls = List.map inductive_of general_decompose (fun (_,t) -> head_in gls indl t) c gls let decompose_nonrec c gls = general_decompose (fun (_,t) -> is_non_recursive_type t) c gls let decompose_and c gls = general_decompose (fun (_,t) -> is_record t) c gls let decompose_or c gls = general_decompose (fun (_,t) -> is_disjunction t) c gls let inj_open c = (Evd.empty,c) let h_decompose l c = Refiner.abstract_tactic (TacDecompose (l,c)) (decompose_these c l) let h_decompose_or c = Refiner.abstract_tactic (TacDecomposeOr c) (decompose_or c) let h_decompose_and c = Refiner.abstract_tactic (TacDecomposeAnd c) (decompose_and c) (* The tactic Double performs a double induction *) let simple_elimination c gls = simple_elimination_then (fun _ -> tclIDTAC) c gls let induction_trailer abs_i abs_j bargs = tclTHEN (tclDO (abs_j - abs_i) intro) (onLastHypId (fun id gls -> let idty = pf_type_of gls (mkVar id) in let fvty = global_vars (pf_env gls) idty in let possible_bring_hyps = (List.tl (nLastDecls (abs_j - abs_i) gls)) @ bargs.assums in let (hyps,_) = List.fold_left (fun (bring_ids,leave_ids) (cid,_,cidty as d) -> if not (List.mem cid leave_ids) then (d::bring_ids,leave_ids) else (bring_ids,cid::leave_ids)) ([],fvty) possible_bring_hyps in let ids = List.rev (ids_of_named_context hyps) in (tclTHENSEQ [bring_hyps hyps; tclTRY (clear ids); simple_elimination (mkVar id)]) gls)) let double_ind h1 h2 gls = let abs_i = depth_of_quantified_hypothesis true h1 gls in let abs_j = depth_of_quantified_hypothesis true h2 gls in let (abs_i,abs_j) = if abs_i < abs_j then (abs_i,abs_j) else if abs_i > abs_j then (abs_j,abs_i) else error "Both hypotheses are the same." in (tclTHEN (tclDO abs_i intro) (onLastHypId (fun id -> elimination_then (introElimAssumsThen (induction_trailer abs_i abs_j)) ([],[]) (mkVar id)))) gls let h_double_induction h1 h2 = Refiner.abstract_tactic (TacDoubleInduction (h1,h2)) (double_ind h1 h2)
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/tactics/elim.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** Meilleures stratégies mais perte de compatibilité true The tactic Double performs a double induction
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * $ I d : elim.ml 13323 2010 - 07 - 24 15:57:30Z herbelin $ open Pp open Util open Names open Term open Termops open Environ open Libnames open Reduction open Inductiveops open Proof_type open Clenv open Hipattern open Tacmach open Tacticals open Tactics open Hiddentac open Genarg open Tacexpr let introElimAssumsThen tac ba = let nassums = List.fold_left (fun acc b -> if b then acc+2 else acc+1) 0 ba.branchsign in let introElimAssums = tclDO nassums intro in (tclTHEN introElimAssums (elim_on_ba tac ba)) let introCaseAssumsThen tac ba = let case_thin_sign = List.flatten (List.map (function b -> if b then [false;true] else [false]) ba.branchsign) in let n1 = List.length case_thin_sign in let n2 = List.length ba.branchnames in let (l1,l2),l3 = if n1 < n2 then list_chop n1 ba.branchnames, [] else (ba.branchnames, []), if n1 > n2 then snd (list_chop n2 case_thin_sign) else [] in let introCaseAssums = tclTHEN (intros_pattern no_move l1) (intros_clearing l3) in (tclTHEN introCaseAssums (case_on_ba (tac l2) ba)) The following tactic Decompose repeatedly applies the elimination(s ) rule(s ) of the types satisfying the predicate ` ` recognizer '' onto a certain hypothesis . For example : Require Elim . Require Le . Goal ( y : nat){x : | ( le O x)/\(le x y)}->{x : | ( le O x ) } . Intros y H. Decompose [ sig and ] H;EAuto . Qed . Another example : Goal ( A , B , C : Prop)(A/\B/\C \/ B/\C \/ C/\A ) - > C. Intros A B C H ; Decompose [ and or ] H ; Assumption . Qed . elimination(s) rule(s) of the types satisfying the predicate ``recognizer'' onto a certain hypothesis. For example : Require Elim. Require Le. Goal (y:nat){x:nat | (le O x)/\(le x y)}->{x:nat | (le O x)}. Intros y H. Decompose [sig and] H;EAuto. Qed. Another example : Goal (A,B,C:Prop)(A/\B/\C \/ B/\C \/ C/\A) -> C. Intros A B C H; Decompose [and or] H; Assumption. Qed. *) let elimHypThen tac id gl = elimination_then tac ([],[]) (mkVar id) gl let rec general_decompose_on_hyp recognizer = ifOnHyp recognizer (general_decompose_aux recognizer) (fun _ -> tclIDTAC) and general_decompose_aux recognizer id = elimHypThen (introElimAssumsThen (fun bas -> tclTHEN (clear [id]) (tclMAP (general_decompose_on_hyp recognizer) (ids_of_named_context bas.assums)))) id Faudrait ajouter un COMPLETE pour que pas si aucune élimination n'est possible pas si aucune élimination n'est possible *) let tmphyp_name = id_of_string "_TmpHyp" let general_decompose recognizer c gl = let typc = pf_type_of gl c in tclTHENSV (cut typc) [| tclTHEN (intro_using tmphyp_name) (onLastHypId (ifOnHyp recognizer (general_decompose_aux recognizer) (fun id -> clear [id]))); exact_no_check c |] gl let head_in gls indl t = try let ity,_ = if !up_to_delta then find_mrectype (pf_env gls) (project gls) t else extract_mrectype t in List.mem ity indl with Not_found -> false let inductive_of = function | IndRef ity -> ity | r -> errorlabstrm "Decompose" (Printer.pr_global r ++ str " is not an inductive type.") let decompose_these c l gls = List.map inductive_of general_decompose (fun (_,t) -> head_in gls indl t) c gls let decompose_nonrec c gls = general_decompose (fun (_,t) -> is_non_recursive_type t) c gls let decompose_and c gls = general_decompose (fun (_,t) -> is_record t) c gls let decompose_or c gls = general_decompose (fun (_,t) -> is_disjunction t) c gls let inj_open c = (Evd.empty,c) let h_decompose l c = Refiner.abstract_tactic (TacDecompose (l,c)) (decompose_these c l) let h_decompose_or c = Refiner.abstract_tactic (TacDecomposeOr c) (decompose_or c) let h_decompose_and c = Refiner.abstract_tactic (TacDecomposeAnd c) (decompose_and c) let simple_elimination c gls = simple_elimination_then (fun _ -> tclIDTAC) c gls let induction_trailer abs_i abs_j bargs = tclTHEN (tclDO (abs_j - abs_i) intro) (onLastHypId (fun id gls -> let idty = pf_type_of gls (mkVar id) in let fvty = global_vars (pf_env gls) idty in let possible_bring_hyps = (List.tl (nLastDecls (abs_j - abs_i) gls)) @ bargs.assums in let (hyps,_) = List.fold_left (fun (bring_ids,leave_ids) (cid,_,cidty as d) -> if not (List.mem cid leave_ids) then (d::bring_ids,leave_ids) else (bring_ids,cid::leave_ids)) ([],fvty) possible_bring_hyps in let ids = List.rev (ids_of_named_context hyps) in (tclTHENSEQ [bring_hyps hyps; tclTRY (clear ids); simple_elimination (mkVar id)]) gls)) let double_ind h1 h2 gls = let abs_i = depth_of_quantified_hypothesis true h1 gls in let abs_j = depth_of_quantified_hypothesis true h2 gls in let (abs_i,abs_j) = if abs_i < abs_j then (abs_i,abs_j) else if abs_i > abs_j then (abs_j,abs_i) else error "Both hypotheses are the same." in (tclTHEN (tclDO abs_i intro) (onLastHypId (fun id -> elimination_then (introElimAssumsThen (induction_trailer abs_i abs_j)) ([],[]) (mkVar id)))) gls let h_double_induction h1 h2 = Refiner.abstract_tactic (TacDoubleInduction (h1,h2)) (double_ind h1 h2)
212c608a4b70c17e8b9340ab5eb39b5057db03380cf76a0e9896c013bb7e855a
Beluga-lang/Beluga
substitution.mli
* Substitutions @author @author Brigitte Pientka *) open Syntax.Int.LF module LF : sig exception NotComposable of string (**************************) (* Explicit substitutions *) (**************************) val id : sub val shift : sub val invShift : sub val bvarSub : int -> sub -> front val frontSub : front -> sub -> front val decSub : typ_decl -> sub -> typ_decl val comp : sub -> sub -> sub val dot1 : sub -> sub val invDot1 : sub - > sub (***************************) (* Inverting substitutions *) (***************************) val invert : sub -> sub val strengthen : sub -> dctx -> dctx val isId : sub -> bool compInv : sub - > sub - > sub (* ****************************** *) (* Apply contextual substitution *) (* ****************************** *) val isMId : msub -> bool val applyMSub : Id.offset -> msub -> mfront identity : id(Psi ) function ( jd 2010 - 05 - 17 ) val identity : dctx -> sub (* justCtxVar: id(\psi) *) val justCtxVar : dctx -> sub end
null
https://raw.githubusercontent.com/Beluga-lang/Beluga/1d39095c99dc255d972a339d447dc04286d8c13f/src/core/substitution.mli
ocaml
************************ Explicit substitutions ************************ ************************* Inverting substitutions ************************* ****************************** Apply contextual substitution ****************************** justCtxVar: id(\psi)
* Substitutions @author @author Brigitte Pientka *) open Syntax.Int.LF module LF : sig exception NotComposable of string val id : sub val shift : sub val invShift : sub val bvarSub : int -> sub -> front val frontSub : front -> sub -> front val decSub : typ_decl -> sub -> typ_decl val comp : sub -> sub -> sub val dot1 : sub -> sub val invDot1 : sub - > sub val invert : sub -> sub val strengthen : sub -> dctx -> dctx val isId : sub -> bool compInv : sub - > sub - > sub val isMId : msub -> bool val applyMSub : Id.offset -> msub -> mfront identity : id(Psi ) function ( jd 2010 - 05 - 17 ) val identity : dctx -> sub val justCtxVar : dctx -> sub end
ea64d0195db25ea2ba443726e1442df4e132513f3727c75edc6bd5a10ef6dc01
Convex-Dev/convex-web
account.clj
(ns convex-web.account (:require [clojure.spec.alpha :as s] [datalevin.core :as d] [convex-web.convex :as convex])) (defn find-all [db] (d/q '[:find [(pull ?e [* {:convex-web.account/faucets [*]}]) ...] :in $ :where [?e :convex-web.account/address]] db)) (defn find-by-address [db address] (d/q '[:find (pull ?e [* {:convex-web.account/faucets [*]}]) . :in $ ?address :where [?e :convex-web.account/address ?address]] db (.longValue (convex/address address)))) (defn equivalent? "Returns true if account-a is equivalent to account-b. Check account's address and key pair for equivalence." [account-a account-b] (let [account-keyseq [:convex-web.account/address :convex-web.account/key-pair]] (= (select-keys account-a account-keyseq) (select-keys account-b account-keyseq)))) (s/fdef equivalent? :args (s/cat :a :convex-web/account :b :convex-web/account) :ret boolean?) (def ^{:arglists '([account-a account-b])} nonequivalent? (complement equivalent?)) (s/fdef nonequivalent? :args (s/cat :a :convex-web/account :b :convex-web/account) :ret boolean?)
null
https://raw.githubusercontent.com/Convex-Dev/convex-web/c1822a14a0459cf622143af30433d9e9544defed/src/main/clojure/convex_web/account.clj
clojure
(ns convex-web.account (:require [clojure.spec.alpha :as s] [datalevin.core :as d] [convex-web.convex :as convex])) (defn find-all [db] (d/q '[:find [(pull ?e [* {:convex-web.account/faucets [*]}]) ...] :in $ :where [?e :convex-web.account/address]] db)) (defn find-by-address [db address] (d/q '[:find (pull ?e [* {:convex-web.account/faucets [*]}]) . :in $ ?address :where [?e :convex-web.account/address ?address]] db (.longValue (convex/address address)))) (defn equivalent? "Returns true if account-a is equivalent to account-b. Check account's address and key pair for equivalence." [account-a account-b] (let [account-keyseq [:convex-web.account/address :convex-web.account/key-pair]] (= (select-keys account-a account-keyseq) (select-keys account-b account-keyseq)))) (s/fdef equivalent? :args (s/cat :a :convex-web/account :b :convex-web/account) :ret boolean?) (def ^{:arglists '([account-a account-b])} nonequivalent? (complement equivalent?)) (s/fdef nonequivalent? :args (s/cat :a :convex-web/account :b :convex-web/account) :ret boolean?)
f09a95bb963324d5e2511792ea21fd0efcfe99d77865ba751f32eae3092572fc
ocaml/ood
tool.ml
type metadata = { name : string; source : string; license : string; synopsis : string; description : string; lifecycle : string; } [@@deriving yaml] let path = Fpath.v "data/tools.yml" module Lifecycle = struct type t = [ `Incubate | `Active | `Sustain | `Deprecate ] let to_string = function | `Incubate -> "incubate" | `Active -> "active" | `Sustain -> "sustain" | `Deprecate -> "deprecate" let of_string = function | "incubate" -> Ok `Incubate | "active" -> Ok `Active | "sustain" -> Ok `Sustain | "deprecate" -> Ok `Deprecate | s -> Error (`Msg ("Unknown lifecycle type: " ^ s)) end type t = { name : string; slug : string; source : string; license : string; synopsis : string; description : string; lifecycle : Lifecycle.t; } let parse s = let yaml = Utils.decode_or_raise Yaml.of_string s in match yaml with | `O [ ("tools", `A xs) ] -> Ok (List.map (fun x -> Utils.decode_or_raise metadata_of_yaml x) xs) | _ -> Error (`Msg "Expected list of tools") let decode s = let yaml = Utils.decode_or_raise Yaml.of_string s in match yaml with | `O [ ("tools", `A xs) ] -> List.map (fun x -> try let (metadata : metadata) = Utils.decode_or_raise metadata_of_yaml x in let lifecycle = match Lifecycle.of_string metadata.lifecycle with | Ok x -> x | Error (`Msg err) -> raise (Exn.Decode_error err) in let description = Omd.of_string metadata.description |> Omd.to_html in ({ name = metadata.name; slug = Utils.slugify metadata.name; source = metadata.source; license = metadata.license; synopsis = metadata.synopsis; description; lifecycle; } : t) with e -> print_endline (Yaml.to_string x |> Result.get_ok); raise e) xs | _ -> raise (Exn.Decode_error "expected a list of tools") let all () = let content = Data.read "tools.yml" |> Option.get in decode content let pp_lifecycle ppf v = Fmt.pf ppf "%s" (match v with | `Incubate -> "`Incubate" | `Active -> "`Active" | `Sustain -> "`Sustain" | `Deprecate -> "`Deprecate") let pp ppf v = Fmt.pf ppf {| { name = %a ; slug = %a ; source = %a ; license = %a ; synopsis = %a ; description = %a ; lifecycle = %a }|} Pp.string v.name Pp.string v.slug Pp.string v.source Pp.string v.license Pp.string v.synopsis Pp.string v.description pp_lifecycle v.lifecycle let pp_list = Pp.list pp let template () = Format.asprintf {| type lifecycle = [ `Incubate | `Active | `Sustain | `Deprecate ] type t = { name : string ; slug : string ; source : string ; license : string ; synopsis : string ; description : string ; lifecycle : lifecycle } let all = %a |} pp_list (all ())
null
https://raw.githubusercontent.com/ocaml/ood/75c4f85e9a8cbe26530301cc14df578f0fc5c494/src/ood-gen/lib/tool.ml
ocaml
type metadata = { name : string; source : string; license : string; synopsis : string; description : string; lifecycle : string; } [@@deriving yaml] let path = Fpath.v "data/tools.yml" module Lifecycle = struct type t = [ `Incubate | `Active | `Sustain | `Deprecate ] let to_string = function | `Incubate -> "incubate" | `Active -> "active" | `Sustain -> "sustain" | `Deprecate -> "deprecate" let of_string = function | "incubate" -> Ok `Incubate | "active" -> Ok `Active | "sustain" -> Ok `Sustain | "deprecate" -> Ok `Deprecate | s -> Error (`Msg ("Unknown lifecycle type: " ^ s)) end type t = { name : string; slug : string; source : string; license : string; synopsis : string; description : string; lifecycle : Lifecycle.t; } let parse s = let yaml = Utils.decode_or_raise Yaml.of_string s in match yaml with | `O [ ("tools", `A xs) ] -> Ok (List.map (fun x -> Utils.decode_or_raise metadata_of_yaml x) xs) | _ -> Error (`Msg "Expected list of tools") let decode s = let yaml = Utils.decode_or_raise Yaml.of_string s in match yaml with | `O [ ("tools", `A xs) ] -> List.map (fun x -> try let (metadata : metadata) = Utils.decode_or_raise metadata_of_yaml x in let lifecycle = match Lifecycle.of_string metadata.lifecycle with | Ok x -> x | Error (`Msg err) -> raise (Exn.Decode_error err) in let description = Omd.of_string metadata.description |> Omd.to_html in ({ name = metadata.name; slug = Utils.slugify metadata.name; source = metadata.source; license = metadata.license; synopsis = metadata.synopsis; description; lifecycle; } : t) with e -> print_endline (Yaml.to_string x |> Result.get_ok); raise e) xs | _ -> raise (Exn.Decode_error "expected a list of tools") let all () = let content = Data.read "tools.yml" |> Option.get in decode content let pp_lifecycle ppf v = Fmt.pf ppf "%s" (match v with | `Incubate -> "`Incubate" | `Active -> "`Active" | `Sustain -> "`Sustain" | `Deprecate -> "`Deprecate") let pp ppf v = Fmt.pf ppf {| { name = %a ; slug = %a ; source = %a ; license = %a ; synopsis = %a ; description = %a ; lifecycle = %a }|} Pp.string v.name Pp.string v.slug Pp.string v.source Pp.string v.license Pp.string v.synopsis Pp.string v.description pp_lifecycle v.lifecycle let pp_list = Pp.list pp let template () = Format.asprintf {| type lifecycle = [ `Incubate | `Active | `Sustain | `Deprecate ] type t = { name : string ; slug : string ; source : string ; license : string ; synopsis : string ; description : string ; lifecycle : lifecycle } let all = %a |} pp_list (all ())
0539ab893efac9846bfa9ff98fef6f8e83ed52bd9f713170ebc126daacbe88d3
input-output-hk/cardano-sl
Update.hs
{-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # TODO rename the module / move defintions / whatever . -- It's not about the network at all. module Pos.Listener.Update ( UpdateMode , handleProposal , handleVote ) where import Universum import Formatting (build, sformat, (%)) import UnliftIO (MonadUnliftIO) import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Update (UpdateConfiguration, UpdateParams, UpdateProposal (..), UpdateVote (..)) import Pos.DB.Class (MonadDB, MonadGState) import Pos.DB.Lrc (HasLrcContext) import Pos.DB.Update (UpdateContext, processProposal, processVote) import Pos.Infra.Recovery.Info (MonadRecoveryInfo) import Pos.Infra.Reporting (MonadReporting) import Pos.Infra.Shutdown.Class (HasShutdownContext) import Pos.Infra.Slotting (MonadSlots) import Pos.Infra.StateLock (StateLock) import Pos.Util.Util (HasLens (..)) import Pos.Util.Wlog (WithLogger, logNotice, logWarning) type UpdateMode ctx m = ( WithLogger m , MonadIO m , MonadUnliftIO m , MonadMask m , MonadGState m , MonadDB m , MonadReader ctx m , HasLrcContext ctx , HasLens UpdateContext ctx UpdateContext , HasLens UpdateConfiguration ctx UpdateConfiguration , HasLens UpdateParams ctx UpdateParams , HasLens StateLock ctx StateLock , HasShutdownContext ctx , MonadReporting m , MonadRecoveryInfo ctx m , MonadSlots ctx m ) handleProposal :: forall ctx m . UpdateMode ctx m => Genesis.Config -> (UpdateProposal, [UpdateVote]) -> m Bool handleProposal genesisConfig (proposal, votes) = do res <- processProposal genesisConfig proposal logProp proposal res let processed = isRight res processed <$ when processed (mapM_ processVoteLog votes) where processVoteLog :: UpdateVote -> m () processVoteLog vote = processVote genesisConfig vote >>= logVote vote logVote vote (Left cause) = logWarning $ sformat ("Proposal is accepted but vote "%build% " is rejected, the reason is: "%build) vote cause logVote vote (Right _) = logVoteAccepted vote logProp prop (Left cause) = logWarning $ sformat ("Processing of proposal "%build% " failed, the reason is: "%build) prop cause Update proposals are accepted rarely ( at least before ) , -- so it deserves 'Notice' severity. logProp prop (Right _) = logNotice $ sformat ("Processing of proposal "%build%" is successful") prop ---------------------------------------------------------------------------- -- UpdateVote ---------------------------------------------------------------------------- handleVote :: UpdateMode ctx m => Genesis.Config -> UpdateVote -> m Bool handleVote genesisConfig uv = do res <- processVote genesisConfig uv logProcess uv res pure $ isRight res where logProcess vote (Left cause) = logWarning $ sformat ("Processing of vote "%build% "failed, the reason is: "%build) vote cause logProcess vote (Right _) = logVoteAccepted vote ---------------------------------------------------------------------------- -- Helpers ---------------------------------------------------------------------------- Update votes are accepted rarely ( at least before ) , so -- it deserves 'Notice' severity. logVoteAccepted :: WithLogger m => UpdateVote -> m () logVoteAccepted = logNotice . sformat ("Processing of vote "%build%"is successfull")
null
https://raw.githubusercontent.com/input-output-hk/cardano-sl/1499214d93767b703b9599369a431e67d83f10a2/lib/src/Pos/Listener/Update.hs
haskell
# LANGUAGE RankNTypes # It's not about the network at all. so it deserves 'Notice' severity. -------------------------------------------------------------------------- UpdateVote -------------------------------------------------------------------------- -------------------------------------------------------------------------- Helpers -------------------------------------------------------------------------- it deserves 'Notice' severity.
# LANGUAGE ScopedTypeVariables # TODO rename the module / move defintions / whatever . module Pos.Listener.Update ( UpdateMode , handleProposal , handleVote ) where import Universum import Formatting (build, sformat, (%)) import UnliftIO (MonadUnliftIO) import Pos.Chain.Genesis as Genesis (Config) import Pos.Chain.Update (UpdateConfiguration, UpdateParams, UpdateProposal (..), UpdateVote (..)) import Pos.DB.Class (MonadDB, MonadGState) import Pos.DB.Lrc (HasLrcContext) import Pos.DB.Update (UpdateContext, processProposal, processVote) import Pos.Infra.Recovery.Info (MonadRecoveryInfo) import Pos.Infra.Reporting (MonadReporting) import Pos.Infra.Shutdown.Class (HasShutdownContext) import Pos.Infra.Slotting (MonadSlots) import Pos.Infra.StateLock (StateLock) import Pos.Util.Util (HasLens (..)) import Pos.Util.Wlog (WithLogger, logNotice, logWarning) type UpdateMode ctx m = ( WithLogger m , MonadIO m , MonadUnliftIO m , MonadMask m , MonadGState m , MonadDB m , MonadReader ctx m , HasLrcContext ctx , HasLens UpdateContext ctx UpdateContext , HasLens UpdateConfiguration ctx UpdateConfiguration , HasLens UpdateParams ctx UpdateParams , HasLens StateLock ctx StateLock , HasShutdownContext ctx , MonadReporting m , MonadRecoveryInfo ctx m , MonadSlots ctx m ) handleProposal :: forall ctx m . UpdateMode ctx m => Genesis.Config -> (UpdateProposal, [UpdateVote]) -> m Bool handleProposal genesisConfig (proposal, votes) = do res <- processProposal genesisConfig proposal logProp proposal res let processed = isRight res processed <$ when processed (mapM_ processVoteLog votes) where processVoteLog :: UpdateVote -> m () processVoteLog vote = processVote genesisConfig vote >>= logVote vote logVote vote (Left cause) = logWarning $ sformat ("Proposal is accepted but vote "%build% " is rejected, the reason is: "%build) vote cause logVote vote (Right _) = logVoteAccepted vote logProp prop (Left cause) = logWarning $ sformat ("Processing of proposal "%build% " failed, the reason is: "%build) prop cause Update proposals are accepted rarely ( at least before ) , logProp prop (Right _) = logNotice $ sformat ("Processing of proposal "%build%" is successful") prop handleVote :: UpdateMode ctx m => Genesis.Config -> UpdateVote -> m Bool handleVote genesisConfig uv = do res <- processVote genesisConfig uv logProcess uv res pure $ isRight res where logProcess vote (Left cause) = logWarning $ sformat ("Processing of vote "%build% "failed, the reason is: "%build) vote cause logProcess vote (Right _) = logVoteAccepted vote Update votes are accepted rarely ( at least before ) , so logVoteAccepted :: WithLogger m => UpdateVote -> m () logVoteAccepted = logNotice . sformat ("Processing of vote "%build%"is successfull")
3cb0da7fe799201b6608b48642b47902ef1de20cfbfd1cfed7f272ee3981d66d
UBTECH-Walker/WalkerSimulationFor2020WAIC
_package_SEAJointState.lisp
(cl:in-package ubt_core_msgs-msg) (cl:export '(HEADER-VAL HEADER NAME-VAL NAME COMMANDED_POSITION-VAL COMMANDED_POSITION COMMANDED_VELOCITY-VAL COMMANDED_VELOCITY COMMANDED_ACCELERATION-VAL COMMANDED_ACCELERATION COMMANDED_EFFORT-VAL COMMANDED_EFFORT ACTUAL_POSITION-VAL ACTUAL_POSITION ACTUAL_VELOCITY-VAL ACTUAL_VELOCITY ACTUAL_EFFORT-VAL ACTUAL_EFFORT GRAVITY_MODEL_EFFORT-VAL GRAVITY_MODEL_EFFORT GRAVITY_ONLY-VAL GRAVITY_ONLY HYSTERESIS_MODEL_EFFORT-VAL HYSTERESIS_MODEL_EFFORT CROSSTALK_MODEL_EFFORT-VAL CROSSTALK_MODEL_EFFORT HYSTSTATE-VAL HYSTSTATE ))
null
https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_16.04_v1.2_20200616/walker_install/share/common-lisp/ros/ubt_core_msgs/msg/_package_SEAJointState.lisp
lisp
(cl:in-package ubt_core_msgs-msg) (cl:export '(HEADER-VAL HEADER NAME-VAL NAME COMMANDED_POSITION-VAL COMMANDED_POSITION COMMANDED_VELOCITY-VAL COMMANDED_VELOCITY COMMANDED_ACCELERATION-VAL COMMANDED_ACCELERATION COMMANDED_EFFORT-VAL COMMANDED_EFFORT ACTUAL_POSITION-VAL ACTUAL_POSITION ACTUAL_VELOCITY-VAL ACTUAL_VELOCITY ACTUAL_EFFORT-VAL ACTUAL_EFFORT GRAVITY_MODEL_EFFORT-VAL GRAVITY_MODEL_EFFORT GRAVITY_ONLY-VAL GRAVITY_ONLY HYSTERESIS_MODEL_EFFORT-VAL HYSTERESIS_MODEL_EFFORT CROSSTALK_MODEL_EFFORT-VAL CROSSTALK_MODEL_EFFORT HYSTSTATE-VAL HYSTSTATE ))
3786c470753da9241bf219ad53c1ce2dc42f40e2535b46ec2a3c25816ec58ee0
awakesecurity/spectacle
Mealy.hs
# LANGUAGE TupleSections # {-# OPTIONS_HADDOCK show-extensions #-} -- | -- Module : Control.Mealy Copyright : ( c ) Arista Networks , 2022 - 2023 License : Apache License 2.0 , see LICENSE -- -- Stability : stable Portability : non - portable ( GHC extensions ) -- -- Mealy machines. -- -- @since 1.0.0 module Control.Mealy * Mealy Machines Mealy, runMealy, -- ** Applicative Transformer MealyM (MealyM), runMealyM, arrM, refold, ) where import Control.Applicative (liftA2) import Data.Functor.Identity (Identity (runIdentity)) -- --------------------------------------------------------------------------------------------------------------------- | A mealy machine @m@ over @a@ producing a value in @b@ , as well as its continuation . -- -- @since 1.0.0 newtype MealyM m a b = MealyM { -- | Run a mealy machine given an initial input value. runMealyM :: a -> m (b, MealyM m a b) } deriving (Functor) -- | A pure mealy machine. -- -- @since 1.0.0 type Mealy = MealyM Identity -- | Run a @'Mealy'@ machine with an initial input. -- -- @since 1.0.0 runMealy :: Mealy a b -> a -> (b, Mealy a b) runMealy (MealyM k) x = runIdentity (k x) | Lift any monadic function @a - > m b@ into a @'MealyM'@ machine . -- -- @since 1.0.0 arrM :: Functor m => (a -> m b) -> MealyM m a b arrM f = let k = MealyM (fmap (,k) . f) in k | " " the type of a mealy machine @a - > m b@ into a new type @a - > m c@. -- -- @since 1.0.0 refold :: Monad m => (a -> b -> MealyM m a c -> m (c, MealyM m a c)) -> MealyM m a b -> MealyM m a c refold f (MealyM k) = MealyM \s -> do (x, k') <- k s f s x (refold f k') -- | @since 1.0.0 instance (Applicative m, Semigroup b) => Semigroup (MealyM m a b) where MealyM f <> MealyM g = MealyM \x -> liftA2 (<>) (f x) (g x) {-# INLINE (<>) #-} -- | @since 1.0.0 instance (Applicative m, Monoid b) => Monoid (MealyM m a b) where mempty = MealyM \_ -> pure mempty # INLINE mempty # -- | @since 1.0.0 instance Applicative m => Applicative (MealyM m a) where pure x = MealyM \_ -> pure (x, pure x) # INLINE pure # MealyM m <*> MealyM n = MealyM \x -> liftA2 (\(f, m') (c, n') -> (f c, m' <*> n')) (m x) (n x) {-# INLINE (<*>) #-}
null
https://raw.githubusercontent.com/awakesecurity/spectacle/430680c28b26dabb50f466948180eb59ba72fc8e/src/Control/Mealy.hs
haskell
# OPTIONS_HADDOCK show-extensions # | Module : Control.Mealy Stability : stable Mealy machines. @since 1.0.0 ** Applicative Transformer --------------------------------------------------------------------------------------------------------------------- @since 1.0.0 | Run a mealy machine given an initial input value. | A pure mealy machine. @since 1.0.0 | Run a @'Mealy'@ machine with an initial input. @since 1.0.0 @since 1.0.0 @since 1.0.0 | @since 1.0.0 # INLINE (<>) # | @since 1.0.0 | @since 1.0.0 # INLINE (<*>) #
# LANGUAGE TupleSections # Copyright : ( c ) Arista Networks , 2022 - 2023 License : Apache License 2.0 , see LICENSE Portability : non - portable ( GHC extensions ) module Control.Mealy * Mealy Machines Mealy, runMealy, MealyM (MealyM), runMealyM, arrM, refold, ) where import Control.Applicative (liftA2) import Data.Functor.Identity (Identity (runIdentity)) | A mealy machine @m@ over @a@ producing a value in @b@ , as well as its continuation . newtype MealyM m a b = MealyM runMealyM :: a -> m (b, MealyM m a b) } deriving (Functor) type Mealy = MealyM Identity runMealy :: Mealy a b -> a -> (b, Mealy a b) runMealy (MealyM k) x = runIdentity (k x) | Lift any monadic function @a - > m b@ into a @'MealyM'@ machine . arrM :: Functor m => (a -> m b) -> MealyM m a b arrM f = let k = MealyM (fmap (,k) . f) in k | " " the type of a mealy machine @a - > m b@ into a new type @a - > m c@. refold :: Monad m => (a -> b -> MealyM m a c -> m (c, MealyM m a c)) -> MealyM m a b -> MealyM m a c refold f (MealyM k) = MealyM \s -> do (x, k') <- k s f s x (refold f k') instance (Applicative m, Semigroup b) => Semigroup (MealyM m a b) where MealyM f <> MealyM g = MealyM \x -> liftA2 (<>) (f x) (g x) instance (Applicative m, Monoid b) => Monoid (MealyM m a b) where mempty = MealyM \_ -> pure mempty # INLINE mempty # instance Applicative m => Applicative (MealyM m a) where pure x = MealyM \_ -> pure (x, pure x) # INLINE pure # MealyM m <*> MealyM n = MealyM \x -> liftA2 (\(f, m') (c, n') -> (f c, m' <*> n')) (m x) (n x)
91f6bd9ddd7f39decaa84889cfd79b2e941947d2cd0983998774c7b60637c381
ocsigen/js_of_ocaml
test4.ml
(* TEST *) open Effect open Effect.Deep type _ t += Foo : int -> int t let r = try_with perform (Foo 3) { effc = fun (type a) (e : a t) -> match e with | Foo i -> Some (fun (k : (a,_) continuation) -> try_with (continue k) (i+1) { effc = fun (type a) (e : a t) -> match e with | Foo i -> Some (fun k -> failwith "NO") | e -> None }) | e -> None } let () = Printf.printf "%d\n" r
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/3a615d693b213140ea8e5c43d5bbe99569bc898d/compiler/tests-ocaml/lib-effects/test4.ml
ocaml
TEST
open Effect open Effect.Deep type _ t += Foo : int -> int t let r = try_with perform (Foo 3) { effc = fun (type a) (e : a t) -> match e with | Foo i -> Some (fun (k : (a,_) continuation) -> try_with (continue k) (i+1) { effc = fun (type a) (e : a t) -> match e with | Foo i -> Some (fun k -> failwith "NO") | e -> None }) | e -> None } let () = Printf.printf "%d\n" r
237efbc2dc8d74c0bef225b08947b0bd304698c3e0b51005b1a47ccd9c29786d
karamellpelle/grid
OpenGL.hs
module OpenGL ( #ifdef GRID_PLATFORM_GLFW module OpenGL.GLFW, #endif module Foreign.Storable, module Foreign.Ptr, module Foreign.C, module Foreign.Marshal.Alloc, module Foreign.Marshal.Array, module Data.Word, module Data.Bits, ) where import Foreign.Storable import Foreign.Ptr import Foreign.C import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Data.Word import Data.Bits #ifdef GRID_PLATFORM_GLFW import OpenGL.GLFW #endif
null
https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/OpenGL.hs
haskell
module OpenGL ( #ifdef GRID_PLATFORM_GLFW module OpenGL.GLFW, #endif module Foreign.Storable, module Foreign.Ptr, module Foreign.C, module Foreign.Marshal.Alloc, module Foreign.Marshal.Array, module Data.Word, module Data.Bits, ) where import Foreign.Storable import Foreign.Ptr import Foreign.C import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Data.Word import Data.Bits #ifdef GRID_PLATFORM_GLFW import OpenGL.GLFW #endif
405a98cde4f0fbb70c6243b5bde6057e3fa4d954991332e3316bacb6fc75a162
luqui/experiments
falgebra.hs
# LANGUAGE ConstraintKinds , DeriveFunctor , , DeriveTraversable , FlexibleContexts , FlexibleInstances , GADTs , GeneralizedNewtypeDeriving , MultiParamTypeClasses , PolyKinds , RankNTypes , ScopedTypeVariables , StandaloneDeriving , TupleSections , TypeFamilies , TypeOperators , UndecidableInstances , UndecidableSuperClasses # import Data.Functor.Classes import Data.Functor.Compose data Void absurd :: Void -> a absurd _ = error "absurd" data Proxy t = Proxy data (f <+> g) a = Inl (f a) | Inr (g a) deriving (Functor, Foldable, Traversable) data (f <*> g) a = Product (f a) (g a) deriving (Functor, Foldable, Traversable) -- F marks that this is to be used as a functor for the purposes of instances. newtype F f a = F { getF :: f a } deriving (Functor, Applicative, Monad, Foldable, Traversable) class (Functor f) => HasAlg f a where alg :: f a -> a instance (Functor f) => HasAlg f () where alg _ = () instance (Functor f, HasAlg f a, HasAlg f b) => HasAlg f (a,b) where alg x = (alg (fmap fst x), alg (fmap snd x)) -- ... etc instance (Traversable f, HasAlg f a) => HasAlg f (r -> a) where alg = getF . alg . fmap F -- Unfortunate that we have to mark this specially. instance (Applicative g, Traversable f, HasAlg f a) => HasAlg f (F g a) where alg = fmap alg . sequenceA -- We can compose functors too, not just data! instance (HasAlg f a, HasAlg g a) => HasAlg (Compose f g) a where alg = alg . fmap alg . getCompose instance (HasAlg f a, HasAlg g a) => HasAlg (f <+> g) a where alg (Inl f) = alg f alg (Inr g) = alg g class (Functor f) => HasCoalg f a where coalg :: a -> f a instance (Functor f) => HasCoalg f Void where coalg = absurd instance (Functor f, HasCoalg f a, HasCoalg f b) => HasCoalg f (Either a b) where coalg (Left x) = Left <$> coalg x coalg (Right x) = Right <$> coalg x instance (Functor f, HasCoalg f a) => HasCoalg f (r,a) where coalg (r,x) = (r,) <$> coalg x -- For pairs, there is also this. It seems we would need some way to differentiate " product"-like data from " environment"-like data . -- instance ( Applicative f , HasCoalg f a , HasCoalg f b ) = > HasCoalg f ( a , b ) where coalg ( a , b ) = ( , ) < $ > coalg a < * > coalg b -- There is also the dual for HasAlg using linear : : f ( a , b ) - > ( a , f b ) -- (or many similar treatments) but this is not given by a standard typeclass -- so I have omitted it. instance (Traversable g, Applicative f, HasCoalg f a) => HasCoalg f (F g a) where coalg = sequenceA . fmap coalg instance (HasCoalg f a, HasCoalg g a) => HasCoalg (Compose f g) a where coalg = Compose . fmap coalg . coalg instance (HasCoalg f a, HasCoalg g a) => HasCoalg (f <*> g) a where coalg x = Product (coalg x) (coalg x) newtype Fix f = Fix { unFix :: f (Fix f) } instance (Show1 f) => Show (Fix f) where showsPrec = showsUnaryWith showsPrec "Fix" instance (Functor f) => HasAlg f (Fix f) where alg = Fix instance (Functor f) => HasCoalg f (Fix f) where coalg = unFix class (Functor (AlgebraOf c)) => Algebraic c where data AlgebraOf c :: * -> * stdAlgebra :: c a => AlgebraOf c a -> a class (Functor (CoalgebraOf c)) => Coalgebraic c where data CoalgebraOf c :: * -> * stdCoalgebra :: c a => a -> CoalgebraOf c a -- To mark the standard instance newtype Std a = Std { getStd :: a } deriving (Show) instance (Algebraic c, c a) => HasAlg (AlgebraOf c) (Std a) where alg = Std . stdAlgebra . fmap getStd instance (Coalgebraic c, c a) => HasCoalg (CoalgebraOf c) (Std a) where coalg = fmap Std . stdCoalgebra . getStd instance Algebraic Num where data AlgebraOf Num a = Plus a a | Minus a a | Times a a | Negate a | Abs a | Signum a | FromInteger Integer deriving (Show, Functor, Foldable, Traversable) stdAlgebra (Plus x y) = x + y stdAlgebra (Minus x y) = x - y stdAlgebra (Times x y) = x * y stdAlgebra (Negate x) = negate x stdAlgebra (Abs x) = abs x stdAlgebra (Signum x) = signum x stdAlgebra (FromInteger i) = fromInteger i newtype New a = New { getNew :: a } deriving Show instance (HasAlg (AlgebraOf Num) a) => Num (New a) where New x + New y = New $ alg (Plus x y) New x - New y = New $ alg (Minus x y) New x * New y = New $ alg (Times x y) negate (New x) = New $ alg (Negate x) abs (New x) = New $ alg (Abs x) signum (New x) = New $ alg (Signum x) fromInteger i = New $ alg (FromInteger i) WOW ( lol , was it worth it ? ) test :: New (Std Int, Std Int) test = 1 -- I think adapting this into the existing ecosystem is not going to happen -- cleanly. Sadly. But for my own classes I could use it.
null
https://raw.githubusercontent.com/luqui/experiments/c0b9153c41507afbfdeb2b32bfc65fd1ac83fb26/falgebra.hs
haskell
F marks that this is to be used as a functor for the purposes of instances. ... etc Unfortunate that we have to mark this specially. We can compose functors too, not just data! For pairs, there is also this. It seems we would need some way to (or many similar treatments) but this is not given by a standard typeclass so I have omitted it. To mark the standard instance I think adapting this into the existing ecosystem is not going to happen cleanly. Sadly. But for my own classes I could use it.
# LANGUAGE ConstraintKinds , DeriveFunctor , , DeriveTraversable , FlexibleContexts , FlexibleInstances , GADTs , GeneralizedNewtypeDeriving , MultiParamTypeClasses , PolyKinds , RankNTypes , ScopedTypeVariables , StandaloneDeriving , TupleSections , TypeFamilies , TypeOperators , UndecidableInstances , UndecidableSuperClasses # import Data.Functor.Classes import Data.Functor.Compose data Void absurd :: Void -> a absurd _ = error "absurd" data Proxy t = Proxy data (f <+> g) a = Inl (f a) | Inr (g a) deriving (Functor, Foldable, Traversable) data (f <*> g) a = Product (f a) (g a) deriving (Functor, Foldable, Traversable) newtype F f a = F { getF :: f a } deriving (Functor, Applicative, Monad, Foldable, Traversable) class (Functor f) => HasAlg f a where alg :: f a -> a instance (Functor f) => HasAlg f () where alg _ = () instance (Functor f, HasAlg f a, HasAlg f b) => HasAlg f (a,b) where alg x = (alg (fmap fst x), alg (fmap snd x)) instance (Traversable f, HasAlg f a) => HasAlg f (r -> a) where alg = getF . alg . fmap F instance (Applicative g, Traversable f, HasAlg f a) => HasAlg f (F g a) where alg = fmap alg . sequenceA instance (HasAlg f a, HasAlg g a) => HasAlg (Compose f g) a where alg = alg . fmap alg . getCompose instance (HasAlg f a, HasAlg g a) => HasAlg (f <+> g) a where alg (Inl f) = alg f alg (Inr g) = alg g class (Functor f) => HasCoalg f a where coalg :: a -> f a instance (Functor f) => HasCoalg f Void where coalg = absurd instance (Functor f, HasCoalg f a, HasCoalg f b) => HasCoalg f (Either a b) where coalg (Left x) = Left <$> coalg x coalg (Right x) = Right <$> coalg x instance (Functor f, HasCoalg f a) => HasCoalg f (r,a) where coalg (r,x) = (r,) <$> coalg x differentiate " product"-like data from " environment"-like data . instance ( Applicative f , HasCoalg f a , HasCoalg f b ) = > HasCoalg f ( a , b ) where coalg ( a , b ) = ( , ) < $ > coalg a < * > coalg b There is also the dual for HasAlg using linear : : f ( a , b ) - > ( a , f b ) instance (Traversable g, Applicative f, HasCoalg f a) => HasCoalg f (F g a) where coalg = sequenceA . fmap coalg instance (HasCoalg f a, HasCoalg g a) => HasCoalg (Compose f g) a where coalg = Compose . fmap coalg . coalg instance (HasCoalg f a, HasCoalg g a) => HasCoalg (f <*> g) a where coalg x = Product (coalg x) (coalg x) newtype Fix f = Fix { unFix :: f (Fix f) } instance (Show1 f) => Show (Fix f) where showsPrec = showsUnaryWith showsPrec "Fix" instance (Functor f) => HasAlg f (Fix f) where alg = Fix instance (Functor f) => HasCoalg f (Fix f) where coalg = unFix class (Functor (AlgebraOf c)) => Algebraic c where data AlgebraOf c :: * -> * stdAlgebra :: c a => AlgebraOf c a -> a class (Functor (CoalgebraOf c)) => Coalgebraic c where data CoalgebraOf c :: * -> * stdCoalgebra :: c a => a -> CoalgebraOf c a newtype Std a = Std { getStd :: a } deriving (Show) instance (Algebraic c, c a) => HasAlg (AlgebraOf c) (Std a) where alg = Std . stdAlgebra . fmap getStd instance (Coalgebraic c, c a) => HasCoalg (CoalgebraOf c) (Std a) where coalg = fmap Std . stdCoalgebra . getStd instance Algebraic Num where data AlgebraOf Num a = Plus a a | Minus a a | Times a a | Negate a | Abs a | Signum a | FromInteger Integer deriving (Show, Functor, Foldable, Traversable) stdAlgebra (Plus x y) = x + y stdAlgebra (Minus x y) = x - y stdAlgebra (Times x y) = x * y stdAlgebra (Negate x) = negate x stdAlgebra (Abs x) = abs x stdAlgebra (Signum x) = signum x stdAlgebra (FromInteger i) = fromInteger i newtype New a = New { getNew :: a } deriving Show instance (HasAlg (AlgebraOf Num) a) => Num (New a) where New x + New y = New $ alg (Plus x y) New x - New y = New $ alg (Minus x y) New x * New y = New $ alg (Times x y) negate (New x) = New $ alg (Negate x) abs (New x) = New $ alg (Abs x) signum (New x) = New $ alg (Signum x) fromInteger i = New $ alg (FromInteger i) WOW ( lol , was it worth it ? ) test :: New (Std Int, Std Int) test = 1
b8632ed415cdf36138899a4419ca74bd5ac29b9532ffac734c868ec6535807fe
immutant/immutant
messaging.clj
Copyright 2014 - 2017 Red Hat , Inc , and individual contributors . ;; Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; ;; -2.0 ;; ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. (ns immutant.messaging "Easily publish and receive messages containing any type of nested data structure to dynamically-created queues and topics." (:require [immutant.internal.options :as o] [immutant.internal.util :as u] [immutant.codecs :as codecs] [immutant.messaging.internal :refer :all]) (:import [org.projectodd.wunderboss.messaging Context Destination Destination$ListenOption Destination$PublishOption Destination$ReceiveOption Message Messaging Messaging$CreateContextOption Messaging$CreateOption Messaging$CreateQueueOption Messaging$CreateTopicOption Queue Topic Topic$SubscribeOption Topic$UnsubscribeOption])) (defn ^Context context "Creates a messaging context. A context represents a remote or local connection to the messaging broker. There are three reasons you would create a context rather than rely on the messaging functions to lazily create them as needed: 1. for communicating with a remote HornetQ instance 2. for sharing a context among a batch of messaging operations 3. for decoupling the client-id from the subscription name for durable topic subscriptions (see [[subscribe]]) You are responsible for closing any contexts created via this function. Options that apply to both local and remote contexts are [default]: * :client-id - identifies the context for use with a durable topic subscriber (see [[subscribe]]) [nil] * :xa? - if true, returns an XA context for use in a distributed transaction [false] * :mode - one of: :auto-ack, :client-ack, :transacted. Ignored if :xa? is true. [:auto-ack] Options that apply to only remote contexts are [default]: * :host - the host of a remote broker [nil] * :port - the port of a remote broker [nil, 5445 if :host provided] * :username - a username for the remote broker [nil] * :password - the corresponding password for :username [nil] * :remote-type - when connecting to a HornetQ instance running inside WildFly, this needs to be set to :hornetq-wildfly [:hornetq-standalone] * :reconnect-attempts - total number of reconnect attempts to make before giving up (-1 for unlimited) [0] * :reconnect-retry-interval - the period in milliseconds between subsequent recontext attempts [2000] * :reconnect-max-retry-interval - the max retry interval that will be used [2000] * :reconnect-retry-interval-multiplier - a multiplier to apply to the time since the last retry to compute the time to the next retry [1.0]" [& options] (let [options (-> options u/kwargs-or-map->map coerce-context-mode (o/validate-options context) (update-in [:remote-type] o/->underscored-string))] (.createContext (broker nil) (o/extract-options options Messaging$CreateContextOption)))) (o/set-valid-options! context (-> (o/opts->set Messaging$CreateContextOption) (o/boolify :xa))) (defn ^Queue queue "Establishes a handle to a messaging queue. If given a :context, the context must be remote, and is remembered and used as a default option to any fn that takes a queue and a context. This creates the queue if no :context is provided and it does not yet exist. The following options are supported [default]: * :context - a context for a *remote* broker. Cannot be specified with any other options. [nil] Or: * :durable? - whether messages persist across restarts [true] * :selector - a JMS (SQL 92) expression to filter published messages [nil]" [queue-name & options] (let [options (-> options u/kwargs-or-map->map (o/validate-options queue))] (queue-with-meta (.findOrCreateQueue (broker options) queue-name (o/extract-options options Messaging$CreateQueueOption)) {:context (:context options)}))) (o/set-valid-options! queue (o/boolify (o/opts->set Messaging$CreateQueueOption) :durable)) (defn ^Topic topic "Establishes a handle to a messaging topic. If given a :context, the context must be remote, and the context is remembered and used as a default option to any fn that takes a topic and a context. This creates the topic if no :context is provided and it does not yet exist. The following options are supported [default]: * :context - a context for a *remote* broker [nil]" [topic-name & options] (let [options (-> options u/kwargs-or-map->map (o/validate-options topic))] (topic-with-meta (.findOrCreateTopic (broker options) topic-name (o/extract-options options Messaging$CreateTopicOption)) {:context (:context options)}))) (o/set-valid-options! topic (o/opts->set Messaging$CreateTopicOption)) (defn publish "Send a message to a destination. If `message` has metadata, it will be transferred as headers and reconstituted upon receipt. Metadata keys must be valid Java identifiers (because they can be used in selectors) and can be overridden using the :properties option. If no context is provided, a new one is created for each call, which can be inefficient if you are sending a large number of messages. The following options are supported [default]: * :encoding - one of: :edn, :json, :none, or other codec you've registered [:edn] * :priority - 0-9, or one of: :low, :normal, :high, :critical [4] * :ttl - time to live, in millis [0 (forever)] * :persistent? - whether undelivered messages survive restarts [true] * :properties - a map to which selectors may be applied, overrides metadata [nil] * :context - a context to use; caller expected to close [nil]" [^Destination destination message & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) (o/validate-options publish) (o/set-properties (meta message))) coerced-options (o/extract-options options Destination$PublishOption)] (.publish destination message (codecs/lookup-codec (:encoding options :edn)) coerced-options))) (o/set-valid-options! publish (-> (o/opts->set Destination$PublishOption) (conj :encoding) (o/boolify :persistent))) (defn receive "Receive a message from `destination`. If a :selector is provided, then only messages having metadata/properties matching that expression may be received. If no context is provided, a new one is created for each call, which can be inefficient if you are receiving a large number of messages. The following options are supported [default]: * :timeout - time in millis, after which the timeout-val is returned. 0 means wait forever, -1 means don't wait at all [10000] * :timeout-val - the value to return when a timeout occurs. Also returned when a timeout of -1 is specified, and no message is available [nil] * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is returned. Otherwise, the base message object is returned [true] * :context - a context to use; caller expected to close [nil]" [^Destination destination & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) (o/validate-options receive)) ^Message message (.receive destination codecs/codecs (o/extract-options options Destination$ReceiveOption))] (if message (if (:decode? options true) (decode-with-metadata message) message) (:timeout-val options)))) (o/set-valid-options! receive (-> (o/opts->set Destination$ReceiveOption) (conj :encoding :timeout-val) (o/boolify :decode))) (defn listen "Registers a single-arity function `f` to handle messages published to `destination`. If a :selector is provided, then only messages having metadata/properties matching that expression will be received. If given a :context, the context must be remote, and the mode of that context is ignored, since it is used solely to generate sub-contexts for each listener thread. Closing the given context will also close the listener. The following options are supported [default]: * :concurrency - the number of threads handling messages [1 for topics, #cores for queues] * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is passed to `f`. Otherwise, the base message object is passed [true] * :context - a context for a *remote* broker; caller expected to close [nil] * :mode - the mode to use for the listener context. One of :auto-ack, :client-ack, :transacted [:transacted] Note the default :mode is :transacted. This can lead to deadlock when [[publish]] or [[request]] is invoked in the handler, since they will attempt to participate in the listener's transaction, which won't be committed until the handler completes. In this case, use either :auto-ack or an XA [[context]]. Returns a listener object that can be stopped by passing it to [[stop]], or by calling .close on it." [^Destination destination f & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) coerce-context-mode (o/validate-options listen))] (.listen destination (message-handler f (:decode? options true)) codecs/codecs (o/extract-options options Destination$ListenOption)))) (o/set-valid-options! listen (o/boolify (o/opts->set Destination$ListenOption) :decode)) (defn request "Send `message` to `queue` and return a Future that will retrieve the response. Implements the request-response pattern, and is used in conjunction with [[respond]]. It takes the same options as [[publish]]." [^Queue queue message & options] (let [options (-> options u/kwargs-or-map->map (merge-context queue) (o/validate-options publish) (o/set-properties (meta message)))] (delegating-future (.request queue message (codecs/lookup-codec (:encoding options :edn)) codecs/codecs (o/extract-options options Destination$PublishOption)) decode-with-metadata))) (defn respond "Listen for messages on `queue` sent by the [[request]] function and respond with the result of applying `f` to the message. Accepts the same options as [[listen]], along with [default]: * :ttl - time for the response mesage to live, in millis [60000 (1 minute)] Note that [[listen]] and [[respond]] should not be called on the same queue." [^Queue queue f & options] (let [options (-> options u/kwargs-or-map->map (merge-context queue) coerce-context-mode (o/validate-options respond))] (.respond queue (message-handler f (:decode? options true) true) codecs/codecs (o/extract-options options Destination$ListenOption)))) (o/set-valid-options! respond (conj (o/valid-options-for listen) :ttl)) (defn subscribe "Sets up a durable subscription to `topic`, and registers a listener with `f`. `subscription-name` is used to identify the subscription, allowing you to stop the listener and resubscribe with the same name in the future without losing messages sent in the interim. The subscription is uniquely identified by the context's :client-id paired with the subscription name. If no :context is provided, a new context is created for this subscriber and the subscription name is used as the :client-id of the internally-created context. If a context is provided, it *must* have its :client-id set. If a :selector is provided, then only messages having metadata/properties matching that expression may be received. The following options are supported [default]: * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is passed to `f`. Otherwise, the javax.jms.Message object is passed [true] * :context - a context to use; caller expected to close [nil] Returns a listener object that can can be stopped by passing it to [[stop]], or by calling .close on it. Subscriptions should be torn down when no longer needed - see [[unsubscribe]]." [^Topic topic subscription-name f & options] (let [options (-> options u/kwargs-or-map->map (merge-context topic) (o/validate-options listen subscribe))] (.subscribe topic (name subscription-name) (message-handler f (:decode? options true)) codecs/codecs (o/extract-options options Topic$SubscribeOption)))) (o/set-valid-options! subscribe (o/boolify (o/opts->set Topic$SubscribeOption) :decode)) (defn unsubscribe "Tears down the durable topic subscription on `topic` named `subscription-name`. The subscription is uniquely identified by the context's :client-id paired with the subscription name. If no :context is provided, a new context is created for this subscriber and the subscription name is used as the :client-id of the internally-created context. If a context is provided, it *must* have its :client-id set to the same value given to the context passed to [[subscribe]]. The following options are supported [default]: * :context - a context to use; caller expected to close [nil]" [^Topic topic subscription-name & options] (let [options (-> options u/kwargs-or-map->map (merge-context topic) (o/validate-options unsubscribe))] (.unsubscribe topic (name subscription-name) (o/extract-options options Topic$UnsubscribeOption)))) (o/set-valid-options! unsubscribe (o/opts->set Topic$UnsubscribeOption)) (defn stop "Stops the given context, destination, listener, or subscription listener. Note that stopping a destination may remove it from the broker if called outside of the container." [x] (if (instance? Destination x) (.stop ^Destination x) (.close ^java.lang.AutoCloseable x)))
null
https://raw.githubusercontent.com/immutant/immutant/6ff8fa03acf73929f61f2ca75446cb559ddfc1ef/messaging/src/immutant/messaging.clj
clojure
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. caller expected to close [nil]" caller expected to close [nil]" caller expected to close [nil] caller expected to close [nil] caller expected to close [nil]"
Copyright 2014 - 2017 Red Hat , Inc , and individual contributors . distributed under the License is distributed on an " AS IS " BASIS , (ns immutant.messaging "Easily publish and receive messages containing any type of nested data structure to dynamically-created queues and topics." (:require [immutant.internal.options :as o] [immutant.internal.util :as u] [immutant.codecs :as codecs] [immutant.messaging.internal :refer :all]) (:import [org.projectodd.wunderboss.messaging Context Destination Destination$ListenOption Destination$PublishOption Destination$ReceiveOption Message Messaging Messaging$CreateContextOption Messaging$CreateOption Messaging$CreateQueueOption Messaging$CreateTopicOption Queue Topic Topic$SubscribeOption Topic$UnsubscribeOption])) (defn ^Context context "Creates a messaging context. A context represents a remote or local connection to the messaging broker. There are three reasons you would create a context rather than rely on the messaging functions to lazily create them as needed: 1. for communicating with a remote HornetQ instance 2. for sharing a context among a batch of messaging operations 3. for decoupling the client-id from the subscription name for durable topic subscriptions (see [[subscribe]]) You are responsible for closing any contexts created via this function. Options that apply to both local and remote contexts are [default]: * :client-id - identifies the context for use with a durable topic subscriber (see [[subscribe]]) [nil] * :xa? - if true, returns an XA context for use in a distributed transaction [false] * :mode - one of: :auto-ack, :client-ack, :transacted. Ignored if :xa? is true. [:auto-ack] Options that apply to only remote contexts are [default]: * :host - the host of a remote broker [nil] * :port - the port of a remote broker [nil, 5445 if :host provided] * :username - a username for the remote broker [nil] * :password - the corresponding password for :username [nil] * :remote-type - when connecting to a HornetQ instance running inside WildFly, this needs to be set to :hornetq-wildfly [:hornetq-standalone] * :reconnect-attempts - total number of reconnect attempts to make before giving up (-1 for unlimited) [0] * :reconnect-retry-interval - the period in milliseconds between subsequent recontext attempts [2000] * :reconnect-max-retry-interval - the max retry interval that will be used [2000] * :reconnect-retry-interval-multiplier - a multiplier to apply to the time since the last retry to compute the time to the next retry [1.0]" [& options] (let [options (-> options u/kwargs-or-map->map coerce-context-mode (o/validate-options context) (update-in [:remote-type] o/->underscored-string))] (.createContext (broker nil) (o/extract-options options Messaging$CreateContextOption)))) (o/set-valid-options! context (-> (o/opts->set Messaging$CreateContextOption) (o/boolify :xa))) (defn ^Queue queue "Establishes a handle to a messaging queue. If given a :context, the context must be remote, and is remembered and used as a default option to any fn that takes a queue and a context. This creates the queue if no :context is provided and it does not yet exist. The following options are supported [default]: * :context - a context for a *remote* broker. Cannot be specified with any other options. [nil] Or: * :durable? - whether messages persist across restarts [true] * :selector - a JMS (SQL 92) expression to filter published messages [nil]" [queue-name & options] (let [options (-> options u/kwargs-or-map->map (o/validate-options queue))] (queue-with-meta (.findOrCreateQueue (broker options) queue-name (o/extract-options options Messaging$CreateQueueOption)) {:context (:context options)}))) (o/set-valid-options! queue (o/boolify (o/opts->set Messaging$CreateQueueOption) :durable)) (defn ^Topic topic "Establishes a handle to a messaging topic. If given a :context, the context must be remote, and the context is remembered and used as a default option to any fn that takes a topic and a context. This creates the topic if no :context is provided and it does not yet exist. The following options are supported [default]: * :context - a context for a *remote* broker [nil]" [topic-name & options] (let [options (-> options u/kwargs-or-map->map (o/validate-options topic))] (topic-with-meta (.findOrCreateTopic (broker options) topic-name (o/extract-options options Messaging$CreateTopicOption)) {:context (:context options)}))) (o/set-valid-options! topic (o/opts->set Messaging$CreateTopicOption)) (defn publish "Send a message to a destination. If `message` has metadata, it will be transferred as headers and reconstituted upon receipt. Metadata keys must be valid Java identifiers (because they can be used in selectors) and can be overridden using the :properties option. If no context is provided, a new one is created for each call, which can be inefficient if you are sending a large number of messages. The following options are supported [default]: * :encoding - one of: :edn, :json, :none, or other codec you've registered [:edn] * :priority - 0-9, or one of: :low, :normal, :high, :critical [4] * :ttl - time to live, in millis [0 (forever)] * :persistent? - whether undelivered messages survive restarts [true] * :properties - a map to which selectors may be applied, overrides metadata [nil] [^Destination destination message & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) (o/validate-options publish) (o/set-properties (meta message))) coerced-options (o/extract-options options Destination$PublishOption)] (.publish destination message (codecs/lookup-codec (:encoding options :edn)) coerced-options))) (o/set-valid-options! publish (-> (o/opts->set Destination$PublishOption) (conj :encoding) (o/boolify :persistent))) (defn receive "Receive a message from `destination`. If a :selector is provided, then only messages having metadata/properties matching that expression may be received. If no context is provided, a new one is created for each call, which can be inefficient if you are receiving a large number of messages. The following options are supported [default]: * :timeout - time in millis, after which the timeout-val is returned. 0 means wait forever, -1 means don't wait at all [10000] * :timeout-val - the value to return when a timeout occurs. Also returned when a timeout of -1 is specified, and no message is available [nil] * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is returned. Otherwise, the base message object is returned [true] [^Destination destination & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) (o/validate-options receive)) ^Message message (.receive destination codecs/codecs (o/extract-options options Destination$ReceiveOption))] (if message (if (:decode? options true) (decode-with-metadata message) message) (:timeout-val options)))) (o/set-valid-options! receive (-> (o/opts->set Destination$ReceiveOption) (conj :encoding :timeout-val) (o/boolify :decode))) (defn listen "Registers a single-arity function `f` to handle messages published to `destination`. If a :selector is provided, then only messages having metadata/properties matching that expression will be received. If given a :context, the context must be remote, and the mode of that context is ignored, since it is used solely to generate sub-contexts for each listener thread. Closing the given context will also close the listener. The following options are supported [default]: * :concurrency - the number of threads handling messages [1 for topics, #cores for queues] * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is passed to `f`. Otherwise, the base message object is passed [true] * :mode - the mode to use for the listener context. One of :auto-ack, :client-ack, :transacted [:transacted] Note the default :mode is :transacted. This can lead to deadlock when [[publish]] or [[request]] is invoked in the handler, since they will attempt to participate in the listener's transaction, which won't be committed until the handler completes. In this case, use either :auto-ack or an XA [[context]]. Returns a listener object that can be stopped by passing it to [[stop]], or by calling .close on it." [^Destination destination f & options] (let [options (-> options u/kwargs-or-map->map (merge-context destination) coerce-context-mode (o/validate-options listen))] (.listen destination (message-handler f (:decode? options true)) codecs/codecs (o/extract-options options Destination$ListenOption)))) (o/set-valid-options! listen (o/boolify (o/opts->set Destination$ListenOption) :decode)) (defn request "Send `message` to `queue` and return a Future that will retrieve the response. Implements the request-response pattern, and is used in conjunction with [[respond]]. It takes the same options as [[publish]]." [^Queue queue message & options] (let [options (-> options u/kwargs-or-map->map (merge-context queue) (o/validate-options publish) (o/set-properties (meta message)))] (delegating-future (.request queue message (codecs/lookup-codec (:encoding options :edn)) codecs/codecs (o/extract-options options Destination$PublishOption)) decode-with-metadata))) (defn respond "Listen for messages on `queue` sent by the [[request]] function and respond with the result of applying `f` to the message. Accepts the same options as [[listen]], along with [default]: * :ttl - time for the response mesage to live, in millis [60000 (1 minute)] Note that [[listen]] and [[respond]] should not be called on the same queue." [^Queue queue f & options] (let [options (-> options u/kwargs-or-map->map (merge-context queue) coerce-context-mode (o/validate-options respond))] (.respond queue (message-handler f (:decode? options true) true) codecs/codecs (o/extract-options options Destination$ListenOption)))) (o/set-valid-options! respond (conj (o/valid-options-for listen) :ttl)) (defn subscribe "Sets up a durable subscription to `topic`, and registers a listener with `f`. `subscription-name` is used to identify the subscription, allowing you to stop the listener and resubscribe with the same name in the future without losing messages sent in the interim. The subscription is uniquely identified by the context's :client-id paired with the subscription name. If no :context is provided, a new context is created for this subscriber and the subscription name is used as the :client-id of the internally-created context. If a context is provided, it *must* have its :client-id set. If a :selector is provided, then only messages having metadata/properties matching that expression may be received. The following options are supported [default]: * :selector - A JMS (SQL 92) expression matching message metadata/properties [nil] * :decode? - if true, the decoded message body is passed to `f`. Otherwise, the javax.jms.Message object is passed [true] Returns a listener object that can can be stopped by passing it to [[stop]], or by calling .close on it. Subscriptions should be torn down when no longer needed - see [[unsubscribe]]." [^Topic topic subscription-name f & options] (let [options (-> options u/kwargs-or-map->map (merge-context topic) (o/validate-options listen subscribe))] (.subscribe topic (name subscription-name) (message-handler f (:decode? options true)) codecs/codecs (o/extract-options options Topic$SubscribeOption)))) (o/set-valid-options! subscribe (o/boolify (o/opts->set Topic$SubscribeOption) :decode)) (defn unsubscribe "Tears down the durable topic subscription on `topic` named `subscription-name`. The subscription is uniquely identified by the context's :client-id paired with the subscription name. If no :context is provided, a new context is created for this subscriber and the subscription name is used as the :client-id of the internally-created context. If a context is provided, it *must* have its :client-id set to the same value given to the context passed to [[subscribe]]. The following options are supported [default]: [^Topic topic subscription-name & options] (let [options (-> options u/kwargs-or-map->map (merge-context topic) (o/validate-options unsubscribe))] (.unsubscribe topic (name subscription-name) (o/extract-options options Topic$UnsubscribeOption)))) (o/set-valid-options! unsubscribe (o/opts->set Topic$UnsubscribeOption)) (defn stop "Stops the given context, destination, listener, or subscription listener. Note that stopping a destination may remove it from the broker if called outside of the container." [x] (if (instance? Destination x) (.stop ^Destination x) (.close ^java.lang.AutoCloseable x)))
3391fd0ca2e2d1848f1b2f21c660d94c586762894ad48e9bbecbca19346040c1
earl-ducaine/cl-garnet
slider-pix.lisp
(create-instance 'v-slid garnet-gadgets:v-slider (:left 40) (:top 20) (:height 250)) (create-instance 'h-slid-top garnet-gadgets:h-slider (:left 120) (:top 80) (:width 200) (:num-marks 6) (:val-1 0) (:val-2 50) (:scr-trill-p NIL) (:page-trill-p NIL)) (create-instance 'h-slid-bottom garnet-gadgets:h-slider (:left 120) (:top 160) (:width 200) (:enumerate-p NIL) (:tic-marks-p NIL) (:value-feedback-p NIL)) (create-instance 'win inter:interactor-window (:aggregate (create-instance 'agg opal:aggregate))) (opal:add-component agg v-slid) (opal:add-component agg h-slid-top) (opal:add-component agg h-slid-bottom) (opal:update win)
null
https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/doc/previous-version/src/gadgets/garnet-code/slider-pix.lisp
lisp
(create-instance 'v-slid garnet-gadgets:v-slider (:left 40) (:top 20) (:height 250)) (create-instance 'h-slid-top garnet-gadgets:h-slider (:left 120) (:top 80) (:width 200) (:num-marks 6) (:val-1 0) (:val-2 50) (:scr-trill-p NIL) (:page-trill-p NIL)) (create-instance 'h-slid-bottom garnet-gadgets:h-slider (:left 120) (:top 160) (:width 200) (:enumerate-p NIL) (:tic-marks-p NIL) (:value-feedback-p NIL)) (create-instance 'win inter:interactor-window (:aggregate (create-instance 'agg opal:aggregate))) (opal:add-component agg v-slid) (opal:add-component agg h-slid-top) (opal:add-component agg h-slid-bottom) (opal:update win)
8c44355beb3e0181d46c4088b4df12afa32e252d7e811bf5c7c4254fb3e97d81
elldritch/hipsterfy
Jobs.hs
module Hipsterfy.Database.Jobs ( UpdateJobInfo, UpdateJobInfoT (..), UpdateJobInfoF, pUpdateJobInfo, updateJobInfoColumns, ) where import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Time (UTCTime) import Opaleye.Field (FieldNullable) import Opaleye.SqlTypes (SqlTimestamptz) import Opaleye.Table (TableFields, required) import Relude data UpdateJobInfoT ts = UpdateJobInfoT { lastUpdateJobSubmitted :: ts, lastUpdateJobCompleted :: ts } type UpdateJobInfo = UpdateJobInfoT (Maybe UTCTime) type UpdateJobInfoF = UpdateJobInfoT (FieldNullable SqlTimestamptz) $(makeAdaptorAndInstance "pUpdateJobInfo" ''UpdateJobInfoT) updateJobInfoColumns :: TableFields UpdateJobInfoF UpdateJobInfoF updateJobInfoColumns = pUpdateJobInfo UpdateJobInfoT { lastUpdateJobSubmitted = required "last_update_job_submitted", lastUpdateJobCompleted = required "last_update_job_completed" }
null
https://raw.githubusercontent.com/elldritch/hipsterfy/7d455697c1146d89fc6b2f78effe6694efe69120/src/Hipsterfy/Database/Jobs.hs
haskell
module Hipsterfy.Database.Jobs ( UpdateJobInfo, UpdateJobInfoT (..), UpdateJobInfoF, pUpdateJobInfo, updateJobInfoColumns, ) where import Data.Profunctor.Product.TH (makeAdaptorAndInstance) import Data.Time (UTCTime) import Opaleye.Field (FieldNullable) import Opaleye.SqlTypes (SqlTimestamptz) import Opaleye.Table (TableFields, required) import Relude data UpdateJobInfoT ts = UpdateJobInfoT { lastUpdateJobSubmitted :: ts, lastUpdateJobCompleted :: ts } type UpdateJobInfo = UpdateJobInfoT (Maybe UTCTime) type UpdateJobInfoF = UpdateJobInfoT (FieldNullable SqlTimestamptz) $(makeAdaptorAndInstance "pUpdateJobInfo" ''UpdateJobInfoT) updateJobInfoColumns :: TableFields UpdateJobInfoF UpdateJobInfoF updateJobInfoColumns = pUpdateJobInfo UpdateJobInfoT { lastUpdateJobSubmitted = required "last_update_job_submitted", lastUpdateJobCompleted = required "last_update_job_completed" }
f5278781c251569720c6f792a03c22f1cc870039d53ef20c308934a88f753d7b
GlideAngle/flare-timing
Ellipsoid.hs
module Ellipsoid.Ellipsoid (units) where import Test.Tasty (TestTree, testGroup) import Ellipsoid.Coincident (coincidentUnits) units :: TestTree units = testGroup "On the WGS84 ellipsoid using Vincenty's solution to the inverse geodetic problem" [ coincidentUnits ]
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/earth/test-suite-zones/Ellipsoid/Ellipsoid.hs
haskell
module Ellipsoid.Ellipsoid (units) where import Test.Tasty (TestTree, testGroup) import Ellipsoid.Coincident (coincidentUnits) units :: TestTree units = testGroup "On the WGS84 ellipsoid using Vincenty's solution to the inverse geodetic problem" [ coincidentUnits ]
1592ca5af8b60dbfe452bef5b334fcefaca614bc97ac9416340580be1f4eaf3a
cffi/cffi
libffi-functions.lisp
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*- ;;; ;;; init.lisp --- Load libffi and define basics ;;; Copyright ( C ) 2009 , 2010 , 2011 < > ;;; ;;; 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. ;;; (in-package #:cffi) ;;; See file-dev/html/The-Basics.html#The-Basics (defcfun ("ffi_prep_cif" libffi/prep-cif) status (ffi-cif :pointer) (ffi-abi abi) (nargs :uint) (rtype :pointer) (argtypes :pointer)) (defcfun ("ffi_call" libffi/call) :void (ffi-cif :pointer) (function :pointer) (rvalue :pointer) (avalues :pointer))
null
https://raw.githubusercontent.com/cffi/cffi/677cabae64b181330a3bbbda9c11891a2a8edcdc/libffi/libffi-functions.lisp
lisp
-*- Mode: lisp; indent-tabs-mode: nil -*- init.lisp --- Load libffi and define basics 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. See file-dev/html/The-Basics.html#The-Basics
Copyright ( C ) 2009 , 2010 , 2011 < > 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 , (in-package #:cffi) (defcfun ("ffi_prep_cif" libffi/prep-cif) status (ffi-cif :pointer) (ffi-abi abi) (nargs :uint) (rtype :pointer) (argtypes :pointer)) (defcfun ("ffi_call" libffi/call) :void (ffi-cif :pointer) (function :pointer) (rvalue :pointer) (avalues :pointer))
05ad0732494803d60dee9e7d0822179d2500a976194324782d2f95019c9e59f6
ertugrulcetin/ClojureNews
forgot_password.cljs
(ns view.forgot-password) (defn component [forgot-password] [:table [:tbody [:tr [:td]] [:tr [:td "username:"] [:td [:input {:id "forgotPassUsernameId" :name "username" :type "text"}]]] [:tr [:td [:button {:id "forgotPassUsernameButtonId" :on-click (fn [_] (forgot-password ["forgotPassUsernameId"]))} "Send reset mail"]]]]]) (defn component-loading [] [:p "Please hold..."])
null
https://raw.githubusercontent.com/ertugrulcetin/ClojureNews/28002f6b620fa4977d561b0cfca0c7f6a635057b/src/cljs/view/forgot_password.cljs
clojure
(ns view.forgot-password) (defn component [forgot-password] [:table [:tbody [:tr [:td]] [:tr [:td "username:"] [:td [:input {:id "forgotPassUsernameId" :name "username" :type "text"}]]] [:tr [:td [:button {:id "forgotPassUsernameButtonId" :on-click (fn [_] (forgot-password ["forgotPassUsernameId"]))} "Send reset mail"]]]]]) (defn component-loading [] [:p "Please hold..."])
83dfa0754acebbfc87b492879cf0d6f2e8aa2fcf028fc4d173f38415a8572e1c
sgbj/MaximaSharp
gentran.lisp
;******************************************************************************* ;* * * copyright ( c ) 1988 kent state univ . kent , ohio 44242 * ;* * ;******************************************************************************* ;; --------- ;; load ;; gtload.l ;; gentran code generation package --------- ; ; for vaxima ( cond ( ( not ( boundp ' * gentran - dir ) ) ( setq * gentran - dir ( " GENTRAN " ) ) ) ) (in-package :maxima) (defvar local-obj-dir) (load (merge-pathnames "convmac.lisp" #-gcl *load-pathname* #+gcl sys:*load-pathname*)) (putprop 'procforttem "templt" 'autoload) (putprop 'procrattem "templt" 'autoload) (putprop 'procctem "templt" 'autoload) (putprop '$readvexp "templt" 'autoload) (putprop 'gentranparse "parser" 'autoload) (putprop 'opt "opt" 'autoload) ;(putprop 'seg "segmnt" 'autoload) (putprop 'fortcode "lspfor" 'autoload) (putprop 'ratcode "lsprat" 'autoload) (putprop 'ccode "lspc" 'autoload) (dolist (fname '( "init" "lspfor" "templt" "global" "intrfc" "pre" "output" "vaxlsp" "segmnt")) (load (merge-pathnames fname #-gcl *load-pathname* #+gcl sys:*load-pathname*)))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/share/contrib/gentran/gentran.lisp
lisp
******************************************************************************* * * * * ******************************************************************************* --------- ;; load gtload.l ;; gentran code generation package ; for vaxima (putprop 'seg "segmnt" 'autoload)
* copyright ( c ) 1988 kent state univ . kent , ohio 44242 * ( cond ( ( not ( boundp ' * gentran - dir ) ) ( setq * gentran - dir ( " GENTRAN " ) ) ) ) (in-package :maxima) (defvar local-obj-dir) (load (merge-pathnames "convmac.lisp" #-gcl *load-pathname* #+gcl sys:*load-pathname*)) (putprop 'procforttem "templt" 'autoload) (putprop 'procrattem "templt" 'autoload) (putprop 'procctem "templt" 'autoload) (putprop '$readvexp "templt" 'autoload) (putprop 'gentranparse "parser" 'autoload) (putprop 'opt "opt" 'autoload) (putprop 'fortcode "lspfor" 'autoload) (putprop 'ratcode "lsprat" 'autoload) (putprop 'ccode "lspc" 'autoload) (dolist (fname '( "init" "lspfor" "templt" "global" "intrfc" "pre" "output" "vaxlsp" "segmnt")) (load (merge-pathnames fname #-gcl *load-pathname* #+gcl sys:*load-pathname*)))
ea08298850c963868d0e6959d488ac2ab867bca51718dcc1b3b2b4d56eea08eb
input-output-hk/project-icarus-importer
Generator.hs
# LANGUAGE TemplateHaskell # module UTxO.Generator ( -- * Inputs -- ** State GenInpState(..) , gisUtxo , initInpState -- ** Generator , RemoveUsedInputs(..) , GenInput , genInput -- * Outputs -- ** Parameters , GenOutParams(..) , defOutParams -- ** State , GenOutState(..) , gosAvailable , initOutState -- ** Generator , GenOutput , genOutput -- * Transactions -- ** Parameters , GenTrParams(..) , defTrParams -- ** State , GenTrState(..) , gtsInpState , gtsNextHash , initTrState -- ** Generator , GenTransaction , MakeOutputsAvailable(..) , genTransaction -- * Chains -- ** Params , GenChainParams(..) , defChainParams -- ** Generator , genChain -- * Auxiliary , replicateAtMostM ) where import Universum import Control.Lens (zoom, (%=), (.=), (<<+=)) import Control.Lens.TH (makeLenses) import qualified Data.Set as Set import Pos.Core (maxCoinVal) import Pos.Util.Chrono import Test.QuickCheck import UTxO.DSL {------------------------------------------------------------------------------- Generate transaction inputs -------------------------------------------------------------------------------} -- | State needed for input generation data GenInpState h a = GenInpState { | Available _gisUtxo :: Utxo h a } makeLenses ''GenInpState -- | Initial 'GenInpState' initInpState :: Utxo h a -> GenInpState h a initInpState utxo = GenInpState { _gisUtxo = utxo } -- | Input generator type GenInput h a = StateT (GenInpState h a) Gen -- | Should we remove used inputs? data RemoveUsedInputs = RemoveUsedInputs | DontRemoveUsedInputs -- | Try to generate an input -- -- Returns nothing if the utxo is empty. genInput :: Hash h a => RemoveUsedInputs -> Set (Input h a) -- Inputs to avoid -> GenInput h a (Maybe (Input h a, Output a)) genInput removeUsedInputs notThese = do utxo <- utxoRemoveInputs notThese <$> use gisUtxo if utxoNull utxo then return Nothing else do (inp, out) <- lift $ elements (utxoToList utxo) case removeUsedInputs of DontRemoveUsedInputs -> return () RemoveUsedInputs -> gisUtxo .= utxoRemoveInputs (Set.singleton inp) utxo return $ Just (inp, out) | Generate up to @n@ distinct inputs genDistinctInputs :: forall h a. Hash h a => RemoveUsedInputs -> Set (Input h a) -- Inputs to avoid -> Int -> GenInput h a [(Input h a, Output a)] genDistinctInputs removeUsedInputs = go where go :: Set (Input h a) -> Int -> GenInput h a [(Input h a, Output a)] go _ 0 = return [] go notThese n = do mInp <- genInput removeUsedInputs notThese case mInp of Nothing -> return [] Just (inp, out) -> -- Removing used inputs or not, don't select same input twice ((inp, out) :) <$> go (Set.insert inp notThese) (n - 1) {------------------------------------------------------------------------------- Generate transaction outputs -------------------------------------------------------------------------------} -- | Parameters for output generation data GenOutParams a = GenOutParams { -- | Addresses we can generate outputs to gopAddresses :: [a] } -- | Default 'GenOutParams' defOutParams :: [a] -- ^ Addresses we can generate outputs to -> GenOutParams a defOutParams addresses = GenOutParams { gopAddresses = addresses } -- | State needed for output generation data GenOutState = GenOutState { -- | Value left _gosAvailable :: Value } makeLenses ''GenOutState | Initial ' GenOutState ' initOutState :: Value -> GenOutState initOutState available = GenOutState { _gosAvailable = available } -- | Output generator type GenOutput = StateT GenOutState Gen -- | Try to generate transaction output -- -- Returns nothing if there is no balance left. genOutput :: GenOutParams a -> GenOutput (Maybe (Output a)) genOutput GenOutParams{..} = do available <- use gosAvailable if available == 0 then return Nothing else do addr <- lift $ elements gopAddresses val <- lift $ choose (1, min available maxCoinVal) gosAvailable .= available - val return $ Just (Output addr val) {------------------------------------------------------------------------------- Generate transaction -------------------------------------------------------------------------------} -- | Parameters for transaction generation data GenTrParams a = GenTrParams { -- | Maximum number of inputs -- -- Generation is biased towards smaller values gtpMaxNumInputs :: Int -- | Maximum number of outputs -- -- Generation does a uniform draw. , gtpMaxNumOutputs :: Int -- | Fee model -- -- Provide fee given number of inputs and outputs , gtpEstimateFee :: Int -> Int -> Value -- | Output parameters , gtpOutParams :: GenOutParams a } -- | Default 'GenTrParams' defTrParams :: (Int -> Int -> Value) -- ^ Fee model -> [a] -- ^ Addresses we can generate outputs to -> GenTrParams a defTrParams feeModel addresses = GenTrParams { gtpMaxNumInputs = 3 , gtpMaxNumOutputs = 3 , gtpEstimateFee = feeModel , gtpOutParams = defOutParams addresses } -- | Should the outputs of the transaction be made available in the -- input generation state? data MakeOutputsAvailable = -- | Yes, make outputs available -- -- This means that the next generation can refer to outputs of the -- previous generated transaction. MakeOutputsAvailable -- | No, don't make output available -- -- Use to generate independent transactions. | DontMakeOutputsAvailable -- | State needed for transaction generation data GenTrState h a = GenTrState { -- | State needed to generate inputs _gtsInpState :: GenInpState h a -- | Next hash , _gtsNextHash :: Int } makeLenses ''GenTrState -- | Initial 'GenTrState' ^ Initial ^ First available hash -> GenTrState h a initTrState utxo nextHash = GenTrState { _gtsInpState = initInpState utxo , _gtsNextHash = nextHash } -- | Transaction generator type GenTransaction h a = StateT (GenTrState h a) Gen -- | Try to generate a transaction -- -- Fails if no inputs were available. genTransaction :: Hash h a => GenTrParams a -> RemoveUsedInputs -> MakeOutputsAvailable -> Set (Input h a) -- ^ Inputs to avoid -> GenTransaction h a (Maybe (Transaction h a)) genTransaction GenTrParams{..} removeUsedInputs makeOutputsAvailable notThese = do numInputs <- lift $ chooseNumInputs inputs <- zoom gtsInpState $ genDistinctInputs removeUsedInputs notThese numInputs if null inputs then return Nothing else do nextHash <- gtsNextHash <<+= 1 numOutputs <- lift $ choose (1, gtpMaxNumOutputs) let fee = gtpEstimateFee numInputs numOutputs inValue = sum (map (outVal . snd) inputs) if inValue <= fee then return Nothing else do let gos = initOutState (inValue - fee) outputs <- lift $ (`evalStateT` gos) $ replicateAtMostM numOutputs $ genOutput gtpOutParams let tr = Transaction { trFresh = 0 , trIns = Set.fromList (map fst inputs) , trOuts = outputs , trFee = fee , trHash = nextHash , trExtra = [] } case makeOutputsAvailable of DontMakeOutputsAvailable -> return () MakeOutputsAvailable -> zoom gtsInpState $ (gisUtxo %= utxoUnion (trUtxo tr)) return $ Just tr where -- Bias towards fewer inputs chooseNumInputs :: Gen Int chooseNumInputs = frequency $ zip [gtpMaxNumInputs, gtpMaxNumInputs-1 ..] (map pure [1 .. gtpMaxNumInputs]) {------------------------------------------------------------------------------- Chains -------------------------------------------------------------------------------} data GenChainParams a = GenChainParams { -- | Maximum number of transactions per block gcpMaxBlockSize :: Int -- | Maximum number of blocks , gcpMaxChainLength :: Int -- | Transaction parameters , gcpTrParams :: GenTrParams a } -- | Default 'GenChainParams' defChainParams :: (Int -> Int -> Value) -- ^ Fee model -> [a] -- ^ Address we can generate outputs for -> GenChainParams a defChainParams feeModel addresses = GenChainParams { gcpMaxBlockSize = 20 , gcpMaxChainLength = 10 , gcpTrParams = defTrParams feeModel addresses } -- | Generate an arbitrary chain -- The chain will have at least one block , but blocks may be empty . genChain :: forall h a. Hash h a => GenChainParams a -> GenTransaction h a (Chain h a) genChain GenChainParams{..} = goChain where goChain :: GenTransaction h a (Chain h a) goChain = OldestFirst <$> do chainLength <- lift $ choose (1, gcpMaxChainLength) replicateM chainLength goBlock goBlock :: GenTransaction h a (Block h a) goBlock = OldestFirst <$> do blockSize <- lift $ choose (0, gcpMaxBlockSize) replicateAtMostM blockSize $ genTransaction gcpTrParams RemoveUsedInputs MakeOutputsAvailable Set.empty {------------------------------------------------------------------------------- Auxiliary -------------------------------------------------------------------------------} replicateAtMostM :: Monad m => Int -> m (Maybe a) -> m [a] replicateAtMostM 0 _ = return [] replicateAtMostM n f = do ma <- f case ma of Just a -> (a :) <$> replicateAtMostM (n - 1) f Nothing -> return []
null
https://raw.githubusercontent.com/input-output-hk/project-icarus-importer/36342f277bcb7f1902e677a02d1ce93e4cf224f0/wallet-new/test/unit/UTxO/Generator.hs
haskell
* Inputs ** State ** Generator * Outputs ** Parameters ** State ** Generator * Transactions ** Parameters ** State ** Generator * Chains ** Params ** Generator * Auxiliary ------------------------------------------------------------------------------ Generate transaction inputs ------------------------------------------------------------------------------ | State needed for input generation | Initial 'GenInpState' | Input generator | Should we remove used inputs? | Try to generate an input Returns nothing if the utxo is empty. Inputs to avoid Inputs to avoid Removing used inputs or not, don't select same input twice ------------------------------------------------------------------------------ Generate transaction outputs ------------------------------------------------------------------------------ | Parameters for output generation | Addresses we can generate outputs to | Default 'GenOutParams' ^ Addresses we can generate outputs to | State needed for output generation | Value left | Output generator | Try to generate transaction output Returns nothing if there is no balance left. ------------------------------------------------------------------------------ Generate transaction ------------------------------------------------------------------------------ | Parameters for transaction generation | Maximum number of inputs Generation is biased towards smaller values | Maximum number of outputs Generation does a uniform draw. | Fee model Provide fee given number of inputs and outputs | Output parameters | Default 'GenTrParams' ^ Fee model ^ Addresses we can generate outputs to | Should the outputs of the transaction be made available in the input generation state? | Yes, make outputs available This means that the next generation can refer to outputs of the previous generated transaction. | No, don't make output available Use to generate independent transactions. | State needed for transaction generation | State needed to generate inputs | Next hash | Initial 'GenTrState' | Transaction generator | Try to generate a transaction Fails if no inputs were available. ^ Inputs to avoid Bias towards fewer inputs ------------------------------------------------------------------------------ Chains ------------------------------------------------------------------------------ | Maximum number of transactions per block | Maximum number of blocks | Transaction parameters | Default 'GenChainParams' ^ Fee model ^ Address we can generate outputs for | Generate an arbitrary chain ------------------------------------------------------------------------------ Auxiliary ------------------------------------------------------------------------------
# LANGUAGE TemplateHaskell # module UTxO.Generator ( GenInpState(..) , gisUtxo , initInpState , RemoveUsedInputs(..) , GenInput , genInput , GenOutParams(..) , defOutParams , GenOutState(..) , gosAvailable , initOutState , GenOutput , genOutput , GenTrParams(..) , defTrParams , GenTrState(..) , gtsInpState , gtsNextHash , initTrState , GenTransaction , MakeOutputsAvailable(..) , genTransaction , GenChainParams(..) , defChainParams , genChain , replicateAtMostM ) where import Universum import Control.Lens (zoom, (%=), (.=), (<<+=)) import Control.Lens.TH (makeLenses) import qualified Data.Set as Set import Pos.Core (maxCoinVal) import Pos.Util.Chrono import Test.QuickCheck import UTxO.DSL data GenInpState h a = GenInpState { | Available _gisUtxo :: Utxo h a } makeLenses ''GenInpState initInpState :: Utxo h a -> GenInpState h a initInpState utxo = GenInpState { _gisUtxo = utxo } type GenInput h a = StateT (GenInpState h a) Gen data RemoveUsedInputs = RemoveUsedInputs | DontRemoveUsedInputs genInput :: Hash h a => RemoveUsedInputs -> GenInput h a (Maybe (Input h a, Output a)) genInput removeUsedInputs notThese = do utxo <- utxoRemoveInputs notThese <$> use gisUtxo if utxoNull utxo then return Nothing else do (inp, out) <- lift $ elements (utxoToList utxo) case removeUsedInputs of DontRemoveUsedInputs -> return () RemoveUsedInputs -> gisUtxo .= utxoRemoveInputs (Set.singleton inp) utxo return $ Just (inp, out) | Generate up to @n@ distinct inputs genDistinctInputs :: forall h a. Hash h a => RemoveUsedInputs -> Int -> GenInput h a [(Input h a, Output a)] genDistinctInputs removeUsedInputs = go where go :: Set (Input h a) -> Int -> GenInput h a [(Input h a, Output a)] go _ 0 = return [] go notThese n = do mInp <- genInput removeUsedInputs notThese case mInp of Nothing -> return [] Just (inp, out) -> ((inp, out) :) <$> go (Set.insert inp notThese) (n - 1) data GenOutParams a = GenOutParams { gopAddresses :: [a] } -> GenOutParams a defOutParams addresses = GenOutParams { gopAddresses = addresses } data GenOutState = GenOutState { _gosAvailable :: Value } makeLenses ''GenOutState | Initial ' GenOutState ' initOutState :: Value -> GenOutState initOutState available = GenOutState { _gosAvailable = available } type GenOutput = StateT GenOutState Gen genOutput :: GenOutParams a -> GenOutput (Maybe (Output a)) genOutput GenOutParams{..} = do available <- use gosAvailable if available == 0 then return Nothing else do addr <- lift $ elements gopAddresses val <- lift $ choose (1, min available maxCoinVal) gosAvailable .= available - val return $ Just (Output addr val) data GenTrParams a = GenTrParams { gtpMaxNumInputs :: Int , gtpMaxNumOutputs :: Int , gtpEstimateFee :: Int -> Int -> Value , gtpOutParams :: GenOutParams a } -> GenTrParams a defTrParams feeModel addresses = GenTrParams { gtpMaxNumInputs = 3 , gtpMaxNumOutputs = 3 , gtpEstimateFee = feeModel , gtpOutParams = defOutParams addresses } data MakeOutputsAvailable = MakeOutputsAvailable | DontMakeOutputsAvailable data GenTrState h a = GenTrState { _gtsInpState :: GenInpState h a , _gtsNextHash :: Int } makeLenses ''GenTrState ^ Initial ^ First available hash -> GenTrState h a initTrState utxo nextHash = GenTrState { _gtsInpState = initInpState utxo , _gtsNextHash = nextHash } type GenTransaction h a = StateT (GenTrState h a) Gen genTransaction :: Hash h a => GenTrParams a -> RemoveUsedInputs -> MakeOutputsAvailable -> GenTransaction h a (Maybe (Transaction h a)) genTransaction GenTrParams{..} removeUsedInputs makeOutputsAvailable notThese = do numInputs <- lift $ chooseNumInputs inputs <- zoom gtsInpState $ genDistinctInputs removeUsedInputs notThese numInputs if null inputs then return Nothing else do nextHash <- gtsNextHash <<+= 1 numOutputs <- lift $ choose (1, gtpMaxNumOutputs) let fee = gtpEstimateFee numInputs numOutputs inValue = sum (map (outVal . snd) inputs) if inValue <= fee then return Nothing else do let gos = initOutState (inValue - fee) outputs <- lift $ (`evalStateT` gos) $ replicateAtMostM numOutputs $ genOutput gtpOutParams let tr = Transaction { trFresh = 0 , trIns = Set.fromList (map fst inputs) , trOuts = outputs , trFee = fee , trHash = nextHash , trExtra = [] } case makeOutputsAvailable of DontMakeOutputsAvailable -> return () MakeOutputsAvailable -> zoom gtsInpState $ (gisUtxo %= utxoUnion (trUtxo tr)) return $ Just tr where chooseNumInputs :: Gen Int chooseNumInputs = frequency $ zip [gtpMaxNumInputs, gtpMaxNumInputs-1 ..] (map pure [1 .. gtpMaxNumInputs]) data GenChainParams a = GenChainParams { gcpMaxBlockSize :: Int , gcpMaxChainLength :: Int , gcpTrParams :: GenTrParams a } -> GenChainParams a defChainParams feeModel addresses = GenChainParams { gcpMaxBlockSize = 20 , gcpMaxChainLength = 10 , gcpTrParams = defTrParams feeModel addresses } The chain will have at least one block , but blocks may be empty . genChain :: forall h a. Hash h a => GenChainParams a -> GenTransaction h a (Chain h a) genChain GenChainParams{..} = goChain where goChain :: GenTransaction h a (Chain h a) goChain = OldestFirst <$> do chainLength <- lift $ choose (1, gcpMaxChainLength) replicateM chainLength goBlock goBlock :: GenTransaction h a (Block h a) goBlock = OldestFirst <$> do blockSize <- lift $ choose (0, gcpMaxBlockSize) replicateAtMostM blockSize $ genTransaction gcpTrParams RemoveUsedInputs MakeOutputsAvailable Set.empty replicateAtMostM :: Monad m => Int -> m (Maybe a) -> m [a] replicateAtMostM 0 _ = return [] replicateAtMostM n f = do ma <- f case ma of Just a -> (a :) <$> replicateAtMostM (n - 1) f Nothing -> return []
a1905a90cff3577e96fec9def91a11a5bcc2044ef7a3ff89fccdd4e6d1a03b1b
ocaml-flambda/ocaml-jst
misc.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (* Errors *) exception Fatal_error let fatal_errorf fmt = Format.kfprintf (fun _ -> raise Fatal_error) Format.err_formatter ("@?>> Fatal error: " ^^ fmt ^^ "@.") let fatal_error msg = fatal_errorf "%s" msg (* Exceptions *) let try_finally ?(always=(fun () -> ())) ?(exceptionally=(fun () -> ())) work = match work () with | result -> begin match always () with | () -> result | exception always_exn -> let always_bt = Printexc.get_raw_backtrace () in exceptionally (); Printexc.raise_with_backtrace always_exn always_bt end | exception work_exn -> let work_bt = Printexc.get_raw_backtrace () in begin match always () with | () -> exceptionally (); Printexc.raise_with_backtrace work_exn work_bt | exception always_exn -> let always_bt = Printexc.get_raw_backtrace () in exceptionally (); Printexc.raise_with_backtrace always_exn always_bt end let reraise_preserving_backtrace e f = let bt = Printexc.get_raw_backtrace () in f (); Printexc.raise_with_backtrace e bt type ref_and_value = R : 'a ref * 'a -> ref_and_value let protect_refs = let set_refs l = List.iter (fun (R (r, v)) -> r := v) l in fun refs f -> let backup = List.map (fun (R (r, _)) -> R (r, !r)) refs in set_refs refs; Fun.protect ~finally:(fun () -> set_refs backup) f (* List functions *) let rec map_end f l1 l2 = match l1 with [] -> l2 | hd::tl -> f hd :: map_end f tl l2 let rec map_left_right f = function [] -> [] | hd::tl -> let res = f hd in res :: map_left_right f tl let rec for_all2 pred l1 l2 = match (l1, l2) with ([], []) -> true | (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2 | (_, _) -> false let rec replicate_list elem n = if n <= 0 then [] else elem :: replicate_list elem (n-1) let rec list_remove x = function [] -> [] | hd :: tl -> if hd = x then tl else hd :: list_remove x tl let rec split_last = function [] -> assert false | [x] -> ([], x) | hd :: tl -> let (lst, last) = split_last tl in (hd :: lst, last) module Stdlib = struct module List = struct include List type 'a t = 'a list let rec compare cmp l1 l2 = match l1, l2 with | [], [] -> 0 | [], _::_ -> -1 | _::_, [] -> 1 | h1::t1, h2::t2 -> let c = cmp h1 h2 in if c <> 0 then c else compare cmp t1 t2 let rec equal eq l1 l2 = match l1, l2 with | ([], []) -> true | (hd1 :: tl1, hd2 :: tl2) -> eq hd1 hd2 && equal eq tl1 tl2 | (_, _) -> false let map2_prefix f l1 l2 = let rec aux acc l1 l2 = match l1, l2 with | [], _ -> (List.rev acc, l2) | _ :: _, [] -> raise (Invalid_argument "map2_prefix") | h1::t1, h2::t2 -> let h = f h1 h2 in aux (h :: acc) t1 t2 in aux [] l1 l2 let some_if_all_elements_are_some l = let rec aux acc l = match l with | [] -> Some (List.rev acc) | None :: _ -> None | Some h :: t -> aux (h :: acc) t in aux [] l let split_at n l = let rec aux n acc l = if n = 0 then List.rev acc, l else match l with | [] -> raise (Invalid_argument "split_at") | t::q -> aux (n-1) (t::acc) q in aux n [] l let rec map_sharing f l0 = match l0 with | a :: l -> let a' = f a in let l' = map_sharing f l in if a' == a && l' == l then l0 else a' :: l' | [] -> [] let rec is_prefix ~equal t ~of_ = match t, of_ with | [], [] -> true | _::_, [] -> false | [], _::_ -> true | x1::t, x2::of_ -> equal x1 x2 && is_prefix ~equal t ~of_ type 'a longest_common_prefix_result = { longest_common_prefix : 'a list; first_without_longest_common_prefix : 'a list; second_without_longest_common_prefix : 'a list; } let find_and_chop_longest_common_prefix ~equal ~first ~second = let rec find_prefix ~longest_common_prefix_rev l1 l2 = match l1, l2 with | elt1 :: l1, elt2 :: l2 when equal elt1 elt2 -> let longest_common_prefix_rev = elt1 :: longest_common_prefix_rev in find_prefix ~longest_common_prefix_rev l1 l2 | l1, l2 -> { longest_common_prefix = List.rev longest_common_prefix_rev; first_without_longest_common_prefix = l1; second_without_longest_common_prefix = l2; } in find_prefix ~longest_common_prefix_rev:[] first second end module Option = struct type 'a t = 'a option let print print_contents ppf t = match t with | None -> Format.pp_print_string ppf "None" | Some contents -> Format.fprintf ppf "@[(Some@ %a)@]" print_contents contents end module Array = struct let exists2 p a1 a2 = let n = Array.length a1 in if Array.length a2 <> n then invalid_arg "Misc.Stdlib.Array.exists2"; let rec loop i = if i = n then false else if p (Array.unsafe_get a1 i) (Array.unsafe_get a2 i) then true else loop (succ i) in loop 0 let for_alli p a = let n = Array.length a in let rec loop i = if i = n then true else if p i (Array.unsafe_get a i) then loop (succ i) else false in loop 0 let all_somes a = try Some (Array.map (function None -> raise_notrace Exit | Some x -> x) a) with | Exit -> None end module String = struct include String module Set = Set.Make(String) module Map = Map.Make(String) module Tbl = Hashtbl.Make(struct include String let hash = Hashtbl.hash end) let for_all f t = let len = String.length t in let rec loop i = i = len || (f t.[i] && loop (i + 1)) in loop 0 let print ppf t = Format.pp_print_string ppf t let begins_with ?(from = 0) str ~prefix = let rec helper idx = if idx < 0 then true else String.get str (from + idx) = String.get prefix idx && helper (idx-1) in let n = String.length str in let m = String.length prefix in if n >= from + m then helper (m-1) else false let split_on_string str ~split_on = let n = String.length str in let m = String.length split_on in let rec helper acc last_idx idx = if idx = n then let cur = String.sub str last_idx (idx - last_idx) in List.rev (cur :: acc) else if begins_with ~from:idx str ~prefix:split_on then let cur = String.sub str last_idx (idx - last_idx) in helper (cur :: acc) (idx + m) (idx + m) else helper acc last_idx (idx + 1) in helper [] 0 0 let split_on_chars str ~split_on:chars = let rec helper chars_left s acc = match chars_left with | [] -> s :: acc | c :: cs -> List.fold_right (helper cs) (String.split_on_char c s) acc in helper chars str [] let split_last_exn str ~split_on = let n = String.length str in let ridx = String.rindex str split_on in String.sub str 0 ridx, String.sub str (ridx + 1) (n - ridx - 1) let starts_with ~prefix s = let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 let ends_with ~suffix s = let len_s = length s and len_suf = length suffix in let diff = len_s - len_suf in let rec aux i = if i = len_suf then true else if unsafe_get s (diff + i) <> unsafe_get suffix i then false else aux (i + 1) in diff >= 0 && aux 0 end module Int = struct include Int let min (a : int) (b : int) = min a b let max (a : int) (b : int) = max a b end external compare : 'a -> 'a -> int = "%compare" end module Int = Stdlib.Int (* File functions *) let find_in_path path name = if not (Filename.is_implicit name) then if Sys.file_exists name then name else raise Not_found else begin let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path end let find_in_path_rel path name = let rec simplify s = let open Filename in let base = basename s in let dir = dirname s in if dir = s then dir else if base = current_dir_name then simplify dir else concat (simplify dir) base in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = simplify (Filename.concat dir name) in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let find_in_path_uncap path name = let uname = String.uncapitalize_ascii name in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name and ufullname = Filename.concat dir uname in if Sys.file_exists ufullname then ufullname else if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let remove_file filename = try if Sys.file_exists filename then Sys.remove filename with Sys_error _msg -> () (* Expand a -I option: if it starts with +, make it relative to the standard library directory *) let expand_directory alt s = if String.length s > 0 && s.[0] = '+' then Filename.concat alt (String.sub s 1 (String.length s - 1)) else s let path_separator = match Sys.os_type with | "Win32" -> ';' | _ -> ':' let split_path_contents ?(sep = path_separator) = function | "" -> [] | s -> String.split_on_char sep s (* Hashtable functions *) let create_hashtable size init = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl (* File copy *) let copy_file ic oc = let buff = Bytes.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then () else (output oc buff 0 n; copy()) in copy() let copy_file_chunk ic oc len = let buff = Bytes.create 0x1000 in let rec copy n = if n <= 0 then () else begin let r = input ic buff 0 (Int.min n 0x1000) in if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r)) end in copy len let string_of_file ic = let b = Buffer.create 0x10000 in let buff = Bytes.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then Buffer.contents b else (Buffer.add_subbytes b buff 0 n; copy()) in copy() let output_to_file_via_temporary ?(mode = [Open_text]) filename fn = let (temp_filename, oc) = Filename.open_temp_file ~mode ~perms:0o666 ~temp_dir:(Filename.dirname filename) (Filename.basename filename) ".tmp" in The 0o666 permissions will be modified by the umask . It 's just like what [ open_out ] and [ open_out_bin ] do . With temp_dir = dirname filename , we ensure that the returned temp file is in the same directory as filename itself , making it safe to rename temp_filename to filename later . With prefix = basename filename , we are almost certain that the first generated name will be unique . A fixed prefix would work too but might generate more collisions if many files are being produced simultaneously in the same directory . like what [open_out] and [open_out_bin] do. With temp_dir = dirname filename, we ensure that the returned temp file is in the same directory as filename itself, making it safe to rename temp_filename to filename later. With prefix = basename filename, we are almost certain that the first generated name will be unique. A fixed prefix would work too but might generate more collisions if many files are being produced simultaneously in the same directory. *) match fn temp_filename oc with | res -> close_out oc; begin try Sys.rename temp_filename filename; res with exn -> remove_file temp_filename; raise exn end | exception exn -> close_out oc; remove_file temp_filename; raise exn let protect_writing_to_file ~filename ~f = let outchan = open_out_bin filename in try_finally ~always:(fun () -> close_out outchan) ~exceptionally:(fun () -> remove_file filename) (fun () -> f outchan) Integer operations let rec log2 n = if n <= 1 then 0 else 1 + log2(n asr 1) let align n a = if n >= 0 then (n + a - 1) land (-a) else n land (-a) let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0 let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0 Taken from Hacker 's Delight , chapter " Overflow Detection " let no_overflow_mul a b = not ((a = min_int && b < 0) || (b <> 0 && (a * b) / b <> a)) let no_overflow_lsl a k = 0 <= k && k < Sys.word_size - 1 && min_int asr k <= a && a <= max_int asr k module Int_literal_converter = struct To convert integer literals , allowing max_int + 1 ( PR#4210 ) let cvt_int_aux str neg of_string = if String.length str = 0 || str.[0]= '-' then of_string str else neg (of_string ("-" ^ str)) let int s = cvt_int_aux s (~-) int_of_string let int32 s = cvt_int_aux s Int32.neg Int32.of_string let int64 s = cvt_int_aux s Int64.neg Int64.of_string let nativeint s = cvt_int_aux s Nativeint.neg Nativeint.of_string end (* String operations *) let chop_extensions file = let dirname = Filename.dirname file and basename = Filename.basename file in try let pos = String.index basename '.' in let basename = String.sub basename 0 pos in if Filename.is_implicit file && dirname = Filename.current_dir_name then basename else Filename.concat dirname basename with Not_found -> file let search_substring pat str start = let rec search i j = if j >= String.length pat then i else if i + j >= String.length str then raise Not_found else if str.[i + j] = pat.[j] then search i (j+1) else search (i+1) 0 in search start 0 let replace_substring ~before ~after str = let rec search acc curr = match search_substring before str curr with | next -> let prefix = String.sub str curr (next - curr) in search (prefix :: acc) (next + String.length before) | exception Not_found -> let suffix = String.sub str curr (String.length str - curr) in List.rev (suffix :: acc) in String.concat after (search [] 0) let rev_split_words s = let rec split1 res i = if i >= String.length s then res else begin match s.[i] with ' ' | '\t' | '\r' | '\n' -> split1 res (i+1) | _ -> split2 res i (i+1) end and split2 res i j = if j >= String.length s then String.sub s i (j-i) :: res else begin match s.[j] with ' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1) | _ -> split2 res i (j+1) end in split1 [] 0 let get_ref r = let v = !r in r := []; v let set_or_ignore f opt x = match f x with | None -> () | Some y -> opt := Some y let fst3 (x, _, _) = x let snd3 (_,x,_) = x let thd3 (_,_,x) = x let fst4 (x, _, _, _) = x let snd4 (_,x,_, _) = x let thd4 (_,_,x,_) = x let for4 (_,_,_,x) = x module LongString = struct type t = bytes array let create str_size = let tbl_size = str_size / Sys.max_string_length + 1 in let tbl = Array.make tbl_size Bytes.empty in for i = 0 to tbl_size - 2 do tbl.(i) <- Bytes.create Sys.max_string_length; done; tbl.(tbl_size - 1) <- Bytes.create (str_size mod Sys.max_string_length); tbl let length tbl = let tbl_size = Array.length tbl in Sys.max_string_length * (tbl_size - 1) + Bytes.length tbl.(tbl_size - 1) let get tbl ind = Bytes.get tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length) let set tbl ind c = Bytes.set tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length) c let blit src srcoff dst dstoff len = for i = 0 to len - 1 do set dst (dstoff + i) (get src (srcoff + i)) done let blit_string src srcoff dst dstoff len = for i = 0 to len - 1 do set dst (dstoff + i) (String.get src (srcoff + i)) done let output oc tbl pos len = for i = pos to pos + len - 1 do output_char oc (get tbl i) done let input_bytes_into tbl ic len = let count = ref len in Array.iter (fun str -> let chunk = Int.min !count (Bytes.length str) in really_input ic str 0 chunk; count := !count - chunk) tbl let input_bytes ic len = let tbl = create len in input_bytes_into tbl ic len; tbl end let edit_distance a b cutoff = let la, lb = String.length a, String.length b in let cutoff = using max_int for cutoff would cause overflows in ( i + cutoff + 1 ) ; we bring it back to the ( max la lb ) we bring it back to the (max la lb) worstcase *) Int.min (Int.max la lb) cutoff in if abs (la - lb) > cutoff then None else begin (* initialize with 'cutoff + 1' so that not-yet-written-to cases have the worst possible cost; this is useful when computing the cost of a case just at the boundary of the cutoff diagonal. *) let m = Array.make_matrix (la + 1) (lb + 1) (cutoff + 1) in m.(0).(0) <- 0; for i = 1 to la do m.(i).(0) <- i; done; for j = 1 to lb do m.(0).(j) <- j; done; for i = 1 to la do for j = Int.max 1 (i - cutoff - 1) to Int.min lb (i + cutoff + 1) do let cost = if a.[i-1] = b.[j-1] then 0 else 1 in let best = (* insert, delete or substitute *) Int.min (1 + Int.min m.(i-1).(j) m.(i).(j-1)) (m.(i-1).(j-1) + cost) in let best = swap two adjacent letters ; we use " cost " again in case of a swap between two identical letters ; this is slightly redundant as this is a double - substitution case , but it was done this way in most online implementations and imitation has its virtues a swap between two identical letters; this is slightly redundant as this is a double-substitution case, but it was done this way in most online implementations and imitation has its virtues *) if not (i > 1 && j > 1 && a.[i-1] = b.[j-2] && a.[i-2] = b.[j-1]) then best else Int.min best (m.(i-2).(j-2) + cost) in m.(i).(j) <- best done; done; let result = m.(la).(lb) in if result > cutoff then None else Some result end let spellcheck env name = let cutoff = match String.length name with | 1 | 2 -> 0 | 3 | 4 -> 1 | 5 | 6 -> 2 | _ -> 3 in let compare target acc head = match edit_distance target head cutoff with | None -> acc | Some dist -> let (best_choice, best_dist) = acc in if dist < best_dist then ([head], dist) else if dist = best_dist then (head :: best_choice, dist) else acc in let env = List.sort_uniq (fun s1 s2 -> String.compare s2 s1) env in fst (List.fold_left (compare name) ([], max_int) env) let did_you_mean ppf get_choices = (* flush now to get the error report early, in the (unheard of) case where the search in the get_choices function would take a bit of time; in the worst case, the user has seen the error, she can interrupt the process before the spell-checking terminates. *) Format.fprintf ppf "@?"; match get_choices () with | [] -> () | choices -> let rest, last = split_last choices in Format.fprintf ppf "@\nHint: Did you mean %s%s%s?@?" (String.concat ", " rest) (if rest = [] then "" else " or ") last let cut_at s c = let pos = String.index s c in String.sub s 0 pos, String.sub s (pos+1) (String.length s - pos - 1) let ordinal_suffix n = let teen = (n mod 100)/10 = 1 in match n mod 10 with | 1 when not teen -> "st" | 2 when not teen -> "nd" | 3 when not teen -> "rd" | _ -> "th" Color handling module Color = struct use ANSI color codes , see type color = | Black | Red | Green | Yellow | Blue | Magenta | Cyan | White ;; type style = | FG of color (* foreground *) | BG of color (* background *) | Bold | Reset let ansi_of_color = function | Black -> "0" | Red -> "1" | Green -> "2" | Yellow -> "3" | Blue -> "4" | Magenta -> "5" | Cyan -> "6" | White -> "7" let code_of_style = function | FG c -> "3" ^ ansi_of_color c | BG c -> "4" ^ ansi_of_color c | Bold -> "1" | Reset -> "0" let ansi_of_style_l l = let s = match l with | [] -> code_of_style Reset | [s] -> code_of_style s | _ -> String.concat ";" (List.map code_of_style l) in "\x1b[" ^ s ^ "m" type Format.stag += Style of style list type styles = { error: style list; warning: style list; loc: style list; } let default_styles = { warning = [Bold; FG Magenta]; error = [Bold; FG Red]; loc = [Bold]; } let cur_styles = ref default_styles let get_styles () = !cur_styles let set_styles s = cur_styles := s (* map a tag to a style, if the tag is known. @raise Not_found otherwise *) let style_of_tag s = match s with | Format.String_tag "error" -> (!cur_styles).error | Format.String_tag "warning" -> (!cur_styles).warning | Format.String_tag "loc" -> (!cur_styles).loc | Style s -> s | _ -> raise Not_found let color_enabled = ref true (* either prints the tag of [s] or delegates to [or_else] *) let mark_open_tag ~or_else s = try let style = style_of_tag s in if !color_enabled then ansi_of_style_l style else "" with Not_found -> or_else s let mark_close_tag ~or_else s = try let _ = style_of_tag s in if !color_enabled then ansi_of_style_l [Reset] else "" with Not_found -> or_else s (* add color handling to formatter [ppf] *) let set_color_tag_handling ppf = let open Format in let functions = pp_get_formatter_stag_functions ppf () in let functions' = {functions with mark_open_stag=(mark_open_tag ~or_else:functions.mark_open_stag); mark_close_stag=(mark_close_tag ~or_else:functions.mark_close_stag); } in pp_set_mark_tags ppf true; (* enable tags *) pp_set_formatter_stag_functions ppf functions'; () external isatty : out_channel -> bool = "caml_sys_isatty" (* reasonable heuristic on whether colors should be enabled *) let should_enable_color () = let term = try Sys.getenv "TERM" with Not_found -> "" in term <> "dumb" && term <> "" && isatty stderr type setting = Auto | Always | Never let default_setting = Auto let setup = let first = ref true in (* initialize only once *) let formatter_l = [Format.std_formatter; Format.err_formatter; Format.str_formatter] in let enable_color = function | Auto -> should_enable_color () | Always -> true | Never -> false in fun o -> if !first then ( first := false; Format.set_mark_tags true; List.iter set_color_tag_handling formatter_l; color_enabled := (match o with | Some s -> enable_color s | None -> enable_color default_setting) ); () end module Error_style = struct type setting = | Contextual | Short let default_setting = Contextual end let normalise_eol s = let b = Buffer.create 80 in for i = 0 to String.length s - 1 do if s.[i] <> '\r' then Buffer.add_char b s.[i] done; Buffer.contents b let delete_eol_spaces src = let len_src = String.length src in let dst = Bytes.create len_src in let rec loop i_src i_dst = if i_src = len_src then i_dst else match src.[i_src] with | ' ' | '\t' -> loop_spaces 1 (i_src + 1) i_dst | c -> Bytes.set dst i_dst c; loop (i_src + 1) (i_dst + 1) and loop_spaces spaces i_src i_dst = if i_src = len_src then i_dst else match src.[i_src] with | ' ' | '\t' -> loop_spaces (spaces + 1) (i_src + 1) i_dst | '\n' -> Bytes.set dst i_dst '\n'; loop (i_src + 1) (i_dst + 1) | _ -> for n = 0 to spaces do Bytes.set dst (i_dst + n) src.[i_src - spaces + n] done; loop (i_src + 1) (i_dst + spaces + 1) in let stop = loop 0 0 in Bytes.sub_string dst 0 stop let pp_two_columns ?(sep = "|") ?max_lines ppf (lines: (string * string) list) = let left_column_size = List.fold_left (fun acc (s, _) -> Int.max acc (String.length s)) 0 lines in let lines_nb = List.length lines in let ellipsed_first, ellipsed_last = match max_lines with | Some max_lines when lines_nb > max_lines -> the ellipsis uses one line let lines_before = printed_lines / 2 + printed_lines mod 2 in let lines_after = printed_lines / 2 in (lines_before, lines_nb - lines_after - 1) | _ -> (-1, -1) in Format.fprintf ppf "@[<v>"; List.iteri (fun k (line_l, line_r) -> if k = ellipsed_first then Format.fprintf ppf "...@,"; if ellipsed_first <= k && k <= ellipsed_last then () else Format.fprintf ppf "%*s %s %s@," left_column_size line_l sep line_r ) lines; Format.fprintf ppf "@]" (* showing configuration and configuration variables *) let show_config_and_exit () = Config.print_config stdout; exit 0 let show_config_variable_and_exit x = match Config.config_var x with | Some v -> we intentionally do n't print a newline to avoid Windows \r issues : bash only strips the trailing when using a command substitution $ ( ocamlc -config - var foo ) , so a trailing \r would remain if printing a newline under Windows and scripts would have to use $ ( ocamlc -config - var foo | tr -d ' \r ' ) for portability . Ugh . issues: bash only strips the trailing \n when using a command substitution $(ocamlc -config-var foo), so a trailing \r would remain if printing a newline under Windows and scripts would have to use $(ocamlc -config-var foo | tr -d '\r') for portability. Ugh. *) print_string v; exit 0 | None -> exit 2 let get_build_path_prefix_map = let init = ref false in let map_cache = ref None in fun () -> if not !init then begin init := true; match Sys.getenv "BUILD_PATH_PREFIX_MAP" with | exception Not_found -> () | encoded_map -> match Build_path_prefix_map.decode_map encoded_map with | Error err -> fatal_errorf "Invalid value for the environment variable \ BUILD_PATH_PREFIX_MAP: %s" err | Ok map -> map_cache := Some map end; !map_cache let debug_prefix_map_flags () = if not Config.as_has_debug_prefix_map then [] else begin match get_build_path_prefix_map () with | None -> [] | Some map -> List.fold_right (fun map_elem acc -> match map_elem with | None -> acc | Some { Build_path_prefix_map.target; source; } -> (Printf.sprintf "--debug-prefix-map %s=%s" (Filename.quote source) (Filename.quote target)) :: acc) map [] end let print_if ppf flag printer arg = if !flag then Format.fprintf ppf "%a@." printer arg; arg type filepath = string type alerts = string Stdlib.String.Map.t module Bitmap = struct type t = { length: int; bits: bytes } let length_bytes len = (len + 7) lsr 3 let make n = { length = n; bits = Bytes.make (length_bytes n) '\000' } let unsafe_get_byte t n = Char.code (Bytes.unsafe_get t.bits n) let unsafe_set_byte t n x = Bytes.unsafe_set t.bits n (Char.unsafe_chr x) let check_bound t n = if n < 0 || n >= t.length then invalid_arg "Bitmap.check_bound" let set t n = check_bound t n; let pos = n lsr 3 and bit = 1 lsl (n land 7) in unsafe_set_byte t pos (unsafe_get_byte t pos lor bit) let clear t n = check_bound t n; let pos = n lsr 3 and nbit = 0xff lxor (1 lsl (n land 7)) in unsafe_set_byte t pos (unsafe_get_byte t pos land nbit) let get t n = check_bound t n; let pos = n lsr 3 and bit = 1 lsl (n land 7) in (unsafe_get_byte t pos land bit) <> 0 let iter f t = for i = 0 to length_bytes t.length - 1 do let c = unsafe_get_byte t i in let pos = i lsl 3 in for j = 0 to 7 do if c land (1 lsl j) <> 0 then f (pos + j) done done end module Magic_number = struct type native_obj_config = { flambda : bool; } let native_obj_config = { flambda = Config.flambda || Config.flambda2; } type version = int type kind = | Exec | Cmi | Cmo | Cma | Cmx of native_obj_config | Cmxa of native_obj_config | Cmxs | Cmt | Ast_impl | Ast_intf (* please keep up-to-date, this is used for sanity checking *) let all_native_obj_configs = [ {flambda = true}; {flambda = false}; ] let all_kinds = [ Exec; Cmi; Cmo; Cma; ] @ List.map (fun conf -> Cmx conf) all_native_obj_configs @ List.map (fun conf -> Cmxa conf) all_native_obj_configs @ [ Cmt; Ast_impl; Ast_intf; ] type raw = string type info = { kind: kind; version: version; } type raw_kind = string let parse_kind : raw_kind -> kind option = function | "Caml1999X" -> Some Exec | "Caml1999I" -> Some Cmi | "Caml1999O" -> Some Cmo | "Caml1999A" -> Some Cma | "Caml2021y" -> Some (Cmx {flambda = true}) | "Caml2021Y" -> Some (Cmx {flambda = false}) | "Caml2021z" -> Some (Cmxa {flambda = true}) | "Caml2021Z" -> Some (Cmxa {flambda = false}) Caml2007D and T were used instead of the common prefix between the introduction of those magic numbers and October 2017 ( 8ba70ff194b66c0a50ffb97d41fe9c4bdf9362d6 ) . We accept them here , but will always produce / show kind prefixes that follow the current convention , Caml1999{D , T } . between the introduction of those magic numbers and October 2017 (8ba70ff194b66c0a50ffb97d41fe9c4bdf9362d6). We accept them here, but will always produce/show kind prefixes that follow the current convention, Caml1999{D,T}. *) | "Caml2007D" | "Caml1999D" -> Some Cmxs | "Caml2012T" | "Caml1999T" -> Some Cmt | "Caml1999M" -> Some Ast_impl | "Caml1999N" -> Some Ast_intf | _ -> None (* note: over time the magic kind number has changed for certain kinds; this function returns them as they are produced by the current compiler, but [parse_kind] accepts older formats as well. *) let raw_kind : kind -> raw = function | Exec -> "Caml1999X" | Cmi -> "Caml1999I" | Cmo -> "Caml1999O" | Cma -> "Caml1999A" | Cmx config -> if config.flambda then "Caml2021y" else "Caml2021Y" | Cmxa config -> if config.flambda then "Caml2021z" else "Caml2021Z" | Cmxs -> "Caml1999D" | Cmt -> "Caml1999T" | Ast_impl -> "Caml1999M" | Ast_intf -> "Caml1999N" let string_of_kind : kind -> string = function | Exec -> "exec" | Cmi -> "cmi" | Cmo -> "cmo" | Cma -> "cma" | Cmx _ -> "cmx" | Cmxa _ -> "cmxa" | Cmxs -> "cmxs" | Cmt -> "cmt" | Ast_impl -> "ast_impl" | Ast_intf -> "ast_intf" let human_description_of_native_obj_config : native_obj_config -> string = fun[@warning "+9"] {flambda} -> if flambda then "flambda" else "non flambda" let human_name_of_kind : kind -> string = function | Exec -> "executable" | Cmi -> "compiled interface file" | Cmo -> "bytecode object file" | Cma -> "bytecode library" | Cmx config -> Printf.sprintf "native compilation unit description (%s)" (human_description_of_native_obj_config config) | Cmxa config -> Printf.sprintf "static native library (%s)" (human_description_of_native_obj_config config) | Cmxs -> "dynamic native library" | Cmt -> "compiled typedtree file" | Ast_impl -> "serialized implementation AST" | Ast_intf -> "serialized interface AST" let kind_length = 9 let version_length = 3 let magic_length = kind_length + version_length type parse_error = | Truncated of string | Not_a_magic_number of string let explain_parse_error kind_opt error = Printf.sprintf "We expected a valid %s, but the file %s." (Option.fold ~none:"object file" ~some:human_name_of_kind kind_opt) (match error with | Truncated "" -> "is empty" | Truncated _ -> "is truncated" | Not_a_magic_number _ -> "has a different format") let parse s : (info, parse_error) result = if String.length s = magic_length then begin let raw_kind = String.sub s 0 kind_length in let raw_version = String.sub s kind_length version_length in match parse_kind raw_kind with | None -> Error (Not_a_magic_number s) | Some kind -> begin match int_of_string raw_version with | exception _ -> Error (Truncated s) | version -> Ok { kind; version } end end else begin a header is " truncated " if it starts like a valid magic number , that is if its longest segment of length at most [ kind_length ] is a prefix of [ raw_kind kind ] for some kind [ kind ] that is if its longest segment of length at most [kind_length] is a prefix of [raw_kind kind] for some kind [kind] *) let sub_length = Int.min kind_length (String.length s) in let starts_as kind = String.sub s 0 sub_length = String.sub (raw_kind kind) 0 sub_length in if List.exists starts_as all_kinds then Error (Truncated s) else Error (Not_a_magic_number s) end let read_info ic = let header = Buffer.create magic_length in begin try Buffer.add_channel header ic magic_length with End_of_file -> () end; parse (Buffer.contents header) let raw { kind; version; } = Printf.sprintf "%s%03d" (raw_kind kind) version let current_raw kind = let open Config in match[@warning "+9"] kind with | Exec -> exec_magic_number | Cmi -> cmi_magic_number | Cmo -> cmo_magic_number | Cma -> cma_magic_number | Cmx config -> (* the 'if' guarantees that in the common case we return the "trusted" value from Config. *) let reference = cmx_magic_number in if config = native_obj_config then reference else (* otherwise we stitch together the magic number for a different configuration by concatenating the right magic kind at this configuration and the rest of the current raw number for our configuration. *) let raw_kind = raw_kind kind in let len = String.length raw_kind in raw_kind ^ String.sub reference len (String.length reference - len) | Cmxa config -> let reference = cmxa_magic_number in if config = native_obj_config then reference else let raw_kind = raw_kind kind in let len = String.length raw_kind in raw_kind ^ String.sub reference len (String.length reference - len) | Cmxs -> cmxs_magic_number | Cmt -> cmt_magic_number | Ast_intf -> ast_intf_magic_number | Ast_impl -> ast_impl_magic_number it would seem more direct to define current_version with the correct numbers and current_raw on top of it , but for now we consider the Config.foo values to be ground truth , and do n't want to trust the present module instead . correct numbers and current_raw on top of it, but for now we consider the Config.foo values to be ground truth, and don't want to trust the present module instead. *) let current_version kind = let raw = current_raw kind in try int_of_string (String.sub raw kind_length version_length) with _ -> assert false type 'a unexpected = { expected : 'a; actual : 'a } type unexpected_error = | Kind of kind unexpected | Version of kind * version unexpected let explain_unexpected_error = function | Kind { actual; expected } -> Printf.sprintf "We expected a %s (%s) but got a %s (%s) instead." (human_name_of_kind expected) (string_of_kind expected) (human_name_of_kind actual) (string_of_kind actual) | Version (kind, { actual; expected }) -> Printf.sprintf "This seems to be a %s (%s) for %s version of OCaml." (human_name_of_kind kind) (string_of_kind kind) (if actual < expected then "an older" else "a newer") let check_current expected_kind { kind; version } : _ result = if kind <> expected_kind then begin let actual, expected = kind, expected_kind in Error (Kind { actual; expected }) end else begin let actual, expected = version, current_version kind in if actual <> expected then Error (Version (kind, { actual; expected })) else Ok () end type error = | Parse_error of parse_error | Unexpected_error of unexpected_error let read_current_info ~expected_kind ic = match read_info ic with | Error err -> Error (Parse_error err) | Ok info -> let kind = Option.value ~default:info.kind expected_kind in match check_current kind info with | Error err -> Error (Unexpected_error err) | Ok () -> Ok info end
null
https://raw.githubusercontent.com/ocaml-flambda/ocaml-jst/1bb6c797df7c63ddae1fc2e6f403a0ee9896cc8e/utils/misc.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ Errors Exceptions List functions File functions Expand a -I option: if it starts with +, make it relative to the standard library directory Hashtable functions File copy String operations initialize with 'cutoff + 1' so that not-yet-written-to cases have the worst possible cost; this is useful when computing the cost of a case just at the boundary of the cutoff diagonal. insert, delete or substitute flush now to get the error report early, in the (unheard of) case where the search in the get_choices function would take a bit of time; in the worst case, the user has seen the error, she can interrupt the process before the spell-checking terminates. foreground background map a tag to a style, if the tag is known. @raise Not_found otherwise either prints the tag of [s] or delegates to [or_else] add color handling to formatter [ppf] enable tags reasonable heuristic on whether colors should be enabled initialize only once showing configuration and configuration variables please keep up-to-date, this is used for sanity checking note: over time the magic kind number has changed for certain kinds; this function returns them as they are produced by the current compiler, but [parse_kind] accepts older formats as well. the 'if' guarantees that in the common case we return the "trusted" value from Config. otherwise we stitch together the magic number for a different configuration by concatenating the right magic kind at this configuration and the rest of the current raw number for our configuration.
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the exception Fatal_error let fatal_errorf fmt = Format.kfprintf (fun _ -> raise Fatal_error) Format.err_formatter ("@?>> Fatal error: " ^^ fmt ^^ "@.") let fatal_error msg = fatal_errorf "%s" msg let try_finally ?(always=(fun () -> ())) ?(exceptionally=(fun () -> ())) work = match work () with | result -> begin match always () with | () -> result | exception always_exn -> let always_bt = Printexc.get_raw_backtrace () in exceptionally (); Printexc.raise_with_backtrace always_exn always_bt end | exception work_exn -> let work_bt = Printexc.get_raw_backtrace () in begin match always () with | () -> exceptionally (); Printexc.raise_with_backtrace work_exn work_bt | exception always_exn -> let always_bt = Printexc.get_raw_backtrace () in exceptionally (); Printexc.raise_with_backtrace always_exn always_bt end let reraise_preserving_backtrace e f = let bt = Printexc.get_raw_backtrace () in f (); Printexc.raise_with_backtrace e bt type ref_and_value = R : 'a ref * 'a -> ref_and_value let protect_refs = let set_refs l = List.iter (fun (R (r, v)) -> r := v) l in fun refs f -> let backup = List.map (fun (R (r, _)) -> R (r, !r)) refs in set_refs refs; Fun.protect ~finally:(fun () -> set_refs backup) f let rec map_end f l1 l2 = match l1 with [] -> l2 | hd::tl -> f hd :: map_end f tl l2 let rec map_left_right f = function [] -> [] | hd::tl -> let res = f hd in res :: map_left_right f tl let rec for_all2 pred l1 l2 = match (l1, l2) with ([], []) -> true | (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2 | (_, _) -> false let rec replicate_list elem n = if n <= 0 then [] else elem :: replicate_list elem (n-1) let rec list_remove x = function [] -> [] | hd :: tl -> if hd = x then tl else hd :: list_remove x tl let rec split_last = function [] -> assert false | [x] -> ([], x) | hd :: tl -> let (lst, last) = split_last tl in (hd :: lst, last) module Stdlib = struct module List = struct include List type 'a t = 'a list let rec compare cmp l1 l2 = match l1, l2 with | [], [] -> 0 | [], _::_ -> -1 | _::_, [] -> 1 | h1::t1, h2::t2 -> let c = cmp h1 h2 in if c <> 0 then c else compare cmp t1 t2 let rec equal eq l1 l2 = match l1, l2 with | ([], []) -> true | (hd1 :: tl1, hd2 :: tl2) -> eq hd1 hd2 && equal eq tl1 tl2 | (_, _) -> false let map2_prefix f l1 l2 = let rec aux acc l1 l2 = match l1, l2 with | [], _ -> (List.rev acc, l2) | _ :: _, [] -> raise (Invalid_argument "map2_prefix") | h1::t1, h2::t2 -> let h = f h1 h2 in aux (h :: acc) t1 t2 in aux [] l1 l2 let some_if_all_elements_are_some l = let rec aux acc l = match l with | [] -> Some (List.rev acc) | None :: _ -> None | Some h :: t -> aux (h :: acc) t in aux [] l let split_at n l = let rec aux n acc l = if n = 0 then List.rev acc, l else match l with | [] -> raise (Invalid_argument "split_at") | t::q -> aux (n-1) (t::acc) q in aux n [] l let rec map_sharing f l0 = match l0 with | a :: l -> let a' = f a in let l' = map_sharing f l in if a' == a && l' == l then l0 else a' :: l' | [] -> [] let rec is_prefix ~equal t ~of_ = match t, of_ with | [], [] -> true | _::_, [] -> false | [], _::_ -> true | x1::t, x2::of_ -> equal x1 x2 && is_prefix ~equal t ~of_ type 'a longest_common_prefix_result = { longest_common_prefix : 'a list; first_without_longest_common_prefix : 'a list; second_without_longest_common_prefix : 'a list; } let find_and_chop_longest_common_prefix ~equal ~first ~second = let rec find_prefix ~longest_common_prefix_rev l1 l2 = match l1, l2 with | elt1 :: l1, elt2 :: l2 when equal elt1 elt2 -> let longest_common_prefix_rev = elt1 :: longest_common_prefix_rev in find_prefix ~longest_common_prefix_rev l1 l2 | l1, l2 -> { longest_common_prefix = List.rev longest_common_prefix_rev; first_without_longest_common_prefix = l1; second_without_longest_common_prefix = l2; } in find_prefix ~longest_common_prefix_rev:[] first second end module Option = struct type 'a t = 'a option let print print_contents ppf t = match t with | None -> Format.pp_print_string ppf "None" | Some contents -> Format.fprintf ppf "@[(Some@ %a)@]" print_contents contents end module Array = struct let exists2 p a1 a2 = let n = Array.length a1 in if Array.length a2 <> n then invalid_arg "Misc.Stdlib.Array.exists2"; let rec loop i = if i = n then false else if p (Array.unsafe_get a1 i) (Array.unsafe_get a2 i) then true else loop (succ i) in loop 0 let for_alli p a = let n = Array.length a in let rec loop i = if i = n then true else if p i (Array.unsafe_get a i) then loop (succ i) else false in loop 0 let all_somes a = try Some (Array.map (function None -> raise_notrace Exit | Some x -> x) a) with | Exit -> None end module String = struct include String module Set = Set.Make(String) module Map = Map.Make(String) module Tbl = Hashtbl.Make(struct include String let hash = Hashtbl.hash end) let for_all f t = let len = String.length t in let rec loop i = i = len || (f t.[i] && loop (i + 1)) in loop 0 let print ppf t = Format.pp_print_string ppf t let begins_with ?(from = 0) str ~prefix = let rec helper idx = if idx < 0 then true else String.get str (from + idx) = String.get prefix idx && helper (idx-1) in let n = String.length str in let m = String.length prefix in if n >= from + m then helper (m-1) else false let split_on_string str ~split_on = let n = String.length str in let m = String.length split_on in let rec helper acc last_idx idx = if idx = n then let cur = String.sub str last_idx (idx - last_idx) in List.rev (cur :: acc) else if begins_with ~from:idx str ~prefix:split_on then let cur = String.sub str last_idx (idx - last_idx) in helper (cur :: acc) (idx + m) (idx + m) else helper acc last_idx (idx + 1) in helper [] 0 0 let split_on_chars str ~split_on:chars = let rec helper chars_left s acc = match chars_left with | [] -> s :: acc | c :: cs -> List.fold_right (helper cs) (String.split_on_char c s) acc in helper chars str [] let split_last_exn str ~split_on = let n = String.length str in let ridx = String.rindex str split_on in String.sub str 0 ridx, String.sub str (ridx + 1) (n - ridx - 1) let starts_with ~prefix s = let len_s = length s and len_pre = length prefix in let rec aux i = if i = len_pre then true else if unsafe_get s i <> unsafe_get prefix i then false else aux (i + 1) in len_s >= len_pre && aux 0 let ends_with ~suffix s = let len_s = length s and len_suf = length suffix in let diff = len_s - len_suf in let rec aux i = if i = len_suf then true else if unsafe_get s (diff + i) <> unsafe_get suffix i then false else aux (i + 1) in diff >= 0 && aux 0 end module Int = struct include Int let min (a : int) (b : int) = min a b let max (a : int) (b : int) = max a b end external compare : 'a -> 'a -> int = "%compare" end module Int = Stdlib.Int let find_in_path path name = if not (Filename.is_implicit name) then if Sys.file_exists name then name else raise Not_found else begin let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path end let find_in_path_rel path name = let rec simplify s = let open Filename in let base = basename s in let dir = dirname s in if dir = s then dir else if base = current_dir_name then simplify dir else concat (simplify dir) base in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = simplify (Filename.concat dir name) in if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let find_in_path_uncap path name = let uname = String.uncapitalize_ascii name in let rec try_dir = function [] -> raise Not_found | dir::rem -> let fullname = Filename.concat dir name and ufullname = Filename.concat dir uname in if Sys.file_exists ufullname then ufullname else if Sys.file_exists fullname then fullname else try_dir rem in try_dir path let remove_file filename = try if Sys.file_exists filename then Sys.remove filename with Sys_error _msg -> () let expand_directory alt s = if String.length s > 0 && s.[0] = '+' then Filename.concat alt (String.sub s 1 (String.length s - 1)) else s let path_separator = match Sys.os_type with | "Win32" -> ';' | _ -> ':' let split_path_contents ?(sep = path_separator) = function | "" -> [] | s -> String.split_on_char sep s let create_hashtable size init = let tbl = Hashtbl.create size in List.iter (fun (key, data) -> Hashtbl.add tbl key data) init; tbl let copy_file ic oc = let buff = Bytes.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then () else (output oc buff 0 n; copy()) in copy() let copy_file_chunk ic oc len = let buff = Bytes.create 0x1000 in let rec copy n = if n <= 0 then () else begin let r = input ic buff 0 (Int.min n 0x1000) in if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r)) end in copy len let string_of_file ic = let b = Buffer.create 0x10000 in let buff = Bytes.create 0x1000 in let rec copy () = let n = input ic buff 0 0x1000 in if n = 0 then Buffer.contents b else (Buffer.add_subbytes b buff 0 n; copy()) in copy() let output_to_file_via_temporary ?(mode = [Open_text]) filename fn = let (temp_filename, oc) = Filename.open_temp_file ~mode ~perms:0o666 ~temp_dir:(Filename.dirname filename) (Filename.basename filename) ".tmp" in The 0o666 permissions will be modified by the umask . It 's just like what [ open_out ] and [ open_out_bin ] do . With temp_dir = dirname filename , we ensure that the returned temp file is in the same directory as filename itself , making it safe to rename temp_filename to filename later . With prefix = basename filename , we are almost certain that the first generated name will be unique . A fixed prefix would work too but might generate more collisions if many files are being produced simultaneously in the same directory . like what [open_out] and [open_out_bin] do. With temp_dir = dirname filename, we ensure that the returned temp file is in the same directory as filename itself, making it safe to rename temp_filename to filename later. With prefix = basename filename, we are almost certain that the first generated name will be unique. A fixed prefix would work too but might generate more collisions if many files are being produced simultaneously in the same directory. *) match fn temp_filename oc with | res -> close_out oc; begin try Sys.rename temp_filename filename; res with exn -> remove_file temp_filename; raise exn end | exception exn -> close_out oc; remove_file temp_filename; raise exn let protect_writing_to_file ~filename ~f = let outchan = open_out_bin filename in try_finally ~always:(fun () -> close_out outchan) ~exceptionally:(fun () -> remove_file filename) (fun () -> f outchan) Integer operations let rec log2 n = if n <= 1 then 0 else 1 + log2(n asr 1) let align n a = if n >= 0 then (n + a - 1) land (-a) else n land (-a) let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0 let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0 Taken from Hacker 's Delight , chapter " Overflow Detection " let no_overflow_mul a b = not ((a = min_int && b < 0) || (b <> 0 && (a * b) / b <> a)) let no_overflow_lsl a k = 0 <= k && k < Sys.word_size - 1 && min_int asr k <= a && a <= max_int asr k module Int_literal_converter = struct To convert integer literals , allowing max_int + 1 ( PR#4210 ) let cvt_int_aux str neg of_string = if String.length str = 0 || str.[0]= '-' then of_string str else neg (of_string ("-" ^ str)) let int s = cvt_int_aux s (~-) int_of_string let int32 s = cvt_int_aux s Int32.neg Int32.of_string let int64 s = cvt_int_aux s Int64.neg Int64.of_string let nativeint s = cvt_int_aux s Nativeint.neg Nativeint.of_string end let chop_extensions file = let dirname = Filename.dirname file and basename = Filename.basename file in try let pos = String.index basename '.' in let basename = String.sub basename 0 pos in if Filename.is_implicit file && dirname = Filename.current_dir_name then basename else Filename.concat dirname basename with Not_found -> file let search_substring pat str start = let rec search i j = if j >= String.length pat then i else if i + j >= String.length str then raise Not_found else if str.[i + j] = pat.[j] then search i (j+1) else search (i+1) 0 in search start 0 let replace_substring ~before ~after str = let rec search acc curr = match search_substring before str curr with | next -> let prefix = String.sub str curr (next - curr) in search (prefix :: acc) (next + String.length before) | exception Not_found -> let suffix = String.sub str curr (String.length str - curr) in List.rev (suffix :: acc) in String.concat after (search [] 0) let rev_split_words s = let rec split1 res i = if i >= String.length s then res else begin match s.[i] with ' ' | '\t' | '\r' | '\n' -> split1 res (i+1) | _ -> split2 res i (i+1) end and split2 res i j = if j >= String.length s then String.sub s i (j-i) :: res else begin match s.[j] with ' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1) | _ -> split2 res i (j+1) end in split1 [] 0 let get_ref r = let v = !r in r := []; v let set_or_ignore f opt x = match f x with | None -> () | Some y -> opt := Some y let fst3 (x, _, _) = x let snd3 (_,x,_) = x let thd3 (_,_,x) = x let fst4 (x, _, _, _) = x let snd4 (_,x,_, _) = x let thd4 (_,_,x,_) = x let for4 (_,_,_,x) = x module LongString = struct type t = bytes array let create str_size = let tbl_size = str_size / Sys.max_string_length + 1 in let tbl = Array.make tbl_size Bytes.empty in for i = 0 to tbl_size - 2 do tbl.(i) <- Bytes.create Sys.max_string_length; done; tbl.(tbl_size - 1) <- Bytes.create (str_size mod Sys.max_string_length); tbl let length tbl = let tbl_size = Array.length tbl in Sys.max_string_length * (tbl_size - 1) + Bytes.length tbl.(tbl_size - 1) let get tbl ind = Bytes.get tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length) let set tbl ind c = Bytes.set tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length) c let blit src srcoff dst dstoff len = for i = 0 to len - 1 do set dst (dstoff + i) (get src (srcoff + i)) done let blit_string src srcoff dst dstoff len = for i = 0 to len - 1 do set dst (dstoff + i) (String.get src (srcoff + i)) done let output oc tbl pos len = for i = pos to pos + len - 1 do output_char oc (get tbl i) done let input_bytes_into tbl ic len = let count = ref len in Array.iter (fun str -> let chunk = Int.min !count (Bytes.length str) in really_input ic str 0 chunk; count := !count - chunk) tbl let input_bytes ic len = let tbl = create len in input_bytes_into tbl ic len; tbl end let edit_distance a b cutoff = let la, lb = String.length a, String.length b in let cutoff = using max_int for cutoff would cause overflows in ( i + cutoff + 1 ) ; we bring it back to the ( max la lb ) we bring it back to the (max la lb) worstcase *) Int.min (Int.max la lb) cutoff in if abs (la - lb) > cutoff then None else begin let m = Array.make_matrix (la + 1) (lb + 1) (cutoff + 1) in m.(0).(0) <- 0; for i = 1 to la do m.(i).(0) <- i; done; for j = 1 to lb do m.(0).(j) <- j; done; for i = 1 to la do for j = Int.max 1 (i - cutoff - 1) to Int.min lb (i + cutoff + 1) do let cost = if a.[i-1] = b.[j-1] then 0 else 1 in let best = Int.min (1 + Int.min m.(i-1).(j) m.(i).(j-1)) (m.(i-1).(j-1) + cost) in let best = swap two adjacent letters ; we use " cost " again in case of a swap between two identical letters ; this is slightly redundant as this is a double - substitution case , but it was done this way in most online implementations and imitation has its virtues a swap between two identical letters; this is slightly redundant as this is a double-substitution case, but it was done this way in most online implementations and imitation has its virtues *) if not (i > 1 && j > 1 && a.[i-1] = b.[j-2] && a.[i-2] = b.[j-1]) then best else Int.min best (m.(i-2).(j-2) + cost) in m.(i).(j) <- best done; done; let result = m.(la).(lb) in if result > cutoff then None else Some result end let spellcheck env name = let cutoff = match String.length name with | 1 | 2 -> 0 | 3 | 4 -> 1 | 5 | 6 -> 2 | _ -> 3 in let compare target acc head = match edit_distance target head cutoff with | None -> acc | Some dist -> let (best_choice, best_dist) = acc in if dist < best_dist then ([head], dist) else if dist = best_dist then (head :: best_choice, dist) else acc in let env = List.sort_uniq (fun s1 s2 -> String.compare s2 s1) env in fst (List.fold_left (compare name) ([], max_int) env) let did_you_mean ppf get_choices = Format.fprintf ppf "@?"; match get_choices () with | [] -> () | choices -> let rest, last = split_last choices in Format.fprintf ppf "@\nHint: Did you mean %s%s%s?@?" (String.concat ", " rest) (if rest = [] then "" else " or ") last let cut_at s c = let pos = String.index s c in String.sub s 0 pos, String.sub s (pos+1) (String.length s - pos - 1) let ordinal_suffix n = let teen = (n mod 100)/10 = 1 in match n mod 10 with | 1 when not teen -> "st" | 2 when not teen -> "nd" | 3 when not teen -> "rd" | _ -> "th" Color handling module Color = struct use ANSI color codes , see type color = | Black | Red | Green | Yellow | Blue | Magenta | Cyan | White ;; type style = | Bold | Reset let ansi_of_color = function | Black -> "0" | Red -> "1" | Green -> "2" | Yellow -> "3" | Blue -> "4" | Magenta -> "5" | Cyan -> "6" | White -> "7" let code_of_style = function | FG c -> "3" ^ ansi_of_color c | BG c -> "4" ^ ansi_of_color c | Bold -> "1" | Reset -> "0" let ansi_of_style_l l = let s = match l with | [] -> code_of_style Reset | [s] -> code_of_style s | _ -> String.concat ";" (List.map code_of_style l) in "\x1b[" ^ s ^ "m" type Format.stag += Style of style list type styles = { error: style list; warning: style list; loc: style list; } let default_styles = { warning = [Bold; FG Magenta]; error = [Bold; FG Red]; loc = [Bold]; } let cur_styles = ref default_styles let get_styles () = !cur_styles let set_styles s = cur_styles := s let style_of_tag s = match s with | Format.String_tag "error" -> (!cur_styles).error | Format.String_tag "warning" -> (!cur_styles).warning | Format.String_tag "loc" -> (!cur_styles).loc | Style s -> s | _ -> raise Not_found let color_enabled = ref true let mark_open_tag ~or_else s = try let style = style_of_tag s in if !color_enabled then ansi_of_style_l style else "" with Not_found -> or_else s let mark_close_tag ~or_else s = try let _ = style_of_tag s in if !color_enabled then ansi_of_style_l [Reset] else "" with Not_found -> or_else s let set_color_tag_handling ppf = let open Format in let functions = pp_get_formatter_stag_functions ppf () in let functions' = {functions with mark_open_stag=(mark_open_tag ~or_else:functions.mark_open_stag); mark_close_stag=(mark_close_tag ~or_else:functions.mark_close_stag); } in pp_set_formatter_stag_functions ppf functions'; () external isatty : out_channel -> bool = "caml_sys_isatty" let should_enable_color () = let term = try Sys.getenv "TERM" with Not_found -> "" in term <> "dumb" && term <> "" && isatty stderr type setting = Auto | Always | Never let default_setting = Auto let setup = let formatter_l = [Format.std_formatter; Format.err_formatter; Format.str_formatter] in let enable_color = function | Auto -> should_enable_color () | Always -> true | Never -> false in fun o -> if !first then ( first := false; Format.set_mark_tags true; List.iter set_color_tag_handling formatter_l; color_enabled := (match o with | Some s -> enable_color s | None -> enable_color default_setting) ); () end module Error_style = struct type setting = | Contextual | Short let default_setting = Contextual end let normalise_eol s = let b = Buffer.create 80 in for i = 0 to String.length s - 1 do if s.[i] <> '\r' then Buffer.add_char b s.[i] done; Buffer.contents b let delete_eol_spaces src = let len_src = String.length src in let dst = Bytes.create len_src in let rec loop i_src i_dst = if i_src = len_src then i_dst else match src.[i_src] with | ' ' | '\t' -> loop_spaces 1 (i_src + 1) i_dst | c -> Bytes.set dst i_dst c; loop (i_src + 1) (i_dst + 1) and loop_spaces spaces i_src i_dst = if i_src = len_src then i_dst else match src.[i_src] with | ' ' | '\t' -> loop_spaces (spaces + 1) (i_src + 1) i_dst | '\n' -> Bytes.set dst i_dst '\n'; loop (i_src + 1) (i_dst + 1) | _ -> for n = 0 to spaces do Bytes.set dst (i_dst + n) src.[i_src - spaces + n] done; loop (i_src + 1) (i_dst + spaces + 1) in let stop = loop 0 0 in Bytes.sub_string dst 0 stop let pp_two_columns ?(sep = "|") ?max_lines ppf (lines: (string * string) list) = let left_column_size = List.fold_left (fun acc (s, _) -> Int.max acc (String.length s)) 0 lines in let lines_nb = List.length lines in let ellipsed_first, ellipsed_last = match max_lines with | Some max_lines when lines_nb > max_lines -> the ellipsis uses one line let lines_before = printed_lines / 2 + printed_lines mod 2 in let lines_after = printed_lines / 2 in (lines_before, lines_nb - lines_after - 1) | _ -> (-1, -1) in Format.fprintf ppf "@[<v>"; List.iteri (fun k (line_l, line_r) -> if k = ellipsed_first then Format.fprintf ppf "...@,"; if ellipsed_first <= k && k <= ellipsed_last then () else Format.fprintf ppf "%*s %s %s@," left_column_size line_l sep line_r ) lines; Format.fprintf ppf "@]" let show_config_and_exit () = Config.print_config stdout; exit 0 let show_config_variable_and_exit x = match Config.config_var x with | Some v -> we intentionally do n't print a newline to avoid Windows \r issues : bash only strips the trailing when using a command substitution $ ( ocamlc -config - var foo ) , so a trailing \r would remain if printing a newline under Windows and scripts would have to use $ ( ocamlc -config - var foo | tr -d ' \r ' ) for portability . Ugh . issues: bash only strips the trailing \n when using a command substitution $(ocamlc -config-var foo), so a trailing \r would remain if printing a newline under Windows and scripts would have to use $(ocamlc -config-var foo | tr -d '\r') for portability. Ugh. *) print_string v; exit 0 | None -> exit 2 let get_build_path_prefix_map = let init = ref false in let map_cache = ref None in fun () -> if not !init then begin init := true; match Sys.getenv "BUILD_PATH_PREFIX_MAP" with | exception Not_found -> () | encoded_map -> match Build_path_prefix_map.decode_map encoded_map with | Error err -> fatal_errorf "Invalid value for the environment variable \ BUILD_PATH_PREFIX_MAP: %s" err | Ok map -> map_cache := Some map end; !map_cache let debug_prefix_map_flags () = if not Config.as_has_debug_prefix_map then [] else begin match get_build_path_prefix_map () with | None -> [] | Some map -> List.fold_right (fun map_elem acc -> match map_elem with | None -> acc | Some { Build_path_prefix_map.target; source; } -> (Printf.sprintf "--debug-prefix-map %s=%s" (Filename.quote source) (Filename.quote target)) :: acc) map [] end let print_if ppf flag printer arg = if !flag then Format.fprintf ppf "%a@." printer arg; arg type filepath = string type alerts = string Stdlib.String.Map.t module Bitmap = struct type t = { length: int; bits: bytes } let length_bytes len = (len + 7) lsr 3 let make n = { length = n; bits = Bytes.make (length_bytes n) '\000' } let unsafe_get_byte t n = Char.code (Bytes.unsafe_get t.bits n) let unsafe_set_byte t n x = Bytes.unsafe_set t.bits n (Char.unsafe_chr x) let check_bound t n = if n < 0 || n >= t.length then invalid_arg "Bitmap.check_bound" let set t n = check_bound t n; let pos = n lsr 3 and bit = 1 lsl (n land 7) in unsafe_set_byte t pos (unsafe_get_byte t pos lor bit) let clear t n = check_bound t n; let pos = n lsr 3 and nbit = 0xff lxor (1 lsl (n land 7)) in unsafe_set_byte t pos (unsafe_get_byte t pos land nbit) let get t n = check_bound t n; let pos = n lsr 3 and bit = 1 lsl (n land 7) in (unsafe_get_byte t pos land bit) <> 0 let iter f t = for i = 0 to length_bytes t.length - 1 do let c = unsafe_get_byte t i in let pos = i lsl 3 in for j = 0 to 7 do if c land (1 lsl j) <> 0 then f (pos + j) done done end module Magic_number = struct type native_obj_config = { flambda : bool; } let native_obj_config = { flambda = Config.flambda || Config.flambda2; } type version = int type kind = | Exec | Cmi | Cmo | Cma | Cmx of native_obj_config | Cmxa of native_obj_config | Cmxs | Cmt | Ast_impl | Ast_intf let all_native_obj_configs = [ {flambda = true}; {flambda = false}; ] let all_kinds = [ Exec; Cmi; Cmo; Cma; ] @ List.map (fun conf -> Cmx conf) all_native_obj_configs @ List.map (fun conf -> Cmxa conf) all_native_obj_configs @ [ Cmt; Ast_impl; Ast_intf; ] type raw = string type info = { kind: kind; version: version; } type raw_kind = string let parse_kind : raw_kind -> kind option = function | "Caml1999X" -> Some Exec | "Caml1999I" -> Some Cmi | "Caml1999O" -> Some Cmo | "Caml1999A" -> Some Cma | "Caml2021y" -> Some (Cmx {flambda = true}) | "Caml2021Y" -> Some (Cmx {flambda = false}) | "Caml2021z" -> Some (Cmxa {flambda = true}) | "Caml2021Z" -> Some (Cmxa {flambda = false}) Caml2007D and T were used instead of the common prefix between the introduction of those magic numbers and October 2017 ( 8ba70ff194b66c0a50ffb97d41fe9c4bdf9362d6 ) . We accept them here , but will always produce / show kind prefixes that follow the current convention , Caml1999{D , T } . between the introduction of those magic numbers and October 2017 (8ba70ff194b66c0a50ffb97d41fe9c4bdf9362d6). We accept them here, but will always produce/show kind prefixes that follow the current convention, Caml1999{D,T}. *) | "Caml2007D" | "Caml1999D" -> Some Cmxs | "Caml2012T" | "Caml1999T" -> Some Cmt | "Caml1999M" -> Some Ast_impl | "Caml1999N" -> Some Ast_intf | _ -> None let raw_kind : kind -> raw = function | Exec -> "Caml1999X" | Cmi -> "Caml1999I" | Cmo -> "Caml1999O" | Cma -> "Caml1999A" | Cmx config -> if config.flambda then "Caml2021y" else "Caml2021Y" | Cmxa config -> if config.flambda then "Caml2021z" else "Caml2021Z" | Cmxs -> "Caml1999D" | Cmt -> "Caml1999T" | Ast_impl -> "Caml1999M" | Ast_intf -> "Caml1999N" let string_of_kind : kind -> string = function | Exec -> "exec" | Cmi -> "cmi" | Cmo -> "cmo" | Cma -> "cma" | Cmx _ -> "cmx" | Cmxa _ -> "cmxa" | Cmxs -> "cmxs" | Cmt -> "cmt" | Ast_impl -> "ast_impl" | Ast_intf -> "ast_intf" let human_description_of_native_obj_config : native_obj_config -> string = fun[@warning "+9"] {flambda} -> if flambda then "flambda" else "non flambda" let human_name_of_kind : kind -> string = function | Exec -> "executable" | Cmi -> "compiled interface file" | Cmo -> "bytecode object file" | Cma -> "bytecode library" | Cmx config -> Printf.sprintf "native compilation unit description (%s)" (human_description_of_native_obj_config config) | Cmxa config -> Printf.sprintf "static native library (%s)" (human_description_of_native_obj_config config) | Cmxs -> "dynamic native library" | Cmt -> "compiled typedtree file" | Ast_impl -> "serialized implementation AST" | Ast_intf -> "serialized interface AST" let kind_length = 9 let version_length = 3 let magic_length = kind_length + version_length type parse_error = | Truncated of string | Not_a_magic_number of string let explain_parse_error kind_opt error = Printf.sprintf "We expected a valid %s, but the file %s." (Option.fold ~none:"object file" ~some:human_name_of_kind kind_opt) (match error with | Truncated "" -> "is empty" | Truncated _ -> "is truncated" | Not_a_magic_number _ -> "has a different format") let parse s : (info, parse_error) result = if String.length s = magic_length then begin let raw_kind = String.sub s 0 kind_length in let raw_version = String.sub s kind_length version_length in match parse_kind raw_kind with | None -> Error (Not_a_magic_number s) | Some kind -> begin match int_of_string raw_version with | exception _ -> Error (Truncated s) | version -> Ok { kind; version } end end else begin a header is " truncated " if it starts like a valid magic number , that is if its longest segment of length at most [ kind_length ] is a prefix of [ raw_kind kind ] for some kind [ kind ] that is if its longest segment of length at most [kind_length] is a prefix of [raw_kind kind] for some kind [kind] *) let sub_length = Int.min kind_length (String.length s) in let starts_as kind = String.sub s 0 sub_length = String.sub (raw_kind kind) 0 sub_length in if List.exists starts_as all_kinds then Error (Truncated s) else Error (Not_a_magic_number s) end let read_info ic = let header = Buffer.create magic_length in begin try Buffer.add_channel header ic magic_length with End_of_file -> () end; parse (Buffer.contents header) let raw { kind; version; } = Printf.sprintf "%s%03d" (raw_kind kind) version let current_raw kind = let open Config in match[@warning "+9"] kind with | Exec -> exec_magic_number | Cmi -> cmi_magic_number | Cmo -> cmo_magic_number | Cma -> cma_magic_number | Cmx config -> let reference = cmx_magic_number in if config = native_obj_config then reference else let raw_kind = raw_kind kind in let len = String.length raw_kind in raw_kind ^ String.sub reference len (String.length reference - len) | Cmxa config -> let reference = cmxa_magic_number in if config = native_obj_config then reference else let raw_kind = raw_kind kind in let len = String.length raw_kind in raw_kind ^ String.sub reference len (String.length reference - len) | Cmxs -> cmxs_magic_number | Cmt -> cmt_magic_number | Ast_intf -> ast_intf_magic_number | Ast_impl -> ast_impl_magic_number it would seem more direct to define current_version with the correct numbers and current_raw on top of it , but for now we consider the Config.foo values to be ground truth , and do n't want to trust the present module instead . correct numbers and current_raw on top of it, but for now we consider the Config.foo values to be ground truth, and don't want to trust the present module instead. *) let current_version kind = let raw = current_raw kind in try int_of_string (String.sub raw kind_length version_length) with _ -> assert false type 'a unexpected = { expected : 'a; actual : 'a } type unexpected_error = | Kind of kind unexpected | Version of kind * version unexpected let explain_unexpected_error = function | Kind { actual; expected } -> Printf.sprintf "We expected a %s (%s) but got a %s (%s) instead." (human_name_of_kind expected) (string_of_kind expected) (human_name_of_kind actual) (string_of_kind actual) | Version (kind, { actual; expected }) -> Printf.sprintf "This seems to be a %s (%s) for %s version of OCaml." (human_name_of_kind kind) (string_of_kind kind) (if actual < expected then "an older" else "a newer") let check_current expected_kind { kind; version } : _ result = if kind <> expected_kind then begin let actual, expected = kind, expected_kind in Error (Kind { actual; expected }) end else begin let actual, expected = version, current_version kind in if actual <> expected then Error (Version (kind, { actual; expected })) else Ok () end type error = | Parse_error of parse_error | Unexpected_error of unexpected_error let read_current_info ~expected_kind ic = match read_info ic with | Error err -> Error (Parse_error err) | Ok info -> let kind = Option.value ~default:info.kind expected_kind in match check_current kind info with | Error err -> Error (Unexpected_error err) | Ok () -> Ok info end
85364a2e91e32948f8af357d50e7a84dd2fc54ad60d2cc4fdea362e6d9568279
SnootyMonkey/Falkland-CMS
clean.clj
(ns fcms.db.clean "Remove all data from a Falkland CMS CouchDB database. USE WITH CAUTION!" (:require [com.ashafa.clutch :as clutch] [fcms.resources.common :as common])) (defn- bulk-delete-record [doc] {:_id (:id doc) :_rev (:value doc) :_deleted true}) (defn clean [] (println "FCMS: Cleaning database...") (let [doc-revs (clutch/get-view (common/db) "fcms" :all-by-rev {:include_docs false})] (clutch/bulk-update (common/db) (map bulk-delete-record doc-revs))) (println "FCMS: Database cleaning complete.")) (defn -main [] (clean))
null
https://raw.githubusercontent.com/SnootyMonkey/Falkland-CMS/bd653c23dd458609b652dfac3f0f2f11526f00d1/src/fcms/db/clean.clj
clojure
(ns fcms.db.clean "Remove all data from a Falkland CMS CouchDB database. USE WITH CAUTION!" (:require [com.ashafa.clutch :as clutch] [fcms.resources.common :as common])) (defn- bulk-delete-record [doc] {:_id (:id doc) :_rev (:value doc) :_deleted true}) (defn clean [] (println "FCMS: Cleaning database...") (let [doc-revs (clutch/get-view (common/db) "fcms" :all-by-rev {:include_docs false})] (clutch/bulk-update (common/db) (map bulk-delete-record doc-revs))) (println "FCMS: Database cleaning complete.")) (defn -main [] (clean))
919b9ce0198cfc0aa90492942b3722968a6efd2faaed52e91e3f7affabd0569f
lisp-korea/sicp2014
ex-2-38.scm
ex 2.38 (define (accumulate op init seq) (if (null? seq) init (op (car seq) (accumulate op init (cdr seq))))) (define nil '()) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) (define fold-right accumulate) ;;-- (fold-right / 1 (list 1 2 3)) = > 3/2 (fold-left / 1 (list 1 2 3)) = > 1/6 (fold-right list nil (list 1 2 3)) = > ( 1 ( 2 ( 3 ( ) ) ) ) (fold-left list nil (list 1 2 3)) = > ( ( ( ( ) 1 ) 2 ) 3 ) ;;-- (fold-right + 1 (list 1 2 3)) = > 7 (fold-left + 1 (list 1 2 3)) = > 7 (fold-right * 1 (list 1 2 3)) = > 6 (fold-left * 1 (list 1 2 3)) = > 6 (fold-right - 1 (list 1 2 3)) = > 1 (fold-left - 1 (list 1 2 3)) ;;=> -5
null
https://raw.githubusercontent.com/lisp-korea/sicp2014/9e60f70cb84ad2ad5987a71aebe1069db288b680/vvalkyrie/2.2/ex-2-38.scm
scheme
-- -- => -5
ex 2.38 (define (accumulate op init seq) (if (null? seq) init (op (car seq) (accumulate op init (cdr seq))))) (define nil '()) (define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) (define fold-right accumulate) (fold-right / 1 (list 1 2 3)) = > 3/2 (fold-left / 1 (list 1 2 3)) = > 1/6 (fold-right list nil (list 1 2 3)) = > ( 1 ( 2 ( 3 ( ) ) ) ) (fold-left list nil (list 1 2 3)) = > ( ( ( ( ) 1 ) 2 ) 3 ) (fold-right + 1 (list 1 2 3)) = > 7 (fold-left + 1 (list 1 2 3)) = > 7 (fold-right * 1 (list 1 2 3)) = > 6 (fold-left * 1 (list 1 2 3)) = > 6 (fold-right - 1 (list 1 2 3)) = > 1 (fold-left - 1 (list 1 2 3))
30197a341854d8d5ab1971115f2fbc3a43e7206da462d39fe08e05717b97dc3a
NorfairKing/validity
Reflexivity.hs
# LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # module Test.Syd.Validity.Relations.Reflexivity ( reflexiveOnElem, reflexivityOnGen, reflexivity, reflexivityOnArbitrary, ) where import Data.GenValidity import Test.QuickCheck -- | -- -- \[ -- Reflexive(\prec) -- \quad\equiv\quad \forall a : ( a \prec a ) -- \] reflexiveOnElem :: -- | A relation (a -> a -> Bool) -> -- | An element a -> Bool reflexiveOnElem func a = func a a reflexivityOnGen :: Show a => (a -> a -> Bool) -> Gen a -> (a -> [a]) -> Property reflexivityOnGen func gen s = forAllShrink gen s $ reflexiveOnElem func -- | -- -- prop> reflexivity ((<=) :: Int -> Int -> Bool) -- prop> reflexivity ((==) :: Int -> Int -> Bool) -- prop> reflexivity ((>=) :: Int -> Int -> Bool) -- prop> reflexivity (Data.List.isPrefixOf :: [Int] -> [Int] -> Bool) -- prop> reflexivity (Data.List.isSuffixOf :: [Int] -> [Int] -> Bool) -- prop> reflexivity (Data.List.isInfixOf :: [Int] -> [Int] -> Bool) reflexivity :: (Show a, GenValid a) => (a -> a -> Bool) -> Property reflexivity func = reflexivityOnGen func genValid shrinkValid -- | -- -- prop> reflexivityOnArbitrary ((<=) :: Int -> Int -> Bool) -- prop> reflexivityOnArbitrary ((==) :: Int -> Int -> Bool) -- prop> reflexivityOnArbitrary ((>=) :: Int -> Int -> Bool) -- prop> reflexivityOnArbitrary (Data.List.isPrefixOf :: [Int] -> [Int] -> Bool) -- prop> reflexivityOnArbitrary (Data.List.isSuffixOf :: [Int] -> [Int] -> Bool) -- prop> reflexivityOnArbitrary (Data.List.isInfixOf :: [Int] -> [Int] -> Bool) reflexivityOnArbitrary :: (Show a, Arbitrary a) => (a -> a -> Bool) -> Property reflexivityOnArbitrary func = reflexivityOnGen func arbitrary shrink
null
https://raw.githubusercontent.com/NorfairKing/validity/35bc8d45b27e6c21429e4b681b16e46ccd541b3b/genvalidity-sydtest/src/Test/Syd/Validity/Relations/Reflexivity.hs
haskell
| \[ Reflexive(\prec) \quad\equiv\quad \] | A relation | An element | prop> reflexivity ((<=) :: Int -> Int -> Bool) prop> reflexivity ((==) :: Int -> Int -> Bool) prop> reflexivity ((>=) :: Int -> Int -> Bool) prop> reflexivity (Data.List.isPrefixOf :: [Int] -> [Int] -> Bool) prop> reflexivity (Data.List.isSuffixOf :: [Int] -> [Int] -> Bool) prop> reflexivity (Data.List.isInfixOf :: [Int] -> [Int] -> Bool) | prop> reflexivityOnArbitrary ((<=) :: Int -> Int -> Bool) prop> reflexivityOnArbitrary ((==) :: Int -> Int -> Bool) prop> reflexivityOnArbitrary ((>=) :: Int -> Int -> Bool) prop> reflexivityOnArbitrary (Data.List.isPrefixOf :: [Int] -> [Int] -> Bool) prop> reflexivityOnArbitrary (Data.List.isSuffixOf :: [Int] -> [Int] -> Bool) prop> reflexivityOnArbitrary (Data.List.isInfixOf :: [Int] -> [Int] -> Bool)
# LANGUAGE MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # module Test.Syd.Validity.Relations.Reflexivity ( reflexiveOnElem, reflexivityOnGen, reflexivity, reflexivityOnArbitrary, ) where import Data.GenValidity import Test.QuickCheck \forall a : ( a \prec a ) reflexiveOnElem :: (a -> a -> Bool) -> a -> Bool reflexiveOnElem func a = func a a reflexivityOnGen :: Show a => (a -> a -> Bool) -> Gen a -> (a -> [a]) -> Property reflexivityOnGen func gen s = forAllShrink gen s $ reflexiveOnElem func reflexivity :: (Show a, GenValid a) => (a -> a -> Bool) -> Property reflexivity func = reflexivityOnGen func genValid shrinkValid reflexivityOnArbitrary :: (Show a, Arbitrary a) => (a -> a -> Bool) -> Property reflexivityOnArbitrary func = reflexivityOnGen func arbitrary shrink
30e3eda27e65d0ef878440536c2cbeb6d2e02078d97a6f66c3526f45b2117ae6
cacheaudit/cacheaudit
accessAD.mli
Copyright ( c ) 2013 - 2015 , IMDEA Software Institute . (* See ../../LICENSE for authorship and licensing information *) (** Access abstract domain: keeps track of possible access sequences to sets in the cache. Can keep track of all accesses or only to changes by preventing stuttering *) (** Whether stuttering should be prevented or not. Default is false. *) val no_stuttering : bool ref module Make : functor (C : CacheAD.S) -> CacheAD.S
null
https://raw.githubusercontent.com/cacheaudit/cacheaudit/f0b52f85771ee31fed2a0a84a7e767a9d19e4b15/abstract_domains/cache/accessAD.mli
ocaml
See ../../LICENSE for authorship and licensing information * Access abstract domain: keeps track of possible access sequences to sets in the cache. Can keep track of all accesses or only to changes by preventing stuttering * Whether stuttering should be prevented or not. Default is false.
Copyright ( c ) 2013 - 2015 , IMDEA Software Institute . val no_stuttering : bool ref module Make : functor (C : CacheAD.S) -> CacheAD.S
8638a56af4deda282e7e4091520fec427aea1793442a7de60dfa08b8d65498f4
haskell-hvr/base-noprelude
Prelude.hs
# LANGUAGE NoImplicitPrelude , PackageImports # -- | An extended prelude to avoid typing all the standard default imports. -- The exports are chosen such that the chance for conflicts is low. -- -- This has been taken adapted from -extended module Prelude ( module StdPrelude -- * Control modules , module Control.Applicative , module Control.Arrow -- Partial , module Control.Monad , module Control.Monad.IO.Class , module Control.Monad.Trans.Class -- * Data modules , module Data.Char -- Partial , module Data.Data -- Partial , module Data.Either , module Data.Function , module Data.List -- Partial , module Data.Maybe , module Data.Monoid -- Partial , module Data.Ord , module Data.Time -- Partial , module Data.Tuple -- * Safe , module Safe -- * System modules , module Data.Time.Locale.Compat -- Partial ) where import qualified "base" Prelude as StdPrelude import Control.Applicative import Control.Arrow (first, second, (&&&), (***), (+++), (|||)) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Data.Char hiding (GeneralCategory (..)) import Data.Data (Data (..), Typeable) import Data.Either import Data.Function (on) import Data.List hiding (delete) import Data.Maybe import Data.Monoid (Monoid (..), (<>)) import Data.Ord import Data.Time (FormatTime, NominalDiffTime, ParseTime, UTCTime, addUTCTime, diffUTCTime, formatTime, getCurrentTime, parseTime) -- Misc orphan instances import Data.Time.Clock () import Data.Tuple import Safe hiding (abort) import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
null
https://raw.githubusercontent.com/haskell-hvr/base-noprelude/e5cb48f7f344de339b9ce5e4473dfbd532ba52bc/examples/extended-prelude/src/Prelude.hs
haskell
| An extended prelude to avoid typing all the standard default imports. The exports are chosen such that the chance for conflicts is low. This has been taken adapted from -extended * Control modules Partial * Data modules Partial Partial Partial Partial Partial * Safe * System modules Partial Misc orphan instances
# LANGUAGE NoImplicitPrelude , PackageImports # module Prelude ( module StdPrelude , module Control.Applicative , module Control.Monad , module Control.Monad.IO.Class , module Control.Monad.Trans.Class , module Data.Either , module Data.Function , module Data.Maybe , module Data.Ord , module Data.Tuple , module Safe ) where import qualified "base" Prelude as StdPrelude import Control.Applicative import Control.Arrow (first, second, (&&&), (***), (+++), (|||)) import Control.Monad import Control.Monad.IO.Class import Control.Monad.Trans.Class import Data.Char hiding (GeneralCategory (..)) import Data.Data (Data (..), Typeable) import Data.Either import Data.Function (on) import Data.List hiding (delete) import Data.Maybe import Data.Monoid (Monoid (..), (<>)) import Data.Ord import Data.Time (FormatTime, NominalDiffTime, ParseTime, UTCTime, addUTCTime, diffUTCTime, formatTime, getCurrentTime, parseTime) import Data.Time.Clock () import Data.Tuple import Safe hiding (abort) import Data.Time.Locale.Compat (TimeLocale, defaultTimeLocale)
0bedd97a3fb1f55632643ae1fa6ffcc865dc63b201931ae5f8ecaf5bcf1627b0
Feldspar/feldspar-language
Language.hs
-- Copyright ( c ) 2019 , ERICSSON AB -- 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. * Neither the name of the ERICSSON AB nor the names of its contributors -- may be used to endorse or promote products derived from this software -- without specific prior written permission. -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , -- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- # LANGUAGE DataKinds # {-# LANGUAGE RankNTypes #-} # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE GeneralizedNewtypeDeriving # # OPTIONS_GHC -Wall # -- I think orphans are unavoidable in this file, so disable the warning. # OPTIONS_GHC -Wno - orphans # module Feldspar.Core.Language where import Feldspar.Core.NestedTuples (Tuple(..), build, tuple) import Feldspar.Core.Reify import Feldspar.Core.Representation as R import Feldspar.Core.Types as T import Feldspar.Lattice (Lattice, universal) import Feldspar.Range import Feldspar.Core.Collection import Control.Monad.Cont (runCont, cont) import Data.Typeable (Typeable) import Control.Applicative import Control.Monad (zipWithM_) import Data.Complex (Complex) import Data.Int import Data.IORef import Data.List (genericLength) import Data.Patch import Data.Word import Data.Hash (Hashable) import qualified Data.Bits as B import Prelude.EDSL import Prelude (Rational, foldr) import qualified Prelude as P -------------------------------------------------- Array.hs -------------------------------------------------- parallel :: Type a => Data Length -> (Data Index -> Data a) -> Data [a] parallel = sugarSym2 Parallel sequential :: (Syntax a, Syntax s) => Data Length -> s -> (Data Index -> s -> (a,s)) -> Data [Internal a] sequential = sugarSym3 Sequential append :: Type a => Data [a] -> Data [a] -> Data [a] append = sugarSym2 Append getLength :: Type a => Data [a] -> Data Length getLength = sugarSym1 GetLength -- | Change the length of the vector to the supplied value. If the supplied -- length is greater than the old length, the new elements will have undefined -- value. setLength :: Type a => Data Length -> Data [a] -> Data [a] setLength = sugarSym2 SetLength getIx :: Type a => Data [a] -> Data Index -> Data a getIx = sugarSym2 GetIx setIx :: Type a => Data [a] -> Data Index -> Data a -> Data [a] setIx = sugarSym3 SetIx type instance Elem (Data [a]) = Data a type instance CollIndex (Data [a]) = Data Index type instance CollSize (Data [a]) = Data Length instance Type a => Indexed (Data [a]) where (!) = getIx instance Type a => Sized (Data [a]) where collSize = getLength setCollSize = setLength instance (Type a, Type b) => CollMap (Data [a]) (Data [b]) where collMap f arr = parallel (getLength arr) (f . getIx arr) -- | Array patch (|>) :: (Sized a, CollMap a a) => Patch (CollSize a) (CollSize a) -> Patch (Elem a) (Elem a) -> Patch a a (sizePatch |> elemPatch) a = collMap elemPatch $ setCollSize (sizePatch (collSize a)) a -------------------------------------------------- Binding.hs -------------------------------------------------- -- | Share an expression in the scope of a function share :: (Syntax a, Syntax b) => a -> (a -> b) -> b share = sugarSym2 Let -- | Share the intermediate result when composing functions (.<) :: (Syntax b, Syntax c) => (b -> c) -> (a -> b) -> a -> c (.<) f g a = share (g a) f infixr 9 .< -- | Share an expression in the scope of a function ($<) :: (Syntax a, Syntax b) => (a -> b) -> a -> b ($<) = flip share infixr 0 $< -------------------------------------------------- Bits.hs -------------------------------------------------- infixl 5 .<<.,.>>. infixl 4 ⊕ class (Type a, Bounded a, B.FiniteBits a, Integral a, Size a ~ Range a, P.Integral (UnsignedRep a), B.FiniteBits (UnsignedRep a)) => Bits a where -- * Logical operations (.&.) :: Data a -> Data a -> Data a (.&.) = sugarSym2 BAnd (.|.) :: Data a -> Data a -> Data a (.|.) = sugarSym2 BOr xor :: Data a -> Data a -> Data a xor = sugarSym2 BXor complement :: Data a -> Data a complement = sugarSym1 Complement -- * Bitwise operations bit :: Data Index -> Data a bit = sugarSym1 Bit setBit :: Data a -> Data Index -> Data a setBit = sugarSym2 SetBit clearBit :: Data a -> Data Index -> Data a clearBit = sugarSym2 ClearBit complementBit :: Data a -> Data Index -> Data a complementBit = sugarSym2 ComplementBit testBit :: Data a -> Data Index -> Data Bool testBit = sugarSym2 TestBit -- * Movement operations shiftLU :: Data a -> Data Index -> Data a shiftLU = sugarSym2 ShiftLU shiftRU :: Data a -> Data Index -> Data a shiftRU = sugarSym2 ShiftRU shiftL :: Data a -> Data IntN -> Data a shiftL = sugarSym2 ShiftL shiftR :: Data a -> Data IntN -> Data a shiftR = sugarSym2 ShiftR rotateLU :: Data a -> Data Index -> Data a rotateLU = sugarSym2 RotateLU rotateRU :: Data a -> Data Index -> Data a rotateRU = sugarSym2 RotateRU rotateL :: Data a -> Data IntN -> Data a rotateL = sugarSym2 RotateL rotateR :: Data a -> Data IntN -> Data a rotateR = sugarSym2 RotateR reverseBits :: Data a -> Data a reverseBits = sugarSym1 ReverseBits -- * Query operations bitScan :: Data a -> Data Index bitScan = sugarSym1 BitScan bitCount :: Data a -> Data Index bitCount = sugarSym1 BitCount bitSize :: Data a -> Data Index bitSize = value . bitSize' bitSize' :: Data a -> Index bitSize' = const $ P.fromIntegral $ finiteBitSize (undefined :: a) isSigned :: Data a -> Data Bool isSigned = value . isSigned' isSigned' :: Data a -> Bool isSigned' = const $ B.isSigned (undefined :: a) finiteBitSize :: B.FiniteBits b => b -> Int finiteBitSize = B.finiteBitSize instance Bits Word8 instance Bits Word16 instance Bits Word32 instance Bits Word64 instance Bits Int8 instance Bits Int16 instance Bits Int32 instance Bits Int64 -- * Combinators (⊕) :: Bits a => Data a -> Data a -> Data a (⊕) = xor (.<<.) :: Bits a => Data a -> Data Index -> Data a (.<<.) = shiftLU (.>>.) :: Bits a => Data a -> Data Index -> Data a (.>>.) = shiftRU | Set all bits to one allOnes :: Bits a => Data a allOnes = complement 0 | Set the ` n ` lowest bits to one oneBits :: Bits a => Data Index -> Data a oneBits n = complement (allOnes .<<. n) -- | Extract the `k` lowest bits lsbs :: Bits a => Data Index -> Data a -> Data a lsbs k i = i .&. oneBits k -------------------------------------------------- -------------------------------------------------- complex :: (Numeric a, P.RealFloat a) => Data a -> Data a -> Data (Complex a) complex = sugarSym2 MkComplex realPart :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a realPart = sugarSym1 RealPart imagPart :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a imagPart = sugarSym1 ImagPart conjugate :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data (Complex a) conjugate = sugarSym1 Conjugate mkPolar :: (Numeric a, P.RealFloat a) => Data a -- ^ Amplitude -> Data a -- ^ Angle -> Data (Complex a) mkPolar = sugarSym2 MkPolar cis :: (Numeric a, P.RealFloat a) => Data a -> Data (Complex a) cis = sugarSym1 Cis magnitude :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a magnitude = sugarSym1 Magnitude phase :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a phase = sugarSym1 Phase polar :: (Numeric a, P.RealFloat a) => Data (Complex a) -> (Data a, Data a) polar c = (magnitude c, phase c) infixl 6 +. (+.) :: (Numeric a, P.RealFloat a) => Data a -> Data a -> Data (Complex a) (+.) = complex iunit :: (Numeric a, P.RealFloat a) => Data (Complex a) iunit = 0 +. 1 -------------------------------------------------- Condition.hs -------------------------------------------------- -- | Condition operator. Use as follows: -- > cond1 ? ex1 $ -- > cond2 ? ex2 $ > cond3 ? ex3 $ -- > exDefault (?) :: Syntax a => Data Bool -> a -> a -> a (?) = sugarSym3 Condition infixl 1 ? -------------------------------------------------- ConditionM.hs -------------------------------------------------- ifM :: Syntax a => Data Bool -> M a -> M a -> M a ifM = sugarSym3 ConditionM whenM :: Data Bool -> M () -> M () whenM c ma = ifM c ma (return ()) unlessM :: Data Bool -> M () -> M () unlessM c = ifM c (return ()) -------------------------------------------------- Conversion.hs -------------------------------------------------- i2f :: (Integral a, Numeric b, P.RealFloat b) => Data a -> Data b i2f = i2n f2i :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a f2i = sugarSym1 F2I i2n :: (Integral a, Numeric b) => Data a -> Data b i2n = sugarSym1 I2N b2i :: Integral a => Data Bool -> Data a b2i = sugarSym1 B2I truncate :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a truncate = f2i round :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a round = sugarSym1 Round ceiling :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a ceiling = sugarSym1 Ceiling floor :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a floor = sugarSym1 Floor -------------------------------------------------- -- Elements.hs -------------------------------------------------- materialize :: Type a => Data Length -> Data (Elements a) -> Data [a] materialize = sugarSym2 EMaterialize write :: Type a => Data Index -> Data a -> Data (Elements a) write = sugarSym2 EWrite par :: Type a => Data (Elements a) -> Data (Elements a) -> Data (Elements a) par = sugarSym2 EPar parFor :: Type a => Data Length -> (Data Index -> Data (Elements a)) -> Data (Elements a) parFor = sugarSym2 EparFor skip :: Type a => Data (Elements a) skip = sugarSym0 ESkip -------------------------------------------------- -- Eq.hs -------------------------------------------------- infix 4 == infix 4 /= | Redefinition of the standard ' P.Eq ' class for Feldspar class Type a => Eq a where (==) :: Data a -> Data a -> Data Bool (==) = sugarSym2 Equal (/=) :: Data a -> Data a -> Data Bool (/=) = sugarSym2 NotEqual instance Eq () instance Eq Bool instance Eq Float instance Eq Double instance Eq Word8 instance Eq Word16 instance Eq Word32 instance Eq Word64 instance Eq Int8 instance Eq Int16 instance Eq Int32 instance Eq Int64 instance (Eq a, Eq b) => Eq (a, b) instance (Eq a, Eq b, Eq c) => Eq (a, b, c) instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b ,c, d, e) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k) => Eq (a, b, c, d, e, f, g, h, i, j, k) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l) => Eq (a, b, c, d, e, f, g, h, i, j, k, l) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n, Eq o) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) instance (Eq a, P.RealFloat a) => Eq (Complex a) -------------------------------------------------- Error.hs -------------------------------------------------- undef :: Syntax a => a undef = sugarSym0 Undefined -- | Assert that the condition holds or fail with message assertMsg :: Syntax a => String -> Data Bool -> a -> a assertMsg s = sugarSym2 (Assert s) -- | Assert that the condition holds, the conditions string representation is used as the message assert :: Syntax a => Data Bool -> a -> a assert cond = assertMsg (show cond) cond err :: Syntax a => String -> a err msg = assertMsg msg false undef -------------------------------------------------- -- FFI.hs -------------------------------------------------- | Arity specific functions for FFI -- | Arity 0 foreignImport0 :: Syntax r => String -> Internal r -> r foreignImport0 s f = sugarSym0 (ForeignImport s (EqBox f)) | Arity 1 foreignImport1 :: (Syntax r, Syntactic a, Typeable (Internal a)) => String -> (Internal a -> Internal r) -> a -> r foreignImport1 s f = sugarSym1 (ForeignImport s (EqBox f)) | Arity 2 foreignImport2 :: (Syntax r, Syntactic a, Syntactic b, Typeable (Internal a), Typeable (Internal b)) => String -> (Internal a -> Internal b -> Internal r) -> a -> b -> r foreignImport2 s f = sugarSym2 (ForeignImport s (EqBox f)) | Arity 3 foreignImport3 :: (Syntax r, Syntactic a, Syntactic b, Syntactic c, Typeable (Internal a), Typeable (Internal b), Typeable (Internal c)) => String -> (Internal a -> Internal b -> Internal c -> Internal r) -> a -> b -> c -> r foreignImport3 s f = sugarSym3 (ForeignImport s (EqBox f)) | Arity 4 foreignImport4 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal r) -> a -> b -> c -> d -> r foreignImport4 s f a b c d = unFull $ sugarSym (ForeignImport s (EqBox f)) a b c d | Arity 5 foreignImport5 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Syntactic e , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) , Typeable (Internal e) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal e -> Internal r) -> a -> b -> c -> d -> e -> r foreignImport5 s f a b c d e = unFull $ sugarSym (ForeignImport s (EqBox f)) a b c d e | Arity 6 foreignImport6 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Syntactic e , Syntactic f , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) , Typeable (Internal e) , Typeable (Internal f) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal e -> Internal f -> Internal r) -> a -> b -> c -> d -> e -> f -> r foreignImport6 s x a b c d e f = unFull $ sugarSym (ForeignImport s (EqBox x)) a b c d e f -------------------------------------------------- -- Floating.hs -------------------------------------------------- -- Make new class, with "Data" in all the types infixr 8 ** class (Fraction a, P.Floating a) => Floating a where pi :: Data a pi = sugarSym0 Pi exp :: Data a -> Data a exp = sugarSym1 Exp sqrt :: Data a -> Data a sqrt = sugarSym1 Sqrt log :: Data a -> Data a log = sugarSym1 Log (**) :: Data a -> Data a -> Data a (**) = sugarSym2 Pow logBase :: Data a -> Data a -> Data a logBase = sugarSym2 LogBase sin :: Data a -> Data a sin = sugarSym1 Sin tan :: Data a -> Data a tan = sugarSym1 Tan cos :: Data a -> Data a cos = sugarSym1 Cos asin :: Data a -> Data a asin = sugarSym1 Asin atan :: Data a -> Data a atan = sugarSym1 Atan acos :: Data a -> Data a acos = sugarSym1 Acos sinh :: Data a -> Data a sinh = sugarSym1 Sinh tanh :: Data a -> Data a tanh = sugarSym1 Tanh cosh :: Data a -> Data a cosh = sugarSym1 Cosh asinh :: Data a -> Data a asinh = sugarSym1 Asinh atanh :: Data a -> Data a atanh = sugarSym1 Atanh acosh :: Data a -> Data a acosh = sugarSym1 Acosh instance Floating Float instance Floating Double instance (Fraction a, P.RealFloat a) => Floating (Complex a) π :: Floating a => Data a π = pi -------------------------------------------------- -- Fractional.hs -------------------------------------------------- -- | Fractional types. The relation to the standard 'Fractional' class is @instance ` Fraction ` a = > ` Fractional ` ( ` Data ` a)@ class (Fractional a, Numeric a) => Fraction a where fromRationalFrac :: Rational -> Data a fromRationalFrac = value . fromRational divFrac :: Data a -> Data a -> Data a divFrac = sugarSym2 DivFrac instance Fraction Float instance Fraction Double instance (Fraction a, P.RealFloat a) => Fraction (Complex a) instance Fraction a => Fractional (Data a) where fromRational = fromRationalFrac (/) = divFrac -------------------------------------------------- -- Future.hs -------------------------------------------------- newtype Future a = Future { unFuture :: Data (FVal (Internal a)) } later :: (Syntax a, Syntax b) => (a -> b) -> Future a -> Future b later f = future . f . await pval :: (Syntax a, Syntax b) => (a -> b) -> a -> b pval f x = await $ force $ future (f x) instance Syntax a => Syntactic (Future a) where type Internal (Future a) = FVal (Internal a) desugar = desugar . unFuture sugar = Future . sugar future :: Syntax a => a -> Future a future = sugarSym1 MkFuture await :: Syntax a => Future a -> a await = sugarSym1 Await -------------------------------------------------- Integral.hs -------------------------------------------------- class (Bounded a, B.FiniteBits a, Ord a, Numeric a, P.Integral a, Size a ~ Range a) => Integral a where quot :: Data a -> Data a -> Data a quot = sugarSym2 Quot rem :: Data a -> Data a -> Data a rem = sugarSym2 Rem div :: Data a -> Data a -> Data a div = sugarSym2 Div mod :: Data a -> Data a -> Data a mod = sugarSym2 Mod (^) :: Data a -> Data a -> Data a (^) = sugarSym2 IExp divSem :: Integral a => Data a -> Data a -> Data a divSem x y = (x > 0 && y < 0 || x < 0 && y > 0) && rem x y /= 0 ? quot x y P.- 1 P.$ quot x y instance Integral Word8 instance Integral Word16 instance Integral Word32 instance Integral Word64 instance Integral Int8 instance Integral Int16 instance Integral Int32 instance Integral Int64 -------------------------------------------------- Literal.hs -------------------------------------------------- false :: Data Bool false = value False true :: Data Bool true = value True -------------------------------------------------- Logic.hs -------------------------------------------------- infixr 3 && infixr 3 &&* infixr 2 || infixr 2 ||* not :: Data Bool -> Data Bool not = sugarSym1 Not (&&) :: Data Bool -> Data Bool -> Data Bool (&&) = sugarSym2 And (||) :: Data Bool -> Data Bool -> Data Bool (||) = sugarSym2 Or | Lazy conjunction , second argument only evaluated if necessary (&&*) :: Data Bool -> Data Bool -> Data Bool a &&* b = a ? b $ false | Lazy disjunction , second argument only evaluated if necessary (||*) :: Data Bool -> Data Bool -> Data Bool a ||* b = a ? true $ b -------------------------------------------------- -- Loop.hs -------------------------------------------------- forLoop :: Syntax a => Data Length -> a -> (Data Index -> a -> a) -> a forLoop = sugarSym3 ForLoop whileLoop :: Syntax a => a -> (a -> Data Bool) -> (a -> a) -> a whileLoop = sugarSym3 WhileLoop -------------------------------------------------- -- LoopM.hs -------------------------------------------------- forM :: Syntax a => Data Length -> (Data Index -> M a) -> M () forM = sugarSym2 For whileM :: Syntax a => M (Data Bool) -> M a -> M () whileM = sugarSym2 While -------------------------------------------------- MutableArray.hs -------------------------------------------------- -- | Create a new 'Mutable' Array and intialize all elements newArr :: Type a => Data Length -> Data a -> M (Data (MArr a)) newArr = sugarSym2 NewArr | Create a new ' Mutable ' Array but leave the elements un - initialized newArr_ :: Type a => Data Length -> M (Data (MArr a)) newArr_ = sugarSym1 NewArr_ -- | Create a new 'Mutable' Array and initialize with elements from the -- list newListArr :: forall a. Type a => [Data a] -> M (Data (MArr a)) newListArr xs = do arr <- newArr_ (value $ genericLength xs) zipWithM_ (setArr arr . value) [0..] xs return arr -- | Extract the element at index getArr :: Type a => Data (MArr a) -> Data Index -> M (Data a) getArr = sugarSym2 GetArr -- | Replace the value at index setArr :: Type a => Data (MArr a) -> Data Index -> Data a -> M () setArr = sugarSym3 SetArr -- | Modify the element at index modifyArr :: Type a => Data (MArr a) -> Data Index -> (Data a -> Data a) -> M () modifyArr arr i f = getArr arr i >>= setArr arr i . f -- | Query the length of the array arrLength :: Type a => Data (MArr a) -> M (Data Length) arrLength = sugarSym1 ArrLength -- | Modify all elements mapArray :: Type a => (Data a -> Data a) -> Data (MArr a) -> M (Data (MArr a)) mapArray f arr = do len <- arrLength arr forArr len (flip (modifyArr arr) f) return arr forArr :: Syntax a => Data Length -> (Data Index -> M a) -> M () forArr = sugarSym2 For | Swap two elements swap :: Type a => Data (MArr a) -> Data Index -> Data Index -> M () swap a i1 i2 = do tmp <- getArr a i1 getArr a i2 >>= setArr a i1 setArr a i2 tmp -------------------------------------------------- Mutable.hs -------------------------------------------------- newtype M a = M { unM :: Mon Mut a } deriving (Functor, Applicative, Monad) instance Syntax a => Syntactic (M a) where type Internal (M a) = Mut (Internal a) desugar = desugar . unM sugar = M . sugar instance P.Eq (Mut a) where (==) = P.error "Eq not implemented for Mut a" instance Show (Mut a) where show = P.error "Show not implemented for Mut a" runMutable :: Syntax a => M a -> a runMutable = sugarSym1 Run when :: Data Bool -> M () -> M () when = sugarSym2 When unless :: Data Bool -> M () -> M () unless = when . not instance Type a => Type (Mut a) where typeRep = T.MutType typeRep sizeOf _ = P.error "sizeOf not implemented for Mut a" -------------------------------------------------- -- MutableReference.hs -------------------------------------------------- newtype Ref a = Ref { unRef :: Data (IORef (Internal a)) } instance Syntax a => Syntactic (Ref a) where type Internal (Ref a) = IORef (Internal a) desugar = desugar . unRef sugar = Ref . sugar newRef :: Syntax a => a -> M (Ref a) newRef = sugarSym1 NewRef getRef :: Syntax a => Ref a -> M a getRef = sugarSym1 GetRef setRef :: Syntax a => Ref a -> a -> M () setRef = sugarSym2 SetRef modifyRef :: Syntax a => Ref a -> (a -> a) -> M () modifyRef = sugarSym2 ModRef -------------------------------------------------- -- MutableToPure.hs -------------------------------------------------- withArray :: (Type a, Syntax b) => Data (MArr a) -> (Data [a] -> M b) -> M b withArray = sugarSym2 WithArray runMutableArray :: Type a => M (Data (MArr a)) -> Data [a] runMutableArray = sugarSym1 RunMutableArray freezeArray :: Type a => Data (MArr a) -> M (Data [a]) freezeArray marr = withArray marr return thawArray :: Type a => Data [a] -> M (Data (MArr a)) thawArray arr = do marr <- newArr_ (getLength arr) forM (getLength arr) (\ix -> setArr marr ix (getIx arr ix) ) return marr -------------------------------------------------- -- Nested tuples -------------------------------------------------- class Type (Tuple (InternalTup a)) => SyntacticTup a where type InternalTup a :: [*] desugarTup :: Tuple a -> ASTF (Tuple (InternalTup a)) sugarTup :: ASTF (Tuple (InternalTup a)) -> Tuple a We call desugarTup explicitly below to avoid use of the Syntactic instance for -- 'Tuple a' which would add 'Tup' around each tail of the tuple, making it sharable. -- The test case 'noshare' in the 'decoration' suite checks that tails are not shared. instance (Syntax a, SyntacticTup b, Typeable (InternalTup b)) => SyntacticTup (a ': b) where type InternalTup (a ': b) = Internal a ': InternalTup b desugarTup (x :* xs) = sugarSym2 Cons x (desugarTup xs) sugarTup e = sugar (sugarSym1 Car e) :* sugarTup (sugarSym1 Cdr e) instance SyntacticTup '[] where type InternalTup '[] = '[] desugarTup TNil = sugarSym0 Nil sugarTup _ = TNil instance SyntacticTup a => Syntactic (Tuple a) where type Internal (Tuple a) = Tuple (InternalTup a) desugar = sugarSym1 Tup . desugarTup sugar = sugarTup -------------------------------------------------- -- NoInline.hs -------------------------------------------------- noInline :: Syntax a => a -> a noInline = sugarSym1 NoInline -------------------------------------------------- -- Num.hs -------------------------------------------------- There are three possibilities for making a ` Num ` instance for ` Data ` : 1 . instance ( Type a , a , ( Size a ) ) = > ( Data a ) 2 . instance ( Data Word8 ) instance ( Data Word16 ) instance ( Data Word32 ) -- ... -- 3. The implementation in this module # 1 has the problem with # 1 that it leaks implementation details . # 2 has the problem that it is verbose : The methods have to be implemented in each instance ( which , of course , can be taken care of using TemplateHaskell ) . # 3 avoids the above problems , but does so at the expense of having two numeric classes , which may -- be confusing to the user. class (Type a, Num a, Num (Size a), Hashable a) => Numeric a where fromIntegerNum :: Integer -> Data a fromIntegerNum = value . fromInteger absNum :: Data a -> Data a absNum = sugarSym1 Abs signumNum :: Data a -> Data a signumNum = sugarSym1 Sign addNum :: Data a -> Data a -> Data a addNum = sugarSym2 Add subNum :: Data a -> Data a -> Data a subNum = sugarSym2 Sub mulNum :: Data a -> Data a -> Data a mulNum = sugarSym2 Mul instance Numeric Word8 instance Numeric Word16 instance Numeric Word32 instance Numeric Word64 instance Numeric Int8 instance Numeric Int16 instance Numeric Int32 instance Numeric Int64 instance Numeric Float instance Numeric Double instance (Type a, P.RealFloat a, Hashable a) => Numeric (Complex a) instance Numeric a => Num (Data a) where fromInteger = fromIntegerNum abs = absNum signum = signumNum (+) = addNum (-) = subNum (*) = mulNum -------------------------------------------------- -- Ord.hs -------------------------------------------------- infix 4 < infix 4 > infix 4 <= infix 4 >= | Redefinition of the standard ' Prelude . ' class for Feldspar class (Eq a, P.Ord a, P.Ord (Size a)) => Ord a where (<) :: Data a -> Data a -> Data Bool (<) = sugarSym2 LTH (>) :: Data a -> Data a -> Data Bool (>) = sugarSym2 GTH (<=) :: Data a -> Data a -> Data Bool (<=) = sugarSym2 LTE (>=) :: Data a -> Data a -> Data Bool (>=) = sugarSym2 GTE min :: Data a -> Data a -> Data a min = sugarSym2 Min max :: Data a -> Data a -> Data a max = sugarSym2 Max instance Ord () instance Ord Bool instance Ord Word8 instance Ord Int8 instance Ord Word16 instance Ord Int16 instance Ord Word32 instance Ord Int32 instance Ord Word64 instance Ord Int64 instance Ord Float instance Ord Double -------------------------------------------------- -- Par.hs -------------------------------------------------- newtype P a = P { unP :: Mon Par a } deriving (Functor, Applicative, Monad) instance Syntax a => Syntactic (P a) where type Internal (P a) = Par (Internal a) desugar = desugar . unP sugar = P . sugar newtype IVar a = IVar { unIVar :: Data (IV (Internal a)) } instance Syntax a => Syntactic (IVar a) where type Internal (IVar a) = IV (Internal a) desugar = desugar . unIVar sugar = IVar . sugar instance P.Eq (Par a) where (==) = P.error "Eq not implemented for Par a" instance Show (Par a) where show = P.error "Show not implemented for Par a" instance Type a => Type (Par a) where typeRep = T.ParType typeRep sizeOf _ = P.error "sizeOf not implemented for Par a" -------------------------------------------------- -- RealFloat.hs -------------------------------------------------- -- Make new class, with "Data" in all the types class (Type a, P.RealFloat a) => RealFloat a where atan2 :: Data a -> Data a -> Data a atan2 = sugarSym2 Atan2 instance RealFloat Float instance RealFloat Double -------------------------------------------------- -- Save.hs -------------------------------------------------- | Tracing execution of Feldspar expressions -- | An identity function that guarantees that the result will be computed as a -- sub-result of the whole program. This is useful to prevent certain -- optimizations. -- Exception: Currently constant folding does not respect 'save'. save :: Syntax a => a -> a save = sugarSym1 Save -- | Equivalent to 'save'. When applied to a lazy data structure, 'force' (and -- 'save') has the effect of forcing evaluation of the whole structure. force :: Syntax a => a -> a force = save -------------------------------------------------- -- SizeProp.hs -------------------------------------------------- -- | The functions in this module can be used to help size inference (which, in -- turn, helps deriving upper bounds of array sizes and helps optimization). -- | An identity function affecting the abstract size information used during optimization . The application of a ' SizeCap ' is a /guarantee/ ( by the caller ) -- that the argument is within a certain size (determined by the creator of the ' SizeCap ' , e.g. ' sizeProp ' ) . -- /Warning: If the guarantee is not fulfilled, optimizations become unsound!/ -- In general, the size of the resulting value is the intersection of the cap size and the size obtained by ordinary size inference . That is , a ' SizeCap ' -- can only make the size more precise, not less precise. type SizeCap a = Data a -> Data a | @sizeProp prop a b@ : A guarantee that @b@ is within the size @(prop sa)@ , where @sa@ is the size of sizeProp :: (Syntax a, Type b) => (Size (Internal a) -> Size b) -> a -> SizeCap b TODO -- | A guarantee that the argument is within the given size cap :: Type a => Size a -> SizeCap a cap sz = sizeProp (const sz) (Data $ desugar ()) -- | @notAbove a b@: A guarantee that @b <= a@ holds notAbove :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> SizeCap a notAbove = sizeProp (Range (lowerBound universal) . upperBound) -- | @notBelow a b@: A guarantee that @b >= a@ holds notBelow :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> SizeCap a notBelow = sizeProp (flip Range (upperBound universal) . lowerBound) -- | @between l u a@: A guarantee that @l <= a <= u@ holds between :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> Data a -> SizeCap a between l u = notBelow l . notAbove u -------------------------------------------------- -- SourceInfo.hs -------------------------------------------------- Omitted -- | Source - code annotations data SourceInfo1 a = SourceInfo1 SourceInfo -- | Annotate an expression with information about its source code sourceData : : Type a = > SourceInfo1 a - > Data a - > Data a sourceData info = sugarSym1 ( Decor info I d ) -- | Source-code annotations data SourceInfo1 a = SourceInfo1 SourceInfo -- | Annotate an expression with information about its source code sourceData :: Type a => SourceInfo1 a -> Data a -> Data a sourceData info = sugarSym1 (Decor info Id) -} -------------------------------------------------- Switch.hs -------------------------------------------------- -- | Select between the cases based on the value of the scrutinee. If no match is found return the first argument switch :: (Eq (Internal a), Hashable (Internal a), Syntax a, Syntax b) => b -> [(Internal a, b)] -> a -> b switch def [] _ = def switch def cs s = let s' = resugar s in sugarSym1 Switch (foldr (\(c,a) b -> value c == s' ? a $ b) def cs) -------------------------------------------------- Tuple.hs -------------------------------------------------- -- | Helper function cdr :: (Type a, Typeable b, Type (Tuple b)) => ASTF (Tuple (a ': b)) -> ASTF (Tuple b) cdr = sugarSym1 Cdr instance (Syntax a, Syntax b) => Syntactic (a, b) where type Internal (a, b) = Tuple '[Internal a, Internal b] sugar e = (sugar $ sugarSym1 Car e, sugar $ sugarSym1 Car $ cdr e) desugar (x, y) = desugar $ build $ tuple x y instance (Syntax a, Syntax b, Syntax c) => Syntactic (a, b, c) where type Internal (a, b, c) = Tuple '[Internal a, Internal b, Internal c] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e ) desugar (a, b, c) = desugar $ build $ tuple a b c instance ( Syntax a, Syntax b, Syntax c, Syntax d ) => Syntactic (a, b, c, d) where type Internal (a, b, c, d) = Tuple '[ Internal a, Internal b, Internal c, Internal d ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e ) desugar (a, b, c, d) = desugar $ build $ tuple a b c d instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e ) => Syntactic (a, b, c, d, e) where type Internal (a, b, c, d, e) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e) = desugar $ build $ tuple a b c d e instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f ) => Syntactic (a, b, c, d, e, f) where type Internal (a, b, c, d, e, f) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f) = desugar $ build $ tuple a b c d e f instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g ) => Syntactic (a, b, c, d, e, f, g) where type Internal (a, b, c, d, e, f, g) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g) = desugar $ build $ tuple a b c d e f g instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h ) => Syntactic (a, b, c, d, e, f, g, h) where type Internal (a, b, c, d, e, f, g, h) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h) = desugar $ build $ tuple a b c d e f g h instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i ) => Syntactic (a, b, c, d, e, f, g, h, i) where type Internal (a, b, c, d, e, f, g, h, i) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i) = desugar $ build $ tuple a b c d e f g h i instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j ) => Syntactic (a, b, c, d, e, f, g, h, i, j) where type Internal (a, b, c, d, e, f, g, h, i, j) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j) = desugar $ build $ tuple a b c d e f g h i j instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k) where type Internal (a, b, c, d, e, f, g, h, i, j, k) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k) = desugar $ build $ tuple a b c d e f g h i j k instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l) = desugar $ build $ tuple a b c d e f g h i j k l instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m) = desugar $ build $ tuple a b c d e f g h i j k l m instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m, Syntax n ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m, n) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m, Internal n ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m, n) = desugar $ build $ tuple a b c d e f g h i j k l m n instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m, Syntax n, Syntax o ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m, Internal n, Internal o ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) = desugar $ build $ tuple a b c d e f g h i j k l m n o ------------------------------------------------- -- Support functions for monads ------------------------------------------------- | One - layer desugaring of monadic actions desugarMonad :: ( Monad m , Typeable m , Typeable a , Type (m a) , Type a , Size a ~ Size (m a) ) => Mon m (ASTF a) -> ASTF (m a) desugarMonad = flip runCont (sugarSym1 Return) . unMon | One - layer sugaring of monadic actions sugarMonad :: ( Monad m , Typeable m , Typeable a , Type (m a) , Type a , Size a ~ Size (m a) ) => ASTF (m a) -> Mon m (ASTF a) sugarMonad ma = Mon $ cont $ sugarSym2 Bind ma instance ( Syntactic a , Monad m , Typeable m , Typeable (Internal a) , Type (Internal a) , Type (m (Internal a)) , Size (Internal a) ~ Size (m (Internal a)) ) => Syntactic (Mon m a) where type Internal (Mon m a) = m (Internal a) desugar = desugarMonad . fmap desugar sugar = fmap sugar . sugarMonad ------------------------------------------------- -- Support functions ------------------------------------------------- -- | Convenience wrappers for sugarSym sugarSym0 :: Syntax a => Op (Internal a) -> a sugarSym0 op = unFull $ sugarSym op sugarSym1 :: (Typeable (Internal a), Syntactic a, Syntax b) => Op (Internal a -> Internal b) -> a -> b sugarSym1 op a = unFull $ sugarSym op a sugarSym2 :: (Typeable (Internal a), Typeable (Internal b), Syntactic a, Syntactic b, Syntax c) => Op (Internal a -> Internal b -> Internal c) -> a -> b -> c sugarSym2 op a b = unFull $ sugarSym op a b sugarSym3 :: (Typeable (Internal a), Typeable (Internal b), Typeable (Internal c), Syntactic a, Syntactic b, Syntactic c, Syntax d) => Op (Internal a -> Internal b -> Internal c -> Internal d) -> a -> b -> c -> d sugarSym3 op a b c = unFull $ sugarSym op a b c
null
https://raw.githubusercontent.com/Feldspar/feldspar-language/499e4e42d462f436a5267ddf0c2f73d5741a8248/src/Feldspar/Core/Language.hs
haskell
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. may be used to endorse or promote products derived from this software without specific prior written permission. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 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. # LANGUAGE RankNTypes # I think orphans are unavoidable in this file, so disable the warning. ------------------------------------------------ ------------------------------------------------ | Change the length of the vector to the supplied value. If the supplied length is greater than the old length, the new elements will have undefined value. | Array patch ------------------------------------------------ ------------------------------------------------ | Share an expression in the scope of a function | Share the intermediate result when composing functions | Share an expression in the scope of a function ------------------------------------------------ ------------------------------------------------ * Logical operations * Bitwise operations * Movement operations * Query operations * Combinators | Extract the `k` lowest bits ------------------------------------------------ ------------------------------------------------ ^ Amplitude ^ Angle ------------------------------------------------ ------------------------------------------------ | Condition operator. Use as follows: > cond1 ? ex1 $ > cond2 ? ex2 $ > exDefault ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ Elements.hs ------------------------------------------------ ------------------------------------------------ Eq.hs ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ | Assert that the condition holds or fail with message | Assert that the condition holds, the conditions string representation is used as the message ------------------------------------------------ FFI.hs ------------------------------------------------ | Arity 0 ------------------------------------------------ Floating.hs ------------------------------------------------ Make new class, with "Data" in all the types ------------------------------------------------ Fractional.hs ------------------------------------------------ | Fractional types. The relation to the standard 'Fractional' class is ------------------------------------------------ Future.hs ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ Loop.hs ------------------------------------------------ ------------------------------------------------ LoopM.hs ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ | Create a new 'Mutable' Array and intialize all elements | Create a new 'Mutable' Array and initialize with elements from the list | Extract the element at index | Replace the value at index | Modify the element at index | Query the length of the array | Modify all elements ------------------------------------------------ ------------------------------------------------ ------------------------------------------------ MutableReference.hs ------------------------------------------------ ------------------------------------------------ MutableToPure.hs ------------------------------------------------ ------------------------------------------------ Nested tuples ------------------------------------------------ 'Tuple a' which would add 'Tup' around each tail of the tuple, making it sharable. The test case 'noshare' in the 'decoration' suite checks that tails are not shared. ------------------------------------------------ NoInline.hs ------------------------------------------------ ------------------------------------------------ Num.hs ------------------------------------------------ ... 3. The implementation in this module be confusing to the user. ------------------------------------------------ Ord.hs ------------------------------------------------ ------------------------------------------------ Par.hs ------------------------------------------------ ------------------------------------------------ RealFloat.hs ------------------------------------------------ Make new class, with "Data" in all the types ------------------------------------------------ Save.hs ------------------------------------------------ | An identity function that guarantees that the result will be computed as a sub-result of the whole program. This is useful to prevent certain optimizations. Exception: Currently constant folding does not respect 'save'. | Equivalent to 'save'. When applied to a lazy data structure, 'force' (and 'save') has the effect of forcing evaluation of the whole structure. ------------------------------------------------ SizeProp.hs ------------------------------------------------ | The functions in this module can be used to help size inference (which, in turn, helps deriving upper bounds of array sizes and helps optimization). | An identity function affecting the abstract size information used during that the argument is within a certain size (determined by the creator of the /Warning: If the guarantee is not fulfilled, optimizations become unsound!/ In general, the size of the resulting value is the intersection of the cap can only make the size more precise, not less precise. | A guarantee that the argument is within the given size | @notAbove a b@: A guarantee that @b <= a@ holds | @notBelow a b@: A guarantee that @b >= a@ holds | @between l u a@: A guarantee that @l <= a <= u@ holds ------------------------------------------------ SourceInfo.hs ------------------------------------------------ | Source - code annotations | Annotate an expression with information about its source code | Source-code annotations | Annotate an expression with information about its source code ------------------------------------------------ ------------------------------------------------ | Select between the cases based on the value of the scrutinee. ------------------------------------------------ ------------------------------------------------ | Helper function ----------------------------------------------- Support functions for monads ----------------------------------------------- ----------------------------------------------- Support functions ----------------------------------------------- | Convenience wrappers for sugarSym
Copyright ( c ) 2019 , ERICSSON AB * Neither the name of the ERICSSON AB nor the names of its contributors THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , # LANGUAGE DataKinds # # LANGUAGE TypeFamilies # # LANGUAGE TypeOperators # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE ScopedTypeVariables # # LANGUAGE UndecidableInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE GeneralizedNewtypeDeriving # # OPTIONS_GHC -Wall # # OPTIONS_GHC -Wno - orphans # module Feldspar.Core.Language where import Feldspar.Core.NestedTuples (Tuple(..), build, tuple) import Feldspar.Core.Reify import Feldspar.Core.Representation as R import Feldspar.Core.Types as T import Feldspar.Lattice (Lattice, universal) import Feldspar.Range import Feldspar.Core.Collection import Control.Monad.Cont (runCont, cont) import Data.Typeable (Typeable) import Control.Applicative import Control.Monad (zipWithM_) import Data.Complex (Complex) import Data.Int import Data.IORef import Data.List (genericLength) import Data.Patch import Data.Word import Data.Hash (Hashable) import qualified Data.Bits as B import Prelude.EDSL import Prelude (Rational, foldr) import qualified Prelude as P Array.hs parallel :: Type a => Data Length -> (Data Index -> Data a) -> Data [a] parallel = sugarSym2 Parallel sequential :: (Syntax a, Syntax s) => Data Length -> s -> (Data Index -> s -> (a,s)) -> Data [Internal a] sequential = sugarSym3 Sequential append :: Type a => Data [a] -> Data [a] -> Data [a] append = sugarSym2 Append getLength :: Type a => Data [a] -> Data Length getLength = sugarSym1 GetLength setLength :: Type a => Data Length -> Data [a] -> Data [a] setLength = sugarSym2 SetLength getIx :: Type a => Data [a] -> Data Index -> Data a getIx = sugarSym2 GetIx setIx :: Type a => Data [a] -> Data Index -> Data a -> Data [a] setIx = sugarSym3 SetIx type instance Elem (Data [a]) = Data a type instance CollIndex (Data [a]) = Data Index type instance CollSize (Data [a]) = Data Length instance Type a => Indexed (Data [a]) where (!) = getIx instance Type a => Sized (Data [a]) where collSize = getLength setCollSize = setLength instance (Type a, Type b) => CollMap (Data [a]) (Data [b]) where collMap f arr = parallel (getLength arr) (f . getIx arr) (|>) :: (Sized a, CollMap a a) => Patch (CollSize a) (CollSize a) -> Patch (Elem a) (Elem a) -> Patch a a (sizePatch |> elemPatch) a = collMap elemPatch $ setCollSize (sizePatch (collSize a)) a Binding.hs share :: (Syntax a, Syntax b) => a -> (a -> b) -> b share = sugarSym2 Let (.<) :: (Syntax b, Syntax c) => (b -> c) -> (a -> b) -> a -> c (.<) f g a = share (g a) f infixr 9 .< ($<) :: (Syntax a, Syntax b) => (a -> b) -> a -> b ($<) = flip share infixr 0 $< Bits.hs infixl 5 .<<.,.>>. infixl 4 ⊕ class (Type a, Bounded a, B.FiniteBits a, Integral a, Size a ~ Range a, P.Integral (UnsignedRep a), B.FiniteBits (UnsignedRep a)) => Bits a where (.&.) :: Data a -> Data a -> Data a (.&.) = sugarSym2 BAnd (.|.) :: Data a -> Data a -> Data a (.|.) = sugarSym2 BOr xor :: Data a -> Data a -> Data a xor = sugarSym2 BXor complement :: Data a -> Data a complement = sugarSym1 Complement bit :: Data Index -> Data a bit = sugarSym1 Bit setBit :: Data a -> Data Index -> Data a setBit = sugarSym2 SetBit clearBit :: Data a -> Data Index -> Data a clearBit = sugarSym2 ClearBit complementBit :: Data a -> Data Index -> Data a complementBit = sugarSym2 ComplementBit testBit :: Data a -> Data Index -> Data Bool testBit = sugarSym2 TestBit shiftLU :: Data a -> Data Index -> Data a shiftLU = sugarSym2 ShiftLU shiftRU :: Data a -> Data Index -> Data a shiftRU = sugarSym2 ShiftRU shiftL :: Data a -> Data IntN -> Data a shiftL = sugarSym2 ShiftL shiftR :: Data a -> Data IntN -> Data a shiftR = sugarSym2 ShiftR rotateLU :: Data a -> Data Index -> Data a rotateLU = sugarSym2 RotateLU rotateRU :: Data a -> Data Index -> Data a rotateRU = sugarSym2 RotateRU rotateL :: Data a -> Data IntN -> Data a rotateL = sugarSym2 RotateL rotateR :: Data a -> Data IntN -> Data a rotateR = sugarSym2 RotateR reverseBits :: Data a -> Data a reverseBits = sugarSym1 ReverseBits bitScan :: Data a -> Data Index bitScan = sugarSym1 BitScan bitCount :: Data a -> Data Index bitCount = sugarSym1 BitCount bitSize :: Data a -> Data Index bitSize = value . bitSize' bitSize' :: Data a -> Index bitSize' = const $ P.fromIntegral $ finiteBitSize (undefined :: a) isSigned :: Data a -> Data Bool isSigned = value . isSigned' isSigned' :: Data a -> Bool isSigned' = const $ B.isSigned (undefined :: a) finiteBitSize :: B.FiniteBits b => b -> Int finiteBitSize = B.finiteBitSize instance Bits Word8 instance Bits Word16 instance Bits Word32 instance Bits Word64 instance Bits Int8 instance Bits Int16 instance Bits Int32 instance Bits Int64 (⊕) :: Bits a => Data a -> Data a -> Data a (⊕) = xor (.<<.) :: Bits a => Data a -> Data Index -> Data a (.<<.) = shiftLU (.>>.) :: Bits a => Data a -> Data Index -> Data a (.>>.) = shiftRU | Set all bits to one allOnes :: Bits a => Data a allOnes = complement 0 | Set the ` n ` lowest bits to one oneBits :: Bits a => Data Index -> Data a oneBits n = complement (allOnes .<<. n) lsbs :: Bits a => Data Index -> Data a -> Data a lsbs k i = i .&. oneBits k complex :: (Numeric a, P.RealFloat a) => Data a -> Data a -> Data (Complex a) complex = sugarSym2 MkComplex realPart :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a realPart = sugarSym1 RealPart imagPart :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a imagPart = sugarSym1 ImagPart conjugate :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data (Complex a) conjugate = sugarSym1 Conjugate mkPolar :: (Numeric a, P.RealFloat a) -> Data (Complex a) mkPolar = sugarSym2 MkPolar cis :: (Numeric a, P.RealFloat a) => Data a -> Data (Complex a) cis = sugarSym1 Cis magnitude :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a magnitude = sugarSym1 Magnitude phase :: (Numeric a, P.RealFloat a) => Data (Complex a) -> Data a phase = sugarSym1 Phase polar :: (Numeric a, P.RealFloat a) => Data (Complex a) -> (Data a, Data a) polar c = (magnitude c, phase c) infixl 6 +. (+.) :: (Numeric a, P.RealFloat a) => Data a -> Data a -> Data (Complex a) (+.) = complex iunit :: (Numeric a, P.RealFloat a) => Data (Complex a) iunit = 0 +. 1 Condition.hs > cond3 ? ex3 $ (?) :: Syntax a => Data Bool -> a -> a -> a (?) = sugarSym3 Condition infixl 1 ? ConditionM.hs ifM :: Syntax a => Data Bool -> M a -> M a -> M a ifM = sugarSym3 ConditionM whenM :: Data Bool -> M () -> M () whenM c ma = ifM c ma (return ()) unlessM :: Data Bool -> M () -> M () unlessM c = ifM c (return ()) Conversion.hs i2f :: (Integral a, Numeric b, P.RealFloat b) => Data a -> Data b i2f = i2n f2i :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a f2i = sugarSym1 F2I i2n :: (Integral a, Numeric b) => Data a -> Data b i2n = sugarSym1 I2N b2i :: Integral a => Data Bool -> Data a b2i = sugarSym1 B2I truncate :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a truncate = f2i round :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a round = sugarSym1 Round ceiling :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a ceiling = sugarSym1 Ceiling floor :: (Integral a, Numeric b, P.RealFloat b) => Data b -> Data a floor = sugarSym1 Floor materialize :: Type a => Data Length -> Data (Elements a) -> Data [a] materialize = sugarSym2 EMaterialize write :: Type a => Data Index -> Data a -> Data (Elements a) write = sugarSym2 EWrite par :: Type a => Data (Elements a) -> Data (Elements a) -> Data (Elements a) par = sugarSym2 EPar parFor :: Type a => Data Length -> (Data Index -> Data (Elements a)) -> Data (Elements a) parFor = sugarSym2 EparFor skip :: Type a => Data (Elements a) skip = sugarSym0 ESkip infix 4 == infix 4 /= | Redefinition of the standard ' P.Eq ' class for Feldspar class Type a => Eq a where (==) :: Data a -> Data a -> Data Bool (==) = sugarSym2 Equal (/=) :: Data a -> Data a -> Data Bool (/=) = sugarSym2 NotEqual instance Eq () instance Eq Bool instance Eq Float instance Eq Double instance Eq Word8 instance Eq Word16 instance Eq Word32 instance Eq Word64 instance Eq Int8 instance Eq Int16 instance Eq Int32 instance Eq Int64 instance (Eq a, Eq b) => Eq (a, b) instance (Eq a, Eq b, Eq c) => Eq (a, b, c) instance (Eq a, Eq b, Eq c, Eq d) => Eq (a, b, c, d) instance (Eq a, Eq b, Eq c, Eq d, Eq e) => Eq (a, b ,c, d, e) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f) => Eq (a, b, c, d, e, f) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g) => Eq (a, b, c, d, e, f, g) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h) => Eq (a, b, c, d, e, f, g, h) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i) => Eq (a, b, c, d, e, f, g, h, i) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j) => Eq (a, b, c, d, e, f, g, h, i, j) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k) => Eq (a, b, c, d, e, f, g, h, i, j, k) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l) => Eq (a, b, c, d, e, f, g, h, i, j, k, l) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n) instance (Eq a, Eq b, Eq c, Eq d, Eq e, Eq f, Eq g, Eq h, Eq i, Eq j, Eq k, Eq l, Eq m, Eq n, Eq o) => Eq (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) instance (Eq a, P.RealFloat a) => Eq (Complex a) Error.hs undef :: Syntax a => a undef = sugarSym0 Undefined assertMsg :: Syntax a => String -> Data Bool -> a -> a assertMsg s = sugarSym2 (Assert s) assert :: Syntax a => Data Bool -> a -> a assert cond = assertMsg (show cond) cond err :: Syntax a => String -> a err msg = assertMsg msg false undef | Arity specific functions for FFI foreignImport0 :: Syntax r => String -> Internal r -> r foreignImport0 s f = sugarSym0 (ForeignImport s (EqBox f)) | Arity 1 foreignImport1 :: (Syntax r, Syntactic a, Typeable (Internal a)) => String -> (Internal a -> Internal r) -> a -> r foreignImport1 s f = sugarSym1 (ForeignImport s (EqBox f)) | Arity 2 foreignImport2 :: (Syntax r, Syntactic a, Syntactic b, Typeable (Internal a), Typeable (Internal b)) => String -> (Internal a -> Internal b -> Internal r) -> a -> b -> r foreignImport2 s f = sugarSym2 (ForeignImport s (EqBox f)) | Arity 3 foreignImport3 :: (Syntax r, Syntactic a, Syntactic b, Syntactic c, Typeable (Internal a), Typeable (Internal b), Typeable (Internal c)) => String -> (Internal a -> Internal b -> Internal c -> Internal r) -> a -> b -> c -> r foreignImport3 s f = sugarSym3 (ForeignImport s (EqBox f)) | Arity 4 foreignImport4 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal r) -> a -> b -> c -> d -> r foreignImport4 s f a b c d = unFull $ sugarSym (ForeignImport s (EqBox f)) a b c d | Arity 5 foreignImport5 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Syntactic e , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) , Typeable (Internal e) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal e -> Internal r) -> a -> b -> c -> d -> e -> r foreignImport5 s f a b c d e = unFull $ sugarSym (ForeignImport s (EqBox f)) a b c d e | Arity 6 foreignImport6 :: ( Syntax r , Syntactic a , Syntactic b , Syntactic c , Syntactic d , Syntactic e , Syntactic f , Typeable (Internal a) , Typeable (Internal b) , Typeable (Internal c) , Typeable (Internal d) , Typeable (Internal e) , Typeable (Internal f) ) => String -> (Internal a -> Internal b -> Internal c -> Internal d -> Internal e -> Internal f -> Internal r) -> a -> b -> c -> d -> e -> f -> r foreignImport6 s x a b c d e f = unFull $ sugarSym (ForeignImport s (EqBox x)) a b c d e f infixr 8 ** class (Fraction a, P.Floating a) => Floating a where pi :: Data a pi = sugarSym0 Pi exp :: Data a -> Data a exp = sugarSym1 Exp sqrt :: Data a -> Data a sqrt = sugarSym1 Sqrt log :: Data a -> Data a log = sugarSym1 Log (**) :: Data a -> Data a -> Data a (**) = sugarSym2 Pow logBase :: Data a -> Data a -> Data a logBase = sugarSym2 LogBase sin :: Data a -> Data a sin = sugarSym1 Sin tan :: Data a -> Data a tan = sugarSym1 Tan cos :: Data a -> Data a cos = sugarSym1 Cos asin :: Data a -> Data a asin = sugarSym1 Asin atan :: Data a -> Data a atan = sugarSym1 Atan acos :: Data a -> Data a acos = sugarSym1 Acos sinh :: Data a -> Data a sinh = sugarSym1 Sinh tanh :: Data a -> Data a tanh = sugarSym1 Tanh cosh :: Data a -> Data a cosh = sugarSym1 Cosh asinh :: Data a -> Data a asinh = sugarSym1 Asinh atanh :: Data a -> Data a atanh = sugarSym1 Atanh acosh :: Data a -> Data a acosh = sugarSym1 Acosh instance Floating Float instance Floating Double instance (Fraction a, P.RealFloat a) => Floating (Complex a) π :: Floating a => Data a π = pi @instance ` Fraction ` a = > ` Fractional ` ( ` Data ` a)@ class (Fractional a, Numeric a) => Fraction a where fromRationalFrac :: Rational -> Data a fromRationalFrac = value . fromRational divFrac :: Data a -> Data a -> Data a divFrac = sugarSym2 DivFrac instance Fraction Float instance Fraction Double instance (Fraction a, P.RealFloat a) => Fraction (Complex a) instance Fraction a => Fractional (Data a) where fromRational = fromRationalFrac (/) = divFrac newtype Future a = Future { unFuture :: Data (FVal (Internal a)) } later :: (Syntax a, Syntax b) => (a -> b) -> Future a -> Future b later f = future . f . await pval :: (Syntax a, Syntax b) => (a -> b) -> a -> b pval f x = await $ force $ future (f x) instance Syntax a => Syntactic (Future a) where type Internal (Future a) = FVal (Internal a) desugar = desugar . unFuture sugar = Future . sugar future :: Syntax a => a -> Future a future = sugarSym1 MkFuture await :: Syntax a => Future a -> a await = sugarSym1 Await Integral.hs class (Bounded a, B.FiniteBits a, Ord a, Numeric a, P.Integral a, Size a ~ Range a) => Integral a where quot :: Data a -> Data a -> Data a quot = sugarSym2 Quot rem :: Data a -> Data a -> Data a rem = sugarSym2 Rem div :: Data a -> Data a -> Data a div = sugarSym2 Div mod :: Data a -> Data a -> Data a mod = sugarSym2 Mod (^) :: Data a -> Data a -> Data a (^) = sugarSym2 IExp divSem :: Integral a => Data a -> Data a -> Data a divSem x y = (x > 0 && y < 0 || x < 0 && y > 0) && rem x y /= 0 ? quot x y P.- 1 P.$ quot x y instance Integral Word8 instance Integral Word16 instance Integral Word32 instance Integral Word64 instance Integral Int8 instance Integral Int16 instance Integral Int32 instance Integral Int64 Literal.hs false :: Data Bool false = value False true :: Data Bool true = value True Logic.hs infixr 3 && infixr 3 &&* infixr 2 || infixr 2 ||* not :: Data Bool -> Data Bool not = sugarSym1 Not (&&) :: Data Bool -> Data Bool -> Data Bool (&&) = sugarSym2 And (||) :: Data Bool -> Data Bool -> Data Bool (||) = sugarSym2 Or | Lazy conjunction , second argument only evaluated if necessary (&&*) :: Data Bool -> Data Bool -> Data Bool a &&* b = a ? b $ false | Lazy disjunction , second argument only evaluated if necessary (||*) :: Data Bool -> Data Bool -> Data Bool a ||* b = a ? true $ b forLoop :: Syntax a => Data Length -> a -> (Data Index -> a -> a) -> a forLoop = sugarSym3 ForLoop whileLoop :: Syntax a => a -> (a -> Data Bool) -> (a -> a) -> a whileLoop = sugarSym3 WhileLoop forM :: Syntax a => Data Length -> (Data Index -> M a) -> M () forM = sugarSym2 For whileM :: Syntax a => M (Data Bool) -> M a -> M () whileM = sugarSym2 While MutableArray.hs newArr :: Type a => Data Length -> Data a -> M (Data (MArr a)) newArr = sugarSym2 NewArr | Create a new ' Mutable ' Array but leave the elements un - initialized newArr_ :: Type a => Data Length -> M (Data (MArr a)) newArr_ = sugarSym1 NewArr_ newListArr :: forall a. Type a => [Data a] -> M (Data (MArr a)) newListArr xs = do arr <- newArr_ (value $ genericLength xs) zipWithM_ (setArr arr . value) [0..] xs return arr getArr :: Type a => Data (MArr a) -> Data Index -> M (Data a) getArr = sugarSym2 GetArr setArr :: Type a => Data (MArr a) -> Data Index -> Data a -> M () setArr = sugarSym3 SetArr modifyArr :: Type a => Data (MArr a) -> Data Index -> (Data a -> Data a) -> M () modifyArr arr i f = getArr arr i >>= setArr arr i . f arrLength :: Type a => Data (MArr a) -> M (Data Length) arrLength = sugarSym1 ArrLength mapArray :: Type a => (Data a -> Data a) -> Data (MArr a) -> M (Data (MArr a)) mapArray f arr = do len <- arrLength arr forArr len (flip (modifyArr arr) f) return arr forArr :: Syntax a => Data Length -> (Data Index -> M a) -> M () forArr = sugarSym2 For | Swap two elements swap :: Type a => Data (MArr a) -> Data Index -> Data Index -> M () swap a i1 i2 = do tmp <- getArr a i1 getArr a i2 >>= setArr a i1 setArr a i2 tmp Mutable.hs newtype M a = M { unM :: Mon Mut a } deriving (Functor, Applicative, Monad) instance Syntax a => Syntactic (M a) where type Internal (M a) = Mut (Internal a) desugar = desugar . unM sugar = M . sugar instance P.Eq (Mut a) where (==) = P.error "Eq not implemented for Mut a" instance Show (Mut a) where show = P.error "Show not implemented for Mut a" runMutable :: Syntax a => M a -> a runMutable = sugarSym1 Run when :: Data Bool -> M () -> M () when = sugarSym2 When unless :: Data Bool -> M () -> M () unless = when . not instance Type a => Type (Mut a) where typeRep = T.MutType typeRep sizeOf _ = P.error "sizeOf not implemented for Mut a" newtype Ref a = Ref { unRef :: Data (IORef (Internal a)) } instance Syntax a => Syntactic (Ref a) where type Internal (Ref a) = IORef (Internal a) desugar = desugar . unRef sugar = Ref . sugar newRef :: Syntax a => a -> M (Ref a) newRef = sugarSym1 NewRef getRef :: Syntax a => Ref a -> M a getRef = sugarSym1 GetRef setRef :: Syntax a => Ref a -> a -> M () setRef = sugarSym2 SetRef modifyRef :: Syntax a => Ref a -> (a -> a) -> M () modifyRef = sugarSym2 ModRef withArray :: (Type a, Syntax b) => Data (MArr a) -> (Data [a] -> M b) -> M b withArray = sugarSym2 WithArray runMutableArray :: Type a => M (Data (MArr a)) -> Data [a] runMutableArray = sugarSym1 RunMutableArray freezeArray :: Type a => Data (MArr a) -> M (Data [a]) freezeArray marr = withArray marr return thawArray :: Type a => Data [a] -> M (Data (MArr a)) thawArray arr = do marr <- newArr_ (getLength arr) forM (getLength arr) (\ix -> setArr marr ix (getIx arr ix) ) return marr class Type (Tuple (InternalTup a)) => SyntacticTup a where type InternalTup a :: [*] desugarTup :: Tuple a -> ASTF (Tuple (InternalTup a)) sugarTup :: ASTF (Tuple (InternalTup a)) -> Tuple a We call desugarTup explicitly below to avoid use of the Syntactic instance for instance (Syntax a, SyntacticTup b, Typeable (InternalTup b)) => SyntacticTup (a ': b) where type InternalTup (a ': b) = Internal a ': InternalTup b desugarTup (x :* xs) = sugarSym2 Cons x (desugarTup xs) sugarTup e = sugar (sugarSym1 Car e) :* sugarTup (sugarSym1 Cdr e) instance SyntacticTup '[] where type InternalTup '[] = '[] desugarTup TNil = sugarSym0 Nil sugarTup _ = TNil instance SyntacticTup a => Syntactic (Tuple a) where type Internal (Tuple a) = Tuple (InternalTup a) desugar = sugarSym1 Tup . desugarTup sugar = sugarTup noInline :: Syntax a => a -> a noInline = sugarSym1 NoInline There are three possibilities for making a ` Num ` instance for ` Data ` : 1 . instance ( Type a , a , ( Size a ) ) = > ( Data a ) 2 . instance ( Data Word8 ) instance ( Data Word16 ) instance ( Data Word32 ) # 1 has the problem with # 1 that it leaks implementation details . # 2 has the problem that it is verbose : The methods have to be implemented in each instance ( which , of course , can be taken care of using TemplateHaskell ) . # 3 avoids the above problems , but does so at the expense of having two numeric classes , which may class (Type a, Num a, Num (Size a), Hashable a) => Numeric a where fromIntegerNum :: Integer -> Data a fromIntegerNum = value . fromInteger absNum :: Data a -> Data a absNum = sugarSym1 Abs signumNum :: Data a -> Data a signumNum = sugarSym1 Sign addNum :: Data a -> Data a -> Data a addNum = sugarSym2 Add subNum :: Data a -> Data a -> Data a subNum = sugarSym2 Sub mulNum :: Data a -> Data a -> Data a mulNum = sugarSym2 Mul instance Numeric Word8 instance Numeric Word16 instance Numeric Word32 instance Numeric Word64 instance Numeric Int8 instance Numeric Int16 instance Numeric Int32 instance Numeric Int64 instance Numeric Float instance Numeric Double instance (Type a, P.RealFloat a, Hashable a) => Numeric (Complex a) instance Numeric a => Num (Data a) where fromInteger = fromIntegerNum abs = absNum signum = signumNum (+) = addNum (-) = subNum (*) = mulNum infix 4 < infix 4 > infix 4 <= infix 4 >= | Redefinition of the standard ' Prelude . ' class for Feldspar class (Eq a, P.Ord a, P.Ord (Size a)) => Ord a where (<) :: Data a -> Data a -> Data Bool (<) = sugarSym2 LTH (>) :: Data a -> Data a -> Data Bool (>) = sugarSym2 GTH (<=) :: Data a -> Data a -> Data Bool (<=) = sugarSym2 LTE (>=) :: Data a -> Data a -> Data Bool (>=) = sugarSym2 GTE min :: Data a -> Data a -> Data a min = sugarSym2 Min max :: Data a -> Data a -> Data a max = sugarSym2 Max instance Ord () instance Ord Bool instance Ord Word8 instance Ord Int8 instance Ord Word16 instance Ord Int16 instance Ord Word32 instance Ord Int32 instance Ord Word64 instance Ord Int64 instance Ord Float instance Ord Double newtype P a = P { unP :: Mon Par a } deriving (Functor, Applicative, Monad) instance Syntax a => Syntactic (P a) where type Internal (P a) = Par (Internal a) desugar = desugar . unP sugar = P . sugar newtype IVar a = IVar { unIVar :: Data (IV (Internal a)) } instance Syntax a => Syntactic (IVar a) where type Internal (IVar a) = IV (Internal a) desugar = desugar . unIVar sugar = IVar . sugar instance P.Eq (Par a) where (==) = P.error "Eq not implemented for Par a" instance Show (Par a) where show = P.error "Show not implemented for Par a" instance Type a => Type (Par a) where typeRep = T.ParType typeRep sizeOf _ = P.error "sizeOf not implemented for Par a" class (Type a, P.RealFloat a) => RealFloat a where atan2 :: Data a -> Data a -> Data a atan2 = sugarSym2 Atan2 instance RealFloat Float instance RealFloat Double | Tracing execution of Feldspar expressions save :: Syntax a => a -> a save = sugarSym1 Save force :: Syntax a => a -> a force = save optimization . The application of a ' SizeCap ' is a /guarantee/ ( by the caller ) ' SizeCap ' , e.g. ' sizeProp ' ) . size and the size obtained by ordinary size inference . That is , a ' SizeCap ' type SizeCap a = Data a -> Data a | @sizeProp prop a b@ : A guarantee that @b@ is within the size @(prop sa)@ , where @sa@ is the size of sizeProp :: (Syntax a, Type b) => (Size (Internal a) -> Size b) -> a -> SizeCap b TODO cap :: Type a => Size a -> SizeCap a cap sz = sizeProp (const sz) (Data $ desugar ()) notAbove :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> SizeCap a notAbove = sizeProp (Range (lowerBound universal) . upperBound) notBelow :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> SizeCap a notBelow = sizeProp (flip Range (upperBound universal) . lowerBound) between :: (Type a, Lattice (Range a), Size a ~ Range a) => Data a -> Data a -> SizeCap a between l u = notBelow l . notAbove u Omitted data SourceInfo1 a = SourceInfo1 SourceInfo sourceData : : Type a = > SourceInfo1 a - > Data a - > Data a sourceData info = sugarSym1 ( Decor info I d ) data SourceInfo1 a = SourceInfo1 SourceInfo sourceData :: Type a => SourceInfo1 a -> Data a -> Data a sourceData info = sugarSym1 (Decor info Id) -} Switch.hs If no match is found return the first argument switch :: (Eq (Internal a), Hashable (Internal a), Syntax a, Syntax b) => b -> [(Internal a, b)] -> a -> b switch def [] _ = def switch def cs s = let s' = resugar s in sugarSym1 Switch (foldr (\(c,a) b -> value c == s' ? a $ b) def cs) Tuple.hs cdr :: (Type a, Typeable b, Type (Tuple b)) => ASTF (Tuple (a ': b)) -> ASTF (Tuple b) cdr = sugarSym1 Cdr instance (Syntax a, Syntax b) => Syntactic (a, b) where type Internal (a, b) = Tuple '[Internal a, Internal b] sugar e = (sugar $ sugarSym1 Car e, sugar $ sugarSym1 Car $ cdr e) desugar (x, y) = desugar $ build $ tuple x y instance (Syntax a, Syntax b, Syntax c) => Syntactic (a, b, c) where type Internal (a, b, c) = Tuple '[Internal a, Internal b, Internal c] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e ) desugar (a, b, c) = desugar $ build $ tuple a b c instance ( Syntax a, Syntax b, Syntax c, Syntax d ) => Syntactic (a, b, c, d) where type Internal (a, b, c, d) = Tuple '[ Internal a, Internal b, Internal c, Internal d ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e ) desugar (a, b, c, d) = desugar $ build $ tuple a b c d instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e ) => Syntactic (a, b, c, d, e) where type Internal (a, b, c, d, e) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e) = desugar $ build $ tuple a b c d e instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f ) => Syntactic (a, b, c, d, e, f) where type Internal (a, b, c, d, e, f) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f) = desugar $ build $ tuple a b c d e f instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g ) => Syntactic (a, b, c, d, e, f, g) where type Internal (a, b, c, d, e, f, g) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g) = desugar $ build $ tuple a b c d e f g instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h ) => Syntactic (a, b, c, d, e, f, g, h) where type Internal (a, b, c, d, e, f, g, h) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h) = desugar $ build $ tuple a b c d e f g h instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i ) => Syntactic (a, b, c, d, e, f, g, h, i) where type Internal (a, b, c, d, e, f, g, h, i) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i) = desugar $ build $ tuple a b c d e f g h i instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j ) => Syntactic (a, b, c, d, e, f, g, h, i, j) where type Internal (a, b, c, d, e, f, g, h, i, j) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j) = desugar $ build $ tuple a b c d e f g h i j instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k) where type Internal (a, b, c, d, e, f, g, h, i, j, k) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k) = desugar $ build $ tuple a b c d e f g h i j k instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l) = desugar $ build $ tuple a b c d e f g h i j k l instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m) = desugar $ build $ tuple a b c d e f g h i j k l m instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m, Syntax n ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m, n) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m, n) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m, Internal n ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m, n) = desugar $ build $ tuple a b c d e f g h i j k l m n instance ( Syntax a, Syntax b, Syntax c, Syntax d , Syntax e, Syntax f, Syntax g, Syntax h , Syntax i, Syntax j, Syntax k, Syntax l , Syntax m, Syntax n, Syntax o ) => Syntactic (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) where type Internal (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) = Tuple '[ Internal a, Internal b, Internal c, Internal d , Internal e, Internal f, Internal g, Internal h , Internal i, Internal j, Internal k, Internal l , Internal m, Internal n, Internal o ] sugar e = ( sugar $ sugarSym1 Car e , sugar $ sugarSym1 Car $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e , sugar $ sugarSym1 Car $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr $ cdr e ) desugar (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) = desugar $ build $ tuple a b c d e f g h i j k l m n o | One - layer desugaring of monadic actions desugarMonad :: ( Monad m , Typeable m , Typeable a , Type (m a) , Type a , Size a ~ Size (m a) ) => Mon m (ASTF a) -> ASTF (m a) desugarMonad = flip runCont (sugarSym1 Return) . unMon | One - layer sugaring of monadic actions sugarMonad :: ( Monad m , Typeable m , Typeable a , Type (m a) , Type a , Size a ~ Size (m a) ) => ASTF (m a) -> Mon m (ASTF a) sugarMonad ma = Mon $ cont $ sugarSym2 Bind ma instance ( Syntactic a , Monad m , Typeable m , Typeable (Internal a) , Type (Internal a) , Type (m (Internal a)) , Size (Internal a) ~ Size (m (Internal a)) ) => Syntactic (Mon m a) where type Internal (Mon m a) = m (Internal a) desugar = desugarMonad . fmap desugar sugar = fmap sugar . sugarMonad sugarSym0 :: Syntax a => Op (Internal a) -> a sugarSym0 op = unFull $ sugarSym op sugarSym1 :: (Typeable (Internal a), Syntactic a, Syntax b) => Op (Internal a -> Internal b) -> a -> b sugarSym1 op a = unFull $ sugarSym op a sugarSym2 :: (Typeable (Internal a), Typeable (Internal b), Syntactic a, Syntactic b, Syntax c) => Op (Internal a -> Internal b -> Internal c) -> a -> b -> c sugarSym2 op a b = unFull $ sugarSym op a b sugarSym3 :: (Typeable (Internal a), Typeable (Internal b), Typeable (Internal c), Syntactic a, Syntactic b, Syntactic c, Syntax d) => Op (Internal a -> Internal b -> Internal c -> Internal d) -> a -> b -> c -> d sugarSym3 op a b c = unFull $ sugarSym op a b c
c4a0d2914c64dfcca0e1999170d26d422f603f5050c8a2acbab518dceed0155b
NorfairKing/autodocodec
YamlSpec.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Autodocodec.YamlSpec (spec) where import Autodocodec import Autodocodec.Usage import Autodocodec.Yaml.Encode import qualified Data.Aeson as JSON import Data.Data import Data.GenValidity import Data.GenValidity.Aeson () import Data.GenValidity.Containers () import Data.GenValidity.Scientific () import Data.GenValidity.Text () import Data.GenValidity.Time () import Data.Int import Data.List.NonEmpty (NonEmpty) import Data.Map (Map) import Data.Scientific import Data.Set (Set) import Data.Text (Text) import qualified Data.Text.Lazy as LT import Data.Time import Data.Word import Data.Yaml as Yaml import Data.Yaml.Builder as YamlBuilder import Test.Syd import Test.Syd.Validity import Test.Syd.Validity.Utils spec :: Spec spec = do yamlCodecSpec @NullUnit yamlCodecSpec @Bool yamlCodecSpec @Ordering xdescribe "does not hold" $ yamlCodecSpec @Char yamlCodecSpec @Text yamlCodecSpec @LT.Text xdescribe "does not hold" $ yamlCodecSpec @String xdescribe "does not hold" $ yamlCodecSpec @Scientific xdescribe "does not hold" $ yamlCodecSpec @JSON.Object xdescribe "does not hold" $ yamlCodecSpec @JSON.Value yamlCodecSpec @Int yamlCodecSpec @Int8 yamlCodecSpec @Int16 yamlCodecSpec @Int32 yamlCodecSpec @Int64 yamlCodecSpec @Word yamlCodecSpec @Word8 yamlCodecSpec @Word16 yamlCodecSpec @Word32 yamlCodecSpec @Word64 yamlCodecSpec @(Maybe Text) yamlCodecSpec @(Either Bool Text) yamlCodecSpec @(Either (Either Bool [Text]) Text) yamlCodecSpec @[Text] yamlCodecSpec @(NonEmpty Text) yamlCodecSpec @(Set Text) yamlCodecSpec @(Map Text Int) yamlCodecSpec @Day yamlCodecSpec @LocalTime yamlCodecSpec @UTCTime yamlCodecSpec @TimeOfDay yamlCodecSpec @DiffTime yamlCodecSpec @NominalDiffTime yamlCodecSpec @Fruit yamlCodecSpec @Example yamlCodecSpec @Recursive yamlCodecSpec @MutuallyRecursiveA yamlCodecSpec @Via yamlCodecSpec @VeryComment yamlCodecSpec @LegacyValue yamlCodecSpec @LegacyObject yamlCodecSpec @Ainur yamlCodecSpec @War yamlCodecSpec @These yamlCodecSpec @Expression yamlCodecSpec :: forall a. ( Show a, Eq a, Typeable a, GenValid a, FromJSON a, HasCodec a ) => Spec yamlCodecSpec = describe (nameOf @a) $ do it "roundtrips through yaml" $ forAllValid $ \(a :: a) -> let encoded = YamlBuilder.toByteString (toYamlViaCodec a) errOrDecoded = Yaml.decodeEither' encoded ctx = unlines [ "Encoded to this value:", ppShow encoded, "with this codec", showCodecABit (codec @a) ] in context ctx $ case errOrDecoded of Left err -> expectationFailure $ Yaml.prettyPrintParseException err Right actual -> actual `shouldBe` a it "roundtrips through yaml and back" $ forAllValid $ \(a :: a) -> let encoded = YamlBuilder.toByteString (toYamlViaCodec a) errOrDecoded = Yaml.decodeEither' encoded ctx = unlines [ "Encoded to this value:", ppShow encoded, "with this codec", showCodecABit (codec @a) ] in context ctx $ case errOrDecoded of Left err -> expectationFailure $ Yaml.prettyPrintParseException err Right actual -> YamlBuilder.toByteString (toYamlViaCodec (actual :: a)) `shouldBe` YamlBuilder.toByteString (toYamlViaCodec a)
null
https://raw.githubusercontent.com/NorfairKing/autodocodec/71c4dcb3c890590cf1a4e42fb9f9f422a7c49ec0/autodocodec-api-usage/test/Autodocodec/YamlSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeApplications # module Autodocodec.YamlSpec (spec) where import Autodocodec import Autodocodec.Usage import Autodocodec.Yaml.Encode import qualified Data.Aeson as JSON import Data.Data import Data.GenValidity import Data.GenValidity.Aeson () import Data.GenValidity.Containers () import Data.GenValidity.Scientific () import Data.GenValidity.Text () import Data.GenValidity.Time () import Data.Int import Data.List.NonEmpty (NonEmpty) import Data.Map (Map) import Data.Scientific import Data.Set (Set) import Data.Text (Text) import qualified Data.Text.Lazy as LT import Data.Time import Data.Word import Data.Yaml as Yaml import Data.Yaml.Builder as YamlBuilder import Test.Syd import Test.Syd.Validity import Test.Syd.Validity.Utils spec :: Spec spec = do yamlCodecSpec @NullUnit yamlCodecSpec @Bool yamlCodecSpec @Ordering xdescribe "does not hold" $ yamlCodecSpec @Char yamlCodecSpec @Text yamlCodecSpec @LT.Text xdescribe "does not hold" $ yamlCodecSpec @String xdescribe "does not hold" $ yamlCodecSpec @Scientific xdescribe "does not hold" $ yamlCodecSpec @JSON.Object xdescribe "does not hold" $ yamlCodecSpec @JSON.Value yamlCodecSpec @Int yamlCodecSpec @Int8 yamlCodecSpec @Int16 yamlCodecSpec @Int32 yamlCodecSpec @Int64 yamlCodecSpec @Word yamlCodecSpec @Word8 yamlCodecSpec @Word16 yamlCodecSpec @Word32 yamlCodecSpec @Word64 yamlCodecSpec @(Maybe Text) yamlCodecSpec @(Either Bool Text) yamlCodecSpec @(Either (Either Bool [Text]) Text) yamlCodecSpec @[Text] yamlCodecSpec @(NonEmpty Text) yamlCodecSpec @(Set Text) yamlCodecSpec @(Map Text Int) yamlCodecSpec @Day yamlCodecSpec @LocalTime yamlCodecSpec @UTCTime yamlCodecSpec @TimeOfDay yamlCodecSpec @DiffTime yamlCodecSpec @NominalDiffTime yamlCodecSpec @Fruit yamlCodecSpec @Example yamlCodecSpec @Recursive yamlCodecSpec @MutuallyRecursiveA yamlCodecSpec @Via yamlCodecSpec @VeryComment yamlCodecSpec @LegacyValue yamlCodecSpec @LegacyObject yamlCodecSpec @Ainur yamlCodecSpec @War yamlCodecSpec @These yamlCodecSpec @Expression yamlCodecSpec :: forall a. ( Show a, Eq a, Typeable a, GenValid a, FromJSON a, HasCodec a ) => Spec yamlCodecSpec = describe (nameOf @a) $ do it "roundtrips through yaml" $ forAllValid $ \(a :: a) -> let encoded = YamlBuilder.toByteString (toYamlViaCodec a) errOrDecoded = Yaml.decodeEither' encoded ctx = unlines [ "Encoded to this value:", ppShow encoded, "with this codec", showCodecABit (codec @a) ] in context ctx $ case errOrDecoded of Left err -> expectationFailure $ Yaml.prettyPrintParseException err Right actual -> actual `shouldBe` a it "roundtrips through yaml and back" $ forAllValid $ \(a :: a) -> let encoded = YamlBuilder.toByteString (toYamlViaCodec a) errOrDecoded = Yaml.decodeEither' encoded ctx = unlines [ "Encoded to this value:", ppShow encoded, "with this codec", showCodecABit (codec @a) ] in context ctx $ case errOrDecoded of Left err -> expectationFailure $ Yaml.prettyPrintParseException err Right actual -> YamlBuilder.toByteString (toYamlViaCodec (actual :: a)) `shouldBe` YamlBuilder.toByteString (toYamlViaCodec a)
75b5cc6dc3e54aaf40e9088f4acded2fe7a6fff4ecdf3b0434a340971507478d
kelamg/HtDP2e-workthrough
ex64.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex64) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) Manhattan distance ;; Position (posn) -> Natural measures the manhattan distance of the given posn to the origin (check-expect (manhattan-distance (make-posn 3 4)) 7) (check-expect (manhattan-distance (make-posn 14 6)) 20) (define (manhattan-distance p) (+ (posn-x p) (posn-y p)))
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex64.rkt
racket
about the language level of this file in a form that our tools can easily process. Position (posn) -> Natural
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex64) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) Manhattan distance measures the manhattan distance of the given posn to the origin (check-expect (manhattan-distance (make-posn 3 4)) 7) (check-expect (manhattan-distance (make-posn 14 6)) 20) (define (manhattan-distance p) (+ (posn-x p) (posn-y p)))
3a63b73e3ea0b4045760ec0d0b69c82dd23d724e8487b4bd9461f70700097113
fugue/fregot
Capabilities.hs
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Encoding builtin information to a capabilities document . Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX Encoding builtin information to a capabilities document. -} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} module Fregot.Capabilities ( renderCapabilities ) where import Control.Lens ((^?)) import qualified Data.Aeson as A import qualified Data.HashMap.Strict as HMS import qualified Data.HashSet as HS import Data.List (sort, sortOn) import qualified Data.Text as T import Fregot.Builtins.Internal import Fregot.Names (nameToText) import Fregot.Prepare.Ast (BinOp (..), binOpToText) import qualified Fregot.Types.Builtins as Ty import qualified Fregot.Types.Internal as Ty renderCapabilities :: Builtins m -> A.Value renderCapabilities builtins = A.object [ "builtins" A..= renderBuiltins builtins ] renderBuiltins :: Builtins m -> A.Value renderBuiltins = A.toJSON . map (uncurry renderBuiltin) . sortOn (functionName . fst) . filter (not . functionHidden . fst) . HMS.toList functionHidden :: Function -> Bool functionHidden = \case NamedFunction _ -> False OperatorFunction _ -> False InternalFunction _ -> True functionName :: Function -> T.Text functionName = \case NamedFunction name -> nameToText name OperatorFunction op -> operatorName op InternalFunction name -> nameToText name renderBuiltin :: Function -> Builtin m -> A.Value renderBuiltin fn (Builtin bt _) = A.object $ [ "decl" A..= renderDecl (Ty.btRepr bt) , "name" A..= functionName fn ] ++ case fn of NamedFunction _ -> [] InternalFunction _ -> [] OperatorFunction op -> ["infix" A..= binOpToText op] operatorName :: BinOp -> T.Text operatorName = \case EqualO -> "eq" NotEqualO -> "neq" LessThanO -> "lt" LessThanOrEqualO -> "lte" GreaterThanO -> "gt" GreaterThanOrEqualO -> "gte" PlusO -> "plus" MinusO -> "minus" TimesO -> "mul" DivideO -> "div" ModuloO -> "rem" BinAndO -> "and" BinOrO -> "or" renderDecl :: Ty.TypeRepr i o -> A.Value renderDecl typeRepr = A.object [ typeTag "function" , "args" A..= map renderType args , "result" A..= renderType ret ] where (args, ret) = Ty.unTypeRepr typeRepr renderType :: Ty.Type -> A.Value renderType = \case t | Just e <- t ^? Ty.singleton -> renderElemType e Ty.Universe -> anyType Ty.Unknown -> anyType Ty.Union multi -> A.object [typeTag "any", "of" A..= fmap renderElemType (sort $ HS.toList multi)] renderElemType :: Ty.Elem Ty.Type -> A.Value renderElemType = \case Ty.Boolean -> A.object [typeTag "boolean"] Ty.Number -> A.object [typeTag "number"] Ty.Null -> A.object [typeTag "null"] Ty.String -> A.object [typeTag "string"] Ty.Scalar s -> renderType $ Ty.scalarType s Ty.Set e -> A.object [typeTag "set", "of" A..= renderType e] Ty.Array sd -> A.object -- TODO (jaspervdj): Expand `static` parts. [ typeTag "array", "dynamic" A..= case Ty.sdDynamic sd of Just (_, ety) -> renderType ety _ -> anyType ] Ty.Object sd -> A.object -- TODO (jaspervdj): Expand `static` parts. [ typeTag "array", "dynamic" A..= case Ty.sdDynamic sd of Just (kty, vty) -> A.object ["key" A..= renderType kty, "value" A..= renderType vty] _ -> A.object ["key" A..= anyType, "value" A..= anyType] ] anyType :: A.Value anyType = A.object [typeTag "any"] typeTag :: A.KeyValue kv => T.Text -> kv typeTag = ("type" A..=)
null
https://raw.githubusercontent.com/fugue/fregot/c3d87f37c43558761d5f6ac758d2f1a4117adb3e/lib/Fregot/Capabilities.hs
haskell
# LANGUAGE OverloadedStrings # TODO (jaspervdj): Expand `static` parts. TODO (jaspervdj): Expand `static` parts.
| Copyright : ( c ) 2020 Fugue , Inc. License : Apache License , version 2.0 Maintainer : Stability : experimental Portability : POSIX Encoding builtin information to a capabilities document . Copyright : (c) 2020 Fugue, Inc. License : Apache License, version 2.0 Maintainer : Stability : experimental Portability : POSIX Encoding builtin information to a capabilities document. -} # LANGUAGE LambdaCase # module Fregot.Capabilities ( renderCapabilities ) where import Control.Lens ((^?)) import qualified Data.Aeson as A import qualified Data.HashMap.Strict as HMS import qualified Data.HashSet as HS import Data.List (sort, sortOn) import qualified Data.Text as T import Fregot.Builtins.Internal import Fregot.Names (nameToText) import Fregot.Prepare.Ast (BinOp (..), binOpToText) import qualified Fregot.Types.Builtins as Ty import qualified Fregot.Types.Internal as Ty renderCapabilities :: Builtins m -> A.Value renderCapabilities builtins = A.object [ "builtins" A..= renderBuiltins builtins ] renderBuiltins :: Builtins m -> A.Value renderBuiltins = A.toJSON . map (uncurry renderBuiltin) . sortOn (functionName . fst) . filter (not . functionHidden . fst) . HMS.toList functionHidden :: Function -> Bool functionHidden = \case NamedFunction _ -> False OperatorFunction _ -> False InternalFunction _ -> True functionName :: Function -> T.Text functionName = \case NamedFunction name -> nameToText name OperatorFunction op -> operatorName op InternalFunction name -> nameToText name renderBuiltin :: Function -> Builtin m -> A.Value renderBuiltin fn (Builtin bt _) = A.object $ [ "decl" A..= renderDecl (Ty.btRepr bt) , "name" A..= functionName fn ] ++ case fn of NamedFunction _ -> [] InternalFunction _ -> [] OperatorFunction op -> ["infix" A..= binOpToText op] operatorName :: BinOp -> T.Text operatorName = \case EqualO -> "eq" NotEqualO -> "neq" LessThanO -> "lt" LessThanOrEqualO -> "lte" GreaterThanO -> "gt" GreaterThanOrEqualO -> "gte" PlusO -> "plus" MinusO -> "minus" TimesO -> "mul" DivideO -> "div" ModuloO -> "rem" BinAndO -> "and" BinOrO -> "or" renderDecl :: Ty.TypeRepr i o -> A.Value renderDecl typeRepr = A.object [ typeTag "function" , "args" A..= map renderType args , "result" A..= renderType ret ] where (args, ret) = Ty.unTypeRepr typeRepr renderType :: Ty.Type -> A.Value renderType = \case t | Just e <- t ^? Ty.singleton -> renderElemType e Ty.Universe -> anyType Ty.Unknown -> anyType Ty.Union multi -> A.object [typeTag "any", "of" A..= fmap renderElemType (sort $ HS.toList multi)] renderElemType :: Ty.Elem Ty.Type -> A.Value renderElemType = \case Ty.Boolean -> A.object [typeTag "boolean"] Ty.Number -> A.object [typeTag "number"] Ty.Null -> A.object [typeTag "null"] Ty.String -> A.object [typeTag "string"] Ty.Scalar s -> renderType $ Ty.scalarType s Ty.Set e -> A.object [typeTag "set", "of" A..= renderType e] Ty.Array sd -> A.object [ typeTag "array", "dynamic" A..= case Ty.sdDynamic sd of Just (_, ety) -> renderType ety _ -> anyType ] Ty.Object sd -> A.object [ typeTag "array", "dynamic" A..= case Ty.sdDynamic sd of Just (kty, vty) -> A.object ["key" A..= renderType kty, "value" A..= renderType vty] _ -> A.object ["key" A..= anyType, "value" A..= anyType] ] anyType :: A.Value anyType = A.object [typeTag "any"] typeTag :: A.KeyValue kv => T.Text -> kv typeTag = ("type" A..=)
c433d5ce1514a761085b7de9d6deb8ec1410b0720f1dc55825b21ed7ecc393b3
serokell/ariadne
Eval.hs
module Knit.Eval ( EvalError(..) , EvalT , ExecContext , ComponentExecContext , ComponentCommandExec(..) , ComponentLitToValue(..) , evaluate ) where import Control.Monad.Except import Data.Type.Equality import Knit.Argument import Knit.Prelude import Knit.Procedure import Knit.Syntax import Knit.Value data EvalError components = InvalidArguments CommandId (ProcError components) deriving instance (Eq (Value components)) => Eq (EvalError components) deriving instance (Ord (Value components)) => Ord (EvalError components) deriving instance (Show (Value components)) => Show (EvalError components) type EvalT components = ExceptT (EvalError components) type ExecContext m components = Rec (ComponentExecContext m components) components data family ComponentExecContext (m :: * -> *) (components :: [*]) component class ComponentCommandExec m components component where componentCommandExec :: ComponentExecContext m components component -> ComponentCommandRepr components component -> m (Value components) class ComponentLitToValue components component where componentLitToValue :: ComponentLit component -> ComponentValue components component evaluate :: ( AllConstrained (ComponentCommandExec m components) components , AllConstrained (ComponentLitToValue components) components , Monad m , Ord (Value components) ) => ExecContext m components -> Expr NoExt (SomeCommandProc components) components -> m (Either (EvalError components) (Value components)) evaluate ctxs expr = runExceptT (eval ctxs expr) eval :: ( AllConstrained (ComponentCommandExec m components) components , AllConstrained (ComponentLitToValue components) components , Monad m , Ord (Value components) ) => ExecContext m components -> Expr NoExt (SomeCommandProc components) components -> EvalT components m (Value components) eval ctxs = \case ExprLit _ l -> return (literalToValue l) ExprProcCall _ procCall -> evalProcCall ctxs =<< traverse (eval ctxs) procCall XExpr xxExpr -> absurd xxExpr evalProcCall :: forall m components. ( AllConstrained (ComponentCommandExec m components) components , Monad m , Ord (Value components) ) => ExecContext m components -> ProcCall NoExt (SomeCommandProc components) (Value components) -> EvalT components m (Value components) evalProcCall ctxs (ProcCall NoExt (SomeCommandProc commandProc) args) = componentEvalProcCall (rget ctxs) (ProcCall NoExt commandProc args) literalToValue :: forall components. AllConstrained (ComponentLitToValue components) components => Lit components -> Value components literalToValue = Value . umapConstrained @(ComponentLitToValue components) componentLitToValue . getLitUnion componentEvalProcCall :: forall m component components. ( AllConstrained (ComponentCommandExec m components) components , Elem components component , Monad m , Ord (Value components) ) => ComponentExecContext m components component -> ProcCall NoExt (CommandProc components component) (Value components) -> EvalT components m (Value components) componentEvalProcCall ctx (ProcCall _ CommandProc{..} args) = do e <- either (throwError . InvalidArguments cpName) return $ consumeArguments cpArgumentConsumer $ cpArgumentPrepare args lift $ commandExec (elemEv @components @component) (cpRepr e) where commandExec :: forall components'. AllConstrained (ComponentCommandExec m components) components' => ElemEv component components' -> ComponentCommandRepr components component -> m (Value components) commandExec (Base v) = absurd v commandExec (Step (Left Refl)) = componentCommandExec ctx commandExec (Step (Right i)) = commandExec i
null
https://raw.githubusercontent.com/serokell/ariadne/5f49ee53b6bbaf332cb6f110c75f7b971acdd452/knit/src/Knit/Eval.hs
haskell
module Knit.Eval ( EvalError(..) , EvalT , ExecContext , ComponentExecContext , ComponentCommandExec(..) , ComponentLitToValue(..) , evaluate ) where import Control.Monad.Except import Data.Type.Equality import Knit.Argument import Knit.Prelude import Knit.Procedure import Knit.Syntax import Knit.Value data EvalError components = InvalidArguments CommandId (ProcError components) deriving instance (Eq (Value components)) => Eq (EvalError components) deriving instance (Ord (Value components)) => Ord (EvalError components) deriving instance (Show (Value components)) => Show (EvalError components) type EvalT components = ExceptT (EvalError components) type ExecContext m components = Rec (ComponentExecContext m components) components data family ComponentExecContext (m :: * -> *) (components :: [*]) component class ComponentCommandExec m components component where componentCommandExec :: ComponentExecContext m components component -> ComponentCommandRepr components component -> m (Value components) class ComponentLitToValue components component where componentLitToValue :: ComponentLit component -> ComponentValue components component evaluate :: ( AllConstrained (ComponentCommandExec m components) components , AllConstrained (ComponentLitToValue components) components , Monad m , Ord (Value components) ) => ExecContext m components -> Expr NoExt (SomeCommandProc components) components -> m (Either (EvalError components) (Value components)) evaluate ctxs expr = runExceptT (eval ctxs expr) eval :: ( AllConstrained (ComponentCommandExec m components) components , AllConstrained (ComponentLitToValue components) components , Monad m , Ord (Value components) ) => ExecContext m components -> Expr NoExt (SomeCommandProc components) components -> EvalT components m (Value components) eval ctxs = \case ExprLit _ l -> return (literalToValue l) ExprProcCall _ procCall -> evalProcCall ctxs =<< traverse (eval ctxs) procCall XExpr xxExpr -> absurd xxExpr evalProcCall :: forall m components. ( AllConstrained (ComponentCommandExec m components) components , Monad m , Ord (Value components) ) => ExecContext m components -> ProcCall NoExt (SomeCommandProc components) (Value components) -> EvalT components m (Value components) evalProcCall ctxs (ProcCall NoExt (SomeCommandProc commandProc) args) = componentEvalProcCall (rget ctxs) (ProcCall NoExt commandProc args) literalToValue :: forall components. AllConstrained (ComponentLitToValue components) components => Lit components -> Value components literalToValue = Value . umapConstrained @(ComponentLitToValue components) componentLitToValue . getLitUnion componentEvalProcCall :: forall m component components. ( AllConstrained (ComponentCommandExec m components) components , Elem components component , Monad m , Ord (Value components) ) => ComponentExecContext m components component -> ProcCall NoExt (CommandProc components component) (Value components) -> EvalT components m (Value components) componentEvalProcCall ctx (ProcCall _ CommandProc{..} args) = do e <- either (throwError . InvalidArguments cpName) return $ consumeArguments cpArgumentConsumer $ cpArgumentPrepare args lift $ commandExec (elemEv @components @component) (cpRepr e) where commandExec :: forall components'. AllConstrained (ComponentCommandExec m components) components' => ElemEv component components' -> ComponentCommandRepr components component -> m (Value components) commandExec (Base v) = absurd v commandExec (Step (Left Refl)) = componentCommandExec ctx commandExec (Step (Right i)) = commandExec i
c8cd31b4f7c525085ebfbd19038282e72da3b03203d871fc0d99d82270d2a39e
rpasta42/ChessKell
Types.hs
module Types ( ChessRet , Piece(..) , OrdPiece(OrdPiece, ordPieceGet) , Color(White, Black) , Position , Coord , BoardPiece(..) , Board(..) , StepFailure(..) , PieceMoves, PieceMoves2 , Move(..) ) where type Position = (Char, Int) type Coord = (Int, Int) type ChessRet a = Either String a data Piece = Pawn | Rook | Knight | Bishop | Queen | King | Empty Eq , Ord , Bounded , ) instance Show Piece where show x = [show' x] where show' Pawn = 'p' show' Rook = 'r' show' Knight = 'h' show' Bishop = 'b' show' Queen = 'q' show' King = 'k' instance Eq Piece where (==) Pawn Pawn = True (==) Rook Rook = True (==) Knight Knight = True (==) Bishop Bishop = True (==) Queen Queen = True (==) King King = True (==) _ _ = False newtype OrdPiece = OrdPiece { ordPieceGet :: Piece } instance Eq OrdPiece where (==) a b = helper (ordPieceGet a) (ordPieceGet b) where helper Pawn Pawn = True helper Rook Rook = True helper Knight Knight = True helper Bishop Bishop = True helper Queen Queen = True helper King King = True helper Knight Bishop = True helper Bishop Knight = True helper _ _ = False instance Ord OrdPiece where compare a b = compare' (ordPieceGet a) (ordPieceGet b) where compare' Pawn Pawn = EQ compare' Rook Rook = EQ compare' Knight Knight = EQ compare' Bishop Bishop = EQ compare' Queen Queen = EQ compare' King King = EQ compare' Pawn b | b == Pawn = EQ | otherwise = LT compare' Rook b | b == Queen || b == King = LT | otherwise = GT compare' Knight b | b == Rook || b == King || b == Queen = LT | b == Bishop = EQ | otherwise = GT compare' Bishop b = compare' Knight b compare' Queen b | b == King = LT | otherwise = GT compare' King _ = GT compare' b a = compare' a b data Color = White | Black deriving (Show, Eq) data BoardPiece = BoardPiece { getPiece :: Piece , getColor :: Color , getPosition :: Position , getHaveMoved :: Bool , getMoves :: Maybe ([Coord], [Coord]) --, getPossibleMoveBoards :: Maybe [Board] } deriving (Show, Eq) data Board = Board { getWhitePieces :: [BoardPiece] , getBlackPieces :: [BoardPiece] , getLastMove :: Maybe Move , getNextPlayer :: Color } deriving (Show) --IsCheckMate has winner color data StepFailure = IsStaleMate | IsCheckMate Color | IsInvalidMove String | IsPieceNotFound String | IsOtherFailure String | NeedPawnPromotion deriving (Show) type PieceMoves = (BoardPiece, [Coord], [Coord]) type PieceMoves2 = ([Coord], [Coord]) data Move = Move (Position, Position) | Castle Bool | EnPassant (BoardPiece, BoardPiece) deriving (Show, Eq) data Either3 a b c = E3Left a | E3Middle b | E3Right c data Either3 a b c = E3Left a | E3Middle b | E3Right c -}
null
https://raw.githubusercontent.com/rpasta42/ChessKell/1b79ebac26bffcc8d18953f1ede862adec23fee1/Types.hs
haskell
, getPossibleMoveBoards :: Maybe [Board] IsCheckMate has winner color
module Types ( ChessRet , Piece(..) , OrdPiece(OrdPiece, ordPieceGet) , Color(White, Black) , Position , Coord , BoardPiece(..) , Board(..) , StepFailure(..) , PieceMoves, PieceMoves2 , Move(..) ) where type Position = (Char, Int) type Coord = (Int, Int) type ChessRet a = Either String a data Piece = Pawn | Rook | Knight | Bishop | Queen | King | Empty Eq , Ord , Bounded , ) instance Show Piece where show x = [show' x] where show' Pawn = 'p' show' Rook = 'r' show' Knight = 'h' show' Bishop = 'b' show' Queen = 'q' show' King = 'k' instance Eq Piece where (==) Pawn Pawn = True (==) Rook Rook = True (==) Knight Knight = True (==) Bishop Bishop = True (==) Queen Queen = True (==) King King = True (==) _ _ = False newtype OrdPiece = OrdPiece { ordPieceGet :: Piece } instance Eq OrdPiece where (==) a b = helper (ordPieceGet a) (ordPieceGet b) where helper Pawn Pawn = True helper Rook Rook = True helper Knight Knight = True helper Bishop Bishop = True helper Queen Queen = True helper King King = True helper Knight Bishop = True helper Bishop Knight = True helper _ _ = False instance Ord OrdPiece where compare a b = compare' (ordPieceGet a) (ordPieceGet b) where compare' Pawn Pawn = EQ compare' Rook Rook = EQ compare' Knight Knight = EQ compare' Bishop Bishop = EQ compare' Queen Queen = EQ compare' King King = EQ compare' Pawn b | b == Pawn = EQ | otherwise = LT compare' Rook b | b == Queen || b == King = LT | otherwise = GT compare' Knight b | b == Rook || b == King || b == Queen = LT | b == Bishop = EQ | otherwise = GT compare' Bishop b = compare' Knight b compare' Queen b | b == King = LT | otherwise = GT compare' King _ = GT compare' b a = compare' a b data Color = White | Black deriving (Show, Eq) data BoardPiece = BoardPiece { getPiece :: Piece , getColor :: Color , getPosition :: Position , getHaveMoved :: Bool , getMoves :: Maybe ([Coord], [Coord]) } deriving (Show, Eq) data Board = Board { getWhitePieces :: [BoardPiece] , getBlackPieces :: [BoardPiece] , getLastMove :: Maybe Move , getNextPlayer :: Color } deriving (Show) data StepFailure = IsStaleMate | IsCheckMate Color | IsInvalidMove String | IsPieceNotFound String | IsOtherFailure String | NeedPawnPromotion deriving (Show) type PieceMoves = (BoardPiece, [Coord], [Coord]) type PieceMoves2 = ([Coord], [Coord]) data Move = Move (Position, Position) | Castle Bool | EnPassant (BoardPiece, BoardPiece) deriving (Show, Eq) data Either3 a b c = E3Left a | E3Middle b | E3Right c data Either3 a b c = E3Left a | E3Middle b | E3Right c -}
26ab6589110f6183272afe947baf790d2e447b56cdc8ab23aaaa02e4cf66be0b
runexec/Moov
tmdb.clj
;- Copyright ( c ) 2012 and individual contributors . ; ( ) ; All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: 1 . Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer ; in this position and unchanged. 2 . Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. 3 . The name of the author may not be used to endorse or promote products ; derived from this software withough specific prior written permission ; THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR ; IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ; OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ; IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; ; (ns Moov.tmdb (:use [Moov.http :only (httpGET)])) (def urlCollection "/") (def urlLatestMovie "") (def urlMovieInfo "/") (def urlMovieSearch "") (def urlPeopleSearch "") (def urlPersonInfo "/") (defn person_images "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "/images" "?api_key=" api_key)) );person_images (defn person_credits "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "/credits" "?api_key=" api_key)) );person_credits (defn person_info "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "?api_key=" api_key)) person_info (defn search_people "Queries TMDB by people. Make sure to try/catch for http/socket io." ([api_key query] (httpGET (str urlPeopleSearch "?api_key=" api_key "&query=" query))) ([api_key query page] (httpGET (str urlPeopleSearch "?api_key=" api_key "&query=" query "&page=" page))) );search_people (defn search_title "Queries TMDB by title. Make sure to try/catch for http/socket io." ([api_key query] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query))) ([api_key query page] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page))) ([api_key query page language] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page "&language=" language))) ([api_key query page language include_adult] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page "&language=" language "&include_adult=" include_adult))) );search_title (defn movie_info ([api_key movie_id] (httpGET (str urlMovieInfo movie_id "?api_key=" api_key))) ([api_key movie_id language] (httpGET (str urlMovieInfo movie_id "?api_key=" api_key "&language=" language))) (defn collection "Returns a movie collection. Make sure to try/catch for http/socket io." [api_key collection_id] (httpGET (str urlCollection collection_id "?api_key=" api_key)) );collection (defn alternative_titles "Make sure to try/catch for http/socket io." ([api_key movie_id] (httpGET (str urlMovieInfo movie_id "/alternative_titles" "?api_key=" api_key))) ([api_key movie_id country] (httpGET (str urlMovieInfo movie_id "/alternative_titles" "?api_key=" api_key "&language=" country))) alternative_titles (defn movie_latest "Make sure to try/catch for http/socket io." [api_key] (httpGET (str urlLatestMovie "?api_key=" api_key)) );movie_latest (defn movie_translations "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/translations" "?api_key=" api_key)) );movie_translations (defn movie_trailers "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/trailers" "?api_key=" api_key)) );movie_trailers (defn movie_release_info "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/releases" "?api_key=" api_key)) );movie_release_info (defn movie_keywords "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/keywords" "?api_key=" api_key)) );movie_keywords (defn movie_images "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/images" "?api_key=" api_key)) );movie_images (defn movie_casts "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/casts" "?api_key=" api_key)) );movie_casts
null
https://raw.githubusercontent.com/runexec/Moov/f18ae6c0d4dec7f3f32bfd8941a0d636eba450a7/src/Moov/tmdb.clj
clojure
- ( ) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: notice, this list of conditions and the following disclaimer in this position and unchanged. notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. derived from this software withough specific prior written permission IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, LOSS OF USE , DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. person_images person_credits search_people search_title collection movie_latest movie_translations movie_trailers movie_release_info movie_keywords movie_images movie_casts
Copyright ( c ) 2012 and individual contributors . 1 . Redistributions of source code must retain the above copyright 2 . Redistributions in binary form must reproduce the above copyright 3 . The name of the author may not be used to endorse or promote products THIS SOFTWARE IS PROVIDED BY THE AUTHOR ` ` AS IS '' AND ANY EXPRESS OR INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT (ns Moov.tmdb (:use [Moov.http :only (httpGET)])) (def urlCollection "/") (def urlLatestMovie "") (def urlMovieInfo "/") (def urlMovieSearch "") (def urlPeopleSearch "") (def urlPersonInfo "/") (defn person_images "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "/images" "?api_key=" api_key)) (defn person_credits "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "/credits" "?api_key=" api_key)) (defn person_info "Make sure to try/catch for http/socket io." [api_key person_id] (httpGET (str urlPersonInfo person_id "?api_key=" api_key)) person_info (defn search_people "Queries TMDB by people. Make sure to try/catch for http/socket io." ([api_key query] (httpGET (str urlPeopleSearch "?api_key=" api_key "&query=" query))) ([api_key query page] (httpGET (str urlPeopleSearch "?api_key=" api_key "&query=" query "&page=" page))) (defn search_title "Queries TMDB by title. Make sure to try/catch for http/socket io." ([api_key query] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query))) ([api_key query page] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page))) ([api_key query page language] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page "&language=" language))) ([api_key query page language include_adult] (httpGET (str urlMovieSearch "?api_key=" api_key "&query=" query "&page=" page "&language=" language "&include_adult=" include_adult))) (defn movie_info ([api_key movie_id] (httpGET (str urlMovieInfo movie_id "?api_key=" api_key))) ([api_key movie_id language] (httpGET (str urlMovieInfo movie_id "?api_key=" api_key "&language=" language))) (defn collection "Returns a movie collection. Make sure to try/catch for http/socket io." [api_key collection_id] (httpGET (str urlCollection collection_id "?api_key=" api_key)) (defn alternative_titles "Make sure to try/catch for http/socket io." ([api_key movie_id] (httpGET (str urlMovieInfo movie_id "/alternative_titles" "?api_key=" api_key))) ([api_key movie_id country] (httpGET (str urlMovieInfo movie_id "/alternative_titles" "?api_key=" api_key "&language=" country))) alternative_titles (defn movie_latest "Make sure to try/catch for http/socket io." [api_key] (httpGET (str urlLatestMovie "?api_key=" api_key)) (defn movie_translations "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/translations" "?api_key=" api_key)) (defn movie_trailers "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/trailers" "?api_key=" api_key)) (defn movie_release_info "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/releases" "?api_key=" api_key)) (defn movie_keywords "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/keywords" "?api_key=" api_key)) (defn movie_images "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/images" "?api_key=" api_key)) (defn movie_casts "Make sure to try/catch for http/socket io." [api_key movie_id] (httpGET (str urlMovieInfo movie_id "/casts" "?api_key=" api_key))
913b84b0b81df04d3abbc673a0706706d7fda55df60263d933a7f865a0699a94
sulami/spielwiese
14.hs
#!/usr/bin/env stack -- stack --resolver lts-9.13 --install-ghc runghc module Main where import Data.Bits (xor) import Data.Char (intToDigit, ord) import Numeric (showIntAtBase) main :: IO () main = do input <- getLine let strings = take 128 $ map (\n -> input ++ "-" ++ show n) ([0..] :: [Int]) print . sum $ concatMap (map (read . (:[]) :: Char -> Int) . knotHash) strings showBinary :: Int -> String showBinary x = let bin = showIntAtBase 2 intToDigit x "" prefix = replicate (4 - length bin) '0' in prefix ++ bin Knot Hash code from day 10 type State = (Int, Int, [Int]) knotHash :: String -> String knotHash input = let input2 = reverse . (++ [17, 31, 73, 47, 23]) $ map ord input sparse = thrd . (!! 64) $ iterate (\st -> foldr step st input2) (0, 0, [0..255]) in concatMap (showBinary . foldr1 xor) $ segment 16 sparse step :: Int -> State -> State step len (pos, skip, s0) = let newPos = (pos + len + skip) `mod` length s0 s1 = rev pos len s0 in (newPos, skip + 1, s1) rev :: Int -> Int -> [Int] -> [Int] rev pos len s0 = let s0' = cycle s0 (pref, post) = splitAt pos s0' (toRev, rest) = splitAt len post newPost = reverse toRev ++ rest infi = pref ++ newPost desiredLen = length s0 toShift = pos + len - desiredLen in if toShift > 0 then shift toShift . take desiredLen $ drop toShift infi else take desiredLen infi shift :: Int -> [a] -> [a] shift _ [] = [] shift 0 xs = xs shift n xs = shift (n - 1) $ last xs : init xs thrd :: (a, b, c) -> c thrd (_, _, x) = x segment :: Int -> [a] -> [[a]] segment _ [] = [] segment i xs = let (h, t) = splitAt i xs in h : segment i t
null
https://raw.githubusercontent.com/sulami/spielwiese/da354aa112d43d7ec5f258f4b5afafd7a88c8aa8/advent17/14.hs
haskell
stack --resolver lts-9.13 --install-ghc runghc
#!/usr/bin/env stack module Main where import Data.Bits (xor) import Data.Char (intToDigit, ord) import Numeric (showIntAtBase) main :: IO () main = do input <- getLine let strings = take 128 $ map (\n -> input ++ "-" ++ show n) ([0..] :: [Int]) print . sum $ concatMap (map (read . (:[]) :: Char -> Int) . knotHash) strings showBinary :: Int -> String showBinary x = let bin = showIntAtBase 2 intToDigit x "" prefix = replicate (4 - length bin) '0' in prefix ++ bin Knot Hash code from day 10 type State = (Int, Int, [Int]) knotHash :: String -> String knotHash input = let input2 = reverse . (++ [17, 31, 73, 47, 23]) $ map ord input sparse = thrd . (!! 64) $ iterate (\st -> foldr step st input2) (0, 0, [0..255]) in concatMap (showBinary . foldr1 xor) $ segment 16 sparse step :: Int -> State -> State step len (pos, skip, s0) = let newPos = (pos + len + skip) `mod` length s0 s1 = rev pos len s0 in (newPos, skip + 1, s1) rev :: Int -> Int -> [Int] -> [Int] rev pos len s0 = let s0' = cycle s0 (pref, post) = splitAt pos s0' (toRev, rest) = splitAt len post newPost = reverse toRev ++ rest infi = pref ++ newPost desiredLen = length s0 toShift = pos + len - desiredLen in if toShift > 0 then shift toShift . take desiredLen $ drop toShift infi else take desiredLen infi shift :: Int -> [a] -> [a] shift _ [] = [] shift 0 xs = xs shift n xs = shift (n - 1) $ last xs : init xs thrd :: (a, b, c) -> c thrd (_, _, x) = x segment :: Int -> [a] -> [[a]] segment _ [] = [] segment i xs = let (h, t) = splitAt i xs in h : segment i t
0bf471e677378b8cc6ae4f106932640149015a271b124d2d4bc83469cb6d16fd
clojure/core.typed
utils.clj
Copyright ( c ) , contributors . ;; The use and distribution terms for this software are covered by the ;; Eclipse Public License 1.0 (-1.0.php) ;; which can be found in the file epl-v10.html at the root of this distribution. ;; By using this software in any fashion, you are agreeing to be bound by ;; the terms of this license. ;; You must not remove this notice, or any other, from this software. (ns ^:skip-wiki clojure.core.typed.checker.utils (:refer-clojure :exclude [defrecord defprotocol]) (:require [clojure.core.typed :as t] [clojure.core.typed.util-vars :as uvs] [clojure.repl :as repl] [clojure.set :as set])) (t/ann subtype-exn Exception) (def subtype-exn (Exception. "Subtyping failed.")) (t/ann cs-gen-exn Exception) (def cs-gen-exn (Exception. "Constraint generation failed.")) (defmacro handle-subtype-failure [& body] `(try ~@body (catch Exception e# (if (identical? subtype-exn e#) false (throw e#))))) (defmacro handle-cs-gen-failure [& body] `(try ~@body (catch Exception e# (if (identical? cs-gen-exn e#) false (throw e#))))) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Utils (defmacro defprotocol [name & args] only define record if symbol does n't resolve , not completely sure if this behaves like defonce (when-not (resolve name) `(clojure.core/defprotocol ~name ~@args))) (defmacro ann-record "Like ann-record, but also adds an unchecked annotation for core.contract's generated nme? predicate." [nme & args] `(do ~(-> `(clojure.core.typed/ann-record ~nme ~@args) (with-meta (meta &form))) ~(-> `(clojure.core.typed/ann ~(with-meta (symbol (str nme "-maker")) {:no-check true}) [~@(map #(nth % 2) (partition 3 (first args))) ~'-> ~nme]) (with-meta (meta &form))) ~(-> `(clojure.core.typed/ann ~(with-meta (symbol (str nme "?")) {:no-check true}) ~(list `t/Pred nme)) (with-meta (meta &form))))) (t/tc-ignore ( t / ann next - sequence - number ( t / ) ) (defonce ^:private ^{:doc "The next number to use for sequence hashing"} next-sequence-number (atom 0)) (defn inc-sequence-number [] (swap! next-sequence-number inc)) (defn get-and-inc-id [] (let [id @next-sequence-number _ (inc-sequence-number)] id)) (def default-xor 1) (defn ^:private inner-deftype [fields hash-field meta-field that name-sym type-hash gs maker methods*] `(deftype ~name-sym [~@fields ~(with-meta hash-field {:unsynchronized-mutable true}) ~meta-field] clojure.lang.IHashEq (equals [_# ~that] (and (instance? ~name-sym ~that) ; do not shadow fields here! ~@(for [f fields] `(= (~(keyword f) ~that) ~f)))) ; don't shadow fields here! (hasheq [this#] (if-let [h# ~hash-field] h# (let [h# ~(if-let [ts (seq (map (fn [f] `(hash ~f)) fields))] `(bit-xor ~type-hash ~@ts) `(bit-xor ~type-hash ~default-xor))] (set! ~hash-field h#) h#))) ; don't shadow fields here! (hashCode [this#] (if-let [h# ~hash-field] h# (let [h# ~(if-let [ts (seq (map (fn [f] `(hash ~f)) fields))] `(bit-xor ~type-hash ~@ts) `(bit-xor ~type-hash ~default-xor))] (set! ~hash-field h#) h#))) clojure.lang.IObj (meta [this#] ~meta-field) (withMeta [this# ~gs] (~maker ~@fields :meta ~gs)) clojure.lang.ILookup (valAt [this# k# else#] (case k# ~@(mapcat (fn [fld] [(keyword fld) fld]) fields) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#))))) (valAt [this# k#] (case k# ~@(mapcat (fn [fld] [(keyword fld) fld]) fields) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#))))) clojure.lang.IKeywordLookup (getLookupThunk [this# k#] (let [~'gclass (class this#)] (case k# ~@(let [hinted-target (with-meta 'gtarget {:tag name-sym})] (mapcat (fn [fld] [(keyword fld) `(reify clojure.lang.ILookupThunk (get [~'thunk ~'gtarget] (if (identical? (class ~'gtarget) ~'gclass) (. ~hinted-target ~(symbol (str "-" fld))) ~'thunk)))]) fields)) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#)))))) clojure.lang.IPersistentMap (assoc [this# k# ~gs] (condp identical? k# ~@(mapcat (fn [fld] [(keyword fld) `(~maker ~@(replace {fld gs} fields) :meta ~meta-field)]) fields) (throw (UnsupportedOperationException. (str "assoc on " '~name-sym " " k#))))) (entryAt [this# k#] (throw (UnsupportedOperationException. (str "entryAt on " '~name-sym " " k#)))) (count [this#] (throw (UnsupportedOperationException. (str "count on " '~name-sym)))) ;; hack for pr-on, don't use empty (empty [this#] this#) (cons [this# e#] (throw (UnsupportedOperationException. (str "cons on " '~name-sym)))) (equiv [_# ~that] (and (instance? ~name-sym ~that) ; do not shadow fields here! ~@(for [f fields] `(= (~(keyword f) ~that) ~f)))) (containsKey [this# k#] (throw (UnsupportedOperationException. (str "containsKey on " '~name-sym)))) (seq [this#] (seq [~@(map #(list `new `clojure.lang.MapEntry (keyword %) %) (concat fields [#_meta-field]))])) (iterator [this#] (throw (UnsupportedOperationException. (str "iterator on " '~name-sym)))) (without [this# k#] (throw (UnsupportedOperationException. (str "without on " '~name-sym)))) Comparable ~(let [this (gensym 'this)] `(compareTo [~this ~that] returns 1 if we have 2 instances of name - sym with ; identical hashs, but are not = (cond (= ~this ~that) 0 (instance? ~name-sym ~that) (if (< (hash ~this) (hash ~that)) -1 1) :else (if (< (hash ~name-sym) (hash (class ~that))) -1 1)))) ~@methods*)) (defn emit-deftype [original-ns def-kind name-sym fields invariants methods*] (assert (symbol? name-sym)) (let [classname (with-meta (symbol (str (namespace-munge *ns*) "." name-sym)) (meta name-sym)) ->ctor (symbol (str "->" name-sym)) maker (symbol (str name-sym "-maker")) that (gensym) gs (gensym) type-hash (hash classname) meta-field '_meta hash-field '_hash] `(do (declare ~maker) ~(inner-deftype fields hash-field meta-field that name-sym type-hash gs maker methods*) (swap! ~(symbol (str original-ns) (str "all-" def-kind "s")) conj '~classname) (alter-meta! (var ~->ctor) assoc :private true) (defn ~(symbol (str name-sym "?")) [a#] (instance? ~name-sym a#)) ( ( Map t / Any Number ) ) (defn ~maker [~@fields & {meta# :meta :as opt#}] {:pre ~invariants} (let [extra# (set/difference (set (keys opt#)) #{:meta})] (assert (empty? extra#) (str "Extra arguments:" extra#))) ~@fields are in scope above (~->ctor ~@fields nil meta#))))) (defmacro mk [original-ns def-kind name-sym fields invariants & {:keys [methods]}] (when-not (resolve name-sym) `(t/tc-ignore ~(emit-deftype original-ns def-kind name-sym fields invariants methods)))) (defmacro defspecial [name] (let [all-entries (symbol (str "all-" name "s"))] `(do (defn ~(symbol (str name "=")) [t1# t2#] (= t1# t2#)) (defn ~(symbol (str name "<")) [t1# t2#] (neg? (compare t1# t2#))) (defn ~(symbol (str name "-comparator")) [t1# t2#] (compare t1# t2#)) (def ~all-entries (atom #{})) (defmacro ~(symbol (str "def-" name)) [name# fields# doc# invariants# & opts#] `(mk ~'~(ns-name *ns*) ~'~name ~name# ~fields# ~invariants# ~@opts#))))) (defspecial type) (defspecial filter) (defspecial object) (defspecial path) ) (t/ann typed-ns-opts [t/Any -> t/Any]) (defn typed-ns-opts [ns] (-> ns meta :core.typed)) (t/ann ^:no-check demunge-ns [(t/U t/Sym String) -> t/Sym]) (defn demunge-ns [nsym] (symbol (clojure.repl/demunge (str nsym)))) (t/tc-ignore ;; multimethods for dispatching on special forms like (do ::special-form ::foobar ...) (defn internal-dispatch-val [expr] (:form (second (:statements expr)))) (defmacro special-do-op "Define a multimethod that takes an expr and an expected type and dispatches on the second statement" [kw nme] `(defmulti ~nme (fn [expr# & _#] (internal-dispatch-val expr#)))) (defn internal-form? [expr kw] (= kw (:form (first (:statements expr))))) (defn ns? [n] (instance? clojure.lang.Namespace n)) (def expr-type ::expr-type) ;(t/ann tc-warning [t/Any * -> nil]) (defn tc-warning [& ss] (let [env uvs/*current-env*] (binding [*out* *err*] (println (apply str "WARNING (" (:file env) ":" (:line env) (when-let [col (:column env)] (str ":" col)) "): " ss)) (flush)))) (defmacro with-tracing [& body] `(binding [uvs/*trace-checker* true] ~@body)) (defmacro trace [& ss] `(when uvs/*trace-checker* (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush))) (defmacro trace-when [p & ss] `(when uvs/*trace-checker* (when ~p (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush)))) (defmacro trace-when-let [p & ss] `(when uvs/*trace-checker* (when-let ~p (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush)))) (defn pad-right "Returns a sequence of length cnt that is s padded to the right with copies of v." [^long cnt s v] {:pre [(integer? cnt)]} (concat s (repeat (- cnt (count s)) v))) (defmacro rewrite-when [p & body] `(binding [vs/*can-rewrite* (if ~p vs/*can-rewrite* nil)] ~@body)) (defn core-typed-ns-meta "Returns the :core.typed entry in the given namespace's metadata" [ns] {:pre [(instance? clojure.lang.Namespace ns)]} (-> ns meta :core.typed)) (defn ns-has-feature? [ns k] (-> (core-typed-ns-meta ns) :features (contains? k))) (defn should-runtime-check-ns? [ns] (ns-has-feature? ns :runtime-check)) (defn should-runtime-infer-ns? [ns] (ns-has-feature? ns :runtime-infer)) )
null
https://raw.githubusercontent.com/clojure/core.typed/f5b7d00bbb29d09000d7fef7cca5b40416c9fa91/typed/checker.jvm/src/clojure/core/typed/checker/utils.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. do not shadow fields here! don't shadow fields here! don't shadow fields here! hack for pr-on, don't use empty do not shadow fields here! identical hashs, but are not = multimethods for dispatching on special forms like (do ::special-form ::foobar ...) (t/ann tc-warning [t/Any * -> nil])
Copyright ( c ) , contributors . (ns ^:skip-wiki clojure.core.typed.checker.utils (:refer-clojure :exclude [defrecord defprotocol]) (:require [clojure.core.typed :as t] [clojure.core.typed.util-vars :as uvs] [clojure.repl :as repl] [clojure.set :as set])) (t/ann subtype-exn Exception) (def subtype-exn (Exception. "Subtyping failed.")) (t/ann cs-gen-exn Exception) (def cs-gen-exn (Exception. "Constraint generation failed.")) (defmacro handle-subtype-failure [& body] `(try ~@body (catch Exception e# (if (identical? subtype-exn e#) false (throw e#))))) (defmacro handle-cs-gen-failure [& body] `(try ~@body (catch Exception e# (if (identical? cs-gen-exn e#) false (throw e#))))) Utils (defmacro defprotocol [name & args] only define record if symbol does n't resolve , not completely sure if this behaves like defonce (when-not (resolve name) `(clojure.core/defprotocol ~name ~@args))) (defmacro ann-record "Like ann-record, but also adds an unchecked annotation for core.contract's generated nme? predicate." [nme & args] `(do ~(-> `(clojure.core.typed/ann-record ~nme ~@args) (with-meta (meta &form))) ~(-> `(clojure.core.typed/ann ~(with-meta (symbol (str nme "-maker")) {:no-check true}) [~@(map #(nth % 2) (partition 3 (first args))) ~'-> ~nme]) (with-meta (meta &form))) ~(-> `(clojure.core.typed/ann ~(with-meta (symbol (str nme "?")) {:no-check true}) ~(list `t/Pred nme)) (with-meta (meta &form))))) (t/tc-ignore ( t / ann next - sequence - number ( t / ) ) (defonce ^:private ^{:doc "The next number to use for sequence hashing"} next-sequence-number (atom 0)) (defn inc-sequence-number [] (swap! next-sequence-number inc)) (defn get-and-inc-id [] (let [id @next-sequence-number _ (inc-sequence-number)] id)) (def default-xor 1) (defn ^:private inner-deftype [fields hash-field meta-field that name-sym type-hash gs maker methods*] `(deftype ~name-sym [~@fields ~(with-meta hash-field {:unsynchronized-mutable true}) ~meta-field] clojure.lang.IHashEq (equals [_# ~that] (and (instance? ~name-sym ~that) ~@(for [f fields] `(= (~(keyword f) ~that) ~f)))) (hasheq [this#] (if-let [h# ~hash-field] h# (let [h# ~(if-let [ts (seq (map (fn [f] `(hash ~f)) fields))] `(bit-xor ~type-hash ~@ts) `(bit-xor ~type-hash ~default-xor))] (set! ~hash-field h#) h#))) (hashCode [this#] (if-let [h# ~hash-field] h# (let [h# ~(if-let [ts (seq (map (fn [f] `(hash ~f)) fields))] `(bit-xor ~type-hash ~@ts) `(bit-xor ~type-hash ~default-xor))] (set! ~hash-field h#) h#))) clojure.lang.IObj (meta [this#] ~meta-field) (withMeta [this# ~gs] (~maker ~@fields :meta ~gs)) clojure.lang.ILookup (valAt [this# k# else#] (case k# ~@(mapcat (fn [fld] [(keyword fld) fld]) fields) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#))))) (valAt [this# k#] (case k# ~@(mapcat (fn [fld] [(keyword fld) fld]) fields) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#))))) clojure.lang.IKeywordLookup (getLookupThunk [this# k#] (let [~'gclass (class this#)] (case k# ~@(let [hinted-target (with-meta 'gtarget {:tag name-sym})] (mapcat (fn [fld] [(keyword fld) `(reify clojure.lang.ILookupThunk (get [~'thunk ~'gtarget] (if (identical? (class ~'gtarget) ~'gclass) (. ~hinted-target ~(symbol (str "-" fld))) ~'thunk)))]) fields)) (throw (UnsupportedOperationException. (str "lookup on " '~name-sym " " k#)))))) clojure.lang.IPersistentMap (assoc [this# k# ~gs] (condp identical? k# ~@(mapcat (fn [fld] [(keyword fld) `(~maker ~@(replace {fld gs} fields) :meta ~meta-field)]) fields) (throw (UnsupportedOperationException. (str "assoc on " '~name-sym " " k#))))) (entryAt [this# k#] (throw (UnsupportedOperationException. (str "entryAt on " '~name-sym " " k#)))) (count [this#] (throw (UnsupportedOperationException. (str "count on " '~name-sym)))) (empty [this#] this#) (cons [this# e#] (throw (UnsupportedOperationException. (str "cons on " '~name-sym)))) (equiv [_# ~that] (and (instance? ~name-sym ~that) ~@(for [f fields] `(= (~(keyword f) ~that) ~f)))) (containsKey [this# k#] (throw (UnsupportedOperationException. (str "containsKey on " '~name-sym)))) (seq [this#] (seq [~@(map #(list `new `clojure.lang.MapEntry (keyword %) %) (concat fields [#_meta-field]))])) (iterator [this#] (throw (UnsupportedOperationException. (str "iterator on " '~name-sym)))) (without [this# k#] (throw (UnsupportedOperationException. (str "without on " '~name-sym)))) Comparable ~(let [this (gensym 'this)] `(compareTo [~this ~that] returns 1 if we have 2 instances of name - sym with (cond (= ~this ~that) 0 (instance? ~name-sym ~that) (if (< (hash ~this) (hash ~that)) -1 1) :else (if (< (hash ~name-sym) (hash (class ~that))) -1 1)))) ~@methods*)) (defn emit-deftype [original-ns def-kind name-sym fields invariants methods*] (assert (symbol? name-sym)) (let [classname (with-meta (symbol (str (namespace-munge *ns*) "." name-sym)) (meta name-sym)) ->ctor (symbol (str "->" name-sym)) maker (symbol (str name-sym "-maker")) that (gensym) gs (gensym) type-hash (hash classname) meta-field '_meta hash-field '_hash] `(do (declare ~maker) ~(inner-deftype fields hash-field meta-field that name-sym type-hash gs maker methods*) (swap! ~(symbol (str original-ns) (str "all-" def-kind "s")) conj '~classname) (alter-meta! (var ~->ctor) assoc :private true) (defn ~(symbol (str name-sym "?")) [a#] (instance? ~name-sym a#)) ( ( Map t / Any Number ) ) (defn ~maker [~@fields & {meta# :meta :as opt#}] {:pre ~invariants} (let [extra# (set/difference (set (keys opt#)) #{:meta})] (assert (empty? extra#) (str "Extra arguments:" extra#))) ~@fields are in scope above (~->ctor ~@fields nil meta#))))) (defmacro mk [original-ns def-kind name-sym fields invariants & {:keys [methods]}] (when-not (resolve name-sym) `(t/tc-ignore ~(emit-deftype original-ns def-kind name-sym fields invariants methods)))) (defmacro defspecial [name] (let [all-entries (symbol (str "all-" name "s"))] `(do (defn ~(symbol (str name "=")) [t1# t2#] (= t1# t2#)) (defn ~(symbol (str name "<")) [t1# t2#] (neg? (compare t1# t2#))) (defn ~(symbol (str name "-comparator")) [t1# t2#] (compare t1# t2#)) (def ~all-entries (atom #{})) (defmacro ~(symbol (str "def-" name)) [name# fields# doc# invariants# & opts#] `(mk ~'~(ns-name *ns*) ~'~name ~name# ~fields# ~invariants# ~@opts#))))) (defspecial type) (defspecial filter) (defspecial object) (defspecial path) ) (t/ann typed-ns-opts [t/Any -> t/Any]) (defn typed-ns-opts [ns] (-> ns meta :core.typed)) (t/ann ^:no-check demunge-ns [(t/U t/Sym String) -> t/Sym]) (defn demunge-ns [nsym] (symbol (clojure.repl/demunge (str nsym)))) (t/tc-ignore (defn internal-dispatch-val [expr] (:form (second (:statements expr)))) (defmacro special-do-op "Define a multimethod that takes an expr and an expected type and dispatches on the second statement" [kw nme] `(defmulti ~nme (fn [expr# & _#] (internal-dispatch-val expr#)))) (defn internal-form? [expr kw] (= kw (:form (first (:statements expr))))) (defn ns? [n] (instance? clojure.lang.Namespace n)) (def expr-type ::expr-type) (defn tc-warning [& ss] (let [env uvs/*current-env*] (binding [*out* *err*] (println (apply str "WARNING (" (:file env) ":" (:line env) (when-let [col (:column env)] (str ":" col)) "): " ss)) (flush)))) (defmacro with-tracing [& body] `(binding [uvs/*trace-checker* true] ~@body)) (defmacro trace [& ss] `(when uvs/*trace-checker* (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush))) (defmacro trace-when [p & ss] `(when uvs/*trace-checker* (when ~p (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush)))) (defmacro trace-when-let [p & ss] `(when uvs/*trace-checker* (when-let ~p (println "TRACE: " " " (:line uvs/*current-env*) ~@ss) (flush)))) (defn pad-right "Returns a sequence of length cnt that is s padded to the right with copies of v." [^long cnt s v] {:pre [(integer? cnt)]} (concat s (repeat (- cnt (count s)) v))) (defmacro rewrite-when [p & body] `(binding [vs/*can-rewrite* (if ~p vs/*can-rewrite* nil)] ~@body)) (defn core-typed-ns-meta "Returns the :core.typed entry in the given namespace's metadata" [ns] {:pre [(instance? clojure.lang.Namespace ns)]} (-> ns meta :core.typed)) (defn ns-has-feature? [ns k] (-> (core-typed-ns-meta ns) :features (contains? k))) (defn should-runtime-check-ns? [ns] (ns-has-feature? ns :runtime-check)) (defn should-runtime-infer-ns? [ns] (ns-has-feature? ns :runtime-infer)) )
0aa8387a6dd4f15682f92d3d6cd9dda25490b466045f38fa3970b22ea693bfa6
facebook/flow
subst.mli
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val subst : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.t -> Type.t val subst_class_bindings : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.class_binding list -> Type.class_binding list val subst_destructor : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.destructor -> Type.destructor
null
https://raw.githubusercontent.com/facebook/flow/d5f497c24463005d105374f70a8377593f3cd0a3/src/typing/subst.mli
ocaml
* Copyright ( c ) Meta Platforms , Inc. and affiliates . * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree . * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) val subst : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.t -> Type.t val subst_class_bindings : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.class_binding list -> Type.class_binding list val subst_destructor : Context.t -> ?use_op:Type.use_op -> ?force:bool -> Type.t Subst_name.Map.t -> Type.destructor -> Type.destructor
6f8977030d33e522bc7ad72a88316dc25e0fb093ad8bf8bd575a01e86e949a98
jellelicht/guix
guix-main.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2014 , 2015 , 2016 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . ;;; Commentary: ;; Information about packages and generations is passed to the elisp ;; side in the form of alists of parameters (such as ‘name’ or ;; ‘version’) and their values. ;; ‘entries’ procedure is the “entry point” for the elisp side to get ;; information about packages and generations. ;; Since name/version pair is not necessarily unique, we use ;; `object-address' to identify a package (for ‘id’ parameter), if ;; possible. However for the obsolete packages (that can be found in ;; installed manifest but not in a package directory), ‘id’ parameter is ;; still "name-version" string. So ‘id’ package parameter in the code ;; below is either an object-address number or a full-name string. ;; To speed-up the process of getting information, the following ;; auxiliary variables are used: ;; ;; - `%packages' - VHash of "package address"/"package" pairs. ;; ;; - `%package-table' - Hash table of " name+version     of   packages " pairs . ;;; Code: (use-modules (ice-9 vlist) (ice-9 match) (ice-9 popen) (srfi srfi-1) (srfi srfi-2) (srfi srfi-11) (srfi srfi-19) (srfi srfi-26) (guix) (guix git-download) (guix packages) (guix profiles) (guix licenses) (guix utils) (guix ui) (guix scripts lint) (guix scripts package) (guix scripts pull) (gnu packages) (gnu system)) (define-syntax-rule (first-or-false lst) (and (not (null? lst)) (first lst))) (define (list-maybe obj) (if (list? obj) obj (list obj))) (define (output+error thunk) "Call THUNK and return 2 values: output and error output as strings." (let ((output-port (open-output-string)) (error-port (open-output-string))) (with-output-to-port output-port (lambda () (with-error-to-port error-port thunk))) (let ((strings (list (get-output-string output-port) (get-output-string error-port)))) (close-output-port output-port) (close-output-port error-port) (apply values strings)))) (define (full-name->name+version spec) "Given package specification SPEC with or without output, return two values: name and version. For example, for SPEC \"foo@0.9.1b:lib\", return \"foo\" and \"0.9.1b\"." (let-values (((name version output) (package-specification->name+version+output spec))) (values name version))) (define (name+version->full-name name version) (string-append name "@" version)) (define* (make-package-specification name #:optional version output) (let ((full-name (if version (name+version->full-name name version) name))) (if output (string-append full-name ":" output) full-name))) (define name+version->key cons) (define key->name+version car+cdr) (define %packages (fold-packages (lambda (pkg res) (vhash-consq (object-address pkg) pkg res)) vlist-null)) (define %package-table (let ((table (make-hash-table (vlist-length %packages)))) (vlist-for-each (lambda (elem) (match elem ((address . pkg) (let* ((key (name+version->key (package-name pkg) (package-version pkg))) (ref (hash-ref table key))) (hash-set! table key (if ref (cons pkg ref) (list pkg))))))) %packages) table)) (define (manifest-entry->name+version+output entry) (values (manifest-entry-name entry) (manifest-entry-version entry) (manifest-entry-output entry))) (define (manifest-entry->package-specification entry) (call-with-values (lambda () (manifest-entry->name+version+output entry)) make-package-specification)) (define (manifest-entries->package-specifications entries) (map manifest-entry->package-specification entries)) (define (profile-package-specifications profile) "Return a list of package specifications for PROFILE." (let ((manifest (profile-manifest profile))) (manifest-entries->package-specifications (manifest-entries manifest)))) (define (profile->specifications+paths profile) "Return a list of package specifications and paths for PROFILE. Each element of the list is a list of the package specification and its path." (let ((manifest (profile-manifest profile))) (map (lambda (entry) (list (manifest-entry->package-specification entry) (manifest-entry-item entry))) (manifest-entries manifest)))) (define (profile-difference profile1 profile2) "Return a list of package specifications for outputs installed in PROFILE1 and not installed in PROFILE2." (let ((specs1 (profile-package-specifications profile1)) (specs2 (profile-package-specifications profile2))) (lset-difference string=? specs1 specs2))) (define (manifest-entries->hash-table entries) "Return a hash table of name keys and lists of matching manifest ENTRIES." (let ((table (make-hash-table (length entries)))) (for-each (lambda (entry) (let* ((key (manifest-entry-name entry)) (ref (hash-ref table key))) (hash-set! table key (if ref (cons entry ref) (list entry))))) entries) table)) (define (manifest=? m1 m2) (or (eq? m1 m2) (equal? m1 m2))) (define manifest->hash-table (let ((current-manifest #f) (current-table #f)) (lambda (manifest) "Return a hash table of name keys and matching MANIFEST entries." (unless (manifest=? manifest current-manifest) (set! current-manifest manifest) (set! current-table (manifest-entries->hash-table (manifest-entries manifest)))) current-table))) (define* (manifest-entries-by-name manifest name #:optional version output) "Return a list of MANIFEST entries matching NAME, VERSION and OUTPUT." (let ((entries (or (hash-ref (manifest->hash-table manifest) name) '()))) (if (or version output) (filter (lambda (entry) (and (or (not version) (equal? version (manifest-entry-version entry))) (or (not output) (equal? output (manifest-entry-output entry))))) entries) entries))) (define (manifest-entry-by-output entries output) "Return a manifest entry from ENTRIES matching OUTPUT." (find (lambda (entry) (string= output (manifest-entry-output entry))) entries)) (define (fold-manifest-by-name manifest proc init) "Fold over MANIFEST entries. Call (PROC NAME VERSION ENTRIES RESULT), using INIT as the initial value of RESULT. ENTRIES is a list of manifest entries with NAME/VERSION." (hash-fold (lambda (name entries res) (proc name (manifest-entry-version (car entries)) entries res)) init (manifest->hash-table manifest))) (define* (object-transformer param-alist #:optional (params '())) "Return procedure transforming objects into alist of parameter/value pairs. PARAM-ALIST is alist of available parameters (symbols) and procedures returning values of these parameters. Each procedure is applied to objects. PARAMS is list of parameters from PARAM-ALIST that should be returned by a resulting procedure. If PARAMS is not specified or is an empty list, use all available parameters. Example: (let* ((alist `((plus1 . ,1+) (minus1 . ,1-) (mul2 . ,(cut * 2 <>)))) (number->alist (object-transformer alist '(plus1 mul2)))) (number->alist 8)) => ((plus1 . 9) (mul2 . 16)) " (let* ((use-all-params (null? params)) (alist (filter-map (match-lambda ((param . proc) (and (or use-all-params (memq param params)) (cons param proc))) (_ #f)) param-alist))) (lambda objects (map (match-lambda ((param . proc) (cons param (apply proc objects)))) alist)))) (define %manifest-entry-param-alist `((output . ,manifest-entry-output) (path . ,manifest-entry-item) (dependencies . ,manifest-entry-dependencies))) (define manifest-entry->sexp (object-transformer %manifest-entry-param-alist)) (define (manifest-entries->sexps entries) (map manifest-entry->sexp entries)) (define (package-inputs-names inputs) "Return a list of full names of the packages from package INPUTS." (filter-map (match-lambda ((_ (? package? package)) (make-package-specification (package-name package) (package-version package))) ((_ (? package? package) output) (make-package-specification (package-name package) (package-version package) output)) (_ #f)) inputs)) (define (package-license-names package) "Return a list of license names of the PACKAGE." (filter-map (lambda (license) (and (license? license) (license-name license))) (list-maybe (package-license package)))) (define (package-source-names package) "Return a list of source names (URLs) of the PACKAGE." (let ((source (package-source package))) (and (origin? source) (filter-map (lambda (uri) (cond ((string? uri) uri) ((git-reference? uri) (git-reference-url uri)) (else "Unknown source type"))) (list-maybe (origin-uri source)))))) (define (package-unique? package) "Return #t if PACKAGE is a single package with such name/version." (null? (cdr (packages-by-name (package-name package) (package-version package))))) (define %package-param-alist `((id . ,object-address) (package-id . ,object-address) (name . ,package-name) (version . ,package-version) (license . ,package-license-names) (source . ,package-source-names) (synopsis . ,package-synopsis) (description . ,package-description-string) (home-url . ,package-home-page) (outputs . ,package-outputs) (systems . ,package-supported-systems) (non-unique . ,(negate package-unique?)) (inputs . ,(lambda (pkg) (package-inputs-names (package-inputs pkg)))) (native-inputs . ,(lambda (pkg) (package-inputs-names (package-native-inputs pkg)))) (propagated-inputs . ,(lambda (pkg) (package-inputs-names (package-propagated-inputs pkg)))) (location . ,(lambda (pkg) (location->string (package-location pkg)))))) (define (package-param package param) "Return a value of a PACKAGE PARAM." (and=> (assq-ref %package-param-alist param) (cut <> package))) ;;; Finding packages. (define (package-by-address address) (and=> (vhash-assq address %packages) cdr)) (define (packages-by-name+version name version) (or (hash-ref %package-table (name+version->key name version)) '())) (define (packages-by-full-name full-name) (call-with-values (lambda () (full-name->name+version full-name)) packages-by-name+version)) (define (packages-by-id id) (if (integer? id) (let ((pkg (package-by-address id))) (if pkg (list pkg) '())) (packages-by-full-name id))) (define (id->name+version id) (if (integer? id) (and=> (package-by-address id) (lambda (pkg) (values (package-name pkg) (package-version pkg)))) (full-name->name+version id))) (define (package-by-id id) (first-or-false (packages-by-id id))) (define (newest-package-by-id id) (and=> (id->name+version id) (lambda (name) (first-or-false (find-best-packages-by-name name #f))))) (define (matching-packages predicate) (fold-packages (lambda (pkg res) (if (predicate pkg) (cons pkg res) res)) '())) (define (filter-packages-by-output packages output) (filter (lambda (package) (member output (package-outputs package))) packages)) (define* (packages-by-name name #:optional version output) "Return a list of packages matching NAME, VERSION and OUTPUT." (let ((packages (if version (packages-by-name+version name version) (matching-packages (lambda (pkg) (string=? name (package-name pkg))))))) (if output (filter-packages-by-output packages output) packages))) (define (manifest-entry->packages entry) (call-with-values (lambda () (manifest-entry->name+version+output entry)) packages-by-name)) (define (packages-by-regexp regexp match-params) "Return a list of packages matching REGEXP string. MATCH-PARAMS is a list of parameters that REGEXP can match." (define (package-match? package regexp) (any (lambda (param) (let ((val (package-param package param))) (and (string? val) (regexp-exec regexp val)))) match-params)) (let ((re (make-regexp regexp regexp/icase))) (matching-packages (cut package-match? <> re)))) (define (packages-by-license license) "Return a list of packages with LICENSE." (matching-packages (lambda (package) (memq license (list-maybe (package-license package)))))) (define (all-available-packages) "Return a list of all available packages." (matching-packages (const #t))) (define (newest-available-packages) "Return a list of the newest available packages." (vhash-fold (lambda (name elem res) (match elem ((_ newest pkgs ...) (cons newest res)))) '() (find-newest-available-packages))) ;;; Making package/output patterns. (define (specification->package-pattern specification) (call-with-values (lambda () (full-name->name+version specification)) list)) (define (specification->output-pattern specification) (call-with-values (lambda () (package-specification->name+version+output specification #f)) list)) (define (id->package-pattern id) (if (integer? id) (package-by-address id) (specification->package-pattern id))) (define (id->output-pattern id) "Return an output pattern by output ID. ID should be '<package-address>:<output>' or '<name>-<version>:<output>'." (let-values (((name version output) (package-specification->name+version+output id))) (if version (list name version output) (list (package-by-address (string->number name)) output)))) (define (specifications->package-patterns . specifications) (map specification->package-pattern specifications)) (define (specifications->output-patterns . specifications) (map specification->output-pattern specifications)) (define (ids->package-patterns . ids) (map id->package-pattern ids)) (define (ids->output-patterns . ids) (map id->output-pattern ids)) (define* (manifest-patterns-result packages res obsolete-pattern #:optional installed-pattern) "Auxiliary procedure for 'manifest-package-patterns' and 'manifest-output-patterns'." (if (null? packages) (cons (obsolete-pattern) res) (if installed-pattern ;; We don't need duplicates for a list of installed packages, ;; so just take any (car) package. (cons (installed-pattern (car packages)) res) res))) (define* (manifest-package-patterns manifest #:optional obsolete-only?) "Return a list of package patterns for MANIFEST entries. If OBSOLETE-ONLY? is #f, use all entries, otherwise make patterns only for obsolete packages." (fold-manifest-by-name manifest (lambda (name version entries res) (manifest-patterns-result (packages-by-name name version) res (lambda () (list name version entries)) (and (not obsolete-only?) (cut list <> entries)))) '())) (define* (manifest-output-patterns manifest #:optional obsolete-only?) "Return a list of output patterns for MANIFEST entries. If OBSOLETE-ONLY? is #f, use all entries, otherwise make patterns only for obsolete packages." (fold (lambda (entry res) (manifest-patterns-result (manifest-entry->packages entry) res (lambda () entry) (and (not obsolete-only?) (cut list <> entry)))) '() (manifest-entries manifest))) (define (obsolete-package-patterns manifest) (manifest-package-patterns manifest #t)) (define (obsolete-output-patterns manifest) (manifest-output-patterns manifest #t)) ;;; Transforming package/output patterns into alists. (define (obsolete-package-sexp name version entries) "Return an alist with information about obsolete package. ENTRIES is a list of installed manifest entries." `((id . ,(name+version->full-name name version)) (name . ,name) (version . ,version) (outputs . ,(map manifest-entry-output entries)) (obsolete . #t) (installed . ,(manifest-entries->sexps entries)))) (define (package-pattern-transformer manifest params) "Return 'package-pattern->package-sexps' procedure." (define package->sexp (object-transformer %package-param-alist params)) (define* (sexp-by-package package #:optional (entries (manifest-entries-by-name manifest (package-name package) (package-version package)))) (cons (cons 'installed (manifest-entries->sexps entries)) (package->sexp package))) (define (->sexps pattern) (match pattern ((? package? package) (list (sexp-by-package package))) (((? package? package) entries) (list (sexp-by-package package entries))) ((name version entries) (list (obsolete-package-sexp name version entries))) ((name version) (let ((packages (packages-by-name name version))) (if (null? packages) (let ((entries (manifest-entries-by-name manifest name version))) (if (null? entries) '() (list (obsolete-package-sexp name version entries)))) (map sexp-by-package packages)))) (_ '()))) ->sexps) (define (output-pattern-transformer manifest params) "Return 'output-pattern->output-sexps' procedure." (define package->sexp (object-transformer (alist-delete 'id %package-param-alist) params)) (define manifest-entry->sexp (object-transformer (alist-delete 'output %manifest-entry-param-alist) params)) (define* (output-sexp pkg-alist pkg-address output #:optional entry) (let ((entry-alist (if entry (manifest-entry->sexp entry) '())) (base `((id . ,(string-append (number->string pkg-address) ":" output)) (output . ,output) (installed . ,(->bool entry))))) (append entry-alist base pkg-alist))) (define (obsolete-output-sexp entry) (let-values (((name version output) (manifest-entry->name+version+output entry))) (let ((base `((id . ,(make-package-specification name version output)) (package-id . ,(name+version->full-name name version)) (name . ,name) (version . ,version) (output . ,output) (obsolete . #t) (installed . #t)))) (append (manifest-entry->sexp entry) base)))) (define* (sexps-by-package package #:optional output (entries (manifest-entries-by-name manifest (package-name package) (package-version package)))) ;; Assuming that PACKAGE has this OUTPUT. (let ((pkg-alist (package->sexp package)) (address (object-address package)) (outputs (if output (list output) (package-outputs package)))) (map (lambda (output) (output-sexp pkg-alist address output (manifest-entry-by-output entries output))) outputs))) (define* (sexps-by-manifest-entry entry #:optional (packages (manifest-entry->packages entry))) (if (null? packages) (list (obsolete-output-sexp entry)) (map (lambda (package) (output-sexp (package->sexp package) (object-address package) (manifest-entry-output entry) entry)) packages))) (define (->sexps pattern) (match pattern ((? package? package) (sexps-by-package package)) ((package (? string? output)) (sexps-by-package package output)) ((? manifest-entry? entry) (list (obsolete-output-sexp entry))) ((package entry) (sexps-by-manifest-entry entry (list package))) ((name version output) (let ((packages (packages-by-name name version output))) (if (null? packages) (let ((entries (manifest-entries-by-name manifest name version output))) (append-map (cut sexps-by-manifest-entry <>) entries)) (append-map (cut sexps-by-package <> output) packages)))) (_ '()))) ->sexps) (define (entry-type-error entry-type) (error (format #f "Wrong entry-type '~a'" entry-type))) (define (search-type-error entry-type search-type) (error (format #f "Wrong search type '~a' for entry-type '~a'" search-type entry-type))) (define %pattern-transformers `((package . ,package-pattern-transformer) (output . ,output-pattern-transformer))) (define (pattern-transformer entry-type) (assq-ref %pattern-transformers entry-type)) All procedures from inner alists are called with ( MANIFEST . SEARCH - VALS ) ;; as arguments; see `package/output-sexps'. (define %patterns-makers (let* ((apply-to-rest (lambda (proc) (lambda (_ . rest) (apply proc rest)))) (apply-to-first (lambda (proc) (lambda (first . _) (proc first)))) (manifest-package-proc (apply-to-first manifest-package-patterns)) (manifest-output-proc (apply-to-first manifest-output-patterns)) (regexp-proc (lambda (_ regexp params . __) (packages-by-regexp regexp params))) (license-proc (lambda (_ license-name) (packages-by-license (lookup-license license-name)))) (all-proc (lambda _ (all-available-packages))) (newest-proc (lambda _ (newest-available-packages)))) `((package (id . ,(apply-to-rest ids->package-patterns)) (name . ,(apply-to-rest specifications->package-patterns)) (installed . ,manifest-package-proc) (obsolete . ,(apply-to-first obsolete-package-patterns)) (regexp . ,regexp-proc) (license . ,license-proc) (all-available . ,all-proc) (newest-available . ,newest-proc)) (output (id . ,(apply-to-rest ids->output-patterns)) (name . ,(apply-to-rest specifications->output-patterns)) (installed . ,manifest-output-proc) (obsolete . ,(apply-to-first obsolete-output-patterns)) (regexp . ,regexp-proc) (license . ,license-proc) (all-available . ,all-proc) (newest-available . ,newest-proc))))) (define (patterns-maker entry-type search-type) (or (and=> (assq-ref %patterns-makers entry-type) (cut assq-ref <> search-type)) (search-type-error entry-type search-type))) (define (package/output-sexps profile params entry-type search-type search-vals) "Return information about packages or package outputs. See 'entry-sexps' for details." (let* ((manifest (profile-manifest profile)) (patterns (if (and (eq? entry-type 'output) (eq? search-type 'profile-diff)) (match search-vals ((p1 p2) (map specification->output-pattern (profile-difference p1 p2))) (_ '())) (apply (patterns-maker entry-type search-type) manifest search-vals))) (->sexps ((pattern-transformer entry-type) manifest params))) (append-map ->sexps patterns))) ;;; Getting information about generations. (define (generation-param-alist profile) "Return an alist of generation parameters and procedures for PROFILE." (let ((current (generation-number profile))) `((id . ,identity) (number . ,identity) (prev-number . ,(cut previous-generation-number profile <>)) (current . ,(cut = current <>)) (path . ,(cut generation-file-name profile <>)) (time . ,(lambda (gen) (time-second (generation-time profile gen))))))) (define (matching-generations profile predicate) "Return a list of PROFILE generations matching PREDICATE." (filter predicate (profile-generations profile))) (define (last-generations profile number) "Return a list of last NUMBER generations. If NUMBER is 0 or less, return all generations." (let ((generations (profile-generations profile)) (number (if (<= number 0) +inf.0 number))) (if (> (length generations) number) (list-head (reverse generations) number) generations))) (define (find-generations profile search-type search-vals) "Find PROFILE's generations matching SEARCH-TYPE and SEARCH-VALS." (case search-type ((id) (matching-generations profile (cut memq <> search-vals))) ((last) (last-generations profile (car search-vals))) ((all) (last-generations profile +inf.0)) ((time) (match search-vals ((from to) (matching-generations profile (lambda (gen) (let ((time (time-second (generation-time profile gen)))) (< from time to))))) (_ '()))) (else (search-type-error "generation" search-type)))) (define (generation-sexps profile params search-type search-vals) "Return information about generations. See 'entry-sexps' for details." (let ((generations (find-generations profile search-type search-vals)) (->sexp (object-transformer (generation-param-alist profile) params))) (map ->sexp generations))) (define system-generation-boot-parameters (memoize (lambda (profile generation) "Return boot parameters for PROFILE's system GENERATION." (let* ((gen-file (generation-file-name profile generation)) (param-file (string-append gen-file "/parameters"))) (call-with-input-file param-file read-boot-parameters))))) (define (system-generation-param-alist profile) "Return an alist of system generation parameters and procedures for PROFILE." (append (generation-param-alist profile) `((label . ,(lambda (gen) (boot-parameters-label (system-generation-boot-parameters profile gen)))) (root-device . ,(lambda (gen) (boot-parameters-root-device (system-generation-boot-parameters profile gen)))) (kernel . ,(lambda (gen) (boot-parameters-kernel (system-generation-boot-parameters profile gen))))))) (define (system-generation-sexps profile params search-type search-vals) "Return an alist with information about system generations." (let ((generations (find-generations profile search-type search-vals)) (->sexp (object-transformer (system-generation-param-alist profile) params))) (map ->sexp generations))) ;;; Getting package/output/generation entries (alists). (define (entries profile params entry-type search-type search-vals) "Return information about entries. ENTRY-TYPE is a symbol defining a type of returning information. Should be: 'package', 'output' or 'generation'. SEARCH-TYPE and SEARCH-VALS define how to get the information. SEARCH-TYPE should be one of the following symbols: - If ENTRY-TYPE is 'package' or 'output': 'id', 'name', 'regexp', 'all-available', 'newest-available', 'installed', 'obsolete', 'generation'. - If ENTRY-TYPE is 'generation': 'id', 'last', 'all', 'time'. PARAMS is a list of parameters for receiving. If it is an empty list, get information with all available parameters, which are: - If ENTRY-TYPE is 'package': 'id', 'name', 'version', 'outputs', 'license', 'synopsis', 'description', 'home-url', 'inputs', 'native-inputs', 'propagated-inputs', 'location', 'installed'. - If ENTRY-TYPE is 'output': 'id', 'package-id', 'name', 'version', 'output', 'license', 'synopsis', 'description', 'home-url', 'inputs', 'native-inputs', 'propagated-inputs', 'location', 'installed', 'path', 'dependencies'. - If ENTRY-TYPE is 'generation': 'id', 'number', 'prev-number', 'path', 'time'. Returning value is a list of alists. Each alist consists of parameter/value pairs." (case entry-type ((package output) (package/output-sexps profile params entry-type search-type search-vals)) ((generation) (generation-sexps profile params search-type search-vals)) ((system-generation) (system-generation-sexps profile params search-type search-vals)) (else (entry-type-error entry-type)))) ;;; Package actions. (define* (package->manifest-entry* package #:optional output) (and package (package->manifest-entry package output))) (define* (make-install-manifest-entries id #:optional output) (package->manifest-entry* (package-by-id id) output)) (define* (make-upgrade-manifest-entries id #:optional output) (package->manifest-entry* (newest-package-by-id id) output)) (define* (make-manifest-pattern id #:optional output) "Make manifest pattern from a package ID and OUTPUT." (let-values (((name version) (id->name+version id))) (and name version (manifest-pattern (name name) (version version) (output output))))) (define (convert-action-pattern pattern proc) "Convert action PATTERN into a list of objects returned by PROC. PROC is called: (PROC ID) or (PROC ID OUTPUT)." (match pattern ((id . outputs) (if (null? outputs) (let ((obj (proc id))) (if obj (list obj) '())) (filter-map (cut proc id <>) outputs))) (_ '()))) (define (convert-action-patterns patterns proc) (append-map (cut convert-action-pattern <> proc) patterns)) (define* (process-package-actions profile #:key (install '()) (upgrade '()) (remove '()) (use-substitutes? #t) dry-run?) "Perform package actions. INSTALL, UPGRADE, REMOVE are lists of 'package action patterns'. Each pattern should have the following form: (ID . OUTPUTS) ID is an object address or a full-name of a package. OUTPUTS is a list of package outputs (may be an empty list)." (format #t "The process begins ...~%") (let* ((install (append (convert-action-patterns install make-install-manifest-entries) (convert-action-patterns upgrade make-upgrade-manifest-entries))) (remove (convert-action-patterns remove make-manifest-pattern)) (transaction (manifest-transaction (install install) (remove remove))) (manifest (profile-manifest profile)) (new-manifest (manifest-perform-transaction manifest transaction))) (unless (and (null? install) (null? remove)) (with-store store (let* ((derivation (run-with-store store (mbegin %store-monad (set-guile-for-build (default-guile)) (profile-derivation new-manifest)))) (derivations (list derivation)) (new-profile (derivation->output-path derivation))) (set-build-options store #:print-build-trace #f #:use-substitutes? use-substitutes?) (show-manifest-transaction store manifest transaction #:dry-run? dry-run?) (show-what-to-build store derivations #:use-substitutes? use-substitutes? #:dry-run? dry-run?) (unless dry-run? (let ((name (generation-file-name profile (+ 1 (generation-number profile))))) (and (build-derivations store derivations) (let* ((entries (manifest-entries new-manifest)) (count (length entries))) (switch-symlinks name new-profile) (switch-symlinks profile name) (format #t (N_ "~a package in profile~%" "~a packages in profile~%" count) count) (display-search-paths entries (list profile))))))))))) (define (delete-generations* profile generations) "Delete GENERATIONS from PROFILE. GENERATIONS is a list of generation numbers." (with-store store (delete-generations store profile generations))) (define (package-location-string id-or-name) "Return a location string of a package with ID-OR-NAME." (and=> (or (package-by-id id-or-name) (match (packages-by-name id-or-name) (() #f) ((package _ ...) package))) (compose location->string package-location))) (define (package-source-derivation->store-path derivation) "Return a store path of the package source DERIVATION." (match (derivation-outputs derivation) ;; Source derivation is always (("out" . derivation)). (((_ . output-drv)) (derivation-output-path output-drv)) (_ #f))) (define (package-source-path package-id) "Return a store file path to a source of a package PACKAGE-ID." (and-let* ((package (package-by-id package-id)) (source (package-source package))) (with-store store (package-source-derivation->store-path (package-source-derivation store source))))) (define* (package-source-build-derivation package-id #:key dry-run? (use-substitutes? #t)) "Build source derivation of a package PACKAGE-ID." (and-let* ((package (package-by-id package-id)) (source (package-source package))) (with-store store (let* ((derivation (package-source-derivation store source)) (derivations (list derivation))) (set-build-options store #:print-build-trace #f #:use-substitutes? use-substitutes?) (show-what-to-build store derivations #:use-substitutes? use-substitutes? #:dry-run? dry-run?) (unless dry-run? (build-derivations store derivations)) (format #t "The source store path: ~a~%" (package-source-derivation->store-path derivation)))))) ;;; Executing guix commands (define (guix-command . args) "Run 'guix ARGS ...' command." (catch 'quit (lambda () (apply run-guix args)) (const #t))) (define (guix-command-output . args) "Return 2 strings with 'guix ARGS ...' output and error output." (output+error (lambda () (parameterize ((guix-warning-port (current-error-port))) (apply guix-command args))))) (define (help-string . commands) "Return string with 'guix COMMANDS ... --help' output." (apply guix-command-output `(,@commands "--help"))) (define (pipe-guix-output guix-args command-args) "Run 'guix GUIX-ARGS ...' command and pipe its output to a shell command defined by COMMAND-ARGS. Return #t if the shell command was executed successfully." (let ((pipe (apply open-pipe* OPEN_WRITE command-args))) (with-output-to-port pipe (lambda () (apply guix-command guix-args))) (zero? (status:exit-val (close-pipe pipe))))) ;;; Lists of packages, lint checkers, etc. (define (graph-type-names) "Return a list of names of available graph node types." (map (@ (guix graph) node-type-name) (@ (guix scripts graph) %node-types))) (define (refresh-updater-names) "Return a list of names of available refresh updater types." (map (@ (guix upstream) upstream-updater-name) (@ (guix scripts refresh) %updaters))) (define (lint-checker-names) "Return a list of names of available lint checkers." (map (lambda (checker) (symbol->string (lint-checker-name checker))) %checkers)) (define (package-names) "Return a list of names of available packages." (delete-duplicates (fold-packages (lambda (pkg res) (cons (package-name pkg) res)) '()))) ;; See the comment to 'guix-package-names' function in "guix-popup.el". (define (package-names-lists) (map list (package-names))) ;;; Licenses (define %licenses (delay (filter license? (module-map (lambda (_ var) (variable-ref var)) (resolve-interface '(guix licenses)))))) (define (licenses) (force %licenses)) (define (license-names) "Return a list of names of available licenses." (map license-name (licenses))) (define lookup-license (memoize (lambda (name) "Return a license by its name." (find (lambda (l) (string=? name (license-name l))) (licenses))))) (define (lookup-license-uri name) "Return a license URI by its name." (and=> (lookup-license name) license-uri)) (define %license-param-alist `((id . ,license-name) (name . ,license-name) (url . ,license-uri) (comment . ,license-comment))) (define license->sexp (object-transformer %license-param-alist)) (define (find-licenses search-type . search-values) "Return a list of licenses depending on SEARCH-TYPE and SEARCH-VALUES." (case search-type ((id name) (let ((names search-values)) (filter-map lookup-license names))) ((all) (licenses)))) (define (license-entries search-type . search-values) (map license->sexp (apply find-licenses search-type search-values)))
null
https://raw.githubusercontent.com/jellelicht/guix/83cfc9414fca3ab57c949e18c1ceb375a179b59c/emacs/guix-main.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Commentary: Information about packages and generations is passed to the elisp side in the form of alists of parameters (such as ‘name’ or ‘version’) and their values. ‘entries’ procedure is the “entry point” for the elisp side to get information about packages and generations. Since name/version pair is not necessarily unique, we use `object-address' to identify a package (for ‘id’ parameter), if possible. However for the obsolete packages (that can be found in installed manifest but not in a package directory), ‘id’ parameter is still "name-version" string. So ‘id’ package parameter in the code below is either an object-address number or a full-name string. To speed-up the process of getting information, the following auxiliary variables are used: - `%packages' - VHash of "package address"/"package" pairs. - `%package-table' - Hash table of Code: Finding packages. Making package/output patterns. We don't need duplicates for a list of installed packages, so just take any (car) package. Transforming package/output patterns into alists. Assuming that PACKAGE has this OUTPUT. as arguments; see `package/output-sexps'. Getting information about generations. Getting package/output/generation entries (alists). Package actions. Source derivation is always (("out" . derivation)). Executing guix commands Lists of packages, lint checkers, etc. See the comment to 'guix-package-names' function in "guix-popup.el". Licenses
Copyright © 2014 , 2015 , 2016 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . " name+version     of   packages " pairs . (use-modules (ice-9 vlist) (ice-9 match) (ice-9 popen) (srfi srfi-1) (srfi srfi-2) (srfi srfi-11) (srfi srfi-19) (srfi srfi-26) (guix) (guix git-download) (guix packages) (guix profiles) (guix licenses) (guix utils) (guix ui) (guix scripts lint) (guix scripts package) (guix scripts pull) (gnu packages) (gnu system)) (define-syntax-rule (first-or-false lst) (and (not (null? lst)) (first lst))) (define (list-maybe obj) (if (list? obj) obj (list obj))) (define (output+error thunk) "Call THUNK and return 2 values: output and error output as strings." (let ((output-port (open-output-string)) (error-port (open-output-string))) (with-output-to-port output-port (lambda () (with-error-to-port error-port thunk))) (let ((strings (list (get-output-string output-port) (get-output-string error-port)))) (close-output-port output-port) (close-output-port error-port) (apply values strings)))) (define (full-name->name+version spec) "Given package specification SPEC with or without output, return two values: name and version. For example, for SPEC \"foo@0.9.1b:lib\", return \"foo\" and \"0.9.1b\"." (let-values (((name version output) (package-specification->name+version+output spec))) (values name version))) (define (name+version->full-name name version) (string-append name "@" version)) (define* (make-package-specification name #:optional version output) (let ((full-name (if version (name+version->full-name name version) name))) (if output (string-append full-name ":" output) full-name))) (define name+version->key cons) (define key->name+version car+cdr) (define %packages (fold-packages (lambda (pkg res) (vhash-consq (object-address pkg) pkg res)) vlist-null)) (define %package-table (let ((table (make-hash-table (vlist-length %packages)))) (vlist-for-each (lambda (elem) (match elem ((address . pkg) (let* ((key (name+version->key (package-name pkg) (package-version pkg))) (ref (hash-ref table key))) (hash-set! table key (if ref (cons pkg ref) (list pkg))))))) %packages) table)) (define (manifest-entry->name+version+output entry) (values (manifest-entry-name entry) (manifest-entry-version entry) (manifest-entry-output entry))) (define (manifest-entry->package-specification entry) (call-with-values (lambda () (manifest-entry->name+version+output entry)) make-package-specification)) (define (manifest-entries->package-specifications entries) (map manifest-entry->package-specification entries)) (define (profile-package-specifications profile) "Return a list of package specifications for PROFILE." (let ((manifest (profile-manifest profile))) (manifest-entries->package-specifications (manifest-entries manifest)))) (define (profile->specifications+paths profile) "Return a list of package specifications and paths for PROFILE. Each element of the list is a list of the package specification and its path." (let ((manifest (profile-manifest profile))) (map (lambda (entry) (list (manifest-entry->package-specification entry) (manifest-entry-item entry))) (manifest-entries manifest)))) (define (profile-difference profile1 profile2) "Return a list of package specifications for outputs installed in PROFILE1 and not installed in PROFILE2." (let ((specs1 (profile-package-specifications profile1)) (specs2 (profile-package-specifications profile2))) (lset-difference string=? specs1 specs2))) (define (manifest-entries->hash-table entries) "Return a hash table of name keys and lists of matching manifest ENTRIES." (let ((table (make-hash-table (length entries)))) (for-each (lambda (entry) (let* ((key (manifest-entry-name entry)) (ref (hash-ref table key))) (hash-set! table key (if ref (cons entry ref) (list entry))))) entries) table)) (define (manifest=? m1 m2) (or (eq? m1 m2) (equal? m1 m2))) (define manifest->hash-table (let ((current-manifest #f) (current-table #f)) (lambda (manifest) "Return a hash table of name keys and matching MANIFEST entries." (unless (manifest=? manifest current-manifest) (set! current-manifest manifest) (set! current-table (manifest-entries->hash-table (manifest-entries manifest)))) current-table))) (define* (manifest-entries-by-name manifest name #:optional version output) "Return a list of MANIFEST entries matching NAME, VERSION and OUTPUT." (let ((entries (or (hash-ref (manifest->hash-table manifest) name) '()))) (if (or version output) (filter (lambda (entry) (and (or (not version) (equal? version (manifest-entry-version entry))) (or (not output) (equal? output (manifest-entry-output entry))))) entries) entries))) (define (manifest-entry-by-output entries output) "Return a manifest entry from ENTRIES matching OUTPUT." (find (lambda (entry) (string= output (manifest-entry-output entry))) entries)) (define (fold-manifest-by-name manifest proc init) "Fold over MANIFEST entries. Call (PROC NAME VERSION ENTRIES RESULT), using INIT as the initial value of RESULT. ENTRIES is a list of manifest entries with NAME/VERSION." (hash-fold (lambda (name entries res) (proc name (manifest-entry-version (car entries)) entries res)) init (manifest->hash-table manifest))) (define* (object-transformer param-alist #:optional (params '())) "Return procedure transforming objects into alist of parameter/value pairs. PARAM-ALIST is alist of available parameters (symbols) and procedures returning values of these parameters. Each procedure is applied to objects. PARAMS is list of parameters from PARAM-ALIST that should be returned by a resulting procedure. If PARAMS is not specified or is an empty list, use all available parameters. Example: (let* ((alist `((plus1 . ,1+) (minus1 . ,1-) (mul2 . ,(cut * 2 <>)))) (number->alist (object-transformer alist '(plus1 mul2)))) (number->alist 8)) => ((plus1 . 9) (mul2 . 16)) " (let* ((use-all-params (null? params)) (alist (filter-map (match-lambda ((param . proc) (and (or use-all-params (memq param params)) (cons param proc))) (_ #f)) param-alist))) (lambda objects (map (match-lambda ((param . proc) (cons param (apply proc objects)))) alist)))) (define %manifest-entry-param-alist `((output . ,manifest-entry-output) (path . ,manifest-entry-item) (dependencies . ,manifest-entry-dependencies))) (define manifest-entry->sexp (object-transformer %manifest-entry-param-alist)) (define (manifest-entries->sexps entries) (map manifest-entry->sexp entries)) (define (package-inputs-names inputs) "Return a list of full names of the packages from package INPUTS." (filter-map (match-lambda ((_ (? package? package)) (make-package-specification (package-name package) (package-version package))) ((_ (? package? package) output) (make-package-specification (package-name package) (package-version package) output)) (_ #f)) inputs)) (define (package-license-names package) "Return a list of license names of the PACKAGE." (filter-map (lambda (license) (and (license? license) (license-name license))) (list-maybe (package-license package)))) (define (package-source-names package) "Return a list of source names (URLs) of the PACKAGE." (let ((source (package-source package))) (and (origin? source) (filter-map (lambda (uri) (cond ((string? uri) uri) ((git-reference? uri) (git-reference-url uri)) (else "Unknown source type"))) (list-maybe (origin-uri source)))))) (define (package-unique? package) "Return #t if PACKAGE is a single package with such name/version." (null? (cdr (packages-by-name (package-name package) (package-version package))))) (define %package-param-alist `((id . ,object-address) (package-id . ,object-address) (name . ,package-name) (version . ,package-version) (license . ,package-license-names) (source . ,package-source-names) (synopsis . ,package-synopsis) (description . ,package-description-string) (home-url . ,package-home-page) (outputs . ,package-outputs) (systems . ,package-supported-systems) (non-unique . ,(negate package-unique?)) (inputs . ,(lambda (pkg) (package-inputs-names (package-inputs pkg)))) (native-inputs . ,(lambda (pkg) (package-inputs-names (package-native-inputs pkg)))) (propagated-inputs . ,(lambda (pkg) (package-inputs-names (package-propagated-inputs pkg)))) (location . ,(lambda (pkg) (location->string (package-location pkg)))))) (define (package-param package param) "Return a value of a PACKAGE PARAM." (and=> (assq-ref %package-param-alist param) (cut <> package))) (define (package-by-address address) (and=> (vhash-assq address %packages) cdr)) (define (packages-by-name+version name version) (or (hash-ref %package-table (name+version->key name version)) '())) (define (packages-by-full-name full-name) (call-with-values (lambda () (full-name->name+version full-name)) packages-by-name+version)) (define (packages-by-id id) (if (integer? id) (let ((pkg (package-by-address id))) (if pkg (list pkg) '())) (packages-by-full-name id))) (define (id->name+version id) (if (integer? id) (and=> (package-by-address id) (lambda (pkg) (values (package-name pkg) (package-version pkg)))) (full-name->name+version id))) (define (package-by-id id) (first-or-false (packages-by-id id))) (define (newest-package-by-id id) (and=> (id->name+version id) (lambda (name) (first-or-false (find-best-packages-by-name name #f))))) (define (matching-packages predicate) (fold-packages (lambda (pkg res) (if (predicate pkg) (cons pkg res) res)) '())) (define (filter-packages-by-output packages output) (filter (lambda (package) (member output (package-outputs package))) packages)) (define* (packages-by-name name #:optional version output) "Return a list of packages matching NAME, VERSION and OUTPUT." (let ((packages (if version (packages-by-name+version name version) (matching-packages (lambda (pkg) (string=? name (package-name pkg))))))) (if output (filter-packages-by-output packages output) packages))) (define (manifest-entry->packages entry) (call-with-values (lambda () (manifest-entry->name+version+output entry)) packages-by-name)) (define (packages-by-regexp regexp match-params) "Return a list of packages matching REGEXP string. MATCH-PARAMS is a list of parameters that REGEXP can match." (define (package-match? package regexp) (any (lambda (param) (let ((val (package-param package param))) (and (string? val) (regexp-exec regexp val)))) match-params)) (let ((re (make-regexp regexp regexp/icase))) (matching-packages (cut package-match? <> re)))) (define (packages-by-license license) "Return a list of packages with LICENSE." (matching-packages (lambda (package) (memq license (list-maybe (package-license package)))))) (define (all-available-packages) "Return a list of all available packages." (matching-packages (const #t))) (define (newest-available-packages) "Return a list of the newest available packages." (vhash-fold (lambda (name elem res) (match elem ((_ newest pkgs ...) (cons newest res)))) '() (find-newest-available-packages))) (define (specification->package-pattern specification) (call-with-values (lambda () (full-name->name+version specification)) list)) (define (specification->output-pattern specification) (call-with-values (lambda () (package-specification->name+version+output specification #f)) list)) (define (id->package-pattern id) (if (integer? id) (package-by-address id) (specification->package-pattern id))) (define (id->output-pattern id) "Return an output pattern by output ID. ID should be '<package-address>:<output>' or '<name>-<version>:<output>'." (let-values (((name version output) (package-specification->name+version+output id))) (if version (list name version output) (list (package-by-address (string->number name)) output)))) (define (specifications->package-patterns . specifications) (map specification->package-pattern specifications)) (define (specifications->output-patterns . specifications) (map specification->output-pattern specifications)) (define (ids->package-patterns . ids) (map id->package-pattern ids)) (define (ids->output-patterns . ids) (map id->output-pattern ids)) (define* (manifest-patterns-result packages res obsolete-pattern #:optional installed-pattern) "Auxiliary procedure for 'manifest-package-patterns' and 'manifest-output-patterns'." (if (null? packages) (cons (obsolete-pattern) res) (if installed-pattern (cons (installed-pattern (car packages)) res) res))) (define* (manifest-package-patterns manifest #:optional obsolete-only?) "Return a list of package patterns for MANIFEST entries. If OBSOLETE-ONLY? is #f, use all entries, otherwise make patterns only for obsolete packages." (fold-manifest-by-name manifest (lambda (name version entries res) (manifest-patterns-result (packages-by-name name version) res (lambda () (list name version entries)) (and (not obsolete-only?) (cut list <> entries)))) '())) (define* (manifest-output-patterns manifest #:optional obsolete-only?) "Return a list of output patterns for MANIFEST entries. If OBSOLETE-ONLY? is #f, use all entries, otherwise make patterns only for obsolete packages." (fold (lambda (entry res) (manifest-patterns-result (manifest-entry->packages entry) res (lambda () entry) (and (not obsolete-only?) (cut list <> entry)))) '() (manifest-entries manifest))) (define (obsolete-package-patterns manifest) (manifest-package-patterns manifest #t)) (define (obsolete-output-patterns manifest) (manifest-output-patterns manifest #t)) (define (obsolete-package-sexp name version entries) "Return an alist with information about obsolete package. ENTRIES is a list of installed manifest entries." `((id . ,(name+version->full-name name version)) (name . ,name) (version . ,version) (outputs . ,(map manifest-entry-output entries)) (obsolete . #t) (installed . ,(manifest-entries->sexps entries)))) (define (package-pattern-transformer manifest params) "Return 'package-pattern->package-sexps' procedure." (define package->sexp (object-transformer %package-param-alist params)) (define* (sexp-by-package package #:optional (entries (manifest-entries-by-name manifest (package-name package) (package-version package)))) (cons (cons 'installed (manifest-entries->sexps entries)) (package->sexp package))) (define (->sexps pattern) (match pattern ((? package? package) (list (sexp-by-package package))) (((? package? package) entries) (list (sexp-by-package package entries))) ((name version entries) (list (obsolete-package-sexp name version entries))) ((name version) (let ((packages (packages-by-name name version))) (if (null? packages) (let ((entries (manifest-entries-by-name manifest name version))) (if (null? entries) '() (list (obsolete-package-sexp name version entries)))) (map sexp-by-package packages)))) (_ '()))) ->sexps) (define (output-pattern-transformer manifest params) "Return 'output-pattern->output-sexps' procedure." (define package->sexp (object-transformer (alist-delete 'id %package-param-alist) params)) (define manifest-entry->sexp (object-transformer (alist-delete 'output %manifest-entry-param-alist) params)) (define* (output-sexp pkg-alist pkg-address output #:optional entry) (let ((entry-alist (if entry (manifest-entry->sexp entry) '())) (base `((id . ,(string-append (number->string pkg-address) ":" output)) (output . ,output) (installed . ,(->bool entry))))) (append entry-alist base pkg-alist))) (define (obsolete-output-sexp entry) (let-values (((name version output) (manifest-entry->name+version+output entry))) (let ((base `((id . ,(make-package-specification name version output)) (package-id . ,(name+version->full-name name version)) (name . ,name) (version . ,version) (output . ,output) (obsolete . #t) (installed . #t)))) (append (manifest-entry->sexp entry) base)))) (define* (sexps-by-package package #:optional output (entries (manifest-entries-by-name manifest (package-name package) (package-version package)))) (let ((pkg-alist (package->sexp package)) (address (object-address package)) (outputs (if output (list output) (package-outputs package)))) (map (lambda (output) (output-sexp pkg-alist address output (manifest-entry-by-output entries output))) outputs))) (define* (sexps-by-manifest-entry entry #:optional (packages (manifest-entry->packages entry))) (if (null? packages) (list (obsolete-output-sexp entry)) (map (lambda (package) (output-sexp (package->sexp package) (object-address package) (manifest-entry-output entry) entry)) packages))) (define (->sexps pattern) (match pattern ((? package? package) (sexps-by-package package)) ((package (? string? output)) (sexps-by-package package output)) ((? manifest-entry? entry) (list (obsolete-output-sexp entry))) ((package entry) (sexps-by-manifest-entry entry (list package))) ((name version output) (let ((packages (packages-by-name name version output))) (if (null? packages) (let ((entries (manifest-entries-by-name manifest name version output))) (append-map (cut sexps-by-manifest-entry <>) entries)) (append-map (cut sexps-by-package <> output) packages)))) (_ '()))) ->sexps) (define (entry-type-error entry-type) (error (format #f "Wrong entry-type '~a'" entry-type))) (define (search-type-error entry-type search-type) (error (format #f "Wrong search type '~a' for entry-type '~a'" search-type entry-type))) (define %pattern-transformers `((package . ,package-pattern-transformer) (output . ,output-pattern-transformer))) (define (pattern-transformer entry-type) (assq-ref %pattern-transformers entry-type)) All procedures from inner alists are called with ( MANIFEST . SEARCH - VALS ) (define %patterns-makers (let* ((apply-to-rest (lambda (proc) (lambda (_ . rest) (apply proc rest)))) (apply-to-first (lambda (proc) (lambda (first . _) (proc first)))) (manifest-package-proc (apply-to-first manifest-package-patterns)) (manifest-output-proc (apply-to-first manifest-output-patterns)) (regexp-proc (lambda (_ regexp params . __) (packages-by-regexp regexp params))) (license-proc (lambda (_ license-name) (packages-by-license (lookup-license license-name)))) (all-proc (lambda _ (all-available-packages))) (newest-proc (lambda _ (newest-available-packages)))) `((package (id . ,(apply-to-rest ids->package-patterns)) (name . ,(apply-to-rest specifications->package-patterns)) (installed . ,manifest-package-proc) (obsolete . ,(apply-to-first obsolete-package-patterns)) (regexp . ,regexp-proc) (license . ,license-proc) (all-available . ,all-proc) (newest-available . ,newest-proc)) (output (id . ,(apply-to-rest ids->output-patterns)) (name . ,(apply-to-rest specifications->output-patterns)) (installed . ,manifest-output-proc) (obsolete . ,(apply-to-first obsolete-output-patterns)) (regexp . ,regexp-proc) (license . ,license-proc) (all-available . ,all-proc) (newest-available . ,newest-proc))))) (define (patterns-maker entry-type search-type) (or (and=> (assq-ref %patterns-makers entry-type) (cut assq-ref <> search-type)) (search-type-error entry-type search-type))) (define (package/output-sexps profile params entry-type search-type search-vals) "Return information about packages or package outputs. See 'entry-sexps' for details." (let* ((manifest (profile-manifest profile)) (patterns (if (and (eq? entry-type 'output) (eq? search-type 'profile-diff)) (match search-vals ((p1 p2) (map specification->output-pattern (profile-difference p1 p2))) (_ '())) (apply (patterns-maker entry-type search-type) manifest search-vals))) (->sexps ((pattern-transformer entry-type) manifest params))) (append-map ->sexps patterns))) (define (generation-param-alist profile) "Return an alist of generation parameters and procedures for PROFILE." (let ((current (generation-number profile))) `((id . ,identity) (number . ,identity) (prev-number . ,(cut previous-generation-number profile <>)) (current . ,(cut = current <>)) (path . ,(cut generation-file-name profile <>)) (time . ,(lambda (gen) (time-second (generation-time profile gen))))))) (define (matching-generations profile predicate) "Return a list of PROFILE generations matching PREDICATE." (filter predicate (profile-generations profile))) (define (last-generations profile number) "Return a list of last NUMBER generations. If NUMBER is 0 or less, return all generations." (let ((generations (profile-generations profile)) (number (if (<= number 0) +inf.0 number))) (if (> (length generations) number) (list-head (reverse generations) number) generations))) (define (find-generations profile search-type search-vals) "Find PROFILE's generations matching SEARCH-TYPE and SEARCH-VALS." (case search-type ((id) (matching-generations profile (cut memq <> search-vals))) ((last) (last-generations profile (car search-vals))) ((all) (last-generations profile +inf.0)) ((time) (match search-vals ((from to) (matching-generations profile (lambda (gen) (let ((time (time-second (generation-time profile gen)))) (< from time to))))) (_ '()))) (else (search-type-error "generation" search-type)))) (define (generation-sexps profile params search-type search-vals) "Return information about generations. See 'entry-sexps' for details." (let ((generations (find-generations profile search-type search-vals)) (->sexp (object-transformer (generation-param-alist profile) params))) (map ->sexp generations))) (define system-generation-boot-parameters (memoize (lambda (profile generation) "Return boot parameters for PROFILE's system GENERATION." (let* ((gen-file (generation-file-name profile generation)) (param-file (string-append gen-file "/parameters"))) (call-with-input-file param-file read-boot-parameters))))) (define (system-generation-param-alist profile) "Return an alist of system generation parameters and procedures for PROFILE." (append (generation-param-alist profile) `((label . ,(lambda (gen) (boot-parameters-label (system-generation-boot-parameters profile gen)))) (root-device . ,(lambda (gen) (boot-parameters-root-device (system-generation-boot-parameters profile gen)))) (kernel . ,(lambda (gen) (boot-parameters-kernel (system-generation-boot-parameters profile gen))))))) (define (system-generation-sexps profile params search-type search-vals) "Return an alist with information about system generations." (let ((generations (find-generations profile search-type search-vals)) (->sexp (object-transformer (system-generation-param-alist profile) params))) (map ->sexp generations))) (define (entries profile params entry-type search-type search-vals) "Return information about entries. ENTRY-TYPE is a symbol defining a type of returning information. Should be: 'package', 'output' or 'generation'. SEARCH-TYPE and SEARCH-VALS define how to get the information. SEARCH-TYPE should be one of the following symbols: - If ENTRY-TYPE is 'package' or 'output': 'id', 'name', 'regexp', 'all-available', 'newest-available', 'installed', 'obsolete', 'generation'. - If ENTRY-TYPE is 'generation': 'id', 'last', 'all', 'time'. PARAMS is a list of parameters for receiving. If it is an empty list, get information with all available parameters, which are: - If ENTRY-TYPE is 'package': 'id', 'name', 'version', 'outputs', 'license', 'synopsis', 'description', 'home-url', 'inputs', 'native-inputs', 'propagated-inputs', 'location', 'installed'. - If ENTRY-TYPE is 'output': 'id', 'package-id', 'name', 'version', 'output', 'license', 'synopsis', 'description', 'home-url', 'inputs', 'native-inputs', 'propagated-inputs', 'location', 'installed', 'path', 'dependencies'. - If ENTRY-TYPE is 'generation': 'id', 'number', 'prev-number', 'path', 'time'. Returning value is a list of alists. Each alist consists of parameter/value pairs." (case entry-type ((package output) (package/output-sexps profile params entry-type search-type search-vals)) ((generation) (generation-sexps profile params search-type search-vals)) ((system-generation) (system-generation-sexps profile params search-type search-vals)) (else (entry-type-error entry-type)))) (define* (package->manifest-entry* package #:optional output) (and package (package->manifest-entry package output))) (define* (make-install-manifest-entries id #:optional output) (package->manifest-entry* (package-by-id id) output)) (define* (make-upgrade-manifest-entries id #:optional output) (package->manifest-entry* (newest-package-by-id id) output)) (define* (make-manifest-pattern id #:optional output) "Make manifest pattern from a package ID and OUTPUT." (let-values (((name version) (id->name+version id))) (and name version (manifest-pattern (name name) (version version) (output output))))) (define (convert-action-pattern pattern proc) "Convert action PATTERN into a list of objects returned by PROC. PROC is called: (PROC ID) or (PROC ID OUTPUT)." (match pattern ((id . outputs) (if (null? outputs) (let ((obj (proc id))) (if obj (list obj) '())) (filter-map (cut proc id <>) outputs))) (_ '()))) (define (convert-action-patterns patterns proc) (append-map (cut convert-action-pattern <> proc) patterns)) (define* (process-package-actions profile #:key (install '()) (upgrade '()) (remove '()) (use-substitutes? #t) dry-run?) "Perform package actions. INSTALL, UPGRADE, REMOVE are lists of 'package action patterns'. Each pattern should have the following form: (ID . OUTPUTS) ID is an object address or a full-name of a package. OUTPUTS is a list of package outputs (may be an empty list)." (format #t "The process begins ...~%") (let* ((install (append (convert-action-patterns install make-install-manifest-entries) (convert-action-patterns upgrade make-upgrade-manifest-entries))) (remove (convert-action-patterns remove make-manifest-pattern)) (transaction (manifest-transaction (install install) (remove remove))) (manifest (profile-manifest profile)) (new-manifest (manifest-perform-transaction manifest transaction))) (unless (and (null? install) (null? remove)) (with-store store (let* ((derivation (run-with-store store (mbegin %store-monad (set-guile-for-build (default-guile)) (profile-derivation new-manifest)))) (derivations (list derivation)) (new-profile (derivation->output-path derivation))) (set-build-options store #:print-build-trace #f #:use-substitutes? use-substitutes?) (show-manifest-transaction store manifest transaction #:dry-run? dry-run?) (show-what-to-build store derivations #:use-substitutes? use-substitutes? #:dry-run? dry-run?) (unless dry-run? (let ((name (generation-file-name profile (+ 1 (generation-number profile))))) (and (build-derivations store derivations) (let* ((entries (manifest-entries new-manifest)) (count (length entries))) (switch-symlinks name new-profile) (switch-symlinks profile name) (format #t (N_ "~a package in profile~%" "~a packages in profile~%" count) count) (display-search-paths entries (list profile))))))))))) (define (delete-generations* profile generations) "Delete GENERATIONS from PROFILE. GENERATIONS is a list of generation numbers." (with-store store (delete-generations store profile generations))) (define (package-location-string id-or-name) "Return a location string of a package with ID-OR-NAME." (and=> (or (package-by-id id-or-name) (match (packages-by-name id-or-name) (() #f) ((package _ ...) package))) (compose location->string package-location))) (define (package-source-derivation->store-path derivation) "Return a store path of the package source DERIVATION." (match (derivation-outputs derivation) (((_ . output-drv)) (derivation-output-path output-drv)) (_ #f))) (define (package-source-path package-id) "Return a store file path to a source of a package PACKAGE-ID." (and-let* ((package (package-by-id package-id)) (source (package-source package))) (with-store store (package-source-derivation->store-path (package-source-derivation store source))))) (define* (package-source-build-derivation package-id #:key dry-run? (use-substitutes? #t)) "Build source derivation of a package PACKAGE-ID." (and-let* ((package (package-by-id package-id)) (source (package-source package))) (with-store store (let* ((derivation (package-source-derivation store source)) (derivations (list derivation))) (set-build-options store #:print-build-trace #f #:use-substitutes? use-substitutes?) (show-what-to-build store derivations #:use-substitutes? use-substitutes? #:dry-run? dry-run?) (unless dry-run? (build-derivations store derivations)) (format #t "The source store path: ~a~%" (package-source-derivation->store-path derivation)))))) (define (guix-command . args) "Run 'guix ARGS ...' command." (catch 'quit (lambda () (apply run-guix args)) (const #t))) (define (guix-command-output . args) "Return 2 strings with 'guix ARGS ...' output and error output." (output+error (lambda () (parameterize ((guix-warning-port (current-error-port))) (apply guix-command args))))) (define (help-string . commands) "Return string with 'guix COMMANDS ... --help' output." (apply guix-command-output `(,@commands "--help"))) (define (pipe-guix-output guix-args command-args) "Run 'guix GUIX-ARGS ...' command and pipe its output to a shell command defined by COMMAND-ARGS. Return #t if the shell command was executed successfully." (let ((pipe (apply open-pipe* OPEN_WRITE command-args))) (with-output-to-port pipe (lambda () (apply guix-command guix-args))) (zero? (status:exit-val (close-pipe pipe))))) (define (graph-type-names) "Return a list of names of available graph node types." (map (@ (guix graph) node-type-name) (@ (guix scripts graph) %node-types))) (define (refresh-updater-names) "Return a list of names of available refresh updater types." (map (@ (guix upstream) upstream-updater-name) (@ (guix scripts refresh) %updaters))) (define (lint-checker-names) "Return a list of names of available lint checkers." (map (lambda (checker) (symbol->string (lint-checker-name checker))) %checkers)) (define (package-names) "Return a list of names of available packages." (delete-duplicates (fold-packages (lambda (pkg res) (cons (package-name pkg) res)) '()))) (define (package-names-lists) (map list (package-names))) (define %licenses (delay (filter license? (module-map (lambda (_ var) (variable-ref var)) (resolve-interface '(guix licenses)))))) (define (licenses) (force %licenses)) (define (license-names) "Return a list of names of available licenses." (map license-name (licenses))) (define lookup-license (memoize (lambda (name) "Return a license by its name." (find (lambda (l) (string=? name (license-name l))) (licenses))))) (define (lookup-license-uri name) "Return a license URI by its name." (and=> (lookup-license name) license-uri)) (define %license-param-alist `((id . ,license-name) (name . ,license-name) (url . ,license-uri) (comment . ,license-comment))) (define license->sexp (object-transformer %license-param-alist)) (define (find-licenses search-type . search-values) "Return a list of licenses depending on SEARCH-TYPE and SEARCH-VALUES." (case search-type ((id name) (let ((names search-values)) (filter-map lookup-license names))) ((all) (licenses)))) (define (license-entries search-type . search-values) (map license->sexp (apply find-licenses search-type search-values)))
ee4411786b7b457db6c97dd3c761e920fa76f0d713d64cd520cfb02b600c0410
bishboria/learnyouahaskell
8_reverse.hs
main = do line <- getLine if null line then return () else do putStrLn $ reverseWords line main reverseWords :: String -> String reverseWords = unwords . map reverse . words -- recursive function is ok because main is an IO action and the do block inside the else wraps two IO actions into one return in does not exit a function . It wraps a pure value in an IO action . Monad stuff again
null
https://raw.githubusercontent.com/bishboria/learnyouahaskell/d8c7b41398e9672db18c1b1360372fc4a4adefa8/08/8_reverse.hs
haskell
recursive function is ok because main is an IO action
main = do line <- getLine if null line then return () else do putStrLn $ reverseWords line main reverseWords :: String -> String reverseWords = unwords . map reverse . words and the do block inside the else wraps two IO actions into one return in does not exit a function . It wraps a pure value in an IO action . Monad stuff again
e1710722b567ecb95f630c2ca15cfae61c7cf7212ddd738f86c67ea46c5099f2
pirapira/coq2rust
cerrors.mli
(************************************************************************) v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * (* // * This file is distributed under the terms of the *) (* * GNU Lesser General Public License Version 2.1 *) (************************************************************************) (** Error report. *) val print_loc : Loc.t -> Pp.std_ppcmds * Pre - explain a interpretation error val process_vernac_interp_error : Util.iexn -> Util.iexn (** General explain function. Should not be used directly now, see instead function [Errors.print] and variants *) val explain_exn_default : exn -> Pp.std_ppcmds
null
https://raw.githubusercontent.com/pirapira/coq2rust/22e8aaefc723bfb324ca2001b2b8e51fcc923543/toplevel/cerrors.mli
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** * Error report. * General explain function. Should not be used directly now, see instead function [Errors.print] and variants
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2012 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * val print_loc : Loc.t -> Pp.std_ppcmds * Pre - explain a interpretation error val process_vernac_interp_error : Util.iexn -> Util.iexn val explain_exn_default : exn -> Pp.std_ppcmds
a9de9666267bb6ff75b128e1d51c01e8161927944ba3fcab73fe66e06235f0e0
nikodemus/SBCL
arith.pure.lisp
;;;; arithmetic tests with no side effects This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. (cl:in-package :cl-user) Once upon a time , in the process of porting CMUCL 's SPARC backend to SBCL , multiplications were excitingly broken . While it 's ;;; unlikely that anything with such fundamental arithmetic errors as ;;; these are going to get this far, it's probably worth checking. (macrolet ((test (op res1 res2) `(progn (assert (= (,op 4 2) ,res1)) (assert (= (,op 2 4) ,res2)) (assert (= (funcall (compile nil '(lambda (x y) (,op x y))) 4 2) ,res1)) (assert (= (funcall (compile nil '(lambda (x y) (,op x y))) 2 4) ,res2))))) (test + 6 6) (test - 2 -2) (test * 8 8) (test / 2 1/2) (test expt 16 16)) In a bug reported by on cmucl - imp 2002 - 06 - 18 ( BUG 184 ) , sbcl did n't catch all divisions by zero , notably divisions ;;; of bignums and ratios by 0. Fixed in sbcl-0.7.6.13. (assert (raises-error? (/ 2/3 0) division-by-zero)) (assert (raises-error? (/ (1+ most-positive-fixnum) 0) division-by-zero)) In a bug reported by on cmucl - imp 2002 - 07 - 18 , ( COERCE ;;; <RATIONAL> '(COMPLEX FLOAT)) was failing to return a complex float ; a patch was given by imp 2002 - 07 - 19 . (assert (= (coerce 1 '(complex float)) #c(1.0 0.0))) (assert (= (coerce 1/2 '(complex float)) #c(0.5 0.0))) (assert (= (coerce 1.0d0 '(complex float)) #c(1.0d0 0.0d0))) ;;; (COERCE #c(<RATIONAL> <RATIONAL>) '(complex float)) resulted in an error up to 0.8.17.31 (assert (= (coerce #c(1 2) '(complex float)) #c(1.0 2.0))) COERCE also sometimes failed to verify that a particular coercion ;;; was possible (in particular coercing rationals to bounded float ;;; types. (assert (raises-error? (coerce 1 '(float 2.0 3.0)) type-error)) (assert (raises-error? (coerce 1 '(single-float -1.0 0.0)) type-error)) (assert (eql (coerce 1 '(single-float -1.0 2.0)) 1.0)) ANSI says MIN and MAX should signal TYPE - ERROR if any argument is n't REAL . SBCL 0.7.7 did n't in the 1 - arg case . ( reported as a bug in CMU CL on # lisp IRC by lrasinen 2002 - 09 - 01 ) (assert (null (ignore-errors (min '(1 2 3))))) (assert (= (min -1) -1)) (assert (null (ignore-errors (min 1 #(1 2 3))))) (assert (= (min 10 11) 10)) (assert (null (ignore-errors (min (find-package "CL") -5.0)))) (assert (= (min 5.0 -3) -3)) (assert (null (ignore-errors (max #c(4 3))))) (assert (= (max 0) 0)) (assert (null (ignore-errors (max "MIX" 3)))) (assert (= (max -1 10.0) 10.0)) (assert (null (ignore-errors (max 3 #'max)))) (assert (= (max -3 0) 0)) ( CEILING x 2^k ) was optimized incorrectly (loop for divisor in '(-4 4) for ceiler = (compile nil `(lambda (x) (declare (fixnum x)) (declare (optimize (speed 3))) (ceiling x ,divisor))) do (loop for i from -5 to 5 for exact-q = (/ i divisor) do (multiple-value-bind (q r) (funcall ceiler i) (assert (= (+ (* q divisor) r) i)) (assert (<= exact-q q)) (assert (< q (1+ exact-q)))))) ( TRUNCATE x 2^k ) was optimized incorrectly (loop for divisor in '(-4 4) for truncater = (compile nil `(lambda (x) (declare (fixnum x)) (declare (optimize (speed 3))) (truncate x ,divisor))) do (loop for i from -9 to 9 for exact-q = (/ i divisor) do (multiple-value-bind (q r) (funcall truncater i) (assert (= (+ (* q divisor) r) i)) (assert (<= (abs q) (abs exact-q))) (assert (< (abs exact-q) (1+ (abs q))))))) CEILING had a corner case , spotted by (assert (= (ceiling most-negative-fixnum (1+ most-positive-fixnum)) -1)) ;;; give any optimizers of constant multiplication a light testing. 100 may seem low , but ( a ) it caught CSR 's initial errors , and ( b ) before checking in , CSR tested with 10000 . So one hundred ;;; checkins later, we'll have doubled the coverage. (dotimes (i 100) (let* ((x (random most-positive-fixnum)) (x2 (* x 2)) (x3 (* x 3))) (let ((fn (handler-bind ((sb-ext:compiler-note (lambda (c) (when (<= x3 most-positive-fixnum) (error c))))) (compile nil `(lambda (y) (declare (optimize speed) (type (integer 0 3) y)) (* y ,x)))))) (unless (and (= (funcall fn 0) 0) (= (funcall fn 1) x) (= (funcall fn 2) x2) (= (funcall fn 3) x3)) (error "bad results for ~D" x))))) Bugs reported by : ;;; (GCD 0 x) must return (abs x) (dolist (x (list -10 (* 3 most-negative-fixnum))) (assert (= (gcd 0 x) (abs x)))) LCM returns a non - negative number (assert (= (lcm 4 -10) 20)) (assert (= (lcm 0 0) 0)) ;;; PPC bignum arithmetic bug: (multiple-value-bind (quo rem) (truncate 291351647815394962053040658028983955 10000000000000000000000000) (assert (= quo 29135164781)) (assert (= rem 5394962053040658028983955))) x86 bug : (assert (= (funcall (compile nil '(lambda (x) (declare (bit x)) (+ x #xf0000000))) 1) #xf0000001)) LOGBITP on bignums : (dolist (x '(((1+ most-positive-fixnum) 1 nil) ((1+ most-positive-fixnum) -1 t) ((1+ most-positive-fixnum) (1+ most-positive-fixnum) nil) ((1+ most-positive-fixnum) (1- most-negative-fixnum) t) (1 (ash most-negative-fixnum 1) nil) (#.(- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1) most-negative-fixnum t) (#.(1+ (- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1)) (ash most-negative-fixnum 1) t) (#.(+ 2 (- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1)) (ash most-negative-fixnum 1) t) (#.(+ sb-vm:n-word-bits 32) (ash most-negative-fixnum #.(+ 32 sb-vm:n-fixnum-tag-bits 2)) nil) (#.(+ sb-vm:n-word-bits 33) (ash most-negative-fixnum #.(+ 32 sb-vm:n-fixnum-tag-bits 2)) t))) (destructuring-bind (index int result) x (assert (eq (eval `(logbitp ,index ,int)) result)))) off - by-1 type inference error for % and % DEPOSIT - FIELD : (let ((f (compile nil '(lambda (b) (integer-length (dpb b (byte 4 28) -1005)))))) (assert (= (funcall f 1230070) 32))) (let ((f (compile nil '(lambda (b) (integer-length (deposit-field b (byte 4 28) -1005)))))) (assert (= (funcall f 1230070) 32))) ;;; type inference leading to an internal compiler error: (let ((f (compile nil '(lambda (x) (declare (type fixnum x)) (ldb (byte 0 0) x))))) (assert (= (funcall f 1) 0)) (assert (= (funcall f most-positive-fixnum) 0)) (assert (= (funcall f -1) 0))) ;;; Alpha bignum arithmetic bug: (assert (= (* 966082078641 419216044685) 404997107848943140073085)) ;;; Alpha smallnum arithmetic bug: (assert (= (ash -129876 -1026) -1)) Alpha middlenum ( yes , really ! Affecting numbers between 2 ^ 32 and 2 ^ 64 :) arithmetic bug (let ((fn (compile nil '(LAMBDA (A B C D) (DECLARE (TYPE (INTEGER -1621 -513) A) (TYPE (INTEGER -3 34163) B) (TYPE (INTEGER -9485132993 81272960) C) (TYPE (INTEGER -255340814 519943) D) (IGNORABLE A B C D) (OPTIMIZE (SPEED 3) (SAFETY 1) (DEBUG 1))) (TRUNCATE C (MIN -100 4149605)))))) (assert (= (funcall fn -1332 5864 -6963328729 -43789079) 69633287))) Here 's another fantastic Alpha backend bug : the code to load immediate 64 - bit constants into a register was wrong . (let ((fn (compile nil '(LAMBDA (A B C D) (DECLARE (TYPE (INTEGER -3563 2733564) A) (TYPE (INTEGER -548947 7159) B) (TYPE (INTEGER -19 0) C) (TYPE (INTEGER -2546009 0) D) (IGNORABLE A B C D) (OPTIMIZE (SPEED 3) (SAFETY 1) (DEBUG 1))) (CASE A ((89 125 16) (ASH A (MIN 18 -706))) (T (DPB -3 (BYTE 30 30) -1))))))) (assert (= (funcall fn 1227072 -529823 -18 -792831) -2147483649))) ASH of a negative bignum by a bignum count would erroneously return 0 prior to (assert (= (ash (1- most-negative-fixnum) (1- most-negative-fixnum)) -1)) Whoops . Too much optimization in division operators for 0 ;;; divisor. (macrolet ((frob (name) `(let ((fn (compile nil '(lambda (x) (declare (optimize speed) (fixnum x)) (,name x 0))))) (assert (raises-error? (funcall fn 1) division-by-zero))))) (frob mod) (frob truncate) (frob rem) (frob /) (frob floor) (frob ceiling)) Check that the logic in SB - KERNEL::BASIC - COMPARE for doing fixnum / float ;; comparisons without rationalizing the floats still gives the right anwers ;; in the edge cases (had a fencepost error). (macrolet ((test (range type sign) `(let (ints floats (start (- ,(find-symbol (format nil "MOST-~A-EXACTLY-~A-FIXNUM" sign type) :sb-kernel) ,range))) (dotimes (i (1+ (* ,range 2))) (let* ((x (+ start i)) (y (coerce x ',type))) (push x ints) (push y floats))) (dolist (i ints) (dolist (f floats) (dolist (op '(< <= = >= >)) (unless (eq (funcall op i f) (funcall op i (rationalize f))) (error "(not (eq (~a ~a ~f) (~a ~a ~a)))~%" op i f op i (rationalize f))) (unless (eq (funcall op f i) (funcall op (rationalize f) i)) (error "(not (eq (~a ~f ~a) (~a ~a ~a)))~%" op f i op (rationalize f) i)))))))) (test 32 double-float negative) (test 32 double-float positive) (test 32 single-float negative) (test 32 single-float positive)) x86 - 64 sign - extension bug found using pfdietz 's random tester . (assert (= 286142502 (funcall (lambda () (declare (notinline logxor)) (min (logxor 0 0 0 286142502)))))) Small bugs in LOGCOUNT can still allow SBCL to be built and thus go ;; unnoticed, so check more thoroughly here. (with-test (:name :logcount) (flet ((test (x n) (unless (= (logcount x) n) (error "logcount failure for ~a" x)))) ;; Test with some patterns with well known number of ones/zeroes ... (dotimes (i 128) (let ((x (ash 1 i))) (test x 1) (test (- x) i) (test (1- x) i))) ;; ... and with some random integers of varying length. (flet ((test-logcount (x) (declare (type integer x)) (do ((result 0 (1+ result)) (x (if (minusp x) (lognot x) x) (logand x (1- x)))) ((zerop x) result)))) (dotimes (i 200) (let ((x (random (ash 1 i)))) (test x (test-logcount x)) (test (- x) (test-logcount (- x)))))))) 1.0 had a broken ATANH on win32 (with-test (:name :atanh) (assert (= (atanh 0.9d0) 1.4722194895832204d0))) ;; Test some cases of integer operations with constant arguments (with-test (:name :constant-integers) (labels ((test-forms (op x y header &rest forms) (let ((val (funcall op x y))) (dolist (form forms) (let ((new-val (funcall (compile nil (append header form)) x y))) (unless (eql val new-val) (error "~S /= ~S: ~S ~S ~S~%" val new-val (append header form) x y)))))) (test-case (op x y type) (test-forms op x y `(lambda (x y &aux z) (declare (type ,type x y) (ignorable x y z) (notinline identity) (optimize speed (safety 0)))) `((,op x ,y)) `((setf z (,op x ,y)) (identity x) z) `((values (,op x ,y) x)) `((,op ,x y)) `((setf z (,op ,x y)) (identity y) z) `((values (,op ,x y) y)) `((identity x) (,op x ,y)) `((identity x) (setf z (,op x ,y)) (identity x) z) `((identity x) (values (,op x ,y) x)) `((identity y) (,op ,x y)) `((identity y) (setf z (,op ,x y)) (identity y) z) `((identity y) (values (,op ,x y) y)))) (test-op (op) (let ((ub `(unsigned-byte ,sb-vm:n-word-bits)) (sb `(signed-byte ,sb-vm:n-word-bits))) (loop for (x y type) in `((2 1 fixnum) (2 1 ,ub) (2 1 ,sb) (,(1+ (ash 1 28)) ,(1- (ash 1 28)) fixnum) (,(+ 3 (ash 1 30)) ,(+ 2 (ash 1 30)) ,ub) (,(- -2 (ash 1 29)) ,(- 3 (ash 1 29)) ,sb) ,@(when (> sb-vm:n-word-bits 32) `((,(1+ (ash 1 29)) ,(1- (ash 1 29)) fixnum) (,(1+ (ash 1 31)) ,(1- (ash 1 31)) ,ub) (,(- -2 (ash 1 31)) ,(- 3 (ash 1 30)) ,sb) (,(ash 1 40) ,(ash 1 39) fixnum) (,(ash 1 40) ,(ash 1 39) ,ub) (,(ash 1 40) ,(ash 1 39) ,sb))) fixnums that can be represented as 32 - bit ;; sign-extended immediates on x86-64 ,@(when (and (> sb-vm:n-word-bits 32) (< sb-vm:n-fixnum-tag-bits 3)) `((,(1+ (ash 1 (- 31 sb-vm:n-fixnum-tag-bits))) ,(1- (ash 1 (- 32 sb-vm:n-fixnum-tag-bits))) fixnum)))) do (test-case op x y type) (test-case op x x type))))) (mapc #'test-op '(+ - * truncate < <= = >= > eql eq)))) GCD used to sometimes return negative values . The following did , on 32 bit ;; builds. (with-test (:name :gcd) ;; from lp#413680 (assert (plusp (gcd 20286123923750474264166990598656 680564733841876926926749214863536422912))) from lp#516750 (assert (plusp (gcd 2596102012663483082521318626691873 2596148429267413814265248164610048)))) (with-test (:name :expt-zero-zero) Check that ( expt 0.0 0.0 ) and ( expt 0 0.0 ) signal error , but ( expt 0.0 0 ) returns 1.0 (assert (raises-error? (expt 0.0 0.0) sb-int:arguments-out-of-domain-error)) (assert (raises-error? (expt 0 0.0) sb-int:arguments-out-of-domain-error)) (assert (eql (expt 0.0 0) 1.0))) (with-test (:name :multiple-constant-folding) (let ((*random-state* (make-random-state t))) (flet ((make-args () (let (args vars) (loop repeat (1+ (random 12)) do (if (zerop (random 2)) (let ((var (gensym))) (push var args) (push var vars)) (push (- (random 21) 10) args))) (values args vars)))) (dolist (op '(+ * logior logxor logand logeqv gcd lcm - /)) (loop repeat 10 do (multiple-value-bind (args vars) (make-args) (let ((fast (compile nil `(lambda ,vars (,op ,@args)))) (slow (compile nil `(lambda ,vars (declare (notinline ,op)) (,op ,@args))))) (loop repeat 3 do (let* ((call-args (loop repeat (length vars) collect (- (random 21) 10))) (fast-result (handler-case (apply fast call-args) (division-by-zero () :div0))) (slow-result (handler-case (apply slow call-args) (division-by-zero () :div0)))) (if (eql fast-result slow-result) (print (list :ok `(,op ,@args) :=> fast-result)) (error "oops: ~S, ~S" args call-args))))))))))) ;;; (TRUNCATE <unsigned-word> <constant unsigned-word>) is optimized ;;; to use multiplication instead of division. This propagates to FLOOR, ;;; MOD and REM. Test that the transform is indeed triggered and test ;;; several cases for correct results. (with-test (:name (:integer-division-using-multiplication :used) :skipped-on '(not (or :x86-64 :x86))) (dolist (fun '(truncate floor ceiling mod rem)) (let* ((foo (compile nil `(lambda (x) (declare (optimize (speed 3) (space 1) (compilation-speed 0)) (type (unsigned-byte ,sb-vm:n-word-bits) x)) (,fun x 9)))) (disassembly (with-output-to-string (s) (disassemble foo :stream s)))) copied from test : float - division - using - exact - reciprocal in compiler.pure.lisp . (assert (and (not (search "DIV" disassembly)) (search "MUL" disassembly)))))) (with-test (:name (:integer-division-using-multiplication :correctness)) (let ((*random-state* (make-random-state t))) (dolist (dividend-type `((unsigned-byte ,sb-vm:n-word-bits) (and fixnum unsigned-byte) (integer 10000 10100))) (dolist (divisor `(;; Some special cases from the paper 7 10 14 641 274177 ;; Range extremes 3 ,most-positive-fixnum ,(1- (expt 2 sb-vm:n-word-bits)) ;; Some random values ,@(loop for i from 8 to sb-vm:n-word-bits for r = (random (expt 2 i)) We do n't want 0 , 1 and powers of 2 . when (not (zerop (logand r (1- r)))) collect r))) (dolist (fun '(truncate ceiling floor mod rem)) (let ((foo (compile nil `(lambda (x) (declare (optimize (speed 3) (space 1) (compilation-speed 0)) (type ,dividend-type x)) (,fun x ,divisor))))) (dolist (dividend `(0 1 ,most-positive-fixnum ,(1- divisor) ,divisor ,(1- (* divisor 2)) ,(* divisor 2) ,@(loop repeat 4 collect (+ 10000 (random 101))) ,@(loop for i from 4 to sb-vm:n-word-bits for pow = (expt 2 (1- i)) for r = (+ pow (random pow)) collect r))) (when (typep dividend dividend-type) (multiple-value-bind (q1 r1) (funcall foo dividend) (multiple-value-bind (q2 r2) (funcall fun dividend divisor) (unless (and (= q1 q2) (eql r1 r2)) (error "bad results for ~s with dividend type ~s" (list fun dividend divisor) dividend-type)))))))))))) The fast path for logbitp underestimated sb!vm : n - positive - fixnum - bits for > 61 bit fixnums . (with-test (:name :logbitp-wide-fixnum) (assert (not (logbitp (1- (integer-length most-positive-fixnum)) most-negative-fixnum)))) ;; EXPT dispatches in a complicated way on the types of its arguments. ;; Check that all possible combinations are covered. (with-test (:name (:expt :argument-type-combinations)) (let ((numbers '(2 ; fixnum 3/5 ; ratio 1.2f0 ; single-float 2.0d0 ; double-float #c(3/5 1/7) ; complex rational #c(1.2f0 1.3f0) ; complex single-float #c(2.0d0 3.0d0))) ; complex double-float (bignum (expt 2 64)) results) (dolist (base (cons bignum numbers)) (dolist (power numbers) (format t "(expt ~s ~s) => " base power) (let ((result (expt base power))) (format t "~s~%" result) (push result results)))) (assert (every #'numberp results)))) (with-test (:name :bug-741564) ;; The bug was that in (expt <fixnum> <(complex double-float)>) the ;; calculation was partially done only to single-float precision, ;; making the complex double-float result too unprecise. Some other ;; combinations of argument types were affected, too; test that all ;; of them are good to double-float precision. (labels ((nearly-equal-p (x y) "Are the arguments equal to nearly double-float precision?" (declare (type double-float x y)) (< (/ (abs (- x y)) (abs y)) Differences in the two least ; significant mantissa bits ; are OK. (test-complex (x y) (and (nearly-equal-p (realpart x) (realpart y)) (nearly-equal-p (imagpart x) (imagpart y)))) (print-result (msg base power got expected) (format t "~a (expt ~s ~s)~%got ~s~%expected ~s~%" msg base power got expected))) (let ((n-broken 0)) (flet ((test (base power coerce-to-type) (let* ((got (expt base power)) (expected (expt (coerce base coerce-to-type) power)) (result (test-complex got expected))) (print-result (if result "Good:" "Bad:") base power got expected) (unless result (incf n-broken))))) (dolist (base (list 2 ; fixnum (expt 2 64) ; bignum 3/5 ; ratio 2.0f0)) ; single-float (let ((power #c(-2.5d0 -4.5d0))) ; complex double-float (test base power 'double-float))) (dolist (base (list #c(2.0f0 3.0f0) ; complex single-float #c(2 3) ; complex fixnum (complex (expt 2 64) (expt 2 65)) ; complex bignum #c(3/5 1/7))) ; complex ratio (dolist (power (list #c(-2.5d0 -4.5d0) ; complex double-float -2.5d0)) ; double-float (test base power '(complex double-float))))) (when (> n-broken 0) (error "Number of broken combinations: ~a" n-broken))))) (with-test (:name (:ldb :rlwinm :ppc)) (let ((one (compile nil '(lambda (a) (ldb (byte 9 27) a)))) (two (compile nil '(lambda (a) (declare (type (integer -3 57216651) a)) (ldb (byte 9 27) a))))) (assert (= 0 (- (funcall one 10) (funcall two 10)))))) The ISQRT implementation is sufficiently complicated that it should ;; be tested. (with-test (:name :isqrt) (labels ((test (x) (let* ((r (isqrt x)) (r2 (expt r 2)) (s2 (expt (1+ r) 2))) (unless (and (<= r2 x) (> s2 x)) (error "isqrt failure for ~a" x)))) (tests (x) (test x) (let ((x2 (expt x 2))) (test x2) (test (1+ x2)) (test (1- x2))))) (loop for i from 1 to 200 for pow = (expt 2 (1- i)) for j = (+ pow (random pow)) do (tests i) (tests j)) (dotimes (i 10) (tests (random (expt 2 (+ 1000 (random 10000))))))))
null
https://raw.githubusercontent.com/nikodemus/SBCL/3c11847d1e12db89b24a7887b18a137c45ed4661/tests/arith.pure.lisp
lisp
arithmetic tests with no side effects more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. unlikely that anything with such fundamental arithmetic errors as these are going to get this far, it's probably worth checking. of bignums and ratios by 0. Fixed in sbcl-0.7.6.13. <RATIONAL> '(COMPLEX FLOAT)) was failing to return a complex a patch was given by imp 2002 - 07 - 19 . (COERCE #c(<RATIONAL> <RATIONAL>) '(complex float)) resulted in was possible (in particular coercing rationals to bounded float types. give any optimizers of constant multiplication a light testing. checkins later, we'll have doubled the coverage. (GCD 0 x) must return (abs x) PPC bignum arithmetic bug: type inference leading to an internal compiler error: Alpha bignum arithmetic bug: Alpha smallnum arithmetic bug: divisor. comparisons without rationalizing the floats still gives the right anwers in the edge cases (had a fencepost error). unnoticed, so check more thoroughly here. Test with some patterns with well known number of ones/zeroes ... ... and with some random integers of varying length. Test some cases of integer operations with constant arguments sign-extended immediates on x86-64 builds. from lp#413680 (TRUNCATE <unsigned-word> <constant unsigned-word>) is optimized to use multiplication instead of division. This propagates to FLOOR, MOD and REM. Test that the transform is indeed triggered and test several cases for correct results. Some special cases from the paper Range extremes Some random values EXPT dispatches in a complicated way on the types of its arguments. Check that all possible combinations are covered. fixnum ratio single-float double-float complex rational complex single-float complex double-float The bug was that in (expt <fixnum> <(complex double-float)>) the calculation was partially done only to single-float precision, making the complex double-float result too unprecise. Some other combinations of argument types were affected, too; test that all of them are good to double-float precision. significant mantissa bits are OK. fixnum bignum ratio single-float complex double-float complex single-float complex fixnum complex bignum complex ratio complex double-float double-float be tested.
This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . (cl:in-package :cl-user) Once upon a time , in the process of porting CMUCL 's SPARC backend to SBCL , multiplications were excitingly broken . While it 's (macrolet ((test (op res1 res2) `(progn (assert (= (,op 4 2) ,res1)) (assert (= (,op 2 4) ,res2)) (assert (= (funcall (compile nil '(lambda (x y) (,op x y))) 4 2) ,res1)) (assert (= (funcall (compile nil '(lambda (x y) (,op x y))) 2 4) ,res2))))) (test + 6 6) (test - 2 -2) (test * 8 8) (test / 2 1/2) (test expt 16 16)) In a bug reported by on cmucl - imp 2002 - 06 - 18 ( BUG 184 ) , sbcl did n't catch all divisions by zero , notably divisions (assert (raises-error? (/ 2/3 0) division-by-zero)) (assert (raises-error? (/ (1+ most-positive-fixnum) 0) division-by-zero)) In a bug reported by on cmucl - imp 2002 - 07 - 18 , ( COERCE (assert (= (coerce 1 '(complex float)) #c(1.0 0.0))) (assert (= (coerce 1/2 '(complex float)) #c(0.5 0.0))) (assert (= (coerce 1.0d0 '(complex float)) #c(1.0d0 0.0d0))) an error up to 0.8.17.31 (assert (= (coerce #c(1 2) '(complex float)) #c(1.0 2.0))) COERCE also sometimes failed to verify that a particular coercion (assert (raises-error? (coerce 1 '(float 2.0 3.0)) type-error)) (assert (raises-error? (coerce 1 '(single-float -1.0 0.0)) type-error)) (assert (eql (coerce 1 '(single-float -1.0 2.0)) 1.0)) ANSI says MIN and MAX should signal TYPE - ERROR if any argument is n't REAL . SBCL 0.7.7 did n't in the 1 - arg case . ( reported as a bug in CMU CL on # lisp IRC by lrasinen 2002 - 09 - 01 ) (assert (null (ignore-errors (min '(1 2 3))))) (assert (= (min -1) -1)) (assert (null (ignore-errors (min 1 #(1 2 3))))) (assert (= (min 10 11) 10)) (assert (null (ignore-errors (min (find-package "CL") -5.0)))) (assert (= (min 5.0 -3) -3)) (assert (null (ignore-errors (max #c(4 3))))) (assert (= (max 0) 0)) (assert (null (ignore-errors (max "MIX" 3)))) (assert (= (max -1 10.0) 10.0)) (assert (null (ignore-errors (max 3 #'max)))) (assert (= (max -3 0) 0)) ( CEILING x 2^k ) was optimized incorrectly (loop for divisor in '(-4 4) for ceiler = (compile nil `(lambda (x) (declare (fixnum x)) (declare (optimize (speed 3))) (ceiling x ,divisor))) do (loop for i from -5 to 5 for exact-q = (/ i divisor) do (multiple-value-bind (q r) (funcall ceiler i) (assert (= (+ (* q divisor) r) i)) (assert (<= exact-q q)) (assert (< q (1+ exact-q)))))) ( TRUNCATE x 2^k ) was optimized incorrectly (loop for divisor in '(-4 4) for truncater = (compile nil `(lambda (x) (declare (fixnum x)) (declare (optimize (speed 3))) (truncate x ,divisor))) do (loop for i from -9 to 9 for exact-q = (/ i divisor) do (multiple-value-bind (q r) (funcall truncater i) (assert (= (+ (* q divisor) r) i)) (assert (<= (abs q) (abs exact-q))) (assert (< (abs exact-q) (1+ (abs q))))))) CEILING had a corner case , spotted by (assert (= (ceiling most-negative-fixnum (1+ most-positive-fixnum)) -1)) 100 may seem low , but ( a ) it caught CSR 's initial errors , and ( b ) before checking in , CSR tested with 10000 . So one hundred (dotimes (i 100) (let* ((x (random most-positive-fixnum)) (x2 (* x 2)) (x3 (* x 3))) (let ((fn (handler-bind ((sb-ext:compiler-note (lambda (c) (when (<= x3 most-positive-fixnum) (error c))))) (compile nil `(lambda (y) (declare (optimize speed) (type (integer 0 3) y)) (* y ,x)))))) (unless (and (= (funcall fn 0) 0) (= (funcall fn 1) x) (= (funcall fn 2) x2) (= (funcall fn 3) x3)) (error "bad results for ~D" x))))) Bugs reported by : (dolist (x (list -10 (* 3 most-negative-fixnum))) (assert (= (gcd 0 x) (abs x)))) LCM returns a non - negative number (assert (= (lcm 4 -10) 20)) (assert (= (lcm 0 0) 0)) (multiple-value-bind (quo rem) (truncate 291351647815394962053040658028983955 10000000000000000000000000) (assert (= quo 29135164781)) (assert (= rem 5394962053040658028983955))) x86 bug : (assert (= (funcall (compile nil '(lambda (x) (declare (bit x)) (+ x #xf0000000))) 1) #xf0000001)) LOGBITP on bignums : (dolist (x '(((1+ most-positive-fixnum) 1 nil) ((1+ most-positive-fixnum) -1 t) ((1+ most-positive-fixnum) (1+ most-positive-fixnum) nil) ((1+ most-positive-fixnum) (1- most-negative-fixnum) t) (1 (ash most-negative-fixnum 1) nil) (#.(- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1) most-negative-fixnum t) (#.(1+ (- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1)) (ash most-negative-fixnum 1) t) (#.(+ 2 (- sb-vm:n-word-bits sb-vm:n-fixnum-tag-bits 1)) (ash most-negative-fixnum 1) t) (#.(+ sb-vm:n-word-bits 32) (ash most-negative-fixnum #.(+ 32 sb-vm:n-fixnum-tag-bits 2)) nil) (#.(+ sb-vm:n-word-bits 33) (ash most-negative-fixnum #.(+ 32 sb-vm:n-fixnum-tag-bits 2)) t))) (destructuring-bind (index int result) x (assert (eq (eval `(logbitp ,index ,int)) result)))) off - by-1 type inference error for % and % DEPOSIT - FIELD : (let ((f (compile nil '(lambda (b) (integer-length (dpb b (byte 4 28) -1005)))))) (assert (= (funcall f 1230070) 32))) (let ((f (compile nil '(lambda (b) (integer-length (deposit-field b (byte 4 28) -1005)))))) (assert (= (funcall f 1230070) 32))) (let ((f (compile nil '(lambda (x) (declare (type fixnum x)) (ldb (byte 0 0) x))))) (assert (= (funcall f 1) 0)) (assert (= (funcall f most-positive-fixnum) 0)) (assert (= (funcall f -1) 0))) (assert (= (* 966082078641 419216044685) 404997107848943140073085)) (assert (= (ash -129876 -1026) -1)) Alpha middlenum ( yes , really ! Affecting numbers between 2 ^ 32 and 2 ^ 64 :) arithmetic bug (let ((fn (compile nil '(LAMBDA (A B C D) (DECLARE (TYPE (INTEGER -1621 -513) A) (TYPE (INTEGER -3 34163) B) (TYPE (INTEGER -9485132993 81272960) C) (TYPE (INTEGER -255340814 519943) D) (IGNORABLE A B C D) (OPTIMIZE (SPEED 3) (SAFETY 1) (DEBUG 1))) (TRUNCATE C (MIN -100 4149605)))))) (assert (= (funcall fn -1332 5864 -6963328729 -43789079) 69633287))) Here 's another fantastic Alpha backend bug : the code to load immediate 64 - bit constants into a register was wrong . (let ((fn (compile nil '(LAMBDA (A B C D) (DECLARE (TYPE (INTEGER -3563 2733564) A) (TYPE (INTEGER -548947 7159) B) (TYPE (INTEGER -19 0) C) (TYPE (INTEGER -2546009 0) D) (IGNORABLE A B C D) (OPTIMIZE (SPEED 3) (SAFETY 1) (DEBUG 1))) (CASE A ((89 125 16) (ASH A (MIN 18 -706))) (T (DPB -3 (BYTE 30 30) -1))))))) (assert (= (funcall fn 1227072 -529823 -18 -792831) -2147483649))) ASH of a negative bignum by a bignum count would erroneously return 0 prior to (assert (= (ash (1- most-negative-fixnum) (1- most-negative-fixnum)) -1)) Whoops . Too much optimization in division operators for 0 (macrolet ((frob (name) `(let ((fn (compile nil '(lambda (x) (declare (optimize speed) (fixnum x)) (,name x 0))))) (assert (raises-error? (funcall fn 1) division-by-zero))))) (frob mod) (frob truncate) (frob rem) (frob /) (frob floor) (frob ceiling)) Check that the logic in SB - KERNEL::BASIC - COMPARE for doing fixnum / float (macrolet ((test (range type sign) `(let (ints floats (start (- ,(find-symbol (format nil "MOST-~A-EXACTLY-~A-FIXNUM" sign type) :sb-kernel) ,range))) (dotimes (i (1+ (* ,range 2))) (let* ((x (+ start i)) (y (coerce x ',type))) (push x ints) (push y floats))) (dolist (i ints) (dolist (f floats) (dolist (op '(< <= = >= >)) (unless (eq (funcall op i f) (funcall op i (rationalize f))) (error "(not (eq (~a ~a ~f) (~a ~a ~a)))~%" op i f op i (rationalize f))) (unless (eq (funcall op f i) (funcall op (rationalize f) i)) (error "(not (eq (~a ~f ~a) (~a ~a ~a)))~%" op f i op (rationalize f) i)))))))) (test 32 double-float negative) (test 32 double-float positive) (test 32 single-float negative) (test 32 single-float positive)) x86 - 64 sign - extension bug found using pfdietz 's random tester . (assert (= 286142502 (funcall (lambda () (declare (notinline logxor)) (min (logxor 0 0 0 286142502)))))) Small bugs in LOGCOUNT can still allow SBCL to be built and thus go (with-test (:name :logcount) (flet ((test (x n) (unless (= (logcount x) n) (error "logcount failure for ~a" x)))) (dotimes (i 128) (let ((x (ash 1 i))) (test x 1) (test (- x) i) (test (1- x) i))) (flet ((test-logcount (x) (declare (type integer x)) (do ((result 0 (1+ result)) (x (if (minusp x) (lognot x) x) (logand x (1- x)))) ((zerop x) result)))) (dotimes (i 200) (let ((x (random (ash 1 i)))) (test x (test-logcount x)) (test (- x) (test-logcount (- x)))))))) 1.0 had a broken ATANH on win32 (with-test (:name :atanh) (assert (= (atanh 0.9d0) 1.4722194895832204d0))) (with-test (:name :constant-integers) (labels ((test-forms (op x y header &rest forms) (let ((val (funcall op x y))) (dolist (form forms) (let ((new-val (funcall (compile nil (append header form)) x y))) (unless (eql val new-val) (error "~S /= ~S: ~S ~S ~S~%" val new-val (append header form) x y)))))) (test-case (op x y type) (test-forms op x y `(lambda (x y &aux z) (declare (type ,type x y) (ignorable x y z) (notinline identity) (optimize speed (safety 0)))) `((,op x ,y)) `((setf z (,op x ,y)) (identity x) z) `((values (,op x ,y) x)) `((,op ,x y)) `((setf z (,op ,x y)) (identity y) z) `((values (,op ,x y) y)) `((identity x) (,op x ,y)) `((identity x) (setf z (,op x ,y)) (identity x) z) `((identity x) (values (,op x ,y) x)) `((identity y) (,op ,x y)) `((identity y) (setf z (,op ,x y)) (identity y) z) `((identity y) (values (,op ,x y) y)))) (test-op (op) (let ((ub `(unsigned-byte ,sb-vm:n-word-bits)) (sb `(signed-byte ,sb-vm:n-word-bits))) (loop for (x y type) in `((2 1 fixnum) (2 1 ,ub) (2 1 ,sb) (,(1+ (ash 1 28)) ,(1- (ash 1 28)) fixnum) (,(+ 3 (ash 1 30)) ,(+ 2 (ash 1 30)) ,ub) (,(- -2 (ash 1 29)) ,(- 3 (ash 1 29)) ,sb) ,@(when (> sb-vm:n-word-bits 32) `((,(1+ (ash 1 29)) ,(1- (ash 1 29)) fixnum) (,(1+ (ash 1 31)) ,(1- (ash 1 31)) ,ub) (,(- -2 (ash 1 31)) ,(- 3 (ash 1 30)) ,sb) (,(ash 1 40) ,(ash 1 39) fixnum) (,(ash 1 40) ,(ash 1 39) ,ub) (,(ash 1 40) ,(ash 1 39) ,sb))) fixnums that can be represented as 32 - bit ,@(when (and (> sb-vm:n-word-bits 32) (< sb-vm:n-fixnum-tag-bits 3)) `((,(1+ (ash 1 (- 31 sb-vm:n-fixnum-tag-bits))) ,(1- (ash 1 (- 32 sb-vm:n-fixnum-tag-bits))) fixnum)))) do (test-case op x y type) (test-case op x x type))))) (mapc #'test-op '(+ - * truncate < <= = >= > eql eq)))) GCD used to sometimes return negative values . The following did , on 32 bit (with-test (:name :gcd) (assert (plusp (gcd 20286123923750474264166990598656 680564733841876926926749214863536422912))) from lp#516750 (assert (plusp (gcd 2596102012663483082521318626691873 2596148429267413814265248164610048)))) (with-test (:name :expt-zero-zero) Check that ( expt 0.0 0.0 ) and ( expt 0 0.0 ) signal error , but ( expt 0.0 0 ) returns 1.0 (assert (raises-error? (expt 0.0 0.0) sb-int:arguments-out-of-domain-error)) (assert (raises-error? (expt 0 0.0) sb-int:arguments-out-of-domain-error)) (assert (eql (expt 0.0 0) 1.0))) (with-test (:name :multiple-constant-folding) (let ((*random-state* (make-random-state t))) (flet ((make-args () (let (args vars) (loop repeat (1+ (random 12)) do (if (zerop (random 2)) (let ((var (gensym))) (push var args) (push var vars)) (push (- (random 21) 10) args))) (values args vars)))) (dolist (op '(+ * logior logxor logand logeqv gcd lcm - /)) (loop repeat 10 do (multiple-value-bind (args vars) (make-args) (let ((fast (compile nil `(lambda ,vars (,op ,@args)))) (slow (compile nil `(lambda ,vars (declare (notinline ,op)) (,op ,@args))))) (loop repeat 3 do (let* ((call-args (loop repeat (length vars) collect (- (random 21) 10))) (fast-result (handler-case (apply fast call-args) (division-by-zero () :div0))) (slow-result (handler-case (apply slow call-args) (division-by-zero () :div0)))) (if (eql fast-result slow-result) (print (list :ok `(,op ,@args) :=> fast-result)) (error "oops: ~S, ~S" args call-args))))))))))) (with-test (:name (:integer-division-using-multiplication :used) :skipped-on '(not (or :x86-64 :x86))) (dolist (fun '(truncate floor ceiling mod rem)) (let* ((foo (compile nil `(lambda (x) (declare (optimize (speed 3) (space 1) (compilation-speed 0)) (type (unsigned-byte ,sb-vm:n-word-bits) x)) (,fun x 9)))) (disassembly (with-output-to-string (s) (disassemble foo :stream s)))) copied from test : float - division - using - exact - reciprocal in compiler.pure.lisp . (assert (and (not (search "DIV" disassembly)) (search "MUL" disassembly)))))) (with-test (:name (:integer-division-using-multiplication :correctness)) (let ((*random-state* (make-random-state t))) (dolist (dividend-type `((unsigned-byte ,sb-vm:n-word-bits) (and fixnum unsigned-byte) (integer 10000 10100))) 7 10 14 641 274177 3 ,most-positive-fixnum ,(1- (expt 2 sb-vm:n-word-bits)) ,@(loop for i from 8 to sb-vm:n-word-bits for r = (random (expt 2 i)) We do n't want 0 , 1 and powers of 2 . when (not (zerop (logand r (1- r)))) collect r))) (dolist (fun '(truncate ceiling floor mod rem)) (let ((foo (compile nil `(lambda (x) (declare (optimize (speed 3) (space 1) (compilation-speed 0)) (type ,dividend-type x)) (,fun x ,divisor))))) (dolist (dividend `(0 1 ,most-positive-fixnum ,(1- divisor) ,divisor ,(1- (* divisor 2)) ,(* divisor 2) ,@(loop repeat 4 collect (+ 10000 (random 101))) ,@(loop for i from 4 to sb-vm:n-word-bits for pow = (expt 2 (1- i)) for r = (+ pow (random pow)) collect r))) (when (typep dividend dividend-type) (multiple-value-bind (q1 r1) (funcall foo dividend) (multiple-value-bind (q2 r2) (funcall fun dividend divisor) (unless (and (= q1 q2) (eql r1 r2)) (error "bad results for ~s with dividend type ~s" (list fun dividend divisor) dividend-type)))))))))))) The fast path for logbitp underestimated sb!vm : n - positive - fixnum - bits for > 61 bit fixnums . (with-test (:name :logbitp-wide-fixnum) (assert (not (logbitp (1- (integer-length most-positive-fixnum)) most-negative-fixnum)))) (with-test (:name (:expt :argument-type-combinations)) (bignum (expt 2 64)) results) (dolist (base (cons bignum numbers)) (dolist (power numbers) (format t "(expt ~s ~s) => " base power) (let ((result (expt base power))) (format t "~s~%" result) (push result results)))) (assert (every #'numberp results)))) (with-test (:name :bug-741564) (labels ((nearly-equal-p (x y) "Are the arguments equal to nearly double-float precision?" (declare (type double-float x y)) (< (/ (abs (- x y)) (abs y)) Differences in the two least (test-complex (x y) (and (nearly-equal-p (realpart x) (realpart y)) (nearly-equal-p (imagpart x) (imagpart y)))) (print-result (msg base power got expected) (format t "~a (expt ~s ~s)~%got ~s~%expected ~s~%" msg base power got expected))) (let ((n-broken 0)) (flet ((test (base power coerce-to-type) (let* ((got (expt base power)) (expected (expt (coerce base coerce-to-type) power)) (result (test-complex got expected))) (print-result (if result "Good:" "Bad:") base power got expected) (unless result (incf n-broken))))) (test base power 'double-float))) (complex (expt 2 64) (expt 2 65)) (test base power '(complex double-float))))) (when (> n-broken 0) (error "Number of broken combinations: ~a" n-broken))))) (with-test (:name (:ldb :rlwinm :ppc)) (let ((one (compile nil '(lambda (a) (ldb (byte 9 27) a)))) (two (compile nil '(lambda (a) (declare (type (integer -3 57216651) a)) (ldb (byte 9 27) a))))) (assert (= 0 (- (funcall one 10) (funcall two 10)))))) The ISQRT implementation is sufficiently complicated that it should (with-test (:name :isqrt) (labels ((test (x) (let* ((r (isqrt x)) (r2 (expt r 2)) (s2 (expt (1+ r) 2))) (unless (and (<= r2 x) (> s2 x)) (error "isqrt failure for ~a" x)))) (tests (x) (test x) (let ((x2 (expt x 2))) (test x2) (test (1+ x2)) (test (1- x2))))) (loop for i from 1 to 200 for pow = (expt 2 (1- i)) for j = (+ pow (random pow)) do (tests i) (tests j)) (dotimes (i 10) (tests (random (expt 2 (+ 1000 (random 10000))))))))
ad585d9241c8bffaf81ba24c842807811fb5ad4c5a9af7089dd15524df53e66d
shirok/Gauche
quasi-ints.scm
(define (check-quasi-integer-operations) (print-header "Checking quasi-integer operations...") (check (bitvector= (bitvector-logical-shift (bitvector 1 0 1 1) 2 0) (bitvector 1 1 0 0)) => #t) (check (bitvector= (bitvector-logical-shift (bitvector 1 0 1 1) -2 #t) (bitvector 1 1 1 0)) => #t) (check (bitvector-count 1 (make-bitvector 8 1)) => 8) (check (bitvector-count #t (make-bitvector 8 0)) => 0) (check (bitvector-count 1 (bitvector 1 1 0 1 1 0 0 0)) => 4) (check (bitvector-count-run 1 (make-bitvector 8 1) 0) => 8) (check (bitvector-count-run #t (make-bitvector 8 0) 4) => 0) (check (bitvector-count-run 1 (bitvector 0 1 1 1) 1) => 3) (let ((then-bvec (bitvector 1 0 1 0)) (else-bvec (bitvector 0 0 0 1))) (check (bitvector= (bitvector-if (make-bitvector 4 1) then-bvec else-bvec) then-bvec) => #t) (check (bitvector= (bitvector-if (make-bitvector 4 0) then-bvec else-bvec) else-bvec) => #t)) (check (bitvector= (bitvector-if (bitvector 1 1 0 0) (bitvector 0 1 1 1) (bitvector 0 0 1 0)) (bitvector 0 1 1 0)) => #t) (check (bitvector-first-bit 0 (make-bitvector 4 0)) => 0) (check (bitvector-first-bit #t (bitvector 0 0 1 0)) => 2) (check (bitvector-first-bit #f (make-bitvector 4 1)) => -1) )
null
https://raw.githubusercontent.com/shirok/Gauche/ecaf82f72e2e946f62d99ed8febe0df8960d20c4/test/include/test/quasi-ints.scm
scheme
(define (check-quasi-integer-operations) (print-header "Checking quasi-integer operations...") (check (bitvector= (bitvector-logical-shift (bitvector 1 0 1 1) 2 0) (bitvector 1 1 0 0)) => #t) (check (bitvector= (bitvector-logical-shift (bitvector 1 0 1 1) -2 #t) (bitvector 1 1 1 0)) => #t) (check (bitvector-count 1 (make-bitvector 8 1)) => 8) (check (bitvector-count #t (make-bitvector 8 0)) => 0) (check (bitvector-count 1 (bitvector 1 1 0 1 1 0 0 0)) => 4) (check (bitvector-count-run 1 (make-bitvector 8 1) 0) => 8) (check (bitvector-count-run #t (make-bitvector 8 0) 4) => 0) (check (bitvector-count-run 1 (bitvector 0 1 1 1) 1) => 3) (let ((then-bvec (bitvector 1 0 1 0)) (else-bvec (bitvector 0 0 0 1))) (check (bitvector= (bitvector-if (make-bitvector 4 1) then-bvec else-bvec) then-bvec) => #t) (check (bitvector= (bitvector-if (make-bitvector 4 0) then-bvec else-bvec) else-bvec) => #t)) (check (bitvector= (bitvector-if (bitvector 1 1 0 0) (bitvector 0 1 1 1) (bitvector 0 0 1 0)) (bitvector 0 1 1 0)) => #t) (check (bitvector-first-bit 0 (make-bitvector 4 0)) => 0) (check (bitvector-first-bit #t (bitvector 0 0 1 0)) => 2) (check (bitvector-first-bit #f (make-bitvector 4 1)) => -1) )
eb8743df9194e7c359c912997e4b5c66c279216d1853f0e3b1e6ec34494d76ba
avatar29A/hs-aitubots-api
FormSwitch.hs
# LANGUAGE DuplicateRecordFields # {-# LANGUAGE OverloadedStrings #-} module FormSwitch where import Aitu.Bot import Aitu.Bot.Types hiding ( InputMediaType(..) ) import Aitu.Bot.Forms import Aitu.Bot.Commands import Aitu.Bot.Widgets import qualified Aitu.Bot.Forms.Content.Content as C open :: Peer -> AituBotClient () open peer = do let header = Header { headerType = TOOLBAR , title = "FormSwitch Example" , options = defaultHeaderOptions , formAction = Nothing } switch1 = Switch "switch1" "Are you accepted rules?" False (Just defaultOptions { indentOuter = Just Indent { left = 30 , right = 30 , top = 50 , bottom = 30 } } ) switch2 = Switch "switch2" "Are you accepted rules?" False Nothing form1 = mkBackdropForm Backdrop { formId = "form1" , header = header , content = [C.Content switch1, C.Content switch2] , options = Just defaultOptions { fullscreen = Just True } , bottomBar = Nothing } sendForm peer form1
null
https://raw.githubusercontent.com/avatar29A/hs-aitubots-api/9cc3fd1e4e9e81491628741a6bbb68afbb85704e/tutorials/simpleui/app/FormSwitch.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DuplicateRecordFields # module FormSwitch where import Aitu.Bot import Aitu.Bot.Types hiding ( InputMediaType(..) ) import Aitu.Bot.Forms import Aitu.Bot.Commands import Aitu.Bot.Widgets import qualified Aitu.Bot.Forms.Content.Content as C open :: Peer -> AituBotClient () open peer = do let header = Header { headerType = TOOLBAR , title = "FormSwitch Example" , options = defaultHeaderOptions , formAction = Nothing } switch1 = Switch "switch1" "Are you accepted rules?" False (Just defaultOptions { indentOuter = Just Indent { left = 30 , right = 30 , top = 50 , bottom = 30 } } ) switch2 = Switch "switch2" "Are you accepted rules?" False Nothing form1 = mkBackdropForm Backdrop { formId = "form1" , header = header , content = [C.Content switch1, C.Content switch2] , options = Just defaultOptions { fullscreen = Just True } , bottomBar = Nothing } sendForm peer form1
1b37d9f1efab1c2dd921423ce9b92af0297402493ed5a1ce13192ae01a0c9a51
unnohideyuki/bunny
sample209.hs
LT `myeq` LT = True EQ `myeq` EQ = True GT `myeq` GT = True _ `myeq` _ = False main = do print $ LT `myeq` LT print $ EQ `myeq` GT
null
https://raw.githubusercontent.com/unnohideyuki/bunny/501856ff48f14b252b674585f25a2bf3801cb185/compiler/test/samples/sample209.hs
haskell
LT `myeq` LT = True EQ `myeq` EQ = True GT `myeq` GT = True _ `myeq` _ = False main = do print $ LT `myeq` LT print $ EQ `myeq` GT
1e68c4942caac8a1735ae64cc1e8581ad439d13e8a5cfb013f091978b3e4508f
argp/bap
ssa_convenience.ml
* Utility functions for SSAs . It 's useful to have these in a separate file so it can use functions from and elsewhere . separate file so it can use functions from Typecheck and elsewhere. *) open Ssa open BatPervasives open Big_int_Z open Big_int_convenience open Type open Typecheck (* exp helpers *) let unknown t s = Unknown(s, t) let binop op a b = match op,a,b with | _, Int(a, at), Int(b, bt) -> assert (at = bt); let (i,t) = Arithmetic.binop op (a,at) (b,bt) in Int(i,t) | (LSHIFT|RSHIFT|ARSHIFT), _, Int(z, _) when bi_is_zero z -> a | _ -> BinOp(op, a, b) let unop op a = match a with | Int(a, at) -> let (i,t) = Arithmetic.unop op (a,at) in Int(i,t) | _ -> UnOp(op, a) let concat a b = match a,b with | Int(a, at), Int(b, bt) -> let (i,t) = Arithmetic.concat (a,at) (b,bt) in Int(i,t) | _ -> Concat(a, b) let extract h l e = let h = Big_int_Z.big_int_of_int h in let l = Big_int_Z.big_int_of_int l in match e with | Int(i, t) -> let (i,t) = Arithmetic.extract h l (i,t) in Int(i,t) | _ -> Extract(h, l, e) (* More convenience functions for building common expressions. *) let exp_and e1 e2 = binop AND e1 e2 let exp_or e1 e2 = binop OR e1 e2 let exp_eq e1 e2 = binop EQ e1 e2 let exp_not e = unop NOT e let exp_implies e1 e2 = exp_or (exp_not e1) e2 let (exp_shl, exp_shr) = let s dir e1 = function | Int(i,_) when bi_is_zero i -> e1 | e2 -> BinOp(dir, e1, e2) in (s LSHIFT, s RSHIFT) let ( +* ) a b = binop PLUS a b let ( -* ) a b = binop MINUS a b let ( ** ) a b = binop TIMES a b let ( <<* ) a b = binop LSHIFT a b let ( >>* ) a b = binop RSHIFT a b let ( >>>* ) a b = binop ARSHIFT a b let ( &* ) a b = binop AND a b let ( |* ) a b = binop OR a b let ( ^* ) a b = binop XOR a b let ( ==* ) a b = binop EQ a b let ( <>* ) a b = binop NEQ a b let ( <* ) a b = binop LT a b let ( >* ) a b = binop LT b a let (<=* ) a b = binop LE a b let (>=* ) a b = binop LE b a (** bitwise equality *) let ( =* ) a b = binop XOR a (unop NOT b) let ( ++* ) a b = concat a b let ( %* ) a b = binop MOD a b let ( $%* ) a b = binop SMOD a b let ( /* ) a b = binop DIVIDE a b let ( $/* ) a b = binop SDIVIDE a b let cast ct tnew = function | Int(i,t) -> let (i',t') = Arithmetic.cast ct (i,t) tnew in Int(i',t') | e -> Cast(ct, tnew, e) let cast_low = cast CAST_LOW let cast_high = cast CAST_HIGH let cast_signed = cast CAST_SIGNED let rec cast_unsigned tnew = function | Int(i,t) -> let (i',t') = Arithmetic.cast CAST_UNSIGNED (i,t) tnew in Int(i',t') | Cast(CAST_UNSIGNED, Reg t', e) when Arithmetic.bits_of_width tnew >= t' -> Recurse , since we might be able to simplify e further now cast_unsigned tnew e | e -> Cast(CAST_UNSIGNED, tnew, e) let exp_int i bits = Int(i, Reg bits) let it i t = Int(biconst i, t) let exp_ite ?t b e1 e2 = (* type inference shouldn't be needed when t is specified, but we're paranoid *) let tb = Typecheck.infer_ssa b in let t1 = Typecheck.infer_ssa e1 in let t2 = Typecheck.infer_ssa e2 in assert (t1 = t2); assert (tb = Reg(1)); (match t with | None -> () | Some t -> assert (t=t1)); if b = exp_true then e1 else if b = exp_false then e2 else Ite(b, e1, e2) let parse_ite = function | BinOp(OR, BinOp(AND, Cast(CAST_SIGNED, _, b1), e1), BinOp(AND, Cast(CAST_SIGNED, _, UnOp(NOT, b2)), e2) ) | BinOp(OR, BinOp(AND, b1, e1), BinOp(AND, UnOp(NOT, b2), e2) ) when full_exp_eq b1 b2 && Typecheck.infer_ssa b1 = Reg(1) -> Some(b1, e1, e2) In case one branch is optimized away | BinOp(AND, Cast(CAST_SIGNED, nt, b1), e1) when Typecheck.infer_ssa b1 = Reg(1) -> Some(b1, e1, Int(zero_big_int, nt)) | _ -> None let parse_implies = function | BinOp(OR, UnOp(NOT, e1), e2) -> Some(e1, e2) | _ -> None (** Duplicate any shared nodes. Useful for using physical location as a unique identity. XXX: I think this would be much faster if we only duplicated things that actually occur more than once. *) let rec rm_duplicates e = let r = rm_duplicates in let newe = match e with | Load(e1, e2, e3, t) -> Load(r e1, r e2, r e3, t) | Store(e1, e2, e3, e4, t) -> Store(r e1, r e2, r e3, r e4, t) | BinOp(bt, e1, e2) -> BinOp(bt, r e1, r e2) | UnOp(ut, e) -> UnOp(ut, r e) | Var(v) -> Var(v) | Lab(s) -> Lab(s) | Int(i, t) -> Int(i, t) | Cast(ct, t, e) -> Cast(ct, t, r e) | Unknown(s, t) -> Unknown(s, t) | Ite(e1, e2, e3) -> Ite(r e1, r e2, r e3) | Extract(i1, i2, e) -> Extract(i1, i2, r e) | Concat(e1, e2) -> Concat(r e1, r e2) | Phi(l) -> Phi(l) in assert (e != newe); newe let parse_extract = function | Cast(CAST_LOW, t, BinOp(RSHIFT, e', Int(i, t2))) -> (* Original: extract 0:bits(t)-1, and then shift left by i bits. New: extract i:bits(t)-1+i *) let et = infer_ssa e' in let bits_t = big_int_of_int (bits_of_width t) in let lbit = i in let hbit = (lbit +% bits_t) -% bi1 in (* XXX: This should be unsigned >, but I don't think it matters. *) if hbit >% big_int_of_int(bits_of_width et) then None else Some(hbit, lbit) | _ -> None let parse_concat = function Note : We should only parse when we would preserve the type . So , ( nt1 = nt2 ) = bits(er ) + bits(el ) XXX : When we convert to normalized memory access , we get expressions like ] ) @ Cast(r32)(mem[1 ] ) < < 8 @ .... It sure would be nice if we could recognize this as a series of concats . So, (nt1=nt2) = bits(er) + bits(el) XXX: When we convert to normalized memory access, we get expressions like Cast(r32)(mem[0]) @ Cast(r32)(mem[1]) << 8 @ .... It sure would be nice if we could recognize this as a series of concats. *) | BinOp(OR, BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _)), Cast(CAST_UNSIGNED, nt2, er)) | BinOp(OR, Cast(CAST_UNSIGNED, nt2, er), BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _))) when nt1 = nt2 && bits ==% big_int_of_int(bits_of_width (infer_ssa er)) && bits_of_width nt1 = bits_of_width (infer_ssa el) + bits_of_width (infer_ssa er) (* Preserve the type *) -> Some(el, er) | BinOp(OR, BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _)), (Int(i, nt2) as er)) | BinOp(OR, (Int(i, nt2) as er), BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _))) If we cast to nt1 and nt2 and we get the same thing , the optimizer probably just dropped the cast . optimizer probably just dropped the cast. *) when Arithmetic.to_big_int (i, nt2) ==% Arithmetic.to_big_int (i, nt1) && bits ==% big_int_of_int(bits_of_width (infer_ssa er)) && bits_of_width nt1 = bits_of_width (infer_ssa el) + bits_of_width (infer_ssa er) (* Preserve the type *) -> Some(el, er) | _ -> None (* Functions for removing expression types Should these recurse on subexpressions? *) let rm_ite = function | Ite(b, e1, e2) -> let t = Typecheck.infer_ssa e1 in (match t with | Reg(1) -> (b &* e1) |* (exp_not b &* e2) | Reg n -> ((cast_signed t b) &* e1) |* ((cast_signed t (exp_not b)) &* e2) | _ -> failwith "rm_ite does not work with memories") | _ -> assert false (* Should we just act as a noop? *) let rm_extract = function | Extract(h, l, e) -> let nb = int_of_big_int ((h -% l) +% bi1) in let nt = Reg(nb) in assert(h >=% bi0); assert (nb >= 0); let t = infer_ssa e in let e = if l <>% bi0 then e >>* Int(l, t) else e in let e = if t <> nt then cast_low nt e else e in e | _ -> assert false let rm_concat = function | Concat(le, re) -> let bitsl,bitsr = Typecheck.bits_of_width (Typecheck.infer_ssa le), Typecheck.bits_of_width (Typecheck.infer_ssa re) in let nt = Reg(bitsl + bitsr) in exp_or ((cast_unsigned nt le) <<* Int(big_int_of_int bitsr, nt)) (cast_unsigned nt re) | _ -> assert false let last_meaningful_stmt p = let rec f = function | Comment _::tl -> f tl | x::_ -> x | [] -> failwith "No meaningful statements" in f (List.rev p) let min_symbolic ~signed e1 e2 = let bop = if signed then SLT else LT in exp_ite (binop bop e1 e2) e1 e2 Extract the nth least significant element of type t from e , starting with zero . n is a non - negative integer . starting with zero. n is a non-negative integer. *) let extract_element t e n = let nbits = Typecheck.bits_of_width t in extract (n*nbits+(nbits-1)) (n*nbits) e (* Extract the nth least significant byte from e, starting with zero. n is a non-negative integer *) let extract_byte e n = extract_element reg_8 e n Extract the nth least significant element of type t from e , starting with zero . n is an expression . starting with zero. n is an expression. *) let extract_element_symbolic t e n = let et = Typecheck.infer_ssa n in cast_low t (e >>* (n ** (it (Typecheck.bits_of_width t) et))) (* Extract the nth least significant byte from e, starting with zero. n is an expression. *) let extract_byte_symbolic e n = extract_element_symbolic reg_8 e n let reverse_bytes e = let bytes = Typecheck.bytes_of_width (Typecheck.infer_ssa e) in let get_byte n = extract_byte e n in reduce (fun bige e -> bige ++* e) (map get_byte (0 -- (bytes-1))) an enumeration of expressions let concat_explist elist = reduce (fun l r -> l ++* r) elist
null
https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/ocaml/ssa_convenience.ml
ocaml
exp helpers More convenience functions for building common expressions. * bitwise equality type inference shouldn't be needed when t is specified, but we're paranoid * Duplicate any shared nodes. Useful for using physical location as a unique identity. XXX: I think this would be much faster if we only duplicated things that actually occur more than once. Original: extract 0:bits(t)-1, and then shift left by i bits. New: extract i:bits(t)-1+i XXX: This should be unsigned >, but I don't think it matters. Preserve the type Preserve the type Functions for removing expression types Should these recurse on subexpressions? Should we just act as a noop? Extract the nth least significant byte from e, starting with zero. n is a non-negative integer Extract the nth least significant byte from e, starting with zero. n is an expression.
* Utility functions for SSAs . It 's useful to have these in a separate file so it can use functions from and elsewhere . separate file so it can use functions from Typecheck and elsewhere. *) open Ssa open BatPervasives open Big_int_Z open Big_int_convenience open Type open Typecheck let unknown t s = Unknown(s, t) let binop op a b = match op,a,b with | _, Int(a, at), Int(b, bt) -> assert (at = bt); let (i,t) = Arithmetic.binop op (a,at) (b,bt) in Int(i,t) | (LSHIFT|RSHIFT|ARSHIFT), _, Int(z, _) when bi_is_zero z -> a | _ -> BinOp(op, a, b) let unop op a = match a with | Int(a, at) -> let (i,t) = Arithmetic.unop op (a,at) in Int(i,t) | _ -> UnOp(op, a) let concat a b = match a,b with | Int(a, at), Int(b, bt) -> let (i,t) = Arithmetic.concat (a,at) (b,bt) in Int(i,t) | _ -> Concat(a, b) let extract h l e = let h = Big_int_Z.big_int_of_int h in let l = Big_int_Z.big_int_of_int l in match e with | Int(i, t) -> let (i,t) = Arithmetic.extract h l (i,t) in Int(i,t) | _ -> Extract(h, l, e) let exp_and e1 e2 = binop AND e1 e2 let exp_or e1 e2 = binop OR e1 e2 let exp_eq e1 e2 = binop EQ e1 e2 let exp_not e = unop NOT e let exp_implies e1 e2 = exp_or (exp_not e1) e2 let (exp_shl, exp_shr) = let s dir e1 = function | Int(i,_) when bi_is_zero i -> e1 | e2 -> BinOp(dir, e1, e2) in (s LSHIFT, s RSHIFT) let ( +* ) a b = binop PLUS a b let ( -* ) a b = binop MINUS a b let ( ** ) a b = binop TIMES a b let ( <<* ) a b = binop LSHIFT a b let ( >>* ) a b = binop RSHIFT a b let ( >>>* ) a b = binop ARSHIFT a b let ( &* ) a b = binop AND a b let ( |* ) a b = binop OR a b let ( ^* ) a b = binop XOR a b let ( ==* ) a b = binop EQ a b let ( <>* ) a b = binop NEQ a b let ( <* ) a b = binop LT a b let ( >* ) a b = binop LT b a let (<=* ) a b = binop LE a b let (>=* ) a b = binop LE b a let ( =* ) a b = binop XOR a (unop NOT b) let ( ++* ) a b = concat a b let ( %* ) a b = binop MOD a b let ( $%* ) a b = binop SMOD a b let ( /* ) a b = binop DIVIDE a b let ( $/* ) a b = binop SDIVIDE a b let cast ct tnew = function | Int(i,t) -> let (i',t') = Arithmetic.cast ct (i,t) tnew in Int(i',t') | e -> Cast(ct, tnew, e) let cast_low = cast CAST_LOW let cast_high = cast CAST_HIGH let cast_signed = cast CAST_SIGNED let rec cast_unsigned tnew = function | Int(i,t) -> let (i',t') = Arithmetic.cast CAST_UNSIGNED (i,t) tnew in Int(i',t') | Cast(CAST_UNSIGNED, Reg t', e) when Arithmetic.bits_of_width tnew >= t' -> Recurse , since we might be able to simplify e further now cast_unsigned tnew e | e -> Cast(CAST_UNSIGNED, tnew, e) let exp_int i bits = Int(i, Reg bits) let it i t = Int(biconst i, t) let exp_ite ?t b e1 e2 = let tb = Typecheck.infer_ssa b in let t1 = Typecheck.infer_ssa e1 in let t2 = Typecheck.infer_ssa e2 in assert (t1 = t2); assert (tb = Reg(1)); (match t with | None -> () | Some t -> assert (t=t1)); if b = exp_true then e1 else if b = exp_false then e2 else Ite(b, e1, e2) let parse_ite = function | BinOp(OR, BinOp(AND, Cast(CAST_SIGNED, _, b1), e1), BinOp(AND, Cast(CAST_SIGNED, _, UnOp(NOT, b2)), e2) ) | BinOp(OR, BinOp(AND, b1, e1), BinOp(AND, UnOp(NOT, b2), e2) ) when full_exp_eq b1 b2 && Typecheck.infer_ssa b1 = Reg(1) -> Some(b1, e1, e2) In case one branch is optimized away | BinOp(AND, Cast(CAST_SIGNED, nt, b1), e1) when Typecheck.infer_ssa b1 = Reg(1) -> Some(b1, e1, Int(zero_big_int, nt)) | _ -> None let parse_implies = function | BinOp(OR, UnOp(NOT, e1), e2) -> Some(e1, e2) | _ -> None let rec rm_duplicates e = let r = rm_duplicates in let newe = match e with | Load(e1, e2, e3, t) -> Load(r e1, r e2, r e3, t) | Store(e1, e2, e3, e4, t) -> Store(r e1, r e2, r e3, r e4, t) | BinOp(bt, e1, e2) -> BinOp(bt, r e1, r e2) | UnOp(ut, e) -> UnOp(ut, r e) | Var(v) -> Var(v) | Lab(s) -> Lab(s) | Int(i, t) -> Int(i, t) | Cast(ct, t, e) -> Cast(ct, t, r e) | Unknown(s, t) -> Unknown(s, t) | Ite(e1, e2, e3) -> Ite(r e1, r e2, r e3) | Extract(i1, i2, e) -> Extract(i1, i2, r e) | Concat(e1, e2) -> Concat(r e1, r e2) | Phi(l) -> Phi(l) in assert (e != newe); newe let parse_extract = function | Cast(CAST_LOW, t, BinOp(RSHIFT, e', Int(i, t2))) -> let et = infer_ssa e' in let bits_t = big_int_of_int (bits_of_width t) in let lbit = i in let hbit = (lbit +% bits_t) -% bi1 in if hbit >% big_int_of_int(bits_of_width et) then None else Some(hbit, lbit) | _ -> None let parse_concat = function Note : We should only parse when we would preserve the type . So , ( nt1 = nt2 ) = bits(er ) + bits(el ) XXX : When we convert to normalized memory access , we get expressions like ] ) @ Cast(r32)(mem[1 ] ) < < 8 @ .... It sure would be nice if we could recognize this as a series of concats . So, (nt1=nt2) = bits(er) + bits(el) XXX: When we convert to normalized memory access, we get expressions like Cast(r32)(mem[0]) @ Cast(r32)(mem[1]) << 8 @ .... It sure would be nice if we could recognize this as a series of concats. *) | BinOp(OR, BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _)), Cast(CAST_UNSIGNED, nt2, er)) | BinOp(OR, Cast(CAST_UNSIGNED, nt2, er), BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _))) when nt1 = nt2 && bits ==% big_int_of_int(bits_of_width (infer_ssa er)) -> Some(el, er) | BinOp(OR, BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _)), (Int(i, nt2) as er)) | BinOp(OR, (Int(i, nt2) as er), BinOp(LSHIFT, Cast(CAST_UNSIGNED, nt1, el), Int(bits, _))) If we cast to nt1 and nt2 and we get the same thing , the optimizer probably just dropped the cast . optimizer probably just dropped the cast. *) when Arithmetic.to_big_int (i, nt2) ==% Arithmetic.to_big_int (i, nt1) && bits ==% big_int_of_int(bits_of_width (infer_ssa er)) -> Some(el, er) | _ -> None let rm_ite = function | Ite(b, e1, e2) -> let t = Typecheck.infer_ssa e1 in (match t with | Reg(1) -> (b &* e1) |* (exp_not b &* e2) | Reg n -> ((cast_signed t b) &* e1) |* ((cast_signed t (exp_not b)) &* e2) | _ -> failwith "rm_ite does not work with memories") let rm_extract = function | Extract(h, l, e) -> let nb = int_of_big_int ((h -% l) +% bi1) in let nt = Reg(nb) in assert(h >=% bi0); assert (nb >= 0); let t = infer_ssa e in let e = if l <>% bi0 then e >>* Int(l, t) else e in let e = if t <> nt then cast_low nt e else e in e | _ -> assert false let rm_concat = function | Concat(le, re) -> let bitsl,bitsr = Typecheck.bits_of_width (Typecheck.infer_ssa le), Typecheck.bits_of_width (Typecheck.infer_ssa re) in let nt = Reg(bitsl + bitsr) in exp_or ((cast_unsigned nt le) <<* Int(big_int_of_int bitsr, nt)) (cast_unsigned nt re) | _ -> assert false let last_meaningful_stmt p = let rec f = function | Comment _::tl -> f tl | x::_ -> x | [] -> failwith "No meaningful statements" in f (List.rev p) let min_symbolic ~signed e1 e2 = let bop = if signed then SLT else LT in exp_ite (binop bop e1 e2) e1 e2 Extract the nth least significant element of type t from e , starting with zero . n is a non - negative integer . starting with zero. n is a non-negative integer. *) let extract_element t e n = let nbits = Typecheck.bits_of_width t in extract (n*nbits+(nbits-1)) (n*nbits) e let extract_byte e n = extract_element reg_8 e n Extract the nth least significant element of type t from e , starting with zero . n is an expression . starting with zero. n is an expression. *) let extract_element_symbolic t e n = let et = Typecheck.infer_ssa n in cast_low t (e >>* (n ** (it (Typecheck.bits_of_width t) et))) let extract_byte_symbolic e n = extract_element_symbolic reg_8 e n let reverse_bytes e = let bytes = Typecheck.bytes_of_width (Typecheck.infer_ssa e) in let get_byte n = extract_byte e n in reduce (fun bige e -> bige ++* e) (map get_byte (0 -- (bytes-1))) an enumeration of expressions let concat_explist elist = reduce (fun l r -> l ++* r) elist
220fb9383f1c952aec36dd60b0e9bd33d4e1ce15ce1aa893d22ce37ce94fbb32
josefs/Gradualizer
pattern.erl
-module(pattern). -export([pattern_test/1]). -spec pattern_test(integer()) -> {}. pattern_test(1) -> true; pattern_test(_) -> {}.
null
https://raw.githubusercontent.com/josefs/Gradualizer/208f5816b0157f282212fc036ba7560f0822f9fc/test/should_fail/pattern.erl
erlang
-module(pattern). -export([pattern_test/1]). -spec pattern_test(integer()) -> {}. pattern_test(1) -> true; pattern_test(_) -> {}.
162234c465bd911e7ec844b26d9681712c84eae2ab342b0b3194099aa8081725
slepher/astranaut
astranaut_error_SUITE.erl
%%%------------------------------------------------------------------- @author < > ( C ) 2020 , %%% @doc %%% %%% @end Created : 6 Jul 2020 by < > %%%------------------------------------------------------------------- -module(astranaut_error_SUITE). -compile(export_all). -compile(nowarn_export_all). -include("rebinding.hrl"). -include_lib("stdlib/include/assert.hrl"). -include_lib("common_test/include/ct.hrl"). -rebinding_all([{clause_pinned, true}]). %%-------------------------------------------------------------------- @spec suite ( ) - > Info %% Info = [tuple()] %% @end %%-------------------------------------------------------------------- suite() -> [{timetrap,{seconds,30}}]. %%-------------------------------------------------------------------- @spec init_per_suite(Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } %% Config0 = Config1 = [tuple()] %% Reason = term() %% @end %%-------------------------------------------------------------------- init_per_suite(Config) -> Config. %%-------------------------------------------------------------------- ) - > term ( ) | { save_config , Config1 } %% Config0 = Config1 = [tuple()] %% @end %%-------------------------------------------------------------------- end_per_suite(_Config) -> ok. %%-------------------------------------------------------------------- @spec init_per_group(GroupName , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } %% GroupName = atom() %% Config0 = Config1 = [tuple()] %% Reason = term() %% @end %%-------------------------------------------------------------------- init_per_group(_GroupName, Config) -> Config. %%-------------------------------------------------------------------- , Config0 ) - > term ( ) | { save_config , Config1 } %% GroupName = atom() %% Config0 = Config1 = [tuple()] %% @end %%-------------------------------------------------------------------- end_per_group(_GroupName, _Config) -> ok. %%-------------------------------------------------------------------- @spec init_per_testcase(TestCase , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } TestCase = atom ( ) %% Config0 = Config1 = [tuple()] %% Reason = term() %% @end %%-------------------------------------------------------------------- init_per_testcase(_TestCase, Config) -> Config. %%-------------------------------------------------------------------- , Config0 ) - > term ( ) | { save_config , Config1 } | { fail , Reason } TestCase = atom ( ) %% Config0 = Config1 = [tuple()] %% Reason = term() %% @end %%-------------------------------------------------------------------- end_per_testcase(_TestCase, _Config) -> ok. %%-------------------------------------------------------------------- @spec groups ( ) - > [ Group ] Group = { GroupName , Properties , } %% GroupName = atom() Properties = [ parallel | sequence | Shuffle | } ] = [ Group | { group , GroupName } | TestCase ] TestCase = atom ( ) Shuffle = shuffle | { shuffle,{integer(),integer(),integer ( ) } } %% RepeatType = repeat | repeat_until_all_ok | repeat_until_all_fail | %% repeat_until_any_ok | repeat_until_any_fail %% N = integer() | forever %% @end %%-------------------------------------------------------------------- groups() -> []. %%-------------------------------------------------------------------- @spec all ( ) - > GroupsAndTestCases | { skip , Reason } = [ { group , GroupName } | TestCase ] %% GroupName = atom() TestCase = atom ( ) %% Reason = term() %% @end %%-------------------------------------------------------------------- all() -> [test_state_1, test_state_2, test_state_3, test_state_4, test_state_5, test_state_6]. %%-------------------------------------------------------------------- ( ) - > Info %% Info = [tuple()] %% @end %%-------------------------------------------------------------------- test_merge_1() -> []. %%-------------------------------------------------------------------- ) - > %% ok | exit() | {skip,Reason} | {comment,Comment} | { save_config , Config1 } | { skip_and_save , Reason , Config1 } %% Config0 = Config1 = [tuple()] %% Reason = term() %% Comment = term() %% @end %%-------------------------------------------------------------------- test_state_1(_Config) -> Init = astranaut_error:new(), Errors = [error_0], Warnings = [], State = astranaut_error:append_error(error_0, Init), ?assertEqual({Errors, Warnings}, {astranaut_error:errors(State), astranaut_error:warnings(State)}), ok. test_state_2(_Config) -> Init = astranaut_error:new(), Errors = [error_0, error_1], State = astranaut_error:append_error(error_0, Init), State = astranaut_error:append_error(error_1, State), ?assertEqual(Errors, astranaut_error:errors(State)), ok. test_state_3(_Config) -> Init = astranaut_error:new(), Errors = [error_0, error_1], Warnings = [warning_0, warning_1, warning_2], State = astranaut_error:append_warnings([warning_0, warning_1], Init), State = astranaut_error:append_error(error_0, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:append_warning(warning_2, State), ?assertEqual({Errors, Warnings}, {astranaut_error:errors(State), astranaut_error:warnings(State)}), ok. test_state_4(_Config) -> State = astranaut_error:new(), Errors = [{10, ?MODULE, error_0}, {20, ?MODULE, error_1}], Warnings = [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}], State = astranaut_error:append_warning(warning_0, State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_error(error_0, State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:append_warning(warning_1, State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:append_warning(warning_2, State), State = astranaut_error:update_pos(25, ?MODULE, State), ?assertEqual({Errors, Warnings}, {astranaut_error:formatted_errors(State), astranaut_error:formatted_warnings(State)}), ok. test_state_5(_Config) -> State = astranaut_error:new(), Errors = [{?FILE, [{10, ?MODULE, error_0}, {20, ?MODULE, error_1}]}], Warnings = [{?FILE, [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}]}], State = astranaut_error:append_warnings([warning_0], State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_errors([error_0], State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:append_warnings([warning_1], State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_errors([error_1], State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:append_warnings([warning_2], State), State = astranaut_error:update_pos(25, ?MODULE, State), State = astranaut_error:eof(State), ?assertEqual({Errors, Warnings}, astranaut_error:realize(State)), ok. test_state_6(_Config) -> State = astranaut_error:new(), File2 = ?FILE ++ "_2", Errors = maps:to_list(#{?FILE =>[{5, ?MODULE, error_0}, {10, ?MODULE, error_1}], File2 => [{20, ?MODULE, error_2}]}), Warnings = [{?FILE, [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}, {30, ?MODULE, warning_3}]}], State = astranaut_error:append_warning(warning_0, State), State = astranaut_error:append_error(error_0, State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_warning(warning_1, State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:update_file(File2, State), State = astranaut_error:append_error(error_2, State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_warning(warning_2, State), State = astranaut_error:update_pos(25, ?MODULE, State), State = astranaut_error:append_warning(warning_3, State), State = astranaut_error:update_pos(30, ?MODULE, State), State = astranaut_error:eof(State), ?assertEqual({Errors, Warnings}, astranaut_error:realize(State)), ok.
null
https://raw.githubusercontent.com/slepher/astranaut/95445ee8de492ead2cd9d9671095e251e902986b/test/astranaut_error_SUITE.erl
erlang
------------------------------------------------------------------- @doc @end ------------------------------------------------------------------- -------------------------------------------------------------------- Info = [tuple()] @end -------------------------------------------------------------------- -------------------------------------------------------------------- Config0 = Config1 = [tuple()] Reason = term() @end -------------------------------------------------------------------- -------------------------------------------------------------------- Config0 = Config1 = [tuple()] @end -------------------------------------------------------------------- -------------------------------------------------------------------- GroupName = atom() Config0 = Config1 = [tuple()] Reason = term() @end -------------------------------------------------------------------- -------------------------------------------------------------------- GroupName = atom() Config0 = Config1 = [tuple()] @end -------------------------------------------------------------------- -------------------------------------------------------------------- Config0 = Config1 = [tuple()] Reason = term() @end -------------------------------------------------------------------- -------------------------------------------------------------------- Config0 = Config1 = [tuple()] Reason = term() @end -------------------------------------------------------------------- -------------------------------------------------------------------- GroupName = atom() RepeatType = repeat | repeat_until_all_ok | repeat_until_all_fail | repeat_until_any_ok | repeat_until_any_fail N = integer() | forever @end -------------------------------------------------------------------- -------------------------------------------------------------------- GroupName = atom() Reason = term() @end -------------------------------------------------------------------- -------------------------------------------------------------------- Info = [tuple()] @end -------------------------------------------------------------------- -------------------------------------------------------------------- ok | exit() | {skip,Reason} | {comment,Comment} | Config0 = Config1 = [tuple()] Reason = term() Comment = term() @end --------------------------------------------------------------------
@author < > ( C ) 2020 , Created : 6 Jul 2020 by < > -module(astranaut_error_SUITE). -compile(export_all). -compile(nowarn_export_all). -include("rebinding.hrl"). -include_lib("stdlib/include/assert.hrl"). -include_lib("common_test/include/ct.hrl"). -rebinding_all([{clause_pinned, true}]). @spec suite ( ) - > Info suite() -> [{timetrap,{seconds,30}}]. @spec init_per_suite(Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } init_per_suite(Config) -> Config. ) - > term ( ) | { save_config , Config1 } end_per_suite(_Config) -> ok. @spec init_per_group(GroupName , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } init_per_group(_GroupName, Config) -> Config. , Config0 ) - > term ( ) | { save_config , Config1 } end_per_group(_GroupName, _Config) -> ok. @spec init_per_testcase(TestCase , Config0 ) - > Config1 | { skip , Reason } | { skip_and_save , Reason , Config1 } TestCase = atom ( ) init_per_testcase(_TestCase, Config) -> Config. , Config0 ) - > term ( ) | { save_config , Config1 } | { fail , Reason } TestCase = atom ( ) end_per_testcase(_TestCase, _Config) -> ok. @spec groups ( ) - > [ Group ] Group = { GroupName , Properties , } Properties = [ parallel | sequence | Shuffle | } ] = [ Group | { group , GroupName } | TestCase ] TestCase = atom ( ) Shuffle = shuffle | { shuffle,{integer(),integer(),integer ( ) } } groups() -> []. @spec all ( ) - > GroupsAndTestCases | { skip , Reason } = [ { group , GroupName } | TestCase ] TestCase = atom ( ) all() -> [test_state_1, test_state_2, test_state_3, test_state_4, test_state_5, test_state_6]. ( ) - > Info test_merge_1() -> []. ) - > { save_config , Config1 } | { skip_and_save , Reason , Config1 } test_state_1(_Config) -> Init = astranaut_error:new(), Errors = [error_0], Warnings = [], State = astranaut_error:append_error(error_0, Init), ?assertEqual({Errors, Warnings}, {astranaut_error:errors(State), astranaut_error:warnings(State)}), ok. test_state_2(_Config) -> Init = astranaut_error:new(), Errors = [error_0, error_1], State = astranaut_error:append_error(error_0, Init), State = astranaut_error:append_error(error_1, State), ?assertEqual(Errors, astranaut_error:errors(State)), ok. test_state_3(_Config) -> Init = astranaut_error:new(), Errors = [error_0, error_1], Warnings = [warning_0, warning_1, warning_2], State = astranaut_error:append_warnings([warning_0, warning_1], Init), State = astranaut_error:append_error(error_0, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:append_warning(warning_2, State), ?assertEqual({Errors, Warnings}, {astranaut_error:errors(State), astranaut_error:warnings(State)}), ok. test_state_4(_Config) -> State = astranaut_error:new(), Errors = [{10, ?MODULE, error_0}, {20, ?MODULE, error_1}], Warnings = [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}], State = astranaut_error:append_warning(warning_0, State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_error(error_0, State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:append_warning(warning_1, State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:append_warning(warning_2, State), State = astranaut_error:update_pos(25, ?MODULE, State), ?assertEqual({Errors, Warnings}, {astranaut_error:formatted_errors(State), astranaut_error:formatted_warnings(State)}), ok. test_state_5(_Config) -> State = astranaut_error:new(), Errors = [{?FILE, [{10, ?MODULE, error_0}, {20, ?MODULE, error_1}]}], Warnings = [{?FILE, [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}]}], State = astranaut_error:append_warnings([warning_0], State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_errors([error_0], State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:append_warnings([warning_1], State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_errors([error_1], State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:append_warnings([warning_2], State), State = astranaut_error:update_pos(25, ?MODULE, State), State = astranaut_error:eof(State), ?assertEqual({Errors, Warnings}, astranaut_error:realize(State)), ok. test_state_6(_Config) -> State = astranaut_error:new(), File2 = ?FILE ++ "_2", Errors = maps:to_list(#{?FILE =>[{5, ?MODULE, error_0}, {10, ?MODULE, error_1}], File2 => [{20, ?MODULE, error_2}]}), Warnings = [{?FILE, [{5, ?MODULE, warning_0}, {15, ?MODULE, warning_1}, {25, ?MODULE, warning_2}, {30, ?MODULE, warning_3}]}], State = astranaut_error:append_warning(warning_0, State), State = astranaut_error:append_error(error_0, State), State = astranaut_error:update_pos(5, ?MODULE, State), State = astranaut_error:append_error(error_1, State), State = astranaut_error:update_pos(10, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_warning(warning_1, State), State = astranaut_error:update_pos(15, ?MODULE, State), State = astranaut_error:update_file(File2, State), State = astranaut_error:append_error(error_2, State), State = astranaut_error:update_pos(20, ?MODULE, State), State = astranaut_error:update_file(?FILE, State), State = astranaut_error:append_warning(warning_2, State), State = astranaut_error:update_pos(25, ?MODULE, State), State = astranaut_error:append_warning(warning_3, State), State = astranaut_error:update_pos(30, ?MODULE, State), State = astranaut_error:eof(State), ?assertEqual({Errors, Warnings}, astranaut_error:realize(State)), ok.
d8ad01190a033372b9e5bac467f3fdc2131a326b7b54e81e6f5c35c32d0187c6
ghcjs/jsaddle-dom
GlobalCrypto.hs
# LANGUAGE PatternSynonyms # -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.GlobalCrypto (getCrypto, GlobalCrypto(..), gTypeGlobalCrypto, IsGlobalCrypto, toGlobalCrypto) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/GlobalCrypto.crypto Mozilla GlobalCrypto.crypto documentation > getCrypto :: (MonadDOM m, IsGlobalCrypto self) => self -> m Crypto getCrypto self = liftDOM (((toGlobalCrypto self) ^. js "crypto") >>= fromJSValUnchecked)
null
https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/GlobalCrypto.hs
haskell
For HasCallStack compatibility # LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
# LANGUAGE PatternSynonyms # # OPTIONS_GHC -fno - warn - unused - imports # module JSDOM.Generated.GlobalCrypto (getCrypto, GlobalCrypto(..), gTypeGlobalCrypto, IsGlobalCrypto, toGlobalCrypto) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums | < -US/docs/Web/API/GlobalCrypto.crypto Mozilla GlobalCrypto.crypto documentation > getCrypto :: (MonadDOM m, IsGlobalCrypto self) => self -> m Crypto getCrypto self = liftDOM (((toGlobalCrypto self) ^. js "crypto") >>= fromJSValUnchecked)
d3f3b485ee81a5aa630ec6a2a8ec6f7950aa58ef98f41a399253150eace83f79
roman01la/clojurescript-workshop
core.cljs
;; Vector (def v [1 2 3 4 5]) 4 4 5 [ 1 2 3 4 ] (conj v 6) ;; [1 2 3 4 5 6] [ 2 3 ] ( 2 3 4 5 6 ) (mapv inc v) ;; [2 3 4 5 6] [ 11 12 13 14 15 ] ;; Map (def m {:a 1 :b 2 :c {:d 3 :e 4}}) 1 1 1 3 { : a 1 : b 2 : c { : d 3 : e 4 } : f 5 } { : a 1 : b 2 : c { : d 3 : e 12 } } { : b 2 : c { : d 3 : e 4 } } { : a 1 : b 2 : c { : d 3 : e 5 } } { : a 1 : b 5 } (def coll (range 0 6)) ;; (0 1 2 3 4 5) (map inc coll) ;; (1 2 3 4 5 6) (filter odd? coll) ;; (1 3 5) 15 9 ;; threading last macro (->> coll (map inc) (filter odd?) 9
null
https://raw.githubusercontent.com/roman01la/clojurescript-workshop/48b02266d65cae8113edd4ce34c4ab282ad256d1/03.data_access_and_transformation/core.cljs
clojure
Vector [1 2 3 4 5 6] [2 3 4 5 6] Map (0 1 2 3 4 5) (1 2 3 4 5 6) (1 3 5) threading last macro
(def v [1 2 3 4 5]) 4 4 5 [ 1 2 3 4 ] [ 2 3 ] ( 2 3 4 5 6 ) [ 11 12 13 14 15 ] (def m {:a 1 :b 2 :c {:d 3 :e 4}}) 1 1 1 3 { : a 1 : b 2 : c { : d 3 : e 4 } : f 5 } { : a 1 : b 2 : c { : d 3 : e 12 } } { : b 2 : c { : d 3 : e 4 } } { : a 1 : b 2 : c { : d 3 : e 5 } } { : a 1 : b 5 } 15 9 (->> coll (map inc) (filter odd?) 9
c4693ecbfa8742f8f03413aa7e2a238743743fdb8a322e67cf5f27c4ffd02f33
kelamg/HtDP2e-workthrough
ex31.rkt
The first three lines of this file were inserted by . They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex31) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define (letter-2 fst lst signature-name) (string-append (opening fst) "\n\n" (body fst lst) "\n\n" (closing signature-name))) (define (opening fst) (string-append "Dear " fst ",")) (define (body fst lst) (string-append "We have discovered that all people with the" "\n" "last name " lst " have won our lottery. So, " "\n" fst ", " "hurry and pick up your prize.")) (define (closing signature-name) (string-append "Sincerely," "\n\n" signature-name "\n")) (define (main in-fst in-lst in-signature out) (write-file out (letter-2 (read-file in-fst) (read-file in-lst) (read-file in-signature)))) (main "fst.txt" "lst.txt" "sig.txt" 'stdout) (main "fst.txt" "lst.txt" "sig.txt" "letter-output.txt")
null
https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex31.rkt
racket
about the language level of this file in a form that our tools can easily process.
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex31) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require 2htdp/batch-io) (define (letter-2 fst lst signature-name) (string-append (opening fst) "\n\n" (body fst lst) "\n\n" (closing signature-name))) (define (opening fst) (string-append "Dear " fst ",")) (define (body fst lst) (string-append "We have discovered that all people with the" "\n" "last name " lst " have won our lottery. So, " "\n" fst ", " "hurry and pick up your prize.")) (define (closing signature-name) (string-append "Sincerely," "\n\n" signature-name "\n")) (define (main in-fst in-lst in-signature out) (write-file out (letter-2 (read-file in-fst) (read-file in-lst) (read-file in-signature)))) (main "fst.txt" "lst.txt" "sig.txt" 'stdout) (main "fst.txt" "lst.txt" "sig.txt" "letter-output.txt")
67747130fc47a2b3928e86120ed51b5d350b77c806747b950da029869d32f714
OlivierSohn/hamazed
Output.hs
# LANGUAGE ForeignFunctionInterface # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} | The functions in this module use < a lockfree , audio - engine > to create the audio signal and output it through the < / portaudio > library . = = = Audio thread isolation from GHC runtime Eventhough during garbage collection , GHC pauses all threads , since the real - time audio thread is /not/ managed by the GHC runtime , there is /no/ audio pause during GHC garbage collection . = = = Memory usage The RAM usage will be proportional to the count of different ' Instrument 's playing music at the same time . = = = Concurrency All exported functions are thread - safe . The functions in this module use < a lockfree, C++17 audio-engine> to create the audio signal and output it through the </ portaudio> library. === Audio thread isolation from GHC runtime Eventhough during garbage collection, GHC pauses all threads, since the real-time audio thread is /not/ managed by the GHC runtime, there is /no/ audio pause during GHC garbage collection. === Memory usage The RAM usage will be proportional to the count of different 'Instrument's playing music at the same time. === Concurrency All exported functions are thread-safe. -} module Imj.Audio.Output * Bracketed init / teardown usingAudioOutput , usingAudioOutputWithMinLatency -- * Avoiding MIDI jitter , setMaxMIDIJitter -- * Playing music , play , MusicalEvent(..) -- * Postprocessing , getReverbInfo , useReverb , setReverbWetRatio -- * C++ audio-engine implementation details | = = = Design evolution , from lockfull to To synchronize accesses to shared data between the audio realtime thread and non realtime threads , a locking approach was first used . = = = = Lockfull This approach , while being easy to implement and reason about , lead to < priority inversion > issues : sometimes , the realtime thread would have to wait ( a too - long time ) for a non - realtime thread to release the lock . This caused audio output buffer overflows , and audio glitches . = = = = Lockfull + thread priority adjustment To fix priority inversion , we raised the priority of every thread that was aiting to acquire the lock , and lowered the priority of the thread once the lock was released . Eventhough this approach was theoretically sound , it has proven ineffective in practice ( maybe because the priority change does n't take effect immediately ? ) and was requiring the program to be run under sudo on Linux , to grant the rights to modify thread priorities . = = = = A second , successfull attempt was made to fix the priority inversion by removing the need to lock in the realtime thread : using lockfree datastructures and algorithms , we could synchronize access to shared data without ever locking ( and without ever waiting in the realtime thread ) . Both modes ( lockfull , lockfree ) are available today via C++ template parametrization . The lockfree mode is the default , and recommended mode today , as it allows to smoothly output audio , even under contention . When compiling the package , you can revert to the old and unsafe lockfull mode by activating the ' Lock ' flag . = = = Benchmarks When compiling the package with the ' LogTime ' flag , the program will write in the console , every 1000 audio callback calls , the and average durations of the audio callback . === Design evolution, from lockfull to lockfree To synchronize accesses to shared data between the audio realtime thread and non realtime threads, a locking approach was first used. ==== Lockfull This approach, while being easy to implement and reason about, lead to < priority inversion> issues: sometimes, the realtime thread would have to wait (a too-long time) for a non-realtime thread to release the lock. This caused audio output buffer overflows, and audio glitches. ==== Lockfull + thread priority adjustment To fix priority inversion, we raised the priority of every thread that was aiting to acquire the lock, and lowered the priority of the thread once the lock was released. Eventhough this approach was theoretically sound, it has proven ineffective in practice (maybe because the priority change doesn't take effect immediately?) and was requiring the program to be run under sudo on Linux, to grant the rights to modify thread priorities. ==== Lockfree A second, successfull attempt was made to fix the priority inversion by removing the need to lock in the realtime thread: using lockfree datastructures and algorithms, we could synchronize access to shared data without ever locking (and without ever waiting in the realtime thread). Both modes (lockfull, lockfree) are available today via C++ template parametrization. The lockfree mode is the default, and recommended mode today, as it allows to smoothly output audio, even under contention. When compiling the package, you can revert to the old and unsafe lockfull mode by activating the 'Lock' flag. === Benchmarks When compiling the package with the 'LogTime' flag, the program will write in the console, every 1000 audio callback calls, the max and average durations of the audio callback. -} ) where import Control.Monad.IO.Unlift(MonadUnliftIO, liftIO) import Data.Bool(bool) import Data.Text(Text) import qualified Data.Vector.Storable as S import Foreign.C(CInt(..), CULLong(..), CShort(..), CFloat(..), CDouble(..), CString, withCString) import Foreign.ForeignPtr(withForeignPtr) import Foreign.Marshal.Alloc import Foreign.Ptr(Ptr, nullPtr) import Foreign.Storable import UnliftIO.Exception(bracket) import Imj.Audio.Envelope import Imj.Audio.Harmonics import Imj.Audio.Midi import Imj.Audio.SampleRate import Imj.Audio.SpaceResponse import Imj.Data.AlmostFloat import Imj.Music.Instruction import Imj.Music.Instrument import Imj.Music.Score(VoiceId(..)) import Imj.Timing -- | -- * initializes the global audio output stream if it is not initialized yet, -- * then runs the action containing calls to 'play', and possibly reentrant calls -- to 'usingAudioOutput' or 'usingAudioOutputWithMinLatency' -- * then if this is currently the only call to 'usingAudioOutput' or 'usingAudioOutputWithMinLatency' in the program , the audio output signal is swiftly cross - faded to zero -- and the global audio output stream is uninitialized. -- -- This function is thread-safe because the initialization and teardown of the -- global audio output stream are protected by a lock. -- -- This function can recursively call 'usingAudioOutput' or -- 'usingAudioOutputWithMinLatency' in the action passed as parameter. usingAudioOutput :: MonadUnliftIO m => m a -> m (Either Text a) usingAudioOutput = usingAudioOutputWithMinLatency globalSampleRate $ fromSecs 0.008 -- if you hear audio cracks, use a larger latency -- | Same as 'usingAudioOutput' except that the minimum latency can be configured. -- -- Note that the latency parameter will be used only if there is currently no other active call to -- 'usingAudioOutput' or 'usingAudioOutputWithMinLatency', else it is ignored (in that case, -- the global audio output stream is already initialized). usingAudioOutputWithMinLatency :: MonadUnliftIO m => Int -- ^ Sampling rate ->Time Duration System -- ^ The minimum latency of the audio output stream. -- -- Depending on your system's characteristics, -- using a too small value may generate audio glitches. -- Hence, when in doubt, use 'usingAudioOutput' which uses -- a safe default value. -> m a -> m (Either Text a) usingAudioOutputWithMinLatency samplingRate minLatency act = bracket bra ket $ either (const $ return $ Left "Audio output failed to initialize") (const $ fmap Right act) where TODO to enable very low ( thus unsafe ) latencies , override portaudio 's min latency ( use a ' Just ' instead of ' Nothing ' ) bra = liftIO $ initializeAudioOutput samplingRate minLatency Nothing -- we ignore the initialization return because regardless of wether it succeeded or not, -- the 'initializeAudioOutput' call must be matched with a 'teardownAudioOutput' call. ket _ = liftIO teardownAudioOutput initializeAudioOutput :: Int -- ^ Sampling rate -> Time Duration System -- ^ The audio output stream will have a latency no smaller than this value. -> Maybe (Time Duration System) -- ^ When the 'Just' value, floored to the previous millisecond, -- is strictly positive, it is used to set the < #portaudio PA_MIN_LATENCY_MSEC > -- environment variable, to override the Portaudio minimum latency . Use only if you know -- your system can handle that latency, else, use 'Nothing'. -> IO (Either () ()) initializeAudioOutput sampling_rate a b = bool (Left ()) (Right ()) <$> initializeAudioOutput_ sampling_rate (realToFrac $ unsafeToSecs a) (maybe 0 (fromIntegral . toMicros) b) -- | Should be called prior to using 'effect***' and 'midi***' functions. foreign import ccall "initializeAudioOutput" initializeAudioOutput_ :: Int -> Float -> Int -> IO Bool -- | Undoes what 'initializeAudioOutput' did. foreign import ccall "teardownAudioOutput" teardownAudioOutput :: IO () foreign import ccall "setMaxMIDIJitter" setMaxMIDIJitter_ :: CULLong -> IO () TODO should this be per - source ? every source can have a different polling setting , -- and different connection characteristics with the server. setMaxMIDIJitter :: MaxMIDIJitter -> IO () setMaxMIDIJitter = setMaxMIDIJitter_ . (*1000) . fromIntegral -- | Plays a 'MusicalEvent'. -- -- If a 'StopNote' is played less than @audio latency@ milliseconds after -- its corresponding 'StartNote', the note won't be audible. -- -- This function is thread-safe. -- -- This function should be called from an action -- run with 'usingAudioOutput' or 'usingAudioOutputWithMinLatency'. -- If this is not the case, it has no effect and returns 'Left ()'. play :: MusicalEvent Instrument -> VoiceId -- ^ Internally, each "instrument" has a separate domain for note ids. -- But when the same instrument is used to play different voices at the same time -- the same noteon for the same pitch could be issued several times. VoiceId will be used to associate a noteoff or notechange ot a previous noteon . -> IO (Either () ()) play (StartNote mayMidi n@(InstrumentNote _ _ i) (NoteVelocity v) (NotePan pan)) (VoiceId voice) = bool (Left ()) (Right ()) <$> case i of Synth (Oscillations osc har) e ahdsr -> let (harPtr, harSz) = S.unsafeToForeignPtr0 $ unHarmonics har in withForeignPtr harPtr $ \harmonicsPtr -> midiNoteOnAHDSR (Right osc) e ahdsr (harmonicsPtr, harSz) pitch vel mayMidi panF voiceI Synth Noise e ahdsr -> midiNoteOnAHDSR (Left $ -1) e ahdsr (nullPtr, 0) pitch vel mayMidi panF voiceI Synth (Sweep sweep_duration freq freqType itp) e ahdsr -> midiNoteOnAHDSRSweep (Left $ -2) e ahdsr (nullPtr, 0) sweep_duration freq freqType itp pitch vel mayMidi panF voiceI Wind k -> effectOn voiceI (fromIntegral k) pitch vel panF where (MidiPitch pitch) = instrumentNoteToMidiPitch n vel = CFloat v panF = CFloat pan voiceI = fromIntegral voice play (StopNote mayMidi n@(InstrumentNote _ _ i)) (VoiceId voice) = bool (Left ()) (Right ()) <$> case i of Synth (Oscillations osc har) e ahdsr -> let (harPtr, harSz) = S.unsafeToForeignPtr0 $ unHarmonics har in withForeignPtr harPtr $ \harmonicsPtr -> midiNoteOffAHDSR (Right osc) e ahdsr (harmonicsPtr, harSz) pitch mayMidi voiceI Synth Noise e ahdsr -> midiNoteOffAHDSR (Left $ -1) e ahdsr (nullPtr, 0) pitch mayMidi voiceI Synth (Sweep sweep_duration freq freqType itp) e ahdsr -> midiNoteOffAHDSRSweep (Left $ -2) e ahdsr (nullPtr, 0) sweep_duration freq freqType itp pitch mayMidi voiceI Wind _ -> effectOff voiceI pitch where (MidiPitch pitch) = instrumentNoteToMidiPitch n voiceI = fromIntegral voice midiNoteOffAHDSR :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> CShort -> Maybe MidiInfo -> CInt -> IO Bool midiNoteOnAHDSR :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> CShort -> CFloat -> Maybe MidiInfo -> CFloat -> CInt -> IO Bool midiNoteOffAHDSRSweep :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> Int -> AlmostFloat -> SweepFreqType -> Interpolation -> CShort -> Maybe MidiInfo -> CInt -> IO Bool midiNoteOnAHDSRSweep :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> Int -> AlmostFloat -> SweepFreqType -> Interpolation -> CShort -> CFloat -> Maybe MidiInfo -> CFloat -> CInt -> IO Bool midiNoteOffAHDSR osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) i mayMidi voice = midiNoteOffAHDSR_ voice (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) i src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOffAHDSRSweep osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) sweep_duration sweep_freq sweep_freq_type sweep_interp i mayMidi voice = midiNoteOffAHDSRSweep_ voice (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) (fromIntegral sweep_duration) (realToFrac $ unAlmostFloat sweep_freq) (fromIntegral $ fromEnum sweep_freq_type) (interpolationToCInt sweep_interp) i src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOnAHDSR osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) i v mayMidi pan voice = midiNoteOnAHDSR_ voice pan (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) i v src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOnAHDSRSweep osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) sweep_duration sweep_freq sweep_freq_type sweep_interp i v mayMidi pan voice = midiNoteOnAHDSRSweep_ voice pan (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) (fromIntegral sweep_duration) (realToFrac $ unAlmostFloat sweep_freq) (fromIntegral $ fromEnum sweep_freq_type) (interpolationToCInt sweep_interp) i v src time where (src, time) = mayMidiInfoToSrcTime mayMidi mayMidiInfoToSrcTime :: Maybe MidiInfo -> (CInt, CULLong) mayMidiInfoToSrcTime mayMidi = (src, time) where -- -1 encodes "no source" src = fromIntegral $ maybe (-1 :: CInt) (fromIntegral . unMidiSourceIdx . source) mayMidi time = fromIntegral $ maybe 0 timestamp mayMidi foreign import ccall "getConvolutionReverbSignature_" getReverbSignature :: CString -> CString -> Ptr SpaceResponse -> IO Bool getReverbInfo :: String -> String -> IO (Maybe SpaceResponse) getReverbInfo dirName fileName = withCString dirName $ \d -> withCString fileName $ \f -> alloca $ \p -> getReverbSignature d f p >>= bool (return Nothing) (Just <$> peek p) foreign import ccall "dontUseReverb_" dontUseReverb_ :: IO Bool foreign import ccall "useReverb_" useReverb_ :: CString -> CString -> CDouble -> IO Bool useReverb :: Double -> Maybe (String, String) -> IO (Either () ()) useReverb wet = fmap (bool (Left ()) (Right ())) . maybe dontUseReverb_ (\(dirName, fileName) -> withCString dirName $ \d -> withCString fileName $ \f -> useReverb_ d f (realToFrac wet)) foreign import ccall "setReverbWetRatio" setReverbWetRatio_ :: CDouble -> IO Bool setReverbWetRatio :: Double -> IO (Either () ()) setReverbWetRatio = fmap (bool (Left ()) (Right ())) . setReverbWetRatio_ . realToFrac foreign import ccall "effectOn" effectOn :: CInt -- ^ voice -> CInt -> CShort -> CFloat -> CFloat -> IO Bool foreign import ccall "effectOff" effectOff :: CInt -- ^ voice -> CShort -> IO Bool foreign import ccall "midiNoteOnAHDSR_" midiNoteOnAHDSR_ :: CInt -- ^ Voice -> CFloat -- ^ Stereo -> CInt -> CInt -- ^ Envelope type -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CShort -> CFloat -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOffAHDSR_" midiNoteOffAHDSR_ :: CInt -- ^ Voice -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CShort -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOnAHDSRSweep_" midiNoteOnAHDSRSweep_ :: CInt -- ^ Voice -> CFloat -- ^ Stereo -> CInt -> CInt -- ^ Envelope type -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CInt -- ^ Sweep duration -> CFloat -- ^ Sweep freq -> CInt -- ^ Sweep freq type -> CInt -- ^ Sweep interpolation -> CShort -> CFloat -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOffAHDSRSweep_" midiNoteOffAHDSRSweep_ :: CInt -- ^ Voice -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CInt -- ^ Sweep duration -> CFloat -- ^ Sweep freq -> CInt -- ^ Sweep freq type -> CInt -- ^ Sweep interpolation -> CShort -> CInt -> CULLong -> IO Bool
null
https://raw.githubusercontent.com/OlivierSohn/hamazed/ea0eb795cab7a3dadd3a0c77465eab358ca5c566/imj-audio/src/Imj/Audio/Output.hs
haskell
# LANGUAGE OverloadedStrings # * Avoiding MIDI jitter * Playing music * Postprocessing * C++ audio-engine implementation details | * initializes the global audio output stream if it is not initialized yet, * then runs the action containing calls to 'play', and possibly reentrant calls to 'usingAudioOutput' or 'usingAudioOutputWithMinLatency' * then if this is currently the only call to 'usingAudioOutput' or 'usingAudioOutputWithMinLatency' and the global audio output stream is uninitialized. This function is thread-safe because the initialization and teardown of the global audio output stream are protected by a lock. This function can recursively call 'usingAudioOutput' or 'usingAudioOutputWithMinLatency' in the action passed as parameter. if you hear audio cracks, use a larger latency | Same as 'usingAudioOutput' except that the minimum latency can be configured. Note that the latency parameter will be used only if there is currently no other active call to 'usingAudioOutput' or 'usingAudioOutputWithMinLatency', else it is ignored (in that case, the global audio output stream is already initialized). ^ Sampling rate ^ The minimum latency of the audio output stream. Depending on your system's characteristics, using a too small value may generate audio glitches. Hence, when in doubt, use 'usingAudioOutput' which uses a safe default value. we ignore the initialization return because regardless of wether it succeeded or not, the 'initializeAudioOutput' call must be matched with a 'teardownAudioOutput' call. ^ Sampling rate ^ The audio output stream will have a latency no smaller than this value. ^ When the 'Just' value, floored to the previous millisecond, is strictly positive, it is used to set the environment variable, your system can handle that latency, else, use 'Nothing'. | Should be called prior to using 'effect***' and 'midi***' functions. | Undoes what 'initializeAudioOutput' did. and different connection characteristics with the server. | Plays a 'MusicalEvent'. If a 'StopNote' is played less than @audio latency@ milliseconds after its corresponding 'StartNote', the note won't be audible. This function is thread-safe. This function should be called from an action run with 'usingAudioOutput' or 'usingAudioOutputWithMinLatency'. If this is not the case, it has no effect and returns 'Left ()'. ^ Internally, each "instrument" has a separate domain for note ids. But when the same instrument is used to play different voices at the same time the same noteon for the same pitch could be issued several times. -1 encodes "no source" ^ voice ^ voice ^ Voice ^ Stereo ^ Envelope type ^ Voice ^ Voice ^ Stereo ^ Envelope type ^ Sweep duration ^ Sweep freq ^ Sweep freq type ^ Sweep interpolation ^ Voice ^ Sweep duration ^ Sweep freq ^ Sweep freq type ^ Sweep interpolation
# LANGUAGE ForeignFunctionInterface # # LANGUAGE LambdaCase # | The functions in this module use < a lockfree , audio - engine > to create the audio signal and output it through the < / portaudio > library . = = = Audio thread isolation from GHC runtime Eventhough during garbage collection , GHC pauses all threads , since the real - time audio thread is /not/ managed by the GHC runtime , there is /no/ audio pause during GHC garbage collection . = = = Memory usage The RAM usage will be proportional to the count of different ' Instrument 's playing music at the same time . = = = Concurrency All exported functions are thread - safe . The functions in this module use < a lockfree, C++17 audio-engine> to create the audio signal and output it through the </ portaudio> library. === Audio thread isolation from GHC runtime Eventhough during garbage collection, GHC pauses all threads, since the real-time audio thread is /not/ managed by the GHC runtime, there is /no/ audio pause during GHC garbage collection. === Memory usage The RAM usage will be proportional to the count of different 'Instrument's playing music at the same time. === Concurrency All exported functions are thread-safe. -} module Imj.Audio.Output * Bracketed init / teardown usingAudioOutput , usingAudioOutputWithMinLatency , setMaxMIDIJitter , play , MusicalEvent(..) , getReverbInfo , useReverb , setReverbWetRatio | = = = Design evolution , from lockfull to To synchronize accesses to shared data between the audio realtime thread and non realtime threads , a locking approach was first used . = = = = Lockfull This approach , while being easy to implement and reason about , lead to < priority inversion > issues : sometimes , the realtime thread would have to wait ( a too - long time ) for a non - realtime thread to release the lock . This caused audio output buffer overflows , and audio glitches . = = = = Lockfull + thread priority adjustment To fix priority inversion , we raised the priority of every thread that was aiting to acquire the lock , and lowered the priority of the thread once the lock was released . Eventhough this approach was theoretically sound , it has proven ineffective in practice ( maybe because the priority change does n't take effect immediately ? ) and was requiring the program to be run under sudo on Linux , to grant the rights to modify thread priorities . = = = = A second , successfull attempt was made to fix the priority inversion by removing the need to lock in the realtime thread : using lockfree datastructures and algorithms , we could synchronize access to shared data without ever locking ( and without ever waiting in the realtime thread ) . Both modes ( lockfull , lockfree ) are available today via C++ template parametrization . The lockfree mode is the default , and recommended mode today , as it allows to smoothly output audio , even under contention . When compiling the package , you can revert to the old and unsafe lockfull mode by activating the ' Lock ' flag . = = = Benchmarks When compiling the package with the ' LogTime ' flag , the program will write in the console , every 1000 audio callback calls , the and average durations of the audio callback . === Design evolution, from lockfull to lockfree To synchronize accesses to shared data between the audio realtime thread and non realtime threads, a locking approach was first used. ==== Lockfull This approach, while being easy to implement and reason about, lead to < priority inversion> issues: sometimes, the realtime thread would have to wait (a too-long time) for a non-realtime thread to release the lock. This caused audio output buffer overflows, and audio glitches. ==== Lockfull + thread priority adjustment To fix priority inversion, we raised the priority of every thread that was aiting to acquire the lock, and lowered the priority of the thread once the lock was released. Eventhough this approach was theoretically sound, it has proven ineffective in practice (maybe because the priority change doesn't take effect immediately?) and was requiring the program to be run under sudo on Linux, to grant the rights to modify thread priorities. ==== Lockfree A second, successfull attempt was made to fix the priority inversion by removing the need to lock in the realtime thread: using lockfree datastructures and algorithms, we could synchronize access to shared data without ever locking (and without ever waiting in the realtime thread). Both modes (lockfull, lockfree) are available today via C++ template parametrization. The lockfree mode is the default, and recommended mode today, as it allows to smoothly output audio, even under contention. When compiling the package, you can revert to the old and unsafe lockfull mode by activating the 'Lock' flag. === Benchmarks When compiling the package with the 'LogTime' flag, the program will write in the console, every 1000 audio callback calls, the max and average durations of the audio callback. -} ) where import Control.Monad.IO.Unlift(MonadUnliftIO, liftIO) import Data.Bool(bool) import Data.Text(Text) import qualified Data.Vector.Storable as S import Foreign.C(CInt(..), CULLong(..), CShort(..), CFloat(..), CDouble(..), CString, withCString) import Foreign.ForeignPtr(withForeignPtr) import Foreign.Marshal.Alloc import Foreign.Ptr(Ptr, nullPtr) import Foreign.Storable import UnliftIO.Exception(bracket) import Imj.Audio.Envelope import Imj.Audio.Harmonics import Imj.Audio.Midi import Imj.Audio.SampleRate import Imj.Audio.SpaceResponse import Imj.Data.AlmostFloat import Imj.Music.Instruction import Imj.Music.Instrument import Imj.Music.Score(VoiceId(..)) import Imj.Timing in the program , the audio output signal is swiftly cross - faded to zero usingAudioOutput :: MonadUnliftIO m => m a -> m (Either Text a) usingAudioOutput = usingAudioOutputWithMinLatency globalSampleRate $ fromSecs 0.008 usingAudioOutputWithMinLatency :: MonadUnliftIO m => Int ->Time Duration System -> m a -> m (Either Text a) usingAudioOutputWithMinLatency samplingRate minLatency act = bracket bra ket $ either (const $ return $ Left "Audio output failed to initialize") (const $ fmap Right act) where TODO to enable very low ( thus unsafe ) latencies , override portaudio 's min latency ( use a ' Just ' instead of ' Nothing ' ) bra = liftIO $ initializeAudioOutput samplingRate minLatency Nothing ket _ = liftIO teardownAudioOutput initializeAudioOutput :: Int -> Time Duration System -> Maybe (Time Duration System) < #portaudio PA_MIN_LATENCY_MSEC > to override the Portaudio minimum latency . Use only if you know -> IO (Either () ()) initializeAudioOutput sampling_rate a b = bool (Left ()) (Right ()) <$> initializeAudioOutput_ sampling_rate (realToFrac $ unsafeToSecs a) (maybe 0 (fromIntegral . toMicros) b) foreign import ccall "initializeAudioOutput" initializeAudioOutput_ :: Int -> Float -> Int -> IO Bool foreign import ccall "teardownAudioOutput" teardownAudioOutput :: IO () foreign import ccall "setMaxMIDIJitter" setMaxMIDIJitter_ :: CULLong -> IO () TODO should this be per - source ? every source can have a different polling setting , setMaxMIDIJitter :: MaxMIDIJitter -> IO () setMaxMIDIJitter = setMaxMIDIJitter_ . (*1000) . fromIntegral play :: MusicalEvent Instrument -> VoiceId VoiceId will be used to associate a noteoff or notechange ot a previous noteon . -> IO (Either () ()) play (StartNote mayMidi n@(InstrumentNote _ _ i) (NoteVelocity v) (NotePan pan)) (VoiceId voice) = bool (Left ()) (Right ()) <$> case i of Synth (Oscillations osc har) e ahdsr -> let (harPtr, harSz) = S.unsafeToForeignPtr0 $ unHarmonics har in withForeignPtr harPtr $ \harmonicsPtr -> midiNoteOnAHDSR (Right osc) e ahdsr (harmonicsPtr, harSz) pitch vel mayMidi panF voiceI Synth Noise e ahdsr -> midiNoteOnAHDSR (Left $ -1) e ahdsr (nullPtr, 0) pitch vel mayMidi panF voiceI Synth (Sweep sweep_duration freq freqType itp) e ahdsr -> midiNoteOnAHDSRSweep (Left $ -2) e ahdsr (nullPtr, 0) sweep_duration freq freqType itp pitch vel mayMidi panF voiceI Wind k -> effectOn voiceI (fromIntegral k) pitch vel panF where (MidiPitch pitch) = instrumentNoteToMidiPitch n vel = CFloat v panF = CFloat pan voiceI = fromIntegral voice play (StopNote mayMidi n@(InstrumentNote _ _ i)) (VoiceId voice) = bool (Left ()) (Right ()) <$> case i of Synth (Oscillations osc har) e ahdsr -> let (harPtr, harSz) = S.unsafeToForeignPtr0 $ unHarmonics har in withForeignPtr harPtr $ \harmonicsPtr -> midiNoteOffAHDSR (Right osc) e ahdsr (harmonicsPtr, harSz) pitch mayMidi voiceI Synth Noise e ahdsr -> midiNoteOffAHDSR (Left $ -1) e ahdsr (nullPtr, 0) pitch mayMidi voiceI Synth (Sweep sweep_duration freq freqType itp) e ahdsr -> midiNoteOffAHDSRSweep (Left $ -2) e ahdsr (nullPtr, 0) sweep_duration freq freqType itp pitch mayMidi voiceI Wind _ -> effectOff voiceI pitch where (MidiPitch pitch) = instrumentNoteToMidiPitch n voiceI = fromIntegral voice midiNoteOffAHDSR :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> CShort -> Maybe MidiInfo -> CInt -> IO Bool midiNoteOnAHDSR :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> CShort -> CFloat -> Maybe MidiInfo -> CFloat -> CInt -> IO Bool midiNoteOffAHDSRSweep :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> Int -> AlmostFloat -> SweepFreqType -> Interpolation -> CShort -> Maybe MidiInfo -> CInt -> IO Bool midiNoteOnAHDSRSweep :: Either Int Oscillator -> ReleaseMode -> AHDSR'Envelope -> (Ptr HarmonicProperties, Int) -> Int -> AlmostFloat -> SweepFreqType -> Interpolation -> CShort -> CFloat -> Maybe MidiInfo -> CFloat -> CInt -> IO Bool midiNoteOffAHDSR osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) i mayMidi voice = midiNoteOffAHDSR_ voice (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) i src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOffAHDSRSweep osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) sweep_duration sweep_freq sweep_freq_type sweep_interp i mayMidi voice = midiNoteOffAHDSRSweep_ voice (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) (fromIntegral sweep_duration) (realToFrac $ unAlmostFloat sweep_freq) (fromIntegral $ fromEnum sweep_freq_type) (interpolationToCInt sweep_interp) i src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOnAHDSR osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) i v mayMidi pan voice = midiNoteOnAHDSR_ voice pan (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) i v src time where (src, time) = mayMidiInfoToSrcTime mayMidi midiNoteOnAHDSRSweep osc t (AHDSR'Envelope a h d r ai di ri s) (harmonicsPtr, harmonicsSz) sweep_duration sweep_freq sweep_freq_type sweep_interp i v mayMidi pan voice = midiNoteOnAHDSRSweep_ voice pan (either fromIntegral (fromIntegral . fromEnum) osc) (fromIntegral $ fromEnum t) (fromIntegral a) (interpolationToCInt ai) (fromIntegral h) (fromIntegral d) (interpolationToCInt di) (realToFrac s) (fromIntegral r) (interpolationToCInt ri) harmonicsPtr (fromIntegral harmonicsSz) (fromIntegral sweep_duration) (realToFrac $ unAlmostFloat sweep_freq) (fromIntegral $ fromEnum sweep_freq_type) (interpolationToCInt sweep_interp) i v src time where (src, time) = mayMidiInfoToSrcTime mayMidi mayMidiInfoToSrcTime :: Maybe MidiInfo -> (CInt, CULLong) mayMidiInfoToSrcTime mayMidi = (src, time) where src = fromIntegral $ maybe (-1 :: CInt) (fromIntegral . unMidiSourceIdx . source) mayMidi time = fromIntegral $ maybe 0 timestamp mayMidi foreign import ccall "getConvolutionReverbSignature_" getReverbSignature :: CString -> CString -> Ptr SpaceResponse -> IO Bool getReverbInfo :: String -> String -> IO (Maybe SpaceResponse) getReverbInfo dirName fileName = withCString dirName $ \d -> withCString fileName $ \f -> alloca $ \p -> getReverbSignature d f p >>= bool (return Nothing) (Just <$> peek p) foreign import ccall "dontUseReverb_" dontUseReverb_ :: IO Bool foreign import ccall "useReverb_" useReverb_ :: CString -> CString -> CDouble -> IO Bool useReverb :: Double -> Maybe (String, String) -> IO (Either () ()) useReverb wet = fmap (bool (Left ()) (Right ())) . maybe dontUseReverb_ (\(dirName, fileName) -> withCString dirName $ \d -> withCString fileName $ \f -> useReverb_ d f (realToFrac wet)) foreign import ccall "setReverbWetRatio" setReverbWetRatio_ :: CDouble -> IO Bool setReverbWetRatio :: Double -> IO (Either () ()) setReverbWetRatio = fmap (bool (Left ()) (Right ())) . setReverbWetRatio_ . realToFrac foreign import ccall "effectOn" effectOn :: CInt -> CInt -> CShort -> CFloat -> CFloat -> IO Bool foreign import ccall "effectOff" effectOff :: CInt -> CShort -> IO Bool foreign import ccall "midiNoteOnAHDSR_" midiNoteOnAHDSR_ :: CInt -> CFloat -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CShort -> CFloat -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOffAHDSR_" midiNoteOffAHDSR_ :: CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CShort -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOnAHDSRSweep_" midiNoteOnAHDSRSweep_ :: CInt -> CFloat -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CInt -> CFloat -> CInt -> CInt -> CShort -> CFloat -> CInt -> CULLong -> IO Bool foreign import ccall "midiNoteOffAHDSRSweep_" midiNoteOffAHDSRSweep_ :: CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CInt -> CFloat -> CInt -> CInt -> Ptr HarmonicProperties -> CInt -> CInt -> CFloat -> CInt -> CInt -> CShort -> CInt -> CULLong -> IO Bool
024655f0940b085bd32cc087a9f194a18a35dcdf8de35e39c23f1449ef7861f7
basho/riak_test
verify_dvv_repl.erl
%% ------------------------------------------------------------------- %% Copyright ( c ) 2014 Basho Technologies , Inc. %% 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. %% %% ------------------------------------------------------------------- ( C ) 2014 , Basho Technologies %%% @doc riak_test repl caused sibling explosion Encodes scenario as %%% described to me in hipchat. Write something to cluster B, enable %%% realtime repl from A to B, read and write object, with resolution to A 100 times . Without DVV you have 100 siblings on B , with , you have 2 ( the original B write , and the converged A writes ) %%% @end -module(verify_dvv_repl). -behavior(riak_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -define(BUCKET, <<"dvv-repl-bucket">>). -define(KEY, <<"dvv-repl-key">>). -define(KEY2, <<"dvv-repl-key2">>). confirm() -> inets:start(), {{ClientA, ClusterA}, {ClientB, ClusterB}} = make_clusters(), %% Write data to B write_object(ClientB), Connect for real time repl A->B connect_realtime(ClusterA, ClusterB), IsReplicating = make_replicate_test_fun(ClientA, ClientB), rt:wait_until(IsReplicating), Update ClusterA 100 times [write_object(ClientA) || _ <- lists:seq(1, 100)], Get the object , and see if it has 100 siblings ( not the two it should have . ) Turn off DVV in ` ` and see the %% siblings explode! AObj = get_object(ClientA), Expected = lists:seq(1, 100), Having up to 3 siblings could happen in rare cases when the writes hit %% different nodes concurrently in the n_val=3 preflist. ?assertMatch(Count when Count =< 3, riakc_obj:value_count(AObj)), WaitFun = fun() -> lager:info("Checking sink object"), BObj = get_object(ClientB), Resolved0 = resolve(riakc_obj:get_values(BObj)), Resolved = lists:sort(sets:to_list(Resolved0)), case Resolved of Expected -> BCount = riakc_obj:value_count(BObj), ?assertMatch(C when C =< 6, BCount), true; _ -> false end end, ?assertEqual(ok, rt:wait_until(WaitFun)), pass. make_replicate_test_fun(From, To) -> fun() -> Obj = riakc_obj:new(?BUCKET, ?KEY2, <<"am I replicated yet?">>), ok = riakc_pb_socket:put(From, Obj), case riakc_pb_socket:get(To, ?BUCKET, ?KEY2) of {ok, _} -> true; {error, notfound} -> false end end. make_clusters() -> Conf = [{riak_repl, [{fullsync_on_connect, false}, {fullsync_interval, disabled}]}, {riak_core, [{default_bucket_props, [{dvv_enabled, true}, {allow_mult, true}]}]}], Nodes = rt:deploy_nodes(6, Conf, [riak_kv, riak_repl]), {ClusterA, ClusterB} = lists:split(3, Nodes), A = make_cluster(ClusterA, "A"), B = make_cluster(ClusterB, "B"), {A, B}. make_cluster(Nodes, Name) -> repl_util:make_cluster(Nodes), repl_util:name_cluster(hd(Nodes), Name), repl_util:wait_until_leader_converge(Nodes), C = rt:pbc(hd(Nodes)), riakc_pb_socket:set_options(C, [queue_if_disconnected]), {C, Nodes}. write_object([]) -> ok; write_object([Client | Rest]) -> ok = write_object(Client), write_object(Rest); write_object(Client) -> fetch_resolve_write(Client). get_object(Client) -> case riakc_pb_socket:get(Client, ?BUCKET, ?KEY) of {ok, Obj} -> Obj; _ -> riakc_obj:new(?BUCKET, ?KEY) end. fetch_resolve_write(Client) -> Obj = get_object(Client), Value = resolve_update(riakc_obj:get_values(Obj)), Obj3 = riakc_obj:update_metadata(riakc_obj:update_value(Obj, Value), dict:new()), ok = riakc_pb_socket:put(Client, Obj3). resolve(Values) -> lists:foldl(fun(V0, Acc) -> V = binary_to_term(V0), sets:union(V, Acc) end, sets:new(), Values). resolve_update([]) -> sets:add_element(1, sets:new()); resolve_update(Values) -> Resolved = resolve(Values), NewValue = lists:max(sets:to_list(Resolved)) + 1, sets:add_element(NewValue, Resolved). Set up one way RT repl connect_realtime(ClusterA, ClusterB) -> lager:info("repl power...ACTIVATE!"), LeaderA = get_leader(hd(ClusterA)), MgrPortB = get_mgr_port(hd(ClusterB)), repl_util:connect_cluster(LeaderA, "127.0.0.1", MgrPortB), ?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")), repl_util:enable_realtime(LeaderA, "B"), repl_util:start_realtime(LeaderA, "B"). get_leader(Node) -> rpc:call(Node, riak_core_cluster_mgr, get_leader, []). get_mgr_port(Node) -> {ok, {_IP, Port}} = rpc:call(Node, application, get_env, [riak_core, cluster_mgr]), Port.
null
https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/verify_dvv_repl.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. ------------------------------------------------------------------- @doc described to me in hipchat. Write something to cluster B, enable realtime repl from A to B, read and write object, with resolution @end Write data to B siblings explode! different nodes concurrently in the n_val=3 preflist.
Copyright ( c ) 2014 Basho Technologies , Inc. 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 ( C ) 2014 , Basho Technologies riak_test repl caused sibling explosion Encodes scenario as to A 100 times . Without DVV you have 100 siblings on B , with , you have 2 ( the original B write , and the converged A writes ) -module(verify_dvv_repl). -behavior(riak_test). -export([confirm/0]). -include_lib("eunit/include/eunit.hrl"). -define(BUCKET, <<"dvv-repl-bucket">>). -define(KEY, <<"dvv-repl-key">>). -define(KEY2, <<"dvv-repl-key2">>). confirm() -> inets:start(), {{ClientA, ClusterA}, {ClientB, ClusterB}} = make_clusters(), write_object(ClientB), Connect for real time repl A->B connect_realtime(ClusterA, ClusterB), IsReplicating = make_replicate_test_fun(ClientA, ClientB), rt:wait_until(IsReplicating), Update ClusterA 100 times [write_object(ClientA) || _ <- lists:seq(1, 100)], Get the object , and see if it has 100 siblings ( not the two it should have . ) Turn off DVV in ` ` and see the AObj = get_object(ClientA), Expected = lists:seq(1, 100), Having up to 3 siblings could happen in rare cases when the writes hit ?assertMatch(Count when Count =< 3, riakc_obj:value_count(AObj)), WaitFun = fun() -> lager:info("Checking sink object"), BObj = get_object(ClientB), Resolved0 = resolve(riakc_obj:get_values(BObj)), Resolved = lists:sort(sets:to_list(Resolved0)), case Resolved of Expected -> BCount = riakc_obj:value_count(BObj), ?assertMatch(C when C =< 6, BCount), true; _ -> false end end, ?assertEqual(ok, rt:wait_until(WaitFun)), pass. make_replicate_test_fun(From, To) -> fun() -> Obj = riakc_obj:new(?BUCKET, ?KEY2, <<"am I replicated yet?">>), ok = riakc_pb_socket:put(From, Obj), case riakc_pb_socket:get(To, ?BUCKET, ?KEY2) of {ok, _} -> true; {error, notfound} -> false end end. make_clusters() -> Conf = [{riak_repl, [{fullsync_on_connect, false}, {fullsync_interval, disabled}]}, {riak_core, [{default_bucket_props, [{dvv_enabled, true}, {allow_mult, true}]}]}], Nodes = rt:deploy_nodes(6, Conf, [riak_kv, riak_repl]), {ClusterA, ClusterB} = lists:split(3, Nodes), A = make_cluster(ClusterA, "A"), B = make_cluster(ClusterB, "B"), {A, B}. make_cluster(Nodes, Name) -> repl_util:make_cluster(Nodes), repl_util:name_cluster(hd(Nodes), Name), repl_util:wait_until_leader_converge(Nodes), C = rt:pbc(hd(Nodes)), riakc_pb_socket:set_options(C, [queue_if_disconnected]), {C, Nodes}. write_object([]) -> ok; write_object([Client | Rest]) -> ok = write_object(Client), write_object(Rest); write_object(Client) -> fetch_resolve_write(Client). get_object(Client) -> case riakc_pb_socket:get(Client, ?BUCKET, ?KEY) of {ok, Obj} -> Obj; _ -> riakc_obj:new(?BUCKET, ?KEY) end. fetch_resolve_write(Client) -> Obj = get_object(Client), Value = resolve_update(riakc_obj:get_values(Obj)), Obj3 = riakc_obj:update_metadata(riakc_obj:update_value(Obj, Value), dict:new()), ok = riakc_pb_socket:put(Client, Obj3). resolve(Values) -> lists:foldl(fun(V0, Acc) -> V = binary_to_term(V0), sets:union(V, Acc) end, sets:new(), Values). resolve_update([]) -> sets:add_element(1, sets:new()); resolve_update(Values) -> Resolved = resolve(Values), NewValue = lists:max(sets:to_list(Resolved)) + 1, sets:add_element(NewValue, Resolved). Set up one way RT repl connect_realtime(ClusterA, ClusterB) -> lager:info("repl power...ACTIVATE!"), LeaderA = get_leader(hd(ClusterA)), MgrPortB = get_mgr_port(hd(ClusterB)), repl_util:connect_cluster(LeaderA, "127.0.0.1", MgrPortB), ?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")), repl_util:enable_realtime(LeaderA, "B"), repl_util:start_realtime(LeaderA, "B"). get_leader(Node) -> rpc:call(Node, riak_core_cluster_mgr, get_leader, []). get_mgr_port(Node) -> {ok, {_IP, Port}} = rpc:call(Node, application, get_env, [riak_core, cluster_mgr]), Port.
5fa109e85a3773272d3a3fedecce3d1fc75bba0b5a3fa9962bc933d7ec9e3479
vbmithr/ocaml-bitcoin
bloom.ml
open Sexplib.Std open Murmur3.Murmur_cstruct open Util let bytes_max = 36000 let funcs_max = 50 let seed_mult = 0xfba4c795l type t = { filter : Bitv.t ; len : int ; nb_funcs : int ; tweak : int32 ; } [@@deriving sexp] let filter_len { filter ; _ } = * Bitv.length filter / 8 * Bitv.length filter / 8 *) let to_filter { filter; _ } = try Bitv.to_string_le filter with _ -> invalid_arg "Bloom.to_string" let pp_hex ppf t = let `Hex filter_hex = Hex.of_string (to_filter t) in Caml.Format.fprintf ppf "%s" filter_hex let of_filter filter nb_funcs tweak = let len = String.length filter in if len > bytes_max || nb_funcs > funcs_max then invalid_arg "Bloom.of_filter" ; { filter = Bitv.of_string_le filter ; len ; nb_funcs ; tweak } let create n p tweak = let n = Float.of_int n in let filter_len_bytes = let open Float in min (-1. /. (log 2. *. log 2.) *. n *. log p /. 8.) (of_int bytes_max) |> to_int in let nb_funcs = let open Float in min (of_int filter_len_bytes *. 8. /. n *. log 2.) (of_int funcs_max) |> to_int in { filter = Bitv.create (filter_len_bytes * 8) false ; len = filter_len_bytes ; nb_funcs ; tweak } let reset t = { t with filter = Bitv.(create (length t.filter) false) } let hash { filter ; tweak ; len; _ } data func_id = let res = Cstruct.create 4 in let seed = Int32.(add (mul (of_int func_id) seed_mult) tweak) in murmur_x86_32 res data seed ; let open Stdint in let res = Uint32.of_int32 (Cstruct.LE.get_uint32 res 0) in let filter_size = Uint32.of_int (len * 8) in let i = Uint32.(rem res filter_size |> to_int) in Bitv.set filter i true let add ({ nb_funcs; _ } as t) data = for i = 0 to nb_funcs - 1 do hash t data i done let mem t data = let empty = reset t in add empty data ; let bitv_and = Bitv.bw_and empty.filter t.filter in Stdlib.(=) bitv_and empty.filter let _ = let data_hex = `Hex "019f5b01d4195ecbc9398fbf3c3b1fa9bb3183301d7a1fb3bd174fcfa40a2b65" in let data = Hex.to_string data_hex |> Cstruct.of_string in let bloom = create 1 0.0001 0l in add bloom data ; let filter = to_filter bloom in let filter2 = of_filter filter bloom.nb_funcs bloom.tweak in let `Hex msg = Hex.of_string filter in Printf.printf "%s\n%!" msg ; assert (filter2 = bloom)
null
https://raw.githubusercontent.com/vbmithr/ocaml-bitcoin/391d7d59461fa73961cc78ff93a8ea8366f24744/src/bloom.ml
ocaml
open Sexplib.Std open Murmur3.Murmur_cstruct open Util let bytes_max = 36000 let funcs_max = 50 let seed_mult = 0xfba4c795l type t = { filter : Bitv.t ; len : int ; nb_funcs : int ; tweak : int32 ; } [@@deriving sexp] let filter_len { filter ; _ } = * Bitv.length filter / 8 * Bitv.length filter / 8 *) let to_filter { filter; _ } = try Bitv.to_string_le filter with _ -> invalid_arg "Bloom.to_string" let pp_hex ppf t = let `Hex filter_hex = Hex.of_string (to_filter t) in Caml.Format.fprintf ppf "%s" filter_hex let of_filter filter nb_funcs tweak = let len = String.length filter in if len > bytes_max || nb_funcs > funcs_max then invalid_arg "Bloom.of_filter" ; { filter = Bitv.of_string_le filter ; len ; nb_funcs ; tweak } let create n p tweak = let n = Float.of_int n in let filter_len_bytes = let open Float in min (-1. /. (log 2. *. log 2.) *. n *. log p /. 8.) (of_int bytes_max) |> to_int in let nb_funcs = let open Float in min (of_int filter_len_bytes *. 8. /. n *. log 2.) (of_int funcs_max) |> to_int in { filter = Bitv.create (filter_len_bytes * 8) false ; len = filter_len_bytes ; nb_funcs ; tweak } let reset t = { t with filter = Bitv.(create (length t.filter) false) } let hash { filter ; tweak ; len; _ } data func_id = let res = Cstruct.create 4 in let seed = Int32.(add (mul (of_int func_id) seed_mult) tweak) in murmur_x86_32 res data seed ; let open Stdint in let res = Uint32.of_int32 (Cstruct.LE.get_uint32 res 0) in let filter_size = Uint32.of_int (len * 8) in let i = Uint32.(rem res filter_size |> to_int) in Bitv.set filter i true let add ({ nb_funcs; _ } as t) data = for i = 0 to nb_funcs - 1 do hash t data i done let mem t data = let empty = reset t in add empty data ; let bitv_and = Bitv.bw_and empty.filter t.filter in Stdlib.(=) bitv_and empty.filter let _ = let data_hex = `Hex "019f5b01d4195ecbc9398fbf3c3b1fa9bb3183301d7a1fb3bd174fcfa40a2b65" in let data = Hex.to_string data_hex |> Cstruct.of_string in let bloom = create 1 0.0001 0l in add bloom data ; let filter = to_filter bloom in let filter2 = of_filter filter bloom.nb_funcs bloom.tweak in let `Hex msg = Hex.of_string filter in Printf.printf "%s\n%!" msg ; assert (filter2 = bloom)
53120b3a4d1395f7bb1e2d5a1941a7f6b322072884c888ffa8ea6b58e4ae6524
threatgrid/ctia
fulltext_search_test.clj
(ns ctia.http.generative.fulltext-search-test (:require [clojure.test :refer [deftest testing is are use-fixtures join-fixtures]] [clojure.test.check.generators :as gen] [ctia.auth.capabilities :as capabilities] [ctia.auth.threatgrid :refer [map->Identity]] [ctia.bundle.core :as bundle] [ctia.http.generative.properties :as prop] [ctia.lib.utils :as utils] [ctia.store :as store] [ctia.store-service :as store-service] [ctia.store-service-core :as store-svc-core] [ctia.stores.es.query :as es.query] [ctia.test-helpers.core :as helpers] [ctia.test-helpers.es :as es-helpers] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.search :as th.search] [ctim.schemas.common :refer [ctim-schema-version]] [clojure.pprint :as pp] [ctim.examples.bundles :refer [bundle-maximal]] [ctim.schemas.bundle :as bundle.schema] [ductile.index :as es-index] [puppetlabs.trapperkeeper.app :as app] [puppetlabs.trapperkeeper.core :as tk] [puppetlabs.trapperkeeper.services :as tk-svcs])) (def ^:private login (map->Identity {:login "foouser" :groups ["foogroup"]})) (use-fixtures :once (join-fixtures [es-helpers/fixture-properties:es-store whoami-helpers/fixture-server])) (def bundle-entity-field-names "extracted non-essential Bundle keys" (->> bundle.schema/objects-entries (into bundle.schema/references-entries) (mapcat #(-> % :key :values)) (set))) (defn- entities-gen "Generator for a map where each k/v represents entity-type/list of entities (of that type)" [& entity-keys] (let [gens (map (fn [e] (-> (->> e helpers/plural-key->entity ffirst name (str "max-new-") prop/spec-gen (gen/fmap #(-> % ;; remove IDs so it can be used it in Bundle import (dissoc :id) scores can generate NaN in CTIM 1.2.1 (cond-> (= :incidents e) (dissoc :scores))))) (gen/vector 5 11))) entity-keys)] (gen/bind (apply gen/tuple gens) (fn [entity-maps] (gen/return (zipmap entity-keys entity-maps)))))) (defn- bundle-gen-for "Generator for a bundle that contains only given entity key(s) Example: (gen/generate (bundle-gen-for :assets :actors))" [& entity-keys] (gen/let [bundle (-> bundle-maximal (dissoc :id) gen/return (gen/bind (fn [bundle] ;; To generate a bundle that contains only given entity(ies), we're gonna need ;; to generate a complete bundle and remove all other keys from it (let [bundle-keys-to-remove (apply disj bundle-entity-field-names entity-keys) new-bundle (apply dissoc bundle bundle-keys-to-remove)] (gen/return new-bundle))))) entities (apply entities-gen entity-keys)] (merge bundle entities))) ;; Every single query gets tested with its own set of generated Bundle ;; data. After the query gets sent, the response results are passed into :check ;; function, together with the test-case map, entity key and the Bundle data (defn test-cases [] (concat [{:test-description "Returns all the records when the wildcard used" :query-params {:query "*"} :bundle-gen (bundle-gen-for :incidents :assets) :check (fn [_ entity bundle res] (is (= (-> res :parsed-body count) (-> bundle (get entity) count))))}] (let [bundle (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (apply utils/update-items incidents update first 3 records , leave the rest unchanged (repeat 3 #(assoc % :title "nunc porta vulputate tellus")))))) (bundle-gen-for :incidents)) check-fn (fn [{:keys [test-description]} _ _ res] (let [matching (->> res :parsed-body (filter #(-> % :title (= "nunc porta vulputate tellus"))))] (is (= 3 (count matching)) test-description)))] [{:test-description "Multiple records with the same value in a given field. Lucene syntax" :query-params {:query "title:nunc porta vulputate tellus"} :bundle-gen bundle :check check-fn} {:test-description "Multiple records with the same value in a given field set in search_fields" :query-params {:query "nunc porta vulputate tellus" :search_fields ["title"]} :bundle-gen bundle :check check-fn} {:test-description "Querying for non-existing value should yield no results. Lucene syntax." :query-params {:query "title:0e1c9f6a-c3ac-4fd5-982e-4981f86df07a"} :bundle-gen bundle :check (fn [_ _ _ res] (is (zero? (-> res :parsed-body count))))} {:test-description "Querying for non-existing field with wildcard should yield no results. Lucene syntax." :query-params {:query "74f93781-f370-46ea-bd53-3193db379e41:*"} :bundle-gen bundle :check (fn [_ _ _ res] (is (empty? (-> res :parsed-body))))} {:test-description "Querying for non-existing field with wildcard should fail the schema validation. search_fields" :query-params {:query "*" :search_fields ["512b8dce-0423-4e9a-aa63-d3c3b91eb8d8"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (= 400 (-> res :status))))}]) Test ` AND ` ( set two different fields that contain the same word in the same entity ) (let [bundle (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents update only the first , leave the rest unchanged #(assoc % :short_description "Log Review" :title "title of test incident"))))) (bundle-gen-for :incidents)) get-fields (fn [res] (->> res :parsed-body (some #(and (-> % :short_description (= "Log Review")) (-> % :title (= "title of test incident"))))))] [{:test-description (str "Should NOT return anything, because query field is missing." "Asking for multiple things in the query, but not providing all the fields.") :query-params {:query "(title of test incident) AND (Log Review)" :search_fields ["title"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (nil? (get-fields res))))} {:test-description "Should return an entity where multiple fields match" :query-params {:query "\"title of test incident\" AND \"Log Review\"" :search_fields ["title" "short_description"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (= 1 (-> res :parsed-body count))) (is (get-fields res)))}]) [{:test-description "multi_match - looking for the same value in different fields in multiple records" :query-params {:query "bibendum" :search_fields ["short_description" "title"]} :bundle-gen (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (apply utils/update-items incidents update first 3 , leave the rest unchanged #(assoc % :title "Etiam vel neque bibendum dignissim" :short_description "bibendum")))))) (bundle-gen-for :incidents)) :check (fn [_ _ _ res] (let [matching (->> res :parsed-body (filter #(and (-> % :short_description (= "bibendum")) (-> % :title (= "Etiam vel neque bibendum dignissim")))))] (is (= 3 (count matching)))))}] (let [bundle-gen (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents #(assoc % :title "fried eggs eggplant") #(assoc % :title "fried eggs potato") #(assoc % :title "fried eggs frittata"))))) (bundle-gen-for :incidents)) check-fn (fn [_ _ _ res] (let [matching (->> res :parsed-body)] (is (= 2 (count matching))) (= #{"fried eggs eggplant" "fried eggs potato"} (->> matching (map :title) set))))] [{:test-description "simple_query_string" :query-params {:simple_query "\"fried eggs\" +(eggplant | potato) -frittata" :search_fields ["title"]} :bundle-gen bundle-gen :check check-fn} {:test-description "simple_query_string and query_string together" :query-params {:simple_query "\"fried eggs\" +(eggplant | potato) -frittata" :query "(fried eggs eggplant) OR (fried eggs potato)" :search_fields ["title"]} :bundle-gen bundle-gen :check check-fn}]) (let [bundle-gen (->> :incidents bundle-gen-for (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents #(assoc % :title "fried eggs"))))))) check-fn (fn [_ _ _ res] (is (seq (get-in res [:parsed-body :errors :search_fields]))))] [{:test-description "passing non-existing fields shouldn't be allowed" :query-params {:query "*", :search_fields ["bad-field"]} :bundle-gen bundle-gen :check check-fn} {:test-description "passing legit entity, albeit non-searchable fields still not allowed" :query-params {:query "*", :search_fields ["incident_time.discovered"]} :bundle-gen bundle-gen :check check-fn}]) ;; TODO: Re-enable after solving #pullrequestreview-780638906 #_(let [expected {:title "intrusion event 3:19187:7 incident" :source "ngfw_ips_event_service"} bundle (gen/fmap (fn [bndl] (update bndl :incidents (fn [items] (utils/update-items items #(merge % expected))))) (bundle-gen-for :incidents)) check-fn (fn [_ _ _ res] (is (= expected (-> res :parsed-body first (select-keys [:source :title])))))] [{:test-description "searching in mixed fields indexed as pure text and keyword" :query-params {:query "the intrusion event 3\\:19187\\:7 incident" :search_fields ["title" "source"]} :bundle-gen bundle :check check-fn}]))) (defn test-search-case [app {:keys [query-params bundle-gen check test-description] :as test-case}] (let [services (app/service-graph app) bundle (gen/generate bundle-gen) ent-keys (->> bundle keys (filter (partial contains? bundle-entity-field-names)))] (bundle/import-bundle bundle nil ;; external-key-prefixes login services) (doseq [plural ent-keys] (let [entity (ffirst (helpers/plural-key->entity plural)) search-res (th.search/search-raw app entity query-params)] (testing test-description (check test-case plural bundle search-res)) (th.search/delete-search app entity {:query "*" :REALLY_DELETE_ALL_THESE_ENTITIES true}))))) (deftest fulltext-search-test (es-helpers/for-each-es-version "Extended Fulltext query search" [5 7] #(es-index/delete! % "ctia_*") (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" (capabilities/all-capabilities)) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (doseq [test-case ((some-fn #(seq (filter :only %)) identity) (test-cases))] (test-search-case app test-case)))))) For the time being ( before we fully migrate to ES7 ) , we need to test the behavior ;; of searching in multiple heterogeneous types of fields, i.e., when some fields are ;; mapped to 'text' and others to 'keyword'. ;; ;; Since at the moment we cannot implement a workaround in the API because that would ;; require updating mappings on the live, production data, we'd have to test this by directly sending queries into ES , bypassing the CTIA routes . (deftest mixed-fields-text-and-keyword-multi-match (es-helpers/for-each-es-version "Mixed fields text and keyword multimatch" [5 7] nil;; fixture-ctia-with-app already clean (helpers/fixture-ctia-with-app (fn [app] (let [{{:keys [get-store]} :StoreService :as services} (app/service-graph app) incidents-store (get-store :incident) expected {:title "intrusion event 3:19187:7 incident" :source "ngfw_ips_event_service"} bundle {:incidents [{:description "desc", :schema_version ctim-schema-version, :type "incident", :source "ngfw_ips_event_service", :tlp "green", :short_description "desc", :title "intrusion event 3:19187:7 incident", :incident_time {:opened #inst "2010-01-01T00:00:00.003-00:00", :discovered #inst "2010-01-01T00:00:00.001-00:00", :reported #inst "2010-01-01T00:00:06.129-00:00", :remediated #inst "2010-01-01T00:02:07.145-00:00", :closed #inst "2010-01-01T00:00:02.349-00:00", :rejected #inst "2010-01-01T00:00:00.327-00:00"}, :status "New", :confidence "High"} {:description "desc", :schema_version ctim-schema-version, :type "incident", :tlp "green", :source "ngfw_ips_event_service", :short_description "desc", :title "this incident should not be matched", :incident_time {:opened #inst "2010-01-01T00:00:00.003-00:00", :discovered #inst "2010-01-01T00:00:00.001-00:00", :reported #inst "2010-01-01T00:00:06.129-00:00", :remediated #inst "2010-01-01T00:02:07.145-00:00", :closed #inst "2010-01-01T00:00:02.349-00:00", :rejected #inst "2010-01-01T00:00:00.327-00:00"}, :status "New", :confidence "High"}]} ignore-ks [:created :groups :id :incident_time :modified :owner :timestamp]] (assert (empty? (-> incidents-store (store/query-string-search {:search-query {:query "intrusion event 3\\:19187\\:7 incident"} :ident login :params {}}) :data)) "The test state is polluted with previous documents.") (bundle/import-bundle bundle nil ;; external-key-prefixes login services) (are [desc query check-fn] (let [query-res (store/query-string-search incidents-store {:search-query (merge query {:default_operator "AND"}) :ident login :params {}}) res (:data query-res)] (testing (format "query:%s\nquery-res =>\n%s\nbundle =>\n %s" query (with-out-str (pp/pprint query-res)) (with-out-str (pp/pprint bundle))) (check-fn res desc) true)) "base query matches expected data" {:full-text [{:query "intrusion event 3\\:19187\\:7 incident"}]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)) "querying all, matches generated incidents, minus selected fields in each entity" {:full-text [{:query "*"}]} (fn [res desc] (let [norm (fn [data] (->> data (map #(apply dissoc % ignore-ks)) set))] (is (= (-> bundle :incidents norm) (-> res norm)) desc))) "using 'title' and 'source' fields + a stop word" {:full-text [{:query "that intrusion event 3\\:19187\\:7 incident"}] :fields ["title" "source"]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)) "using double-quotes at the end of the query" {:full-text [{:query "intrusion event 3\\:19187\\:7 incident \\\"\\\""}] :fields ["title" "source"]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)))))))) (def enforced-fields-flag-query-params (atom nil)) (defrecord FakeIncidentStore [state] store/IQueryStringSearchableStore (query-string-search [_ {:keys [search-query]}] (reset! enforced-fields-flag-query-params search-query) {:data (), :paging {:total-hits 0}})) (tk/defservice fake-store-service "A service to manage the central storage area for all stores." store-service/StoreService [[:ConfigService get-in-config] [:FeaturesService flag-value]] (init [this context] (store-svc-core/init context)) (start [this context] (store-svc-core/start {:ConfigService {:get-in-config get-in-config} :FeaturesService {:flag-value flag-value}} context)) (stop [this context] (store-svc-core/stop context)) (all-stores [this] (store-svc-core/all-stores (tk-svcs/service-context this))) (get-store [this store-id] (let [store (store-svc-core/get-store (tk-svcs/service-context this) store-id)] (if (= :incident store-id) (->FakeIncidentStore (:state store)) store)))) (deftest enforcing-fields-with-feature-flag-test (testing "unit testing enforce-search-fields" (are [fields expected-search-fields] (let [res (es.query/enforce-search-fields {:props {:entity :incident} :searchable-fields #{:foo :bar :zap} :services {:FeaturesService {:flag-value (constantly "true")}}} fields)] (is (= expected-search-fields res))) [] ["zap" "bar" "foo"] ["title" "description"] ["title" "description"])) (testing "feature flag set? fields should be enforced" (reset! enforced-fields-flag-query-params nil) (helpers/with-properties ["ctia.feature-flags" "enforce-search-fields:false"] (helpers/fixture-ctia-with-app {:enable-http? true :services {:StoreService fake-store-service}} (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" (capabilities/all-capabilities)) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (th.search/search-raw app :incident {:query "*"}) (is (->> @enforced-fields-flag-query-params :full-text (not-any? #(contains? % :fields)))))))))
null
https://raw.githubusercontent.com/threatgrid/ctia/6c11ba6a7c57a44de64c16601d3914f5b0cf308e/test/ctia/http/generative/fulltext_search_test.clj
clojure
remove IDs so it can be used it in Bundle import To generate a bundle that contains only given entity(ies), we're gonna need to generate a complete bundle and remove all other keys from it Every single query gets tested with its own set of generated Bundle data. After the query gets sent, the response results are passed into :check function, together with the test-case map, entity key and the Bundle data TODO: Re-enable after solving #pullrequestreview-780638906 external-key-prefixes of searching in multiple heterogeneous types of fields, i.e., when some fields are mapped to 'text' and others to 'keyword'. Since at the moment we cannot implement a workaround in the API because that would require updating mappings on the live, production data, we'd have to test this by fixture-ctia-with-app already clean external-key-prefixes
(ns ctia.http.generative.fulltext-search-test (:require [clojure.test :refer [deftest testing is are use-fixtures join-fixtures]] [clojure.test.check.generators :as gen] [ctia.auth.capabilities :as capabilities] [ctia.auth.threatgrid :refer [map->Identity]] [ctia.bundle.core :as bundle] [ctia.http.generative.properties :as prop] [ctia.lib.utils :as utils] [ctia.store :as store] [ctia.store-service :as store-service] [ctia.store-service-core :as store-svc-core] [ctia.stores.es.query :as es.query] [ctia.test-helpers.core :as helpers] [ctia.test-helpers.es :as es-helpers] [ctia.test-helpers.fake-whoami-service :as whoami-helpers] [ctia.test-helpers.search :as th.search] [ctim.schemas.common :refer [ctim-schema-version]] [clojure.pprint :as pp] [ctim.examples.bundles :refer [bundle-maximal]] [ctim.schemas.bundle :as bundle.schema] [ductile.index :as es-index] [puppetlabs.trapperkeeper.app :as app] [puppetlabs.trapperkeeper.core :as tk] [puppetlabs.trapperkeeper.services :as tk-svcs])) (def ^:private login (map->Identity {:login "foouser" :groups ["foogroup"]})) (use-fixtures :once (join-fixtures [es-helpers/fixture-properties:es-store whoami-helpers/fixture-server])) (def bundle-entity-field-names "extracted non-essential Bundle keys" (->> bundle.schema/objects-entries (into bundle.schema/references-entries) (mapcat #(-> % :key :values)) (set))) (defn- entities-gen "Generator for a map where each k/v represents entity-type/list of entities (of that type)" [& entity-keys] (let [gens (map (fn [e] (-> (->> e helpers/plural-key->entity ffirst name (str "max-new-") prop/spec-gen (gen/fmap #(-> % (dissoc :id) scores can generate NaN in CTIM 1.2.1 (cond-> (= :incidents e) (dissoc :scores))))) (gen/vector 5 11))) entity-keys)] (gen/bind (apply gen/tuple gens) (fn [entity-maps] (gen/return (zipmap entity-keys entity-maps)))))) (defn- bundle-gen-for "Generator for a bundle that contains only given entity key(s) Example: (gen/generate (bundle-gen-for :assets :actors))" [& entity-keys] (gen/let [bundle (-> bundle-maximal (dissoc :id) gen/return (gen/bind (fn [bundle] (let [bundle-keys-to-remove (apply disj bundle-entity-field-names entity-keys) new-bundle (apply dissoc bundle bundle-keys-to-remove)] (gen/return new-bundle))))) entities (apply entities-gen entity-keys)] (merge bundle entities))) (defn test-cases [] (concat [{:test-description "Returns all the records when the wildcard used" :query-params {:query "*"} :bundle-gen (bundle-gen-for :incidents :assets) :check (fn [_ entity bundle res] (is (= (-> res :parsed-body count) (-> bundle (get entity) count))))}] (let [bundle (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (apply utils/update-items incidents update first 3 records , leave the rest unchanged (repeat 3 #(assoc % :title "nunc porta vulputate tellus")))))) (bundle-gen-for :incidents)) check-fn (fn [{:keys [test-description]} _ _ res] (let [matching (->> res :parsed-body (filter #(-> % :title (= "nunc porta vulputate tellus"))))] (is (= 3 (count matching)) test-description)))] [{:test-description "Multiple records with the same value in a given field. Lucene syntax" :query-params {:query "title:nunc porta vulputate tellus"} :bundle-gen bundle :check check-fn} {:test-description "Multiple records with the same value in a given field set in search_fields" :query-params {:query "nunc porta vulputate tellus" :search_fields ["title"]} :bundle-gen bundle :check check-fn} {:test-description "Querying for non-existing value should yield no results. Lucene syntax." :query-params {:query "title:0e1c9f6a-c3ac-4fd5-982e-4981f86df07a"} :bundle-gen bundle :check (fn [_ _ _ res] (is (zero? (-> res :parsed-body count))))} {:test-description "Querying for non-existing field with wildcard should yield no results. Lucene syntax." :query-params {:query "74f93781-f370-46ea-bd53-3193db379e41:*"} :bundle-gen bundle :check (fn [_ _ _ res] (is (empty? (-> res :parsed-body))))} {:test-description "Querying for non-existing field with wildcard should fail the schema validation. search_fields" :query-params {:query "*" :search_fields ["512b8dce-0423-4e9a-aa63-d3c3b91eb8d8"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (= 400 (-> res :status))))}]) Test ` AND ` ( set two different fields that contain the same word in the same entity ) (let [bundle (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents update only the first , leave the rest unchanged #(assoc % :short_description "Log Review" :title "title of test incident"))))) (bundle-gen-for :incidents)) get-fields (fn [res] (->> res :parsed-body (some #(and (-> % :short_description (= "Log Review")) (-> % :title (= "title of test incident"))))))] [{:test-description (str "Should NOT return anything, because query field is missing." "Asking for multiple things in the query, but not providing all the fields.") :query-params {:query "(title of test incident) AND (Log Review)" :search_fields ["title"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (nil? (get-fields res))))} {:test-description "Should return an entity where multiple fields match" :query-params {:query "\"title of test incident\" AND \"Log Review\"" :search_fields ["title" "short_description"]} :bundle-gen bundle :check (fn [_ _ _ res] (is (= 1 (-> res :parsed-body count))) (is (get-fields res)))}]) [{:test-description "multi_match - looking for the same value in different fields in multiple records" :query-params {:query "bibendum" :search_fields ["short_description" "title"]} :bundle-gen (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (apply utils/update-items incidents update first 3 , leave the rest unchanged #(assoc % :title "Etiam vel neque bibendum dignissim" :short_description "bibendum")))))) (bundle-gen-for :incidents)) :check (fn [_ _ _ res] (let [matching (->> res :parsed-body (filter #(and (-> % :short_description (= "bibendum")) (-> % :title (= "Etiam vel neque bibendum dignissim")))))] (is (= 3 (count matching)))))}] (let [bundle-gen (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents #(assoc % :title "fried eggs eggplant") #(assoc % :title "fried eggs potato") #(assoc % :title "fried eggs frittata"))))) (bundle-gen-for :incidents)) check-fn (fn [_ _ _ res] (let [matching (->> res :parsed-body)] (is (= 2 (count matching))) (= #{"fried eggs eggplant" "fried eggs potato"} (->> matching (map :title) set))))] [{:test-description "simple_query_string" :query-params {:simple_query "\"fried eggs\" +(eggplant | potato) -frittata" :search_fields ["title"]} :bundle-gen bundle-gen :check check-fn} {:test-description "simple_query_string and query_string together" :query-params {:simple_query "\"fried eggs\" +(eggplant | potato) -frittata" :query "(fried eggs eggplant) OR (fried eggs potato)" :search_fields ["title"]} :bundle-gen bundle-gen :check check-fn}]) (let [bundle-gen (->> :incidents bundle-gen-for (gen/fmap (fn [bundle] (update bundle :incidents (fn [incidents] (utils/update-items incidents #(assoc % :title "fried eggs"))))))) check-fn (fn [_ _ _ res] (is (seq (get-in res [:parsed-body :errors :search_fields]))))] [{:test-description "passing non-existing fields shouldn't be allowed" :query-params {:query "*", :search_fields ["bad-field"]} :bundle-gen bundle-gen :check check-fn} {:test-description "passing legit entity, albeit non-searchable fields still not allowed" :query-params {:query "*", :search_fields ["incident_time.discovered"]} :bundle-gen bundle-gen :check check-fn}]) #_(let [expected {:title "intrusion event 3:19187:7 incident" :source "ngfw_ips_event_service"} bundle (gen/fmap (fn [bndl] (update bndl :incidents (fn [items] (utils/update-items items #(merge % expected))))) (bundle-gen-for :incidents)) check-fn (fn [_ _ _ res] (is (= expected (-> res :parsed-body first (select-keys [:source :title])))))] [{:test-description "searching in mixed fields indexed as pure text and keyword" :query-params {:query "the intrusion event 3\\:19187\\:7 incident" :search_fields ["title" "source"]} :bundle-gen bundle :check check-fn}]))) (defn test-search-case [app {:keys [query-params bundle-gen check test-description] :as test-case}] (let [services (app/service-graph app) bundle (gen/generate bundle-gen) ent-keys (->> bundle keys (filter (partial contains? bundle-entity-field-names)))] (bundle/import-bundle bundle login services) (doseq [plural ent-keys] (let [entity (ffirst (helpers/plural-key->entity plural)) search-res (th.search/search-raw app entity query-params)] (testing test-description (check test-case plural bundle search-res)) (th.search/delete-search app entity {:query "*" :REALLY_DELETE_ALL_THESE_ENTITIES true}))))) (deftest fulltext-search-test (es-helpers/for-each-es-version "Extended Fulltext query search" [5 7] #(es-index/delete! % "ctia_*") (helpers/fixture-ctia-with-app (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" (capabilities/all-capabilities)) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (doseq [test-case ((some-fn #(seq (filter :only %)) identity) (test-cases))] (test-search-case app test-case)))))) For the time being ( before we fully migrate to ES7 ) , we need to test the behavior directly sending queries into ES , bypassing the CTIA routes . (deftest mixed-fields-text-and-keyword-multi-match (es-helpers/for-each-es-version "Mixed fields text and keyword multimatch" [5 7] (helpers/fixture-ctia-with-app (fn [app] (let [{{:keys [get-store]} :StoreService :as services} (app/service-graph app) incidents-store (get-store :incident) expected {:title "intrusion event 3:19187:7 incident" :source "ngfw_ips_event_service"} bundle {:incidents [{:description "desc", :schema_version ctim-schema-version, :type "incident", :source "ngfw_ips_event_service", :tlp "green", :short_description "desc", :title "intrusion event 3:19187:7 incident", :incident_time {:opened #inst "2010-01-01T00:00:00.003-00:00", :discovered #inst "2010-01-01T00:00:00.001-00:00", :reported #inst "2010-01-01T00:00:06.129-00:00", :remediated #inst "2010-01-01T00:02:07.145-00:00", :closed #inst "2010-01-01T00:00:02.349-00:00", :rejected #inst "2010-01-01T00:00:00.327-00:00"}, :status "New", :confidence "High"} {:description "desc", :schema_version ctim-schema-version, :type "incident", :tlp "green", :source "ngfw_ips_event_service", :short_description "desc", :title "this incident should not be matched", :incident_time {:opened #inst "2010-01-01T00:00:00.003-00:00", :discovered #inst "2010-01-01T00:00:00.001-00:00", :reported #inst "2010-01-01T00:00:06.129-00:00", :remediated #inst "2010-01-01T00:02:07.145-00:00", :closed #inst "2010-01-01T00:00:02.349-00:00", :rejected #inst "2010-01-01T00:00:00.327-00:00"}, :status "New", :confidence "High"}]} ignore-ks [:created :groups :id :incident_time :modified :owner :timestamp]] (assert (empty? (-> incidents-store (store/query-string-search {:search-query {:query "intrusion event 3\\:19187\\:7 incident"} :ident login :params {}}) :data)) "The test state is polluted with previous documents.") (bundle/import-bundle bundle login services) (are [desc query check-fn] (let [query-res (store/query-string-search incidents-store {:search-query (merge query {:default_operator "AND"}) :ident login :params {}}) res (:data query-res)] (testing (format "query:%s\nquery-res =>\n%s\nbundle =>\n %s" query (with-out-str (pp/pprint query-res)) (with-out-str (pp/pprint bundle))) (check-fn res desc) true)) "base query matches expected data" {:full-text [{:query "intrusion event 3\\:19187\\:7 incident"}]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)) "querying all, matches generated incidents, minus selected fields in each entity" {:full-text [{:query "*"}]} (fn [res desc] (let [norm (fn [data] (->> data (map #(apply dissoc % ignore-ks)) set))] (is (= (-> bundle :incidents norm) (-> res norm)) desc))) "using 'title' and 'source' fields + a stop word" {:full-text [{:query "that intrusion event 3\\:19187\\:7 incident"}] :fields ["title" "source"]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)) "using double-quotes at the end of the query" {:full-text [{:query "intrusion event 3\\:19187\\:7 incident \\\"\\\""}] :fields ["title" "source"]} (fn [res desc] (is (= 1 (count res)) desc) (is (= expected (-> res first (select-keys (keys expected)))) desc)))))))) (def enforced-fields-flag-query-params (atom nil)) (defrecord FakeIncidentStore [state] store/IQueryStringSearchableStore (query-string-search [_ {:keys [search-query]}] (reset! enforced-fields-flag-query-params search-query) {:data (), :paging {:total-hits 0}})) (tk/defservice fake-store-service "A service to manage the central storage area for all stores." store-service/StoreService [[:ConfigService get-in-config] [:FeaturesService flag-value]] (init [this context] (store-svc-core/init context)) (start [this context] (store-svc-core/start {:ConfigService {:get-in-config get-in-config} :FeaturesService {:flag-value flag-value}} context)) (stop [this context] (store-svc-core/stop context)) (all-stores [this] (store-svc-core/all-stores (tk-svcs/service-context this))) (get-store [this store-id] (let [store (store-svc-core/get-store (tk-svcs/service-context this) store-id)] (if (= :incident store-id) (->FakeIncidentStore (:state store)) store)))) (deftest enforcing-fields-with-feature-flag-test (testing "unit testing enforce-search-fields" (are [fields expected-search-fields] (let [res (es.query/enforce-search-fields {:props {:entity :incident} :searchable-fields #{:foo :bar :zap} :services {:FeaturesService {:flag-value (constantly "true")}}} fields)] (is (= expected-search-fields res))) [] ["zap" "bar" "foo"] ["title" "description"] ["title" "description"])) (testing "feature flag set? fields should be enforced" (reset! enforced-fields-flag-query-params nil) (helpers/with-properties ["ctia.feature-flags" "enforce-search-fields:false"] (helpers/fixture-ctia-with-app {:enable-http? true :services {:StoreService fake-store-service}} (fn [app] (helpers/set-capabilities! app "foouser" ["foogroup"] "user" (capabilities/all-capabilities)) (whoami-helpers/set-whoami-response app "45c1f5e3f05d0" "foouser" "foogroup" "user") (th.search/search-raw app :incident {:query "*"}) (is (->> @enforced-fields-flag-query-params :full-text (not-any? #(contains? % :fields)))))))))
610cda3f1d2752cb39426f0ab133b4255d700253c2be0cd934340061bdb554b0
ghc/packages-dph
Benchmarks.hs
{-# OPTIONS -fno-warn-type-defaults #-} module Benchmarks where import Config import BuildBox import Control.Monad import qualified BuildBox.Data.Log as Log | DPH benchmark configuation . benchmarksDPH :: Config -> [Benchmark] benchmarksDPH config -- dot product -------------------------------------------------------- = (let run n = bench config ("dph.dotp.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-dotp/dph-dotp vectorised 10000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.dotp.vectorised.seq.N4" "dph-examples/dist/build/dph-dotp-seq/dph-dotp-seq vectorised 10000000 +RTS -N4" , bench config "dph.dotp.vector.seq.N4" "dph-examples/dist/build/dph-dotp/dph-dotp vector 10000000 +RTS -N4" ] -- sum of squares --------------------------------------------------- ++ (let run n = bench config ("dph.sumsq.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-sumsq/dph-sumsq vectorised 100000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.sumsq.vectorised.seq.N4" "dph-examples/dist/build/dph-sumsq-seq/dph-sumsq-seq vectorised 100000000 +RTS -N4" , bench config "dph.sumsq.vector.seq.N4" "dph-examples/dist/build/dph-sumsq/dph-sumsq vector 100000000 +RTS -N4" ] -- evens ------------------------------------------------------------ ++ (let run n = bench config ("dph.evens.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-evens/dph-evens vectorised 10000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.evens.vectorised.seq.N4" "dph-examples/dist/build/dph-evens-seq/dph-evens-seq vectorised 10000000 +RTS -N4" , bench config "dph.evens.vector.seq.N4" "dph-examples/dist/build/dph-evens-seq/dph-evens-seq vector 10000000 +RTS -N4" ] -- primes ------------------------------------------------------------ + + ( let run n = bench config ( " dph.primes.vectorised.par . N " + + show n ) ( " dph - examples / dist / build / dph - primes / dph - primes vectorised 20000000 + RTS -N " + + show n ) in map run [ 1 , 2 , 4 , 8 ] ) + + [ bench config " dph.primes.vectorised.seq . N4 " " dph - examples / dist / build / dph - primes - seq / dph - primes - seq vectorised 20000000 + RTS -N4 " , bench config " dph.primes.vector.seq . N4 " " dph - examples / dist / build / dph - primes - seq / dph - primes - seq vector 20000000 + RTS -N4 " ] ++ (let run n = bench config ("dph.primes.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-primes/dph-primes vectorised 20000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.primes.vectorised.seq.N4" "dph-examples/dist/build/dph-primes-seq/dph-primes-seq vectorised 20000000 +RTS -N4" , bench config "dph.primes.vector.seq.N4" "dph-examples/dist/build/dph-primes-seq/dph-primes-seq vector 20000000 +RTS -N4" ] -} -- quicksort -------------------------------------------------------- ++ (let run n = bench config ("dph.quicksort.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-quicksort/dph-quicksort 100000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) -- quickhull -------------------------------------------------------- ++ (let run n = bench config ("dph.quickhull.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-quickhull/dph-quickhull 1000000 +RTS -K20M -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.quickhull.vectorised.seq.N4" "dph-examples/dist/build/dph-quickhull-seq/dph-quickhull-seq 1000000 +RTS -N4 -K40M" , bench config "dph.quickhull.vector-immutable.seq.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector split 1000000 +RTS -N4" , bench config "dph.quickhull.vector-mutable.seq.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector vector 1000000 +RTS -N4" , bench config "dph.quickhull.vector-forkIO.par.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector io 1000000 +RTS -N4" , bench config "dph.quickhull.vector-forkIO.par.N8" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector io 1000000 +RTS -N8" , benchUp config "dph.quickhull.c.seq" (inDir "dph-examples/spectral/QuickHull/c" $ qssystem "make") "dph-examples/spectral/QuickHull/c/quickhull 1000000" ] -- ------------------------------------------------------------ + + ( let run n = bench config ( " dph.nbody.vectorised.par . N " + + show n ) ( " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s nested - bh + RTS -N " + + show n ) in map run [ 1 , 2 , 4 ] ) + + [ bench config " dph.nbody.vectorised.seq . N4 " " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s nested - bh + RTS -N4 " , bench config " dph.nbody.vector.seq . N4 " " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s vector - bh + RTS -N4 " ] ++ (let run n = bench config ("dph.nbody.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s nested-bh +RTS -N" ++ show n) in map run [1, 2, 4]) ++ [ bench config "dph.nbody.vectorised.seq.N4" "dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s nested-bh +RTS -N4" , bench config "dph.nbody.vector.seq.N4" "dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s vector-bh +RTS -N4" ] -} -- | Repa benchmark configuration. benchmarksRepa :: Config -> [Benchmark] benchmarksRepa config = -- mmult -------------------------------------------------------------- (let mmult = "repa-examples/dist/build/repa-mmult/repa-mmult" run n = bench config ("repa.mmult.par.N" ++ show n) (mmult ++ " -random 1024 1024 -random 1024 1024 +RTS -N" ++ show n) in [run 1, run 2, run 4, run 8]) ++ [ benchUp config "repa.mmult.c.seq" (inDir "repa-examples" $ qssystem "make dist/build/repa-mmult-c/repa-mmult-c") "repa-examples/dist/build/repa-mmult-c/repa-mmult-c -random 1024 1024 -random 1024 1024" ] -- laplace ------------------------------------------------------------ ++ (let laplace = "repa-examples/dist/build/repa-laplace/repa-laplace" input = "repa-examples/examples/Laplace/data/pls-400x400.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.laplace.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable laplace whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (laplace ++ " get 1000 " ++ input ++ " output/laplace.bmp +RTS -qg -N" ++ show n) in [run 1, run 2, run 4, run 6, run 8]) ++ [ benchUp config "repa.laplace.c.seq" (inDir "repa-examples" $ qssystem "make dist/build/repa-laplace-c/repa-laplace-c") "repa-examples/dist/build/repa-laplace-c/repa-laplace-c 400 400 1000 output/laplace_c-seq.ppm" ] -- blur --------------------------------------------------------------- ++ (let blur = "repa-examples/dist/build/repa-blur/repa-blur" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.blur.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable blur whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (blur ++ " 5 " ++ input ++ " output/lena-blur.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) -- canny ------------------------------------------------------------- ++ (let canny = "repa-examples/dist/build/repa-canny/repa-canny" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.canny.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable canny whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (canny ++ " " ++ input ++ " output/lena-canny.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) -- fft2d-highpass ----------------------------------------------------- ++ (let fft2d = "repa-examples/dist/build/repa-fft2d-highpass/repa-fft2d-highpass" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.fft2d.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable fft2d whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (fft2d ++ " 1 " ++ input ++ " output/fft2d.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) -- fft3d-highpass ----------------------------------------------------- ++ (let fft3d = "repa-examples/dist/build/repa-fft3d-highpass/repa-fft3d-highpass" run n = benchUp config ("repa.fft3d.par.N" ++ show n) (ensureDir "output/fft3d") (fft3d ++ " 128 output/fft3d/slice +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) -- | Define a plain benchmark with no setup or teardown command bench :: Config -> String -> String -> Benchmark bench config name cmd = Benchmark name (return ()) (systemWithTimings (configVerbose config) cmd) (return []) -- | Define a benchmark with a setup command benchUp :: Config -> String -> Build () -> String -> Benchmark benchUp config name cmdUp cmdBench = Benchmark name cmdUp (systemWithTimings (configVerbose config) cmdBench) (return []) -- | Run a system command, expecing it to print the kernel timings to stdout. -- We ignore whatever is printed to stderr. systemWithTimings :: Bool -> String -> Build [WithUnits (Aspect Single)] systemWithTimings verbose cmd = do when verbose $ outLn $ "\n " ++ cmd (code, logOut, logErr) <- systemTeeLog False cmd Log.empty if code == ExitSuccess then return $ parseTimings (Log.toString logOut) else throw $ ErrorSystemCmdFailed cmd code logOut logErr -- | Parse kernel timings from a repa example program. -- Format is elapsedTime/systemTime in milliseconds. parseTimings :: String -> [WithUnits (Aspect Single)] parseTimings str = let (lElapsed : _) = lines str thing = dropWhile (/= '=') lElapsed elapsedTime = case thing of [] -> error $ "parseTimings: no time in " ++ show thing _ -> tail thing in [ Time KernelWall `secs` (read elapsedTime / 1000) ]
null
https://raw.githubusercontent.com/ghc/packages-dph/64eca669f13f4d216af9024474a3fc73ce101793/dph-buildbot/src/Benchmarks.hs
haskell
# OPTIONS -fno-warn-type-defaults # dot product -------------------------------------------------------- sum of squares --------------------------------------------------- evens ------------------------------------------------------------ primes ------------------------------------------------------------ quicksort -------------------------------------------------------- quickhull -------------------------------------------------------- ------------------------------------------------------------ | Repa benchmark configuration. mmult -------------------------------------------------------------- laplace ------------------------------------------------------------ blur --------------------------------------------------------------- canny ------------------------------------------------------------- fft2d-highpass ----------------------------------------------------- fft3d-highpass ----------------------------------------------------- | Define a plain benchmark with no setup or teardown command | Define a benchmark with a setup command | Run a system command, expecing it to print the kernel timings to stdout. We ignore whatever is printed to stderr. | Parse kernel timings from a repa example program. Format is elapsedTime/systemTime in milliseconds.
module Benchmarks where import Config import BuildBox import Control.Monad import qualified BuildBox.Data.Log as Log | DPH benchmark configuation . benchmarksDPH :: Config -> [Benchmark] benchmarksDPH config = (let run n = bench config ("dph.dotp.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-dotp/dph-dotp vectorised 10000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.dotp.vectorised.seq.N4" "dph-examples/dist/build/dph-dotp-seq/dph-dotp-seq vectorised 10000000 +RTS -N4" , bench config "dph.dotp.vector.seq.N4" "dph-examples/dist/build/dph-dotp/dph-dotp vector 10000000 +RTS -N4" ] ++ (let run n = bench config ("dph.sumsq.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-sumsq/dph-sumsq vectorised 100000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.sumsq.vectorised.seq.N4" "dph-examples/dist/build/dph-sumsq-seq/dph-sumsq-seq vectorised 100000000 +RTS -N4" , bench config "dph.sumsq.vector.seq.N4" "dph-examples/dist/build/dph-sumsq/dph-sumsq vector 100000000 +RTS -N4" ] ++ (let run n = bench config ("dph.evens.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-evens/dph-evens vectorised 10000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.evens.vectorised.seq.N4" "dph-examples/dist/build/dph-evens-seq/dph-evens-seq vectorised 10000000 +RTS -N4" , bench config "dph.evens.vector.seq.N4" "dph-examples/dist/build/dph-evens-seq/dph-evens-seq vector 10000000 +RTS -N4" ] + + ( let run n = bench config ( " dph.primes.vectorised.par . N " + + show n ) ( " dph - examples / dist / build / dph - primes / dph - primes vectorised 20000000 + RTS -N " + + show n ) in map run [ 1 , 2 , 4 , 8 ] ) + + [ bench config " dph.primes.vectorised.seq . N4 " " dph - examples / dist / build / dph - primes - seq / dph - primes - seq vectorised 20000000 + RTS -N4 " , bench config " dph.primes.vector.seq . N4 " " dph - examples / dist / build / dph - primes - seq / dph - primes - seq vector 20000000 + RTS -N4 " ] ++ (let run n = bench config ("dph.primes.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-primes/dph-primes vectorised 20000000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.primes.vectorised.seq.N4" "dph-examples/dist/build/dph-primes-seq/dph-primes-seq vectorised 20000000 +RTS -N4" , bench config "dph.primes.vector.seq.N4" "dph-examples/dist/build/dph-primes-seq/dph-primes-seq vector 20000000 +RTS -N4" ] -} ++ (let run n = bench config ("dph.quicksort.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-quicksort/dph-quicksort 100000 +RTS -N" ++ show n) in map run [1, 2, 4, 8]) ++ (let run n = bench config ("dph.quickhull.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-quickhull/dph-quickhull 1000000 +RTS -K20M -N" ++ show n) in map run [1, 2, 4, 8]) ++ [ bench config "dph.quickhull.vectorised.seq.N4" "dph-examples/dist/build/dph-quickhull-seq/dph-quickhull-seq 1000000 +RTS -N4 -K40M" , bench config "dph.quickhull.vector-immutable.seq.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector split 1000000 +RTS -N4" , bench config "dph.quickhull.vector-mutable.seq.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector vector 1000000 +RTS -N4" , bench config "dph.quickhull.vector-forkIO.par.N4" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector io 1000000 +RTS -N4" , bench config "dph.quickhull.vector-forkIO.par.N8" "dph-examples/dist/build/dph-quickhull-vector/dph-quickhull-vector io 1000000 +RTS -N8" , benchUp config "dph.quickhull.c.seq" (inDir "dph-examples/spectral/QuickHull/c" $ qssystem "make") "dph-examples/spectral/QuickHull/c/quickhull 1000000" ] + + ( let run n = bench config ( " dph.nbody.vectorised.par . N " + + show n ) ( " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s nested - bh + RTS -N " + + show n ) in map run [ 1 , 2 , 4 ] ) + + [ bench config " dph.nbody.vectorised.seq . N4 " " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s nested - bh + RTS -N4 " , bench config " dph.nbody.vector.seq . N4 " " dph - examples / dist / build / dph - nbody / dph - nbody --max - steps 10 -b 100 -s vector - bh + RTS -N4 " ] ++ (let run n = bench config ("dph.nbody.vectorised.par.N" ++ show n) ("dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s nested-bh +RTS -N" ++ show n) in map run [1, 2, 4]) ++ [ bench config "dph.nbody.vectorised.seq.N4" "dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s nested-bh +RTS -N4" , bench config "dph.nbody.vector.seq.N4" "dph-examples/dist/build/dph-nbody/dph-nbody --max-steps 10 -b 100 -s vector-bh +RTS -N4" ] -} benchmarksRepa :: Config -> [Benchmark] benchmarksRepa config (let mmult = "repa-examples/dist/build/repa-mmult/repa-mmult" run n = bench config ("repa.mmult.par.N" ++ show n) (mmult ++ " -random 1024 1024 -random 1024 1024 +RTS -N" ++ show n) in [run 1, run 2, run 4, run 8]) ++ [ benchUp config "repa.mmult.c.seq" (inDir "repa-examples" $ qssystem "make dist/build/repa-mmult-c/repa-mmult-c") "repa-examples/dist/build/repa-mmult-c/repa-mmult-c -random 1024 1024 -random 1024 1024" ] ++ (let laplace = "repa-examples/dist/build/repa-laplace/repa-laplace" input = "repa-examples/examples/Laplace/data/pls-400x400.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.laplace.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable laplace whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (laplace ++ " get 1000 " ++ input ++ " output/laplace.bmp +RTS -qg -N" ++ show n) in [run 1, run 2, run 4, run 6, run 8]) ++ [ benchUp config "repa.laplace.c.seq" (inDir "repa-examples" $ qssystem "make dist/build/repa-laplace-c/repa-laplace-c") "repa-examples/dist/build/repa-laplace-c/repa-laplace-c 400 400 1000 output/laplace_c-seq.ppm" ] ++ (let blur = "repa-examples/dist/build/repa-blur/repa-blur" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.blur.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable blur whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (blur ++ " 5 " ++ input ++ " output/lena-blur.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) ++ (let canny = "repa-examples/dist/build/repa-canny/repa-canny" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.canny.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable canny whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (canny ++ " " ++ input ++ " output/lena-canny.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) ++ (let fft2d = "repa-examples/dist/build/repa-fft2d-highpass/repa-fft2d-highpass" input = "repa-examples/data/lena.bmp" inputgz = input ++ ".gz" run n = benchUp config ("repa.fft2d.par.N" ++ show n) (do ensureDir "output" check $ HasExecutable fft2d whenM (test $ HasFile inputgz) $ qssystem $ "gzip -d " ++ inputgz) (fft2d ++ " 1 " ++ input ++ " output/fft2d.bmp +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) ++ (let fft3d = "repa-examples/dist/build/repa-fft3d-highpass/repa-fft3d-highpass" run n = benchUp config ("repa.fft3d.par.N" ++ show n) (ensureDir "output/fft3d") (fft3d ++ " 128 output/fft3d/slice +RTS -qg -N" ++ show n) in map run [1, 2, 4, 6, 8]) bench :: Config -> String -> String -> Benchmark bench config name cmd = Benchmark name (return ()) (systemWithTimings (configVerbose config) cmd) (return []) benchUp :: Config -> String -> Build () -> String -> Benchmark benchUp config name cmdUp cmdBench = Benchmark name cmdUp (systemWithTimings (configVerbose config) cmdBench) (return []) systemWithTimings :: Bool -> String -> Build [WithUnits (Aspect Single)] systemWithTimings verbose cmd = do when verbose $ outLn $ "\n " ++ cmd (code, logOut, logErr) <- systemTeeLog False cmd Log.empty if code == ExitSuccess then return $ parseTimings (Log.toString logOut) else throw $ ErrorSystemCmdFailed cmd code logOut logErr parseTimings :: String -> [WithUnits (Aspect Single)] parseTimings str = let (lElapsed : _) = lines str thing = dropWhile (/= '=') lElapsed elapsedTime = case thing of [] -> error $ "parseTimings: no time in " ++ show thing _ -> tail thing in [ Time KernelWall `secs` (read elapsedTime / 1000) ]
fddcc9b052aa5333af7516531b9b20b18828652bf2080084e1dc0f48b6d6cfaf
ocaml-flambda/flambda-backend
tast_iterator.ml
(**************************************************************************) (* *) (* OCaml *) (* *) Isaac " " Avram (* *) Copyright 2019 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) open Asttypes open Typedtree type iterator = { binding_op: iterator -> binding_op -> unit; case: 'k . iterator -> 'k case -> unit; class_declaration: iterator -> class_declaration -> unit; class_description: iterator -> class_description -> unit; class_expr: iterator -> class_expr -> unit; class_field: iterator -> class_field -> unit; class_signature: iterator -> class_signature -> unit; class_structure: iterator -> class_structure -> unit; class_type: iterator -> class_type -> unit; class_type_declaration: iterator -> class_type_declaration -> unit; class_type_field: iterator -> class_type_field -> unit; env: iterator -> Env.t -> unit; expr: iterator -> expression -> unit; extension_constructor: iterator -> extension_constructor -> unit; module_binding: iterator -> module_binding -> unit; module_coercion: iterator -> module_coercion -> unit; module_declaration: iterator -> module_declaration -> unit; module_substitution: iterator -> module_substitution -> unit; module_expr: iterator -> module_expr -> unit; module_type: iterator -> module_type -> unit; module_type_declaration: iterator -> module_type_declaration -> unit; package_type: iterator -> package_type -> unit; pat: 'k . iterator -> 'k general_pattern -> unit; row_field: iterator -> row_field -> unit; object_field: iterator -> object_field -> unit; open_declaration: iterator -> open_declaration -> unit; open_description: iterator -> open_description -> unit; signature: iterator -> signature -> unit; signature_item: iterator -> signature_item -> unit; structure: iterator -> structure -> unit; structure_item: iterator -> structure_item -> unit; typ: iterator -> core_type -> unit; type_declaration: iterator -> type_declaration -> unit; type_declarations: iterator -> (rec_flag * type_declaration list) -> unit; type_extension: iterator -> type_extension -> unit; type_exception: iterator -> type_exception -> unit; type_kind: iterator -> type_kind -> unit; value_binding: iterator -> value_binding -> unit; value_bindings: iterator -> (rec_flag * value_binding list) -> unit; value_description: iterator -> value_description -> unit; with_constraint: iterator -> with_constraint -> unit; } let structure sub {str_items; str_final_env; _} = List.iter (sub.structure_item sub) str_items; sub.env sub str_final_env let class_infos sub f x = List.iter (fun (ct, _) -> sub.typ sub ct) x.ci_params; f x.ci_expr let module_type_declaration sub {mtd_type; _} = Option.iter (sub.module_type sub) mtd_type let module_declaration sub {md_type; _} = sub.module_type sub md_type let module_substitution _ _ = () let include_kind sub = function | Tincl_structure -> () | Tincl_functor ccs -> List.iter (fun (_, cc) -> sub.module_coercion sub cc) ccs | Tincl_gen_functor ccs -> List.iter (fun (_, cc) -> sub.module_coercion sub cc) ccs let str_include_infos sub {incl_mod; incl_kind} = sub.module_expr sub incl_mod; include_kind sub incl_kind let class_type_declaration sub x = class_infos sub (sub.class_type sub) x let class_declaration sub x = class_infos sub (sub.class_expr sub) x let structure_item sub {str_desc; str_env; _} = sub.env sub str_env; match str_desc with | Tstr_eval (exp, _) -> sub.expr sub exp | Tstr_value (rec_flag, list) -> sub.value_bindings sub (rec_flag, list) | Tstr_primitive v -> sub.value_description sub v | Tstr_type (rec_flag, list) -> sub.type_declarations sub (rec_flag, list) | Tstr_typext te -> sub.type_extension sub te | Tstr_exception ext -> sub.type_exception sub ext | Tstr_module mb -> sub.module_binding sub mb | Tstr_recmodule list -> List.iter (sub.module_binding sub) list | Tstr_modtype x -> sub.module_type_declaration sub x | Tstr_class list -> List.iter (fun (cls,_) -> sub.class_declaration sub cls) list | Tstr_class_type list -> List.iter (fun (_, _, cltd) -> sub.class_type_declaration sub cltd) list | Tstr_include incl -> str_include_infos sub incl | Tstr_open od -> sub.open_declaration sub od | Tstr_attribute _ -> () let value_description sub x = sub.typ sub x.val_desc let label_decl sub {ld_type; _} = sub.typ sub ld_type let field_decl sub (ty, _) = sub.typ sub ty let constructor_args sub = function | Cstr_tuple l -> List.iter (field_decl sub) l | Cstr_record l -> List.iter (label_decl sub) l let constructor_decl sub {cd_args; cd_res; _} = constructor_args sub cd_args; Option.iter (sub.typ sub) cd_res let type_kind sub = function | Ttype_abstract -> () | Ttype_variant list -> List.iter (constructor_decl sub) list | Ttype_record list -> List.iter (label_decl sub) list | Ttype_open -> () let type_declaration sub {typ_cstrs; typ_kind; typ_manifest; typ_params; _} = List.iter (fun (c1, c2, _) -> sub.typ sub c1; sub.typ sub c2) typ_cstrs; sub.type_kind sub typ_kind; Option.iter (sub.typ sub) typ_manifest; List.iter (fun (c, _) -> sub.typ sub c) typ_params let type_declarations sub (_, list) = List.iter (sub.type_declaration sub) list let type_extension sub {tyext_constructors; tyext_params; _} = List.iter (fun (c, _) -> sub.typ sub c) tyext_params; List.iter (sub.extension_constructor sub) tyext_constructors let type_exception sub {tyexn_constructor; _} = sub.extension_constructor sub tyexn_constructor let extension_constructor sub {ext_kind; _} = match ext_kind with | Text_decl (_, ctl, cto) -> constructor_args sub ctl; Option.iter (sub.typ sub) cto | Text_rebind _ -> () let pat_extra sub (e, _loc, _attrs) = match e with | Tpat_type _ -> () | Tpat_unpack -> () | Tpat_open (_, _, env) -> sub.env sub env | Tpat_constraint ct -> sub.typ sub ct let pat : type k . iterator -> k general_pattern -> unit = fun sub {pat_extra = extra; pat_desc; pat_env; _} -> sub.env sub pat_env; List.iter (pat_extra sub) extra; match pat_desc with | Tpat_any -> () | Tpat_var _ -> () | Tpat_constant _ -> () | Tpat_tuple l -> List.iter (sub.pat sub) l | Tpat_construct (_, _, l, vto) -> List.iter (sub.pat sub) l; Option.iter (fun (_ids, ct) -> sub.typ sub ct) vto | Tpat_variant (_, po, _) -> Option.iter (sub.pat sub) po | Tpat_record (l, _) -> List.iter (fun (_, _, i) -> sub.pat sub i) l | Tpat_array (_, l) -> List.iter (sub.pat sub) l | Tpat_alias (p, _, _, _) -> sub.pat sub p | Tpat_lazy p -> sub.pat sub p | Tpat_value p -> sub.pat sub (p :> pattern) | Tpat_exception p -> sub.pat sub p | Tpat_or (p1, p2, _) -> sub.pat sub p1; sub.pat sub p2 let expr sub {exp_extra; exp_desc; exp_env; _} = let extra = function | Texp_constraint cty -> sub.typ sub cty | Texp_coerce (cty1, cty2) -> Option.iter (sub.typ sub) cty1; sub.typ sub cty2 | Texp_newtype _ -> () | Texp_poly cto -> Option.iter (sub.typ sub) cto in List.iter (fun (e, _, _) -> extra e) exp_extra; sub.env sub exp_env; match exp_desc with | Texp_ident _ -> () | Texp_constant _ -> () | Texp_let (rec_flag, list, exp) -> sub.value_bindings sub (rec_flag, list); sub.expr sub exp | Texp_function {cases; _} -> List.iter (sub.case sub) cases | Texp_apply (exp, list, _, _) -> sub.expr sub exp; List.iter (function | (_, Arg exp) -> sub.expr sub exp | (_, Omitted _) -> ()) list | Texp_match (exp, cases, _) -> sub.expr sub exp; List.iter (sub.case sub) cases | Texp_try (exp, cases) -> sub.expr sub exp; List.iter (sub.case sub) cases | Texp_tuple (list, _) -> List.iter (sub.expr sub) list | Texp_construct (_, _, args, _) -> List.iter (sub.expr sub) args | Texp_variant (_, expo) -> Option.iter (fun (expr, _) -> sub.expr sub expr) expo | Texp_record { fields; extended_expression; _} -> Array.iter (function | _, Kept _ -> () | _, Overridden (_, exp) -> sub.expr sub exp) fields; Option.iter (sub.expr sub) extended_expression; | Texp_field (exp, _, _, _) -> sub.expr sub exp | Texp_setfield (exp1, _, _, _, exp2) -> sub.expr sub exp1; sub.expr sub exp2 | Texp_array (_, list, _) -> List.iter (sub.expr sub) list | Texp_list_comprehension { comp_body; comp_clauses } | Texp_array_comprehension (_, { comp_body; comp_clauses }) -> sub.expr sub comp_body; List.iter (function | Texp_comp_for bindings -> List.iter (fun { comp_cb_iterator; comp_cb_attributes = _ } -> match comp_cb_iterator with | Texp_comp_range { ident = _; start; stop; direction = _ } -> sub.expr sub start; sub.expr sub stop | Texp_comp_in { pattern; sequence } -> sub.pat sub pattern; sub.expr sub sequence) bindings | Texp_comp_when exp -> sub.expr sub exp) comp_clauses | Texp_ifthenelse (exp1, exp2, expo) -> sub.expr sub exp1; sub.expr sub exp2; Option.iter (sub.expr sub) expo | Texp_sequence (exp1, exp2) -> sub.expr sub exp1; sub.expr sub exp2 | Texp_while { wh_cond; wh_body } -> sub.expr sub wh_cond; sub.expr sub wh_body | Texp_for {for_from; for_to; for_body} -> sub.expr sub for_from; sub.expr sub for_to; sub.expr sub for_body | Texp_send (exp, _, _, _) -> sub.expr sub exp | Texp_new _ -> () | Texp_instvar _ -> () | Texp_setinstvar (_, _, _, exp) ->sub.expr sub exp | Texp_override (_, list) -> List.iter (fun (_, _, e) -> sub.expr sub e) list | Texp_letmodule (_, _, _, mexpr, exp) -> sub.module_expr sub mexpr; sub.expr sub exp | Texp_letexception (cd, exp) -> sub.extension_constructor sub cd; sub.expr sub exp | Texp_assert exp -> sub.expr sub exp | Texp_lazy exp -> sub.expr sub exp | Texp_object (cl, _) -> sub.class_structure sub cl | Texp_pack mexpr -> sub.module_expr sub mexpr | Texp_letop {let_ = l; ands; body; _} -> sub.binding_op sub l; List.iter (sub.binding_op sub) ands; sub.case sub body | Texp_unreachable -> () | Texp_extension_constructor _ -> () | Texp_open (od, e) -> sub.open_declaration sub od; sub.expr sub e | Texp_probe {handler;_} -> sub.expr sub handler | Texp_probe_is_enabled _ -> () let package_type sub {pack_fields; _} = List.iter (fun (_, p) -> sub.typ sub p) pack_fields let binding_op sub {bop_exp; _} = sub.expr sub bop_exp let signature sub {sig_items; sig_final_env; _} = sub.env sub sig_final_env; List.iter (sub.signature_item sub) sig_items let sig_include_infos sub {incl_mod; incl_kind} = sub.module_type sub incl_mod; include_kind sub incl_kind let signature_item sub {sig_desc; sig_env; _} = sub.env sub sig_env; match sig_desc with | Tsig_value v -> sub.value_description sub v | Tsig_type (rf, tdl) -> sub.type_declarations sub (rf, tdl) | Tsig_typesubst list -> sub.type_declarations sub (Nonrecursive, list) | Tsig_typext te -> sub.type_extension sub te | Tsig_exception ext -> sub.type_exception sub ext | Tsig_module x -> sub.module_declaration sub x | Tsig_modsubst x -> sub.module_substitution sub x | Tsig_recmodule list -> List.iter (sub.module_declaration sub) list | Tsig_modtype x -> sub.module_type_declaration sub x | Tsig_modtypesubst x -> sub.module_type_declaration sub x | Tsig_include incl -> sig_include_infos sub incl | Tsig_class list -> List.iter (sub.class_description sub) list | Tsig_class_type list -> List.iter (sub.class_type_declaration sub) list | Tsig_open od -> sub.open_description sub od | Tsig_attribute _ -> () let class_description sub x = class_infos sub (sub.class_type sub) x let functor_parameter sub = function | Unit -> () | Named (_, _, mtype) -> sub.module_type sub mtype let module_type sub {mty_desc; mty_env; _} = sub.env sub mty_env; match mty_desc with | Tmty_ident _ -> () | Tmty_alias _ -> () | Tmty_signature sg -> sub.signature sub sg | Tmty_functor (arg, mtype2) -> functor_parameter sub arg; sub.module_type sub mtype2 | Tmty_with (mtype, list) -> sub.module_type sub mtype; List.iter (fun (_, _, e) -> sub.with_constraint sub e) list | Tmty_typeof mexpr -> sub.module_expr sub mexpr let with_constraint sub = function | Twith_type decl -> sub.type_declaration sub decl | Twith_typesubst decl -> sub.type_declaration sub decl | Twith_module _ -> () | Twith_modsubst _ -> () | Twith_modtype _ -> () | Twith_modtypesubst _ -> () let open_description sub {open_env; _} = sub.env sub open_env let open_declaration sub {open_expr; open_env; _} = sub.module_expr sub open_expr; sub.env sub open_env let module_coercion sub = function | Tcoerce_none -> () | Tcoerce_functor (c1,c2) -> sub.module_coercion sub c1; sub.module_coercion sub c2 | Tcoerce_alias (env, _, c1) -> sub.env sub env; sub.module_coercion sub c1 | Tcoerce_structure (l1, l2) -> List.iter (fun (_, c) -> sub.module_coercion sub c) l1; List.iter (fun (_, _ ,c) -> sub.module_coercion sub c) l2 | Tcoerce_primitive {pc_env; _} -> sub.env sub pc_env let module_expr sub {mod_desc; mod_env; _} = sub.env sub mod_env; match mod_desc with | Tmod_ident _ -> () | Tmod_structure st -> sub.structure sub st | Tmod_functor (arg, mexpr) -> functor_parameter sub arg; sub.module_expr sub mexpr | Tmod_apply (mexp1, mexp2, c) -> sub.module_expr sub mexp1; sub.module_expr sub mexp2; sub.module_coercion sub c | Tmod_constraint (mexpr, _, Tmodtype_implicit, c) -> sub.module_expr sub mexpr; sub.module_coercion sub c | Tmod_constraint (mexpr, _, Tmodtype_explicit mtype, c) -> sub.module_expr sub mexpr; sub.module_type sub mtype; sub.module_coercion sub c | Tmod_unpack (exp, _) -> sub.expr sub exp let module_binding sub {mb_expr; _} = sub.module_expr sub mb_expr let class_expr sub {cl_desc; cl_env; _} = sub.env sub cl_env; match cl_desc with | Tcl_constraint (cl, clty, _, _, _) -> sub.class_expr sub cl; Option.iter (sub.class_type sub) clty | Tcl_structure clstr -> sub.class_structure sub clstr | Tcl_fun (_, pat, priv, cl, _) -> sub.pat sub pat; List.iter (fun (_, e) -> sub.expr sub e) priv; sub.class_expr sub cl | Tcl_apply (cl, args) -> sub.class_expr sub cl; List.iter (function | (_, Arg exp) -> sub.expr sub exp | (_, Omitted o) -> sub.env sub o.ty_env) args | Tcl_let (rec_flag, value_bindings, ivars, cl) -> sub.value_bindings sub (rec_flag, value_bindings); List.iter (fun (_, e) -> sub.expr sub e) ivars; sub.class_expr sub cl | Tcl_ident (_, _, tyl) -> List.iter (sub.typ sub) tyl | Tcl_open (od, e) -> sub.open_description sub od; sub.class_expr sub e let class_type sub {cltyp_desc; cltyp_env; _} = sub.env sub cltyp_env; match cltyp_desc with | Tcty_signature csg -> sub.class_signature sub csg | Tcty_constr (_, _, list) -> List.iter (sub.typ sub) list | Tcty_arrow (_, ct, cl) -> sub.typ sub ct; sub.class_type sub cl | Tcty_open (od, e) -> sub.open_description sub od; sub.class_type sub e let class_signature sub {csig_self; csig_fields; _} = sub.typ sub csig_self; List.iter (sub.class_type_field sub) csig_fields let class_type_field sub {ctf_desc; _} = match ctf_desc with | Tctf_inherit ct -> sub.class_type sub ct | Tctf_val (_, _, _, ct) -> sub.typ sub ct | Tctf_method (_, _, _, ct) -> sub.typ sub ct | Tctf_constraint (ct1, ct2) -> sub.typ sub ct1; sub.typ sub ct2 | Tctf_attribute _ -> () let typ sub {ctyp_desc; ctyp_env; _} = sub.env sub ctyp_env; match ctyp_desc with | Ttyp_any -> () | Ttyp_var _ -> () | Ttyp_arrow (_, ct1, ct2) -> sub.typ sub ct1; sub.typ sub ct2 | Ttyp_tuple list -> List.iter (sub.typ sub) list | Ttyp_constr (_, _, list) -> List.iter (sub.typ sub) list | Ttyp_object (list, _) -> List.iter (sub.object_field sub) list | Ttyp_class (_, _, list) -> List.iter (sub.typ sub) list | Ttyp_alias (ct, _) -> sub.typ sub ct | Ttyp_variant (list, _, _) -> List.iter (sub.row_field sub) list | Ttyp_poly (_, ct) -> sub.typ sub ct | Ttyp_package pack -> sub.package_type sub pack let class_structure sub {cstr_self; cstr_fields; _} = sub.pat sub cstr_self; List.iter (sub.class_field sub) cstr_fields let row_field sub {rf_desc; _} = match rf_desc with | Ttag (_, _, list) -> List.iter (sub.typ sub) list | Tinherit ct -> sub.typ sub ct let object_field sub {of_desc; _} = match of_desc with | OTtag (_, ct) -> sub.typ sub ct | OTinherit ct -> sub.typ sub ct let class_field_kind sub = function | Tcfk_virtual ct -> sub.typ sub ct | Tcfk_concrete (_, e) -> sub.expr sub e let class_field sub {cf_desc; _} = match cf_desc with | Tcf_inherit (_, cl, _, _, _) -> sub.class_expr sub cl | Tcf_constraint (cty1, cty2) -> sub.typ sub cty1; sub.typ sub cty2 | Tcf_val (_, _, _, k, _) -> class_field_kind sub k | Tcf_method (_, _, k) -> class_field_kind sub k | Tcf_initializer exp -> sub.expr sub exp | Tcf_attribute _ -> () let value_bindings sub (_, list) = List.iter (sub.value_binding sub) list let case sub {c_lhs; c_guard; c_rhs} = sub.pat sub c_lhs; Option.iter (sub.expr sub) c_guard; sub.expr sub c_rhs let value_binding sub {vb_pat; vb_expr; _} = sub.pat sub vb_pat; sub.expr sub vb_expr let env _sub _ = () let default_iterator = { binding_op; case; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; env; expr; extension_constructor; module_binding; module_coercion; module_declaration; module_substitution; module_expr; module_type; module_type_declaration; package_type; pat; row_field; object_field; open_declaration; open_description; signature; signature_item; structure; structure_item; typ; type_declaration; type_declarations; type_extension; type_exception; type_kind; value_binding; value_bindings; value_description; with_constraint; }
null
https://raw.githubusercontent.com/ocaml-flambda/flambda-backend/14e94c382a2ea09956a217c1ffb25ad5c24e3c89/ocaml/typing/tast_iterator.ml
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************
Isaac " " Avram Copyright 2019 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Asttypes open Typedtree type iterator = { binding_op: iterator -> binding_op -> unit; case: 'k . iterator -> 'k case -> unit; class_declaration: iterator -> class_declaration -> unit; class_description: iterator -> class_description -> unit; class_expr: iterator -> class_expr -> unit; class_field: iterator -> class_field -> unit; class_signature: iterator -> class_signature -> unit; class_structure: iterator -> class_structure -> unit; class_type: iterator -> class_type -> unit; class_type_declaration: iterator -> class_type_declaration -> unit; class_type_field: iterator -> class_type_field -> unit; env: iterator -> Env.t -> unit; expr: iterator -> expression -> unit; extension_constructor: iterator -> extension_constructor -> unit; module_binding: iterator -> module_binding -> unit; module_coercion: iterator -> module_coercion -> unit; module_declaration: iterator -> module_declaration -> unit; module_substitution: iterator -> module_substitution -> unit; module_expr: iterator -> module_expr -> unit; module_type: iterator -> module_type -> unit; module_type_declaration: iterator -> module_type_declaration -> unit; package_type: iterator -> package_type -> unit; pat: 'k . iterator -> 'k general_pattern -> unit; row_field: iterator -> row_field -> unit; object_field: iterator -> object_field -> unit; open_declaration: iterator -> open_declaration -> unit; open_description: iterator -> open_description -> unit; signature: iterator -> signature -> unit; signature_item: iterator -> signature_item -> unit; structure: iterator -> structure -> unit; structure_item: iterator -> structure_item -> unit; typ: iterator -> core_type -> unit; type_declaration: iterator -> type_declaration -> unit; type_declarations: iterator -> (rec_flag * type_declaration list) -> unit; type_extension: iterator -> type_extension -> unit; type_exception: iterator -> type_exception -> unit; type_kind: iterator -> type_kind -> unit; value_binding: iterator -> value_binding -> unit; value_bindings: iterator -> (rec_flag * value_binding list) -> unit; value_description: iterator -> value_description -> unit; with_constraint: iterator -> with_constraint -> unit; } let structure sub {str_items; str_final_env; _} = List.iter (sub.structure_item sub) str_items; sub.env sub str_final_env let class_infos sub f x = List.iter (fun (ct, _) -> sub.typ sub ct) x.ci_params; f x.ci_expr let module_type_declaration sub {mtd_type; _} = Option.iter (sub.module_type sub) mtd_type let module_declaration sub {md_type; _} = sub.module_type sub md_type let module_substitution _ _ = () let include_kind sub = function | Tincl_structure -> () | Tincl_functor ccs -> List.iter (fun (_, cc) -> sub.module_coercion sub cc) ccs | Tincl_gen_functor ccs -> List.iter (fun (_, cc) -> sub.module_coercion sub cc) ccs let str_include_infos sub {incl_mod; incl_kind} = sub.module_expr sub incl_mod; include_kind sub incl_kind let class_type_declaration sub x = class_infos sub (sub.class_type sub) x let class_declaration sub x = class_infos sub (sub.class_expr sub) x let structure_item sub {str_desc; str_env; _} = sub.env sub str_env; match str_desc with | Tstr_eval (exp, _) -> sub.expr sub exp | Tstr_value (rec_flag, list) -> sub.value_bindings sub (rec_flag, list) | Tstr_primitive v -> sub.value_description sub v | Tstr_type (rec_flag, list) -> sub.type_declarations sub (rec_flag, list) | Tstr_typext te -> sub.type_extension sub te | Tstr_exception ext -> sub.type_exception sub ext | Tstr_module mb -> sub.module_binding sub mb | Tstr_recmodule list -> List.iter (sub.module_binding sub) list | Tstr_modtype x -> sub.module_type_declaration sub x | Tstr_class list -> List.iter (fun (cls,_) -> sub.class_declaration sub cls) list | Tstr_class_type list -> List.iter (fun (_, _, cltd) -> sub.class_type_declaration sub cltd) list | Tstr_include incl -> str_include_infos sub incl | Tstr_open od -> sub.open_declaration sub od | Tstr_attribute _ -> () let value_description sub x = sub.typ sub x.val_desc let label_decl sub {ld_type; _} = sub.typ sub ld_type let field_decl sub (ty, _) = sub.typ sub ty let constructor_args sub = function | Cstr_tuple l -> List.iter (field_decl sub) l | Cstr_record l -> List.iter (label_decl sub) l let constructor_decl sub {cd_args; cd_res; _} = constructor_args sub cd_args; Option.iter (sub.typ sub) cd_res let type_kind sub = function | Ttype_abstract -> () | Ttype_variant list -> List.iter (constructor_decl sub) list | Ttype_record list -> List.iter (label_decl sub) list | Ttype_open -> () let type_declaration sub {typ_cstrs; typ_kind; typ_manifest; typ_params; _} = List.iter (fun (c1, c2, _) -> sub.typ sub c1; sub.typ sub c2) typ_cstrs; sub.type_kind sub typ_kind; Option.iter (sub.typ sub) typ_manifest; List.iter (fun (c, _) -> sub.typ sub c) typ_params let type_declarations sub (_, list) = List.iter (sub.type_declaration sub) list let type_extension sub {tyext_constructors; tyext_params; _} = List.iter (fun (c, _) -> sub.typ sub c) tyext_params; List.iter (sub.extension_constructor sub) tyext_constructors let type_exception sub {tyexn_constructor; _} = sub.extension_constructor sub tyexn_constructor let extension_constructor sub {ext_kind; _} = match ext_kind with | Text_decl (_, ctl, cto) -> constructor_args sub ctl; Option.iter (sub.typ sub) cto | Text_rebind _ -> () let pat_extra sub (e, _loc, _attrs) = match e with | Tpat_type _ -> () | Tpat_unpack -> () | Tpat_open (_, _, env) -> sub.env sub env | Tpat_constraint ct -> sub.typ sub ct let pat : type k . iterator -> k general_pattern -> unit = fun sub {pat_extra = extra; pat_desc; pat_env; _} -> sub.env sub pat_env; List.iter (pat_extra sub) extra; match pat_desc with | Tpat_any -> () | Tpat_var _ -> () | Tpat_constant _ -> () | Tpat_tuple l -> List.iter (sub.pat sub) l | Tpat_construct (_, _, l, vto) -> List.iter (sub.pat sub) l; Option.iter (fun (_ids, ct) -> sub.typ sub ct) vto | Tpat_variant (_, po, _) -> Option.iter (sub.pat sub) po | Tpat_record (l, _) -> List.iter (fun (_, _, i) -> sub.pat sub i) l | Tpat_array (_, l) -> List.iter (sub.pat sub) l | Tpat_alias (p, _, _, _) -> sub.pat sub p | Tpat_lazy p -> sub.pat sub p | Tpat_value p -> sub.pat sub (p :> pattern) | Tpat_exception p -> sub.pat sub p | Tpat_or (p1, p2, _) -> sub.pat sub p1; sub.pat sub p2 let expr sub {exp_extra; exp_desc; exp_env; _} = let extra = function | Texp_constraint cty -> sub.typ sub cty | Texp_coerce (cty1, cty2) -> Option.iter (sub.typ sub) cty1; sub.typ sub cty2 | Texp_newtype _ -> () | Texp_poly cto -> Option.iter (sub.typ sub) cto in List.iter (fun (e, _, _) -> extra e) exp_extra; sub.env sub exp_env; match exp_desc with | Texp_ident _ -> () | Texp_constant _ -> () | Texp_let (rec_flag, list, exp) -> sub.value_bindings sub (rec_flag, list); sub.expr sub exp | Texp_function {cases; _} -> List.iter (sub.case sub) cases | Texp_apply (exp, list, _, _) -> sub.expr sub exp; List.iter (function | (_, Arg exp) -> sub.expr sub exp | (_, Omitted _) -> ()) list | Texp_match (exp, cases, _) -> sub.expr sub exp; List.iter (sub.case sub) cases | Texp_try (exp, cases) -> sub.expr sub exp; List.iter (sub.case sub) cases | Texp_tuple (list, _) -> List.iter (sub.expr sub) list | Texp_construct (_, _, args, _) -> List.iter (sub.expr sub) args | Texp_variant (_, expo) -> Option.iter (fun (expr, _) -> sub.expr sub expr) expo | Texp_record { fields; extended_expression; _} -> Array.iter (function | _, Kept _ -> () | _, Overridden (_, exp) -> sub.expr sub exp) fields; Option.iter (sub.expr sub) extended_expression; | Texp_field (exp, _, _, _) -> sub.expr sub exp | Texp_setfield (exp1, _, _, _, exp2) -> sub.expr sub exp1; sub.expr sub exp2 | Texp_array (_, list, _) -> List.iter (sub.expr sub) list | Texp_list_comprehension { comp_body; comp_clauses } | Texp_array_comprehension (_, { comp_body; comp_clauses }) -> sub.expr sub comp_body; List.iter (function | Texp_comp_for bindings -> List.iter (fun { comp_cb_iterator; comp_cb_attributes = _ } -> match comp_cb_iterator with | Texp_comp_range { ident = _; start; stop; direction = _ } -> sub.expr sub start; sub.expr sub stop | Texp_comp_in { pattern; sequence } -> sub.pat sub pattern; sub.expr sub sequence) bindings | Texp_comp_when exp -> sub.expr sub exp) comp_clauses | Texp_ifthenelse (exp1, exp2, expo) -> sub.expr sub exp1; sub.expr sub exp2; Option.iter (sub.expr sub) expo | Texp_sequence (exp1, exp2) -> sub.expr sub exp1; sub.expr sub exp2 | Texp_while { wh_cond; wh_body } -> sub.expr sub wh_cond; sub.expr sub wh_body | Texp_for {for_from; for_to; for_body} -> sub.expr sub for_from; sub.expr sub for_to; sub.expr sub for_body | Texp_send (exp, _, _, _) -> sub.expr sub exp | Texp_new _ -> () | Texp_instvar _ -> () | Texp_setinstvar (_, _, _, exp) ->sub.expr sub exp | Texp_override (_, list) -> List.iter (fun (_, _, e) -> sub.expr sub e) list | Texp_letmodule (_, _, _, mexpr, exp) -> sub.module_expr sub mexpr; sub.expr sub exp | Texp_letexception (cd, exp) -> sub.extension_constructor sub cd; sub.expr sub exp | Texp_assert exp -> sub.expr sub exp | Texp_lazy exp -> sub.expr sub exp | Texp_object (cl, _) -> sub.class_structure sub cl | Texp_pack mexpr -> sub.module_expr sub mexpr | Texp_letop {let_ = l; ands; body; _} -> sub.binding_op sub l; List.iter (sub.binding_op sub) ands; sub.case sub body | Texp_unreachable -> () | Texp_extension_constructor _ -> () | Texp_open (od, e) -> sub.open_declaration sub od; sub.expr sub e | Texp_probe {handler;_} -> sub.expr sub handler | Texp_probe_is_enabled _ -> () let package_type sub {pack_fields; _} = List.iter (fun (_, p) -> sub.typ sub p) pack_fields let binding_op sub {bop_exp; _} = sub.expr sub bop_exp let signature sub {sig_items; sig_final_env; _} = sub.env sub sig_final_env; List.iter (sub.signature_item sub) sig_items let sig_include_infos sub {incl_mod; incl_kind} = sub.module_type sub incl_mod; include_kind sub incl_kind let signature_item sub {sig_desc; sig_env; _} = sub.env sub sig_env; match sig_desc with | Tsig_value v -> sub.value_description sub v | Tsig_type (rf, tdl) -> sub.type_declarations sub (rf, tdl) | Tsig_typesubst list -> sub.type_declarations sub (Nonrecursive, list) | Tsig_typext te -> sub.type_extension sub te | Tsig_exception ext -> sub.type_exception sub ext | Tsig_module x -> sub.module_declaration sub x | Tsig_modsubst x -> sub.module_substitution sub x | Tsig_recmodule list -> List.iter (sub.module_declaration sub) list | Tsig_modtype x -> sub.module_type_declaration sub x | Tsig_modtypesubst x -> sub.module_type_declaration sub x | Tsig_include incl -> sig_include_infos sub incl | Tsig_class list -> List.iter (sub.class_description sub) list | Tsig_class_type list -> List.iter (sub.class_type_declaration sub) list | Tsig_open od -> sub.open_description sub od | Tsig_attribute _ -> () let class_description sub x = class_infos sub (sub.class_type sub) x let functor_parameter sub = function | Unit -> () | Named (_, _, mtype) -> sub.module_type sub mtype let module_type sub {mty_desc; mty_env; _} = sub.env sub mty_env; match mty_desc with | Tmty_ident _ -> () | Tmty_alias _ -> () | Tmty_signature sg -> sub.signature sub sg | Tmty_functor (arg, mtype2) -> functor_parameter sub arg; sub.module_type sub mtype2 | Tmty_with (mtype, list) -> sub.module_type sub mtype; List.iter (fun (_, _, e) -> sub.with_constraint sub e) list | Tmty_typeof mexpr -> sub.module_expr sub mexpr let with_constraint sub = function | Twith_type decl -> sub.type_declaration sub decl | Twith_typesubst decl -> sub.type_declaration sub decl | Twith_module _ -> () | Twith_modsubst _ -> () | Twith_modtype _ -> () | Twith_modtypesubst _ -> () let open_description sub {open_env; _} = sub.env sub open_env let open_declaration sub {open_expr; open_env; _} = sub.module_expr sub open_expr; sub.env sub open_env let module_coercion sub = function | Tcoerce_none -> () | Tcoerce_functor (c1,c2) -> sub.module_coercion sub c1; sub.module_coercion sub c2 | Tcoerce_alias (env, _, c1) -> sub.env sub env; sub.module_coercion sub c1 | Tcoerce_structure (l1, l2) -> List.iter (fun (_, c) -> sub.module_coercion sub c) l1; List.iter (fun (_, _ ,c) -> sub.module_coercion sub c) l2 | Tcoerce_primitive {pc_env; _} -> sub.env sub pc_env let module_expr sub {mod_desc; mod_env; _} = sub.env sub mod_env; match mod_desc with | Tmod_ident _ -> () | Tmod_structure st -> sub.structure sub st | Tmod_functor (arg, mexpr) -> functor_parameter sub arg; sub.module_expr sub mexpr | Tmod_apply (mexp1, mexp2, c) -> sub.module_expr sub mexp1; sub.module_expr sub mexp2; sub.module_coercion sub c | Tmod_constraint (mexpr, _, Tmodtype_implicit, c) -> sub.module_expr sub mexpr; sub.module_coercion sub c | Tmod_constraint (mexpr, _, Tmodtype_explicit mtype, c) -> sub.module_expr sub mexpr; sub.module_type sub mtype; sub.module_coercion sub c | Tmod_unpack (exp, _) -> sub.expr sub exp let module_binding sub {mb_expr; _} = sub.module_expr sub mb_expr let class_expr sub {cl_desc; cl_env; _} = sub.env sub cl_env; match cl_desc with | Tcl_constraint (cl, clty, _, _, _) -> sub.class_expr sub cl; Option.iter (sub.class_type sub) clty | Tcl_structure clstr -> sub.class_structure sub clstr | Tcl_fun (_, pat, priv, cl, _) -> sub.pat sub pat; List.iter (fun (_, e) -> sub.expr sub e) priv; sub.class_expr sub cl | Tcl_apply (cl, args) -> sub.class_expr sub cl; List.iter (function | (_, Arg exp) -> sub.expr sub exp | (_, Omitted o) -> sub.env sub o.ty_env) args | Tcl_let (rec_flag, value_bindings, ivars, cl) -> sub.value_bindings sub (rec_flag, value_bindings); List.iter (fun (_, e) -> sub.expr sub e) ivars; sub.class_expr sub cl | Tcl_ident (_, _, tyl) -> List.iter (sub.typ sub) tyl | Tcl_open (od, e) -> sub.open_description sub od; sub.class_expr sub e let class_type sub {cltyp_desc; cltyp_env; _} = sub.env sub cltyp_env; match cltyp_desc with | Tcty_signature csg -> sub.class_signature sub csg | Tcty_constr (_, _, list) -> List.iter (sub.typ sub) list | Tcty_arrow (_, ct, cl) -> sub.typ sub ct; sub.class_type sub cl | Tcty_open (od, e) -> sub.open_description sub od; sub.class_type sub e let class_signature sub {csig_self; csig_fields; _} = sub.typ sub csig_self; List.iter (sub.class_type_field sub) csig_fields let class_type_field sub {ctf_desc; _} = match ctf_desc with | Tctf_inherit ct -> sub.class_type sub ct | Tctf_val (_, _, _, ct) -> sub.typ sub ct | Tctf_method (_, _, _, ct) -> sub.typ sub ct | Tctf_constraint (ct1, ct2) -> sub.typ sub ct1; sub.typ sub ct2 | Tctf_attribute _ -> () let typ sub {ctyp_desc; ctyp_env; _} = sub.env sub ctyp_env; match ctyp_desc with | Ttyp_any -> () | Ttyp_var _ -> () | Ttyp_arrow (_, ct1, ct2) -> sub.typ sub ct1; sub.typ sub ct2 | Ttyp_tuple list -> List.iter (sub.typ sub) list | Ttyp_constr (_, _, list) -> List.iter (sub.typ sub) list | Ttyp_object (list, _) -> List.iter (sub.object_field sub) list | Ttyp_class (_, _, list) -> List.iter (sub.typ sub) list | Ttyp_alias (ct, _) -> sub.typ sub ct | Ttyp_variant (list, _, _) -> List.iter (sub.row_field sub) list | Ttyp_poly (_, ct) -> sub.typ sub ct | Ttyp_package pack -> sub.package_type sub pack let class_structure sub {cstr_self; cstr_fields; _} = sub.pat sub cstr_self; List.iter (sub.class_field sub) cstr_fields let row_field sub {rf_desc; _} = match rf_desc with | Ttag (_, _, list) -> List.iter (sub.typ sub) list | Tinherit ct -> sub.typ sub ct let object_field sub {of_desc; _} = match of_desc with | OTtag (_, ct) -> sub.typ sub ct | OTinherit ct -> sub.typ sub ct let class_field_kind sub = function | Tcfk_virtual ct -> sub.typ sub ct | Tcfk_concrete (_, e) -> sub.expr sub e let class_field sub {cf_desc; _} = match cf_desc with | Tcf_inherit (_, cl, _, _, _) -> sub.class_expr sub cl | Tcf_constraint (cty1, cty2) -> sub.typ sub cty1; sub.typ sub cty2 | Tcf_val (_, _, _, k, _) -> class_field_kind sub k | Tcf_method (_, _, k) -> class_field_kind sub k | Tcf_initializer exp -> sub.expr sub exp | Tcf_attribute _ -> () let value_bindings sub (_, list) = List.iter (sub.value_binding sub) list let case sub {c_lhs; c_guard; c_rhs} = sub.pat sub c_lhs; Option.iter (sub.expr sub) c_guard; sub.expr sub c_rhs let value_binding sub {vb_pat; vb_expr; _} = sub.pat sub vb_pat; sub.expr sub vb_expr let env _sub _ = () let default_iterator = { binding_op; case; class_declaration; class_description; class_expr; class_field; class_signature; class_structure; class_type; class_type_declaration; class_type_field; env; expr; extension_constructor; module_binding; module_coercion; module_declaration; module_substitution; module_expr; module_type; module_type_declaration; package_type; pat; row_field; object_field; open_declaration; open_description; signature; signature_item; structure; structure_item; typ; type_declaration; type_declarations; type_extension; type_exception; type_kind; value_binding; value_bindings; value_description; with_constraint; }
3b9cede17fba87c7562fd537985e7231dc595e7607ead774c2bf3ca741b59758
opencog/pln
abduction.scm
;; ============================================================================= ;; AbductionRule ;; ;; <LinkType> ;; A ;; B ;; <LinkType> ;; C ;; B ;; |- ;; <LinkType> ;; A ;; C ;; Due to type system limitations , the rule has been divided into 3 : ;; abduction-inheritance-rule ;; abduction-implication-rule ;; abduction-subset-rule ;; TODO : make BC compatible ( check if the premises could be unordered ) ;; ;; ----------------------------------------------------------------------------- (load "formulas.scm") ;; Generate the corresponding abduction rule given its link-type. (define (gen-abduction-rule link-type) (BindLink (VariableList (VariableNode "$A") (VariableNode "$B") (VariableNode "$C")) (AndLink (link-type (VariableNode "$A") (VariableNode "$B")) (link-type (VariableNode "$C") (VariableNode "$B")) (NotLink (IdenticalLink (VariableNode "$A") (VariableNode "$C")))) (ExecutionOutputLink (GroundedSchemaNode "scm: abduction-formula") (ListLink (link-type (VariableNode "$A") (VariableNode "$B")) (link-type (VariableNode "$C") (VariableNode "$B")) (link-type (VariableNode "$A") (VariableNode "$C")))))) (define abduction-inheritance-rule (gen-abduction-rule InheritanceLink)) (define abduction-implication-rule (gen-abduction-rule ImplicationLink)) (define abduction-subset-rule (gen-abduction-rule SubsetLink)) (define (abduction-formula AB CB AC) (let ((sA (cog-mean (gar AB))) (cA (cog-confidence (gar AB))) (sB (cog-mean (gdr AB))) (cB (cog-confidence (gdr AB))) (sC (cog-mean (gar CB))) (cC (cog-confidence (gar CB))) (sAB (cog-mean AB)) (cAB (cog-confidence AB)) (sCB (cog-mean CB)) (cCB (cog-confidence CB))) (cog-merge-hi-conf-tv! AC (stv (simple-deduction-strength-formula sA sB sC sAB (inversion-strength-formula sCB sC sB)) (min cAB cCB))))) ;; Name the rules (define abduction-inheritance-rule-name (DefinedSchemaNode "abduction-inheritance-rule")) (DefineLink abduction-inheritance-rule-name abduction-inheritance-rule) (define abduction-implication-rule-name (DefinedSchemaNode "abduction-implication-rule")) (DefineLink abduction-implication-rule-name abduction-implication-rule) (define abduction-subset-rule-name (DefinedSchemaNode "abduction-subset-rule")) (DefineLink abduction-subset-rule-name abduction-subset-rule)
null
https://raw.githubusercontent.com/opencog/pln/332d2e0dc1ebdcc27b5f0c0e59d3bdebe98aa5ba/opencog/pln/rules/wip/abduction.scm
scheme
============================================================================= AbductionRule <LinkType> A B <LinkType> C B |- <LinkType> A C abduction-inheritance-rule abduction-implication-rule abduction-subset-rule ----------------------------------------------------------------------------- Generate the corresponding abduction rule given its link-type. Name the rules
Due to type system limitations , the rule has been divided into 3 : TODO : make BC compatible ( check if the premises could be unordered ) (load "formulas.scm") (define (gen-abduction-rule link-type) (BindLink (VariableList (VariableNode "$A") (VariableNode "$B") (VariableNode "$C")) (AndLink (link-type (VariableNode "$A") (VariableNode "$B")) (link-type (VariableNode "$C") (VariableNode "$B")) (NotLink (IdenticalLink (VariableNode "$A") (VariableNode "$C")))) (ExecutionOutputLink (GroundedSchemaNode "scm: abduction-formula") (ListLink (link-type (VariableNode "$A") (VariableNode "$B")) (link-type (VariableNode "$C") (VariableNode "$B")) (link-type (VariableNode "$A") (VariableNode "$C")))))) (define abduction-inheritance-rule (gen-abduction-rule InheritanceLink)) (define abduction-implication-rule (gen-abduction-rule ImplicationLink)) (define abduction-subset-rule (gen-abduction-rule SubsetLink)) (define (abduction-formula AB CB AC) (let ((sA (cog-mean (gar AB))) (cA (cog-confidence (gar AB))) (sB (cog-mean (gdr AB))) (cB (cog-confidence (gdr AB))) (sC (cog-mean (gar CB))) (cC (cog-confidence (gar CB))) (sAB (cog-mean AB)) (cAB (cog-confidence AB)) (sCB (cog-mean CB)) (cCB (cog-confidence CB))) (cog-merge-hi-conf-tv! AC (stv (simple-deduction-strength-formula sA sB sC sAB (inversion-strength-formula sCB sC sB)) (min cAB cCB))))) (define abduction-inheritance-rule-name (DefinedSchemaNode "abduction-inheritance-rule")) (DefineLink abduction-inheritance-rule-name abduction-inheritance-rule) (define abduction-implication-rule-name (DefinedSchemaNode "abduction-implication-rule")) (DefineLink abduction-implication-rule-name abduction-implication-rule) (define abduction-subset-rule-name (DefinedSchemaNode "abduction-subset-rule")) (DefineLink abduction-subset-rule-name abduction-subset-rule)
0779cec027384c63b0828bd74176b22594d25c5e0f6ab4ee95917efefc1ab8f7
tomjaguarpaw/haskell-opaleye
Values.hs
{-# LANGUAGE Arrows #-} # LANGUAGE FlexibleInstances , MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # module Opaleye.Internal.Values where import Opaleye.Internal.Column (Field_(Column)) import qualified Opaleye.Internal.Column as C import qualified Opaleye.Column as OC import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.Internal.Tag as T import qualified Opaleye.Internal.Operators as O import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.PackMap as PM import qualified Opaleye.Internal.QueryArr as Q import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Opaleye.Internal.PGTypes import qualified Opaleye.SqlTypes import Control.Arrow (returnA) import qualified Control.Monad.Trans.State.Strict as State import qualified Data.List.NonEmpty as NEL import Data.Profunctor (Profunctor, dimap, rmap, lmap) import Data.Profunctor.Product (ProductProfunctor) import qualified Data.Profunctor.Product as PP import Data.Profunctor.Product.Default (Default, def) import Data.Semigroup (Semigroup, (<>)) import Control.Applicative (Applicative, pure, (<*>), liftA2) nonEmptyValues :: Rowspec columns columns' -> NEL.NonEmpty columns -> Q.Select columns' nonEmptyValues rowspec rows = let nerowspec' = case rowspec of NonEmptyRows nerowspec -> nerowspec EmptyRows fields -> dimap (const zero) (const fields) nonEmptyRowspecField where zero = 0 :: C.Field Opaleye.SqlTypes.SqlInt4 in nonEmptyRows nerowspec' rows nonEmptyRows :: NonEmptyRowspec fields fields' -> NEL.NonEmpty fields -> Q.Select fields' nonEmptyRows (NonEmptyRowspec runRow fields) rows = Q.productQueryArr $ do (valuesPEs, newColumns) <- fields pure (newColumns, PQ.Values (NEL.toList valuesPEs) (fmap (NEL.toList . runRow) rows)) emptySelectExplicit :: Nullspec columns a -> Q.Select a emptySelectExplicit nullspec = proc () -> do O.restrict -< Opaleye.SqlTypes.sqlBool False returnA -< nullFields nullspec data NonEmptyRowspec fields fields' = NonEmptyRowspec (fields -> NEL.NonEmpty HPQ.PrimExpr) (State.State T.Tag (NEL.NonEmpty HPQ.Symbol, fields')) -- Some overlap here with extractAttrPE nonEmptyRowspecField :: NonEmptyRowspec (Field_ n a) (Field_ n a) nonEmptyRowspecField = NonEmptyRowspec (pure . C.unColumn) s where s = do t <- T.fresh let symbol = HPQ.Symbol "values" t pure (pure symbol, C.Column (HPQ.AttrExpr symbol)) rowspecField :: Rowspec (Field_ n a) (Field_ n a) rowspecField = NonEmptyRows nonEmptyRowspecField data Rowspec fields fields' = NonEmptyRows (NonEmptyRowspec fields fields') | EmptyRows fields' data Valuesspec fields fields' = ValuesspecSafe (Nullspec fields fields') (Rowspec fields fields') valuesspecField :: Opaleye.SqlTypes.IsSqlType a => Valuesspec (Field_ n a) (Field_ n a) valuesspecField = def_ where def_ = valuesspecFieldType (Opaleye.Internal.PGTypes.showSqlType sqlType) sqlType = columnProxy def_ columnProxy :: f (Field_ n sqlType) -> Maybe sqlType columnProxy _ = Nothing -- For rel8 valuesspecFieldType :: String -> Valuesspec (Field_ n a) (Field_ n a) valuesspecFieldType sqlType = ValuesspecSafe (nullspecFieldType sqlType) rowspecField instance forall a n. Opaleye.Internal.PGTypes.IsSqlType a => Default Valuesspec (Field_ n a) (Field_ n a) where def = ValuesspecSafe nullspecField rowspecField newtype Nullspec fields fields' = Nullspec fields' nullspecField :: forall a n sqlType. Opaleye.SqlTypes.IsSqlType sqlType => Nullspec a (Field_ n sqlType) nullspecField = nullspecFieldType ty where ty = Opaleye.Internal.PGTypes.showSqlType (Nothing :: Maybe sqlType) nullspecFieldType :: String -> Nullspec a (Field_ n sqlType) nullspecFieldType sqlType = (Nullspec . C.unsafeCast sqlType . C.unsafeCoerceColumn) OC.null nullspecList :: Nullspec a [b] nullspecList = pure [] nullspecEitherLeft :: Nullspec a b -> Nullspec a (Either b b') nullspecEitherLeft = fmap Left nullspecEitherRight :: Nullspec a b' -> Nullspec a (Either b b') nullspecEitherRight = fmap Right instance Opaleye.SqlTypes.IsSqlType b => Default Nullspec a (Field_ n b) where def = nullspecField -- | All fields @NULL@, even though technically the type may forbid -- that! Used to create such fields when we know we will never look -- at them expecting to find something non-NULL. nullFields :: Nullspec a fields -> fields nullFields (Nullspec v) = v -- { -- Boilerplate instance definitions. Theoretically, these are derivable. instance Functor (ValuesspecUnsafe a) where fmap f (Valuesspec g) = Valuesspec (fmap f g) instance Applicative (ValuesspecUnsafe a) where pure = Valuesspec . pure Valuesspec f <*> Valuesspec x = Valuesspec (f <*> x) instance Profunctor ValuesspecUnsafe where dimap _ g (Valuesspec q) = Valuesspec (rmap g q) instance ProductProfunctor ValuesspecUnsafe where purePP = pure (****) = (<*>) instance Functor (Valuesspec a) where fmap f (ValuesspecSafe g h) = ValuesspecSafe (fmap f g) (fmap f h) instance Applicative (Valuesspec a) where pure a = ValuesspecSafe (pure a) (pure a) ValuesspecSafe f f' <*> ValuesspecSafe x x' = ValuesspecSafe (f <*> x) (f' <*> x') instance Profunctor Valuesspec where dimap f g (ValuesspecSafe q q') = ValuesspecSafe (dimap f g q) (dimap f g q') instance ProductProfunctor Valuesspec where purePP = pure (****) = (<*>) instance Functor (Nullspec a) where fmap f (Nullspec g) = Nullspec (f g) instance Applicative (Nullspec a) where pure = Nullspec Nullspec f <*> Nullspec x = Nullspec (f x) instance Profunctor Nullspec where dimap _ g (Nullspec q) = Nullspec (g q) instance ProductProfunctor Nullspec where purePP = pure (****) = (<*>) instance Functor (NonEmptyRowspec a) where fmap = rmap instance Profunctor NonEmptyRowspec where dimap f g (NonEmptyRowspec a b) = NonEmptyRowspec (lmap f a) ((fmap . fmap) g b) instance Functor (Rowspec a) where fmap = rmap instance Applicative (Rowspec a) where pure x = EmptyRows x r1 <*> r2 = case (r1, r2) of (EmptyRows f, EmptyRows x) -> EmptyRows (f x) (EmptyRows f, NonEmptyRows (NonEmptyRowspec x1 x2)) -> NonEmptyRows (NonEmptyRowspec x1 ((fmap . fmap) f x2)) (NonEmptyRows (NonEmptyRowspec f1 f2), EmptyRows x) -> NonEmptyRows (NonEmptyRowspec f1 ((fmap . fmap) ($ x) f2)) (NonEmptyRows (NonEmptyRowspec f1 f2), NonEmptyRows (NonEmptyRowspec x1 x2)) -> NonEmptyRows (NonEmptyRowspec (f1 <> x1) ((liftA2 . liftF2) ($) f2 x2)) where -- Instead of depending on Apply -19.16/semigroupoids-5.3.7/Data-Functor-Apply.html#v:liftF2 liftF2 :: Semigroup m => (a' -> b -> c) -> (m, a') -> (m, b) -> (m, c) liftF2 f (ys1, x1) (ys2, x2) = (ys1 <> ys2, f x1 x2) instance Profunctor Rowspec where dimap f g = \case EmptyRows x -> EmptyRows (g x) NonEmptyRows x -> NonEmptyRows (dimap f g x) instance ProductProfunctor Rowspec where purePP = pure (****) = (<*>) -- } # DEPRECATED valuesU " Will be removed in 0.10 " # valuesU :: U.Unpackspec columns columns' -> ValuesspecUnsafe columns columns' -> [columns] -> ((), T.Tag) -> (columns', PQ.PrimQuery) valuesU unpack valuesspec rows ((), t) = (newColumns, primQ') where runRow row = valuesRow where (_, valuesRow) = PM.run (U.runUnpackspec unpack extractValuesEntry row) (newColumns, valuesPEs_nulls) = PM.run (runValuesspec valuesspec (extractValuesField t)) valuesPEs = map fst valuesPEs_nulls values :: [[HPQ.PrimExpr]] values = map runRow rows primQ' = case NEL.nonEmpty values of Nothing -> PQ.Empty () Just values' -> PQ.Values valuesPEs values' # DEPRECATED extractValuesEntry " Will be removed in 0.10 " # extractValuesEntry :: HPQ.PrimExpr -> PM.PM [HPQ.PrimExpr] HPQ.PrimExpr extractValuesEntry pe = do PM.write pe return pe # DEPRECATED extractValuesField " Will be removed in 0.10 " # extractValuesField :: T.Tag -> primExpr -> PM.PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr extractValuesField = PM.extractAttr "values" # DEPRECATED runValuesspec " Will be removed in 0.10 " # runValuesspec :: Applicative f => ValuesspecUnsafe columns columns' -> (() -> f HPQ.PrimExpr) -> f columns' runValuesspec (Valuesspec v) f = PM.traversePM v f () newtype ValuesspecUnsafe columns columns' = Valuesspec (PM.PackMap () HPQ.PrimExpr () columns') instance Default ValuesspecUnsafe (Field_ n a) (Field_ n a) where def = Valuesspec (PM.iso id Column) # DEPRECATED ValuesspecSafe " Use Valuesspec instead . Will be removed in version 0.10 . " # type ValuesspecSafe = Valuesspec
null
https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/6edcc5bd25c05d9a323417d0a5dec19ba0013852/src/Opaleye/Internal/Values.hs
haskell
# LANGUAGE Arrows # Some overlap here with extractAttrPE For rel8 | All fields @NULL@, even though technically the type may forbid that! Used to create such fields when we know we will never look at them expecting to find something non-NULL. { Boilerplate instance definitions. Theoretically, these are derivable. Instead of depending on Apply }
# LANGUAGE FlexibleInstances , MultiParamTypeClasses # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # module Opaleye.Internal.Values where import Opaleye.Internal.Column (Field_(Column)) import qualified Opaleye.Internal.Column as C import qualified Opaleye.Column as OC import qualified Opaleye.Internal.Unpackspec as U import qualified Opaleye.Internal.Tag as T import qualified Opaleye.Internal.Operators as O import qualified Opaleye.Internal.PrimQuery as PQ import qualified Opaleye.Internal.PackMap as PM import qualified Opaleye.Internal.QueryArr as Q import qualified Opaleye.Internal.HaskellDB.PrimQuery as HPQ import qualified Opaleye.Internal.PGTypes import qualified Opaleye.SqlTypes import Control.Arrow (returnA) import qualified Control.Monad.Trans.State.Strict as State import qualified Data.List.NonEmpty as NEL import Data.Profunctor (Profunctor, dimap, rmap, lmap) import Data.Profunctor.Product (ProductProfunctor) import qualified Data.Profunctor.Product as PP import Data.Profunctor.Product.Default (Default, def) import Data.Semigroup (Semigroup, (<>)) import Control.Applicative (Applicative, pure, (<*>), liftA2) nonEmptyValues :: Rowspec columns columns' -> NEL.NonEmpty columns -> Q.Select columns' nonEmptyValues rowspec rows = let nerowspec' = case rowspec of NonEmptyRows nerowspec -> nerowspec EmptyRows fields -> dimap (const zero) (const fields) nonEmptyRowspecField where zero = 0 :: C.Field Opaleye.SqlTypes.SqlInt4 in nonEmptyRows nerowspec' rows nonEmptyRows :: NonEmptyRowspec fields fields' -> NEL.NonEmpty fields -> Q.Select fields' nonEmptyRows (NonEmptyRowspec runRow fields) rows = Q.productQueryArr $ do (valuesPEs, newColumns) <- fields pure (newColumns, PQ.Values (NEL.toList valuesPEs) (fmap (NEL.toList . runRow) rows)) emptySelectExplicit :: Nullspec columns a -> Q.Select a emptySelectExplicit nullspec = proc () -> do O.restrict -< Opaleye.SqlTypes.sqlBool False returnA -< nullFields nullspec data NonEmptyRowspec fields fields' = NonEmptyRowspec (fields -> NEL.NonEmpty HPQ.PrimExpr) (State.State T.Tag (NEL.NonEmpty HPQ.Symbol, fields')) nonEmptyRowspecField :: NonEmptyRowspec (Field_ n a) (Field_ n a) nonEmptyRowspecField = NonEmptyRowspec (pure . C.unColumn) s where s = do t <- T.fresh let symbol = HPQ.Symbol "values" t pure (pure symbol, C.Column (HPQ.AttrExpr symbol)) rowspecField :: Rowspec (Field_ n a) (Field_ n a) rowspecField = NonEmptyRows nonEmptyRowspecField data Rowspec fields fields' = NonEmptyRows (NonEmptyRowspec fields fields') | EmptyRows fields' data Valuesspec fields fields' = ValuesspecSafe (Nullspec fields fields') (Rowspec fields fields') valuesspecField :: Opaleye.SqlTypes.IsSqlType a => Valuesspec (Field_ n a) (Field_ n a) valuesspecField = def_ where def_ = valuesspecFieldType (Opaleye.Internal.PGTypes.showSqlType sqlType) sqlType = columnProxy def_ columnProxy :: f (Field_ n sqlType) -> Maybe sqlType columnProxy _ = Nothing valuesspecFieldType :: String -> Valuesspec (Field_ n a) (Field_ n a) valuesspecFieldType sqlType = ValuesspecSafe (nullspecFieldType sqlType) rowspecField instance forall a n. Opaleye.Internal.PGTypes.IsSqlType a => Default Valuesspec (Field_ n a) (Field_ n a) where def = ValuesspecSafe nullspecField rowspecField newtype Nullspec fields fields' = Nullspec fields' nullspecField :: forall a n sqlType. Opaleye.SqlTypes.IsSqlType sqlType => Nullspec a (Field_ n sqlType) nullspecField = nullspecFieldType ty where ty = Opaleye.Internal.PGTypes.showSqlType (Nothing :: Maybe sqlType) nullspecFieldType :: String -> Nullspec a (Field_ n sqlType) nullspecFieldType sqlType = (Nullspec . C.unsafeCast sqlType . C.unsafeCoerceColumn) OC.null nullspecList :: Nullspec a [b] nullspecList = pure [] nullspecEitherLeft :: Nullspec a b -> Nullspec a (Either b b') nullspecEitherLeft = fmap Left nullspecEitherRight :: Nullspec a b' -> Nullspec a (Either b b') nullspecEitherRight = fmap Right instance Opaleye.SqlTypes.IsSqlType b => Default Nullspec a (Field_ n b) where def = nullspecField nullFields :: Nullspec a fields -> fields nullFields (Nullspec v) = v instance Functor (ValuesspecUnsafe a) where fmap f (Valuesspec g) = Valuesspec (fmap f g) instance Applicative (ValuesspecUnsafe a) where pure = Valuesspec . pure Valuesspec f <*> Valuesspec x = Valuesspec (f <*> x) instance Profunctor ValuesspecUnsafe where dimap _ g (Valuesspec q) = Valuesspec (rmap g q) instance ProductProfunctor ValuesspecUnsafe where purePP = pure (****) = (<*>) instance Functor (Valuesspec a) where fmap f (ValuesspecSafe g h) = ValuesspecSafe (fmap f g) (fmap f h) instance Applicative (Valuesspec a) where pure a = ValuesspecSafe (pure a) (pure a) ValuesspecSafe f f' <*> ValuesspecSafe x x' = ValuesspecSafe (f <*> x) (f' <*> x') instance Profunctor Valuesspec where dimap f g (ValuesspecSafe q q') = ValuesspecSafe (dimap f g q) (dimap f g q') instance ProductProfunctor Valuesspec where purePP = pure (****) = (<*>) instance Functor (Nullspec a) where fmap f (Nullspec g) = Nullspec (f g) instance Applicative (Nullspec a) where pure = Nullspec Nullspec f <*> Nullspec x = Nullspec (f x) instance Profunctor Nullspec where dimap _ g (Nullspec q) = Nullspec (g q) instance ProductProfunctor Nullspec where purePP = pure (****) = (<*>) instance Functor (NonEmptyRowspec a) where fmap = rmap instance Profunctor NonEmptyRowspec where dimap f g (NonEmptyRowspec a b) = NonEmptyRowspec (lmap f a) ((fmap . fmap) g b) instance Functor (Rowspec a) where fmap = rmap instance Applicative (Rowspec a) where pure x = EmptyRows x r1 <*> r2 = case (r1, r2) of (EmptyRows f, EmptyRows x) -> EmptyRows (f x) (EmptyRows f, NonEmptyRows (NonEmptyRowspec x1 x2)) -> NonEmptyRows (NonEmptyRowspec x1 ((fmap . fmap) f x2)) (NonEmptyRows (NonEmptyRowspec f1 f2), EmptyRows x) -> NonEmptyRows (NonEmptyRowspec f1 ((fmap . fmap) ($ x) f2)) (NonEmptyRows (NonEmptyRowspec f1 f2), NonEmptyRows (NonEmptyRowspec x1 x2)) -> NonEmptyRows (NonEmptyRowspec (f1 <> x1) ((liftA2 . liftF2) ($) f2 x2)) -19.16/semigroupoids-5.3.7/Data-Functor-Apply.html#v:liftF2 liftF2 :: Semigroup m => (a' -> b -> c) -> (m, a') -> (m, b) -> (m, c) liftF2 f (ys1, x1) (ys2, x2) = (ys1 <> ys2, f x1 x2) instance Profunctor Rowspec where dimap f g = \case EmptyRows x -> EmptyRows (g x) NonEmptyRows x -> NonEmptyRows (dimap f g x) instance ProductProfunctor Rowspec where purePP = pure (****) = (<*>) # DEPRECATED valuesU " Will be removed in 0.10 " # valuesU :: U.Unpackspec columns columns' -> ValuesspecUnsafe columns columns' -> [columns] -> ((), T.Tag) -> (columns', PQ.PrimQuery) valuesU unpack valuesspec rows ((), t) = (newColumns, primQ') where runRow row = valuesRow where (_, valuesRow) = PM.run (U.runUnpackspec unpack extractValuesEntry row) (newColumns, valuesPEs_nulls) = PM.run (runValuesspec valuesspec (extractValuesField t)) valuesPEs = map fst valuesPEs_nulls values :: [[HPQ.PrimExpr]] values = map runRow rows primQ' = case NEL.nonEmpty values of Nothing -> PQ.Empty () Just values' -> PQ.Values valuesPEs values' # DEPRECATED extractValuesEntry " Will be removed in 0.10 " # extractValuesEntry :: HPQ.PrimExpr -> PM.PM [HPQ.PrimExpr] HPQ.PrimExpr extractValuesEntry pe = do PM.write pe return pe # DEPRECATED extractValuesField " Will be removed in 0.10 " # extractValuesField :: T.Tag -> primExpr -> PM.PM [(HPQ.Symbol, primExpr)] HPQ.PrimExpr extractValuesField = PM.extractAttr "values" # DEPRECATED runValuesspec " Will be removed in 0.10 " # runValuesspec :: Applicative f => ValuesspecUnsafe columns columns' -> (() -> f HPQ.PrimExpr) -> f columns' runValuesspec (Valuesspec v) f = PM.traversePM v f () newtype ValuesspecUnsafe columns columns' = Valuesspec (PM.PackMap () HPQ.PrimExpr () columns') instance Default ValuesspecUnsafe (Field_ n a) (Field_ n a) where def = Valuesspec (PM.iso id Column) # DEPRECATED ValuesspecSafe " Use Valuesspec instead . Will be removed in version 0.10 . " # type ValuesspecSafe = Valuesspec
53f8a9721499e8d4a9c519d4a14cd7420779c1cead7ee6ed3d764873c758687c
axelarge/advent-of-code
day14.clj
(ns advent-of-code.y2017.day14 (:require [advent-of-code.support :refer :all] [advent-of-code.y2017.day10 :as day10])) (def test-input "flqrgnkx") (def input "ljoxqyyw") (defn knot-hash [input n] (day10/solve2 (str input "-" n))) (defn to-bit-string [^String hashed] (-> (.toString (BigInteger. hashed 16) 2) (left-pad 128 "0"))) (defn bitmap [input] (->> (range 128) (pmap (comp to-bit-string #(knot-hash input %))) vec)) (defn cardinality [m] (->> m (map (partial count-where #{\1})) (apply +))) (defn neighbors [m [x0 y0]] (for [[xd yd] [[-1 0] [1 0] [0 -1] [0 1]] :let [x (+ x0 xd) y (+ y0 yd)] :when (= \1 (get-in m [x y]))] [x y])) (defn connected [m from] (connected-nodes (partial neighbors m) from)) (defn connected-fast [m from] (connected-nodes-fast (partial neighbors m) from)) (defn groups [bmp] (group-count (for [x (range 128) y (range 128) :when (= \1 (get-in bmp [x y]))] [x y]) (partial connected bmp))) (def solve1 (comp cardinality bitmap)) (def solve2 (comp groups bitmap))
null
https://raw.githubusercontent.com/axelarge/advent-of-code/4c62a53ef71605780a22cf8219029453d8e1b977/src/advent_of_code/y2017/day14.clj
clojure
(ns advent-of-code.y2017.day14 (:require [advent-of-code.support :refer :all] [advent-of-code.y2017.day10 :as day10])) (def test-input "flqrgnkx") (def input "ljoxqyyw") (defn knot-hash [input n] (day10/solve2 (str input "-" n))) (defn to-bit-string [^String hashed] (-> (.toString (BigInteger. hashed 16) 2) (left-pad 128 "0"))) (defn bitmap [input] (->> (range 128) (pmap (comp to-bit-string #(knot-hash input %))) vec)) (defn cardinality [m] (->> m (map (partial count-where #{\1})) (apply +))) (defn neighbors [m [x0 y0]] (for [[xd yd] [[-1 0] [1 0] [0 -1] [0 1]] :let [x (+ x0 xd) y (+ y0 yd)] :when (= \1 (get-in m [x y]))] [x y])) (defn connected [m from] (connected-nodes (partial neighbors m) from)) (defn connected-fast [m from] (connected-nodes-fast (partial neighbors m) from)) (defn groups [bmp] (group-count (for [x (range 128) y (range 128) :when (= \1 (get-in bmp [x y]))] [x y]) (partial connected bmp))) (def solve1 (comp cardinality bitmap)) (def solve2 (comp groups bitmap))
4c8f90741c17555ab589daf4794be60d83f3a0144a8d2c92c91a264b94853b42
processone/xmpp
xmpp_config.erl
%%%------------------------------------------------------------------- @author < > %%% %%% Copyright ( C ) 2002 - 2023 ProcessOne , SARL . All Rights Reserved . %%% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. %%% %%%------------------------------------------------------------------- -module(xmpp_config). %% API -export([debug/1, fqdn/1]). %%%=================================================================== %%% API %%%=================================================================== -spec fqdn(any()) -> {ok, [binary()]}. fqdn(_) -> {ok, []}. -spec debug(any()) -> {ok, boolean()}. debug(_) -> {ok, false}. %%%=================================================================== Internal functions %%%===================================================================
null
https://raw.githubusercontent.com/processone/xmpp/3e0f4b07af708718cf891ca409c0819e60606cf9/src/xmpp_config.erl
erlang
------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- API =================================================================== API =================================================================== =================================================================== ===================================================================
@author < > Copyright ( C ) 2002 - 2023 ProcessOne , SARL . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(xmpp_config). -export([debug/1, fqdn/1]). -spec fqdn(any()) -> {ok, [binary()]}. fqdn(_) -> {ok, []}. -spec debug(any()) -> {ok, boolean()}. debug(_) -> {ok, false}. Internal functions