_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
9013578204a9ef032fe84697c73b60627053cde841ac12185cadee67852f61d2
let-def/grenier
physh.mli
* and sets using objects addresses and physical equality , and * behave well with OCaml GC . * * This is useful to observe sharing , traverse cyclic structures , ... * Highly experimental , this relies on a lot of GC internals ! * * Hashtables and sets using objects addresses and physical equality, and * behave well with OCaml GC. * * This is useful to observe sharing, traverse cyclic structures, ... * Highly experimental, this relies on a lot of GC internals! * *) module Set : sig type 'a t val create : unit -> 'a t val length : 'a t -> int val mem : 'a t -> 'a -> bool val add : 'a t -> 'a -> unit end module Map : sig type ('a,'b) t val create : unit -> ('a,'b) t val length : ('a,'b) t -> int val find : ('a,'b) t -> 'a -> 'b val add : ('a,'b) t -> 'a -> 'b -> unit end
null
https://raw.githubusercontent.com/let-def/grenier/3391e5e31db88e587100436e9407881fb8ef7873/physh/physh.mli
ocaml
* and sets using objects addresses and physical equality , and * behave well with OCaml GC . * * This is useful to observe sharing , traverse cyclic structures , ... * Highly experimental , this relies on a lot of GC internals ! * * Hashtables and sets using objects addresses and physical equality, and * behave well with OCaml GC. * * This is useful to observe sharing, traverse cyclic structures, ... * Highly experimental, this relies on a lot of GC internals! * *) module Set : sig type 'a t val create : unit -> 'a t val length : 'a t -> int val mem : 'a t -> 'a -> bool val add : 'a t -> 'a -> unit end module Map : sig type ('a,'b) t val create : unit -> ('a,'b) t val length : ('a,'b) t -> int val find : ('a,'b) t -> 'a -> 'b val add : ('a,'b) t -> 'a -> 'b -> unit end
a0108ae25e38ce1b4eb3bb8fa1407de98e0904f00105e4e1bf288119f54b96e6
dterei/SafeHaskellExamples
TypeClassSafe.hs
{-# LANGUAGE Safe #-} -- | Module defining a new typeclass that has a safe interface. Also define the Int and instances . module TypeClassSafe where -- | Safe interface but can still do an unsafe implementation. class SafeClass a where same :: a -> a instance SafeClass Int where same = id instance SafeClass Char where same = id
null
https://raw.githubusercontent.com/dterei/SafeHaskellExamples/0f7bbb53cf1cbb8419ce3a4aa4258b84be30ffcc/typeclasses/TypeClassSafe.hs
haskell
# LANGUAGE Safe # | Module defining a new typeclass that has a safe interface. Also define the | Safe interface but can still do an unsafe implementation.
Int and instances . module TypeClassSafe where class SafeClass a where same :: a -> a instance SafeClass Int where same = id instance SafeClass Char where same = id
689c7c9be82b05ec5a072dbb2872608985d3a2c9da308a9f718a2d36538646b5
nuprl/gradual-typing-performance
matrix.rkt
#lang racket/base (require htdp/matrix) (provide (all-from-out htdp/matrix))
null
https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/htdp-lib/teachpack/htdp/matrix.rkt
racket
#lang racket/base (require htdp/matrix) (provide (all-from-out htdp/matrix))
1ec70a1d9fc6cc2c8122363e6f90b09c207b1d39ebf3a7afbb29afb5bfc187e8
schell/aeson-tiled
ParseObjectSpec.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TypeApplications # module ParseObjectSpec where import Data.Aeson (encode, eitherDecode) import Test.Hspec import Data.Either (isRight) import Control.Monad (forM_) import qualified Data.ByteString.Lazy.Char8 as C8 import Data.Aeson.Tiled file :: FilePath file = "maps/objects/obj1.json" spec :: Spec spec = describe "Obj1" $ do it "should parse just fine" $ do eobj <- fmap (eitherDecode @Object) $ C8.readFile file eobj `shouldSatisfy` isRight
null
https://raw.githubusercontent.com/schell/aeson-tiled/e782189f222bae594cf8424d3d892e7217ab7c75/test/ParseObjectSpec.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeApplications # module ParseObjectSpec where import Data.Aeson (encode, eitherDecode) import Test.Hspec import Data.Either (isRight) import Control.Monad (forM_) import qualified Data.ByteString.Lazy.Char8 as C8 import Data.Aeson.Tiled file :: FilePath file = "maps/objects/obj1.json" spec :: Spec spec = describe "Obj1" $ do it "should parse just fine" $ do eobj <- fmap (eitherDecode @Object) $ C8.readFile file eobj `shouldSatisfy` isRight
41544340de07eaa9ea7f84d4e07821fbb9de3dfec147baa745734e6d1eef14c8
S8A/htdp-exercises
ex209.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-abbr-reader.ss" "lang")((modname ex209) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f))) ; A Word is ... ; A List-of-words is ... ; Word -> List-of-words ; finds all rearrangements of word (define (arrangements word) (list word)) ; List-of-strings -> Boolean (define (all-words-from-rat? w) (and (member? "rat" w) (member? "art" w) (member? "tar" w))) ; String -> List-of-strings ; finds all words that the letters of some given word spell (define (alternative-words s) (in-dictionary (words->strings (arrangements (string->word s))))) ;(check-member-of (alternative-words "cat") ; (list "act" "cat") (list "cat" "act")) ;(check-satisfied (alternative-words "rat") all-words-from-rat?) ; List-of-words -> List-of-strings ; turns all Words in low into Strings (define (words->strings low) '()) ; List-of-strings -> List-of-strings ; picks out all those Strings that occur in the dictionary (define (in-dictionary los) '()) ; String -> Word ; converts s to the chosen word representation (define (string->word s) (explode s)) (check-expect (string->word "") '()) (check-expect (string->word "cat") (list "c" "a" "t")) ; Word -> String ; converts w to a string (define (word->string w) (implode w)) (check-expect (word->string '()) "") (check-expect (word->string (list "c" "a" "t")) "cat")
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex209.rkt
racket
about the language level of this file in a form that our tools can easily process. A Word is ... A List-of-words is ... Word -> List-of-words finds all rearrangements of word List-of-strings -> Boolean String -> List-of-strings finds all words that the letters of some given word spell (check-member-of (alternative-words "cat") (list "act" "cat") (list "cat" "act")) (check-satisfied (alternative-words "rat") all-words-from-rat?) List-of-words -> List-of-strings turns all Words in low into Strings List-of-strings -> List-of-strings picks out all those Strings that occur in the dictionary String -> Word converts s to the chosen word representation Word -> String converts w to a string
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-abbr-reader.ss" "lang")((modname ex209) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp") (lib "itunes.rkt" "teachpack" "2htdp")) #f))) (define (arrangements word) (list word)) (define (all-words-from-rat? w) (and (member? "rat" w) (member? "art" w) (member? "tar" w))) (define (alternative-words s) (in-dictionary (words->strings (arrangements (string->word s))))) (define (words->strings low) '()) (define (in-dictionary los) '()) (define (string->word s) (explode s)) (check-expect (string->word "") '()) (check-expect (string->word "cat") (list "c" "a" "t")) (define (word->string w) (implode w)) (check-expect (word->string '()) "") (check-expect (word->string (list "c" "a" "t")) "cat")
2f65e1f98d1e8c851e1d7dcbb58f8e262746bf311adeb26c0d3e7310aca863ec
stuhlmueller/jschurch
tuplespace.scm
;;; ;;; tuplespace.scm ;;; (define-module tuplespace (use util.match) (use srfi-1) (use gauche.threads) (export tuplespace-unsafe-query? <tuplespace> tuplespace-init tuplespace-write tuplespace-read tuplespace-readp tuplespace-read-async tuplespace-take tuplespace-takep tuplespace-take-async tuplespace-dump tuplespace-clear) ) (select-module tuplespace) (define *debug* #t) ;; ;; class ;; (define-class <tuplespace> () ; () = no super class ((tuples :init-value '() :accessor tuples-of) (waiters :init-value '() :accessor waiters-of) (whitelist :init-value #f :accessor whitelist-of) (filter :init-value identity :accessor filter-of) (mutex :init-form (make-mutex) :accessor mutex-of) )) (define-class <waiter> () ; () = no super class ((query :init-keyword :query :accessor query-of) (notifier :init-keyword :notifier :accessor notifier-of) (type :init-keyword :type :accessor type-of) )) (define-method inspect-waiters ((ts <tuplespace>)) (map (lambda (waiter) (write-to-string (query-of waiter))) (waiters-of ts))) ;; ;; methods ;; ;utility (define (tuplespace-unsafe-query? query whitelist) (define (unsafe-question-item? x) (cond ((pair? x) (any unsafe-question-item? x)) ((symbol? x) (if (memq x whitelist) #f x)) (else #f))) (define (unsafe-pair? ls) (and (pair? ls) (eq? (car ls) '?) (any unsafe-question-item? (cdr ls)))) (define (unsafe-query? ls) (any unsafe-pair? ls)) (if whitelist (unsafe-query? query) #f)) (define (matches? ts value query) (cond ((eq? query '_) #t) ((tuplespace-unsafe-query? query (whitelist-of ts)) => (lambda (sym) (error #`"unsafe query: ,sym"))) (else (let1 matcher `(match ',value (,query #t) (_ #f)) (eval matcher (current-module)))))) (define-method tuplespace-add-waiter ((ts <tuplespace>) query type notifier) (with-locking-mutex (mutex-of ts) (lambda () (let1 waiter (make <waiter> :query query :type type :notifier notifier) (set! (waiters-of ts) (cons waiter (waiters-of ts))) (when *debug* (print "\nwaiter+ " (inspect-waiters ts))))))) ;init (define (tuplespace-init . args) (apply make <tuplespace> args)) ;write (define (notify-waiters value ts) (with-locking-mutex (mutex-of ts) (lambda () (set! (waiters-of ts) (let loop ((waiters (waiters-of ts))) (if (null? waiters) '() (let1 waiter (car waiters) (if (matches? ts value (query-of waiter)) (begin ((notifier-of waiter) value) (when *debug* (print "\nwaiter- " (inspect-waiters ts))) (if (eq? (type-of waiter) 'read) (loop (cdr waiters)) (cdr waiters))) (begin (cons waiter (loop (cdr waiters)))))))))))) (define-method tuplespace-write ((ts <tuplespace>) value) (let1 value ((filter-of ts) value) (when *debug* (print "write " value "; " (ref ts 'tuples))) (slot-set! ts 'tuples (cons value (ref ts 'tuples))) (notify-waiters value ts) value)) (define (find-tuple ts query) (find (cut matches? ts <> query) (ref ts 'tuples))) (define-method tuplespace-readp ((ts <tuplespace>) query) (find-tuple ts query)) ;read (define-method tuplespace-async ((ts <tuplespace>) query type notifier) (let1 found (find-tuple ts query) (if found (notifier found) (tuplespace-add-waiter ts query type notifier)))) (define-method tuplespace-read-async ((ts <tuplespace>) query notifier) (tuplespace-async ts query 'read notifier)) (define-method tuplespace-read ((ts <tuplespace>) query) (tuplespace-wait ts tuplespace-read-async query)) takep (define (remove-tuple! ts tuple) (slot-set! ts 'tuples (remove (cut eq? tuple <>) (ref ts 'tuples)))) (define-method tuplespace-takep ((ts <tuplespace>) query) (let1 found (find-tuple ts query) (when found (remove-tuple! ts found)) found)) ;take (define-method tuplespace-take-async ((ts <tuplespace>) query notifier) (tuplespace-async ts query 'take (lambda (result) (remove-tuple! ts result) (when *debug* (print "took " result "; " (ref ts 'tuples))) (notifier result)))) (define-method tuplespace-take ((ts <tuplespace>) query) (tuplespace-wait ts tuplespace-take-async query)) ;wait (define-method tuplespace-wait ((ts <tuplespace>) ts-method query) (let1 mutex (make-mutex "mutex for tuplespace-wait") (mutex-lock! mutex) (ts-method ts query (lambda (result) ;; will be called when a tuple is found (mutex-specific-set! mutex result) (mutex-unlock! mutex))) (mutex-lock! mutex) ;blocks until mutex is unlocked (mutex-specific mutex))) ;dump (define-method tuplespace-dump ((ts <tuplespace>)) (x->string (ref ts 'tuples))) ;clear (define-method tuplespace-clear ((ts <tuplespace>)) (set! (tuples-of ts) '())) (provide "tuplespace")
null
https://raw.githubusercontent.com/stuhlmueller/jschurch/58a94802ba987c92cb81e556341f86dba66a8fd1/external/biwascheme/tuplespace/tuplespace.scm
scheme
tuplespace.scm class () = no super class () = no super class methods utility init write read take wait will be called when a tuple is found blocks until mutex is unlocked dump clear
(define-module tuplespace (use util.match) (use srfi-1) (use gauche.threads) (export tuplespace-unsafe-query? <tuplespace> tuplespace-init tuplespace-write tuplespace-read tuplespace-readp tuplespace-read-async tuplespace-take tuplespace-takep tuplespace-take-async tuplespace-dump tuplespace-clear) ) (select-module tuplespace) (define *debug* #t) ((tuples :init-value '() :accessor tuples-of) (waiters :init-value '() :accessor waiters-of) (whitelist :init-value #f :accessor whitelist-of) (filter :init-value identity :accessor filter-of) (mutex :init-form (make-mutex) :accessor mutex-of) )) ((query :init-keyword :query :accessor query-of) (notifier :init-keyword :notifier :accessor notifier-of) (type :init-keyword :type :accessor type-of) )) (define-method inspect-waiters ((ts <tuplespace>)) (map (lambda (waiter) (write-to-string (query-of waiter))) (waiters-of ts))) (define (tuplespace-unsafe-query? query whitelist) (define (unsafe-question-item? x) (cond ((pair? x) (any unsafe-question-item? x)) ((symbol? x) (if (memq x whitelist) #f x)) (else #f))) (define (unsafe-pair? ls) (and (pair? ls) (eq? (car ls) '?) (any unsafe-question-item? (cdr ls)))) (define (unsafe-query? ls) (any unsafe-pair? ls)) (if whitelist (unsafe-query? query) #f)) (define (matches? ts value query) (cond ((eq? query '_) #t) ((tuplespace-unsafe-query? query (whitelist-of ts)) => (lambda (sym) (error #`"unsafe query: ,sym"))) (else (let1 matcher `(match ',value (,query #t) (_ #f)) (eval matcher (current-module)))))) (define-method tuplespace-add-waiter ((ts <tuplespace>) query type notifier) (with-locking-mutex (mutex-of ts) (lambda () (let1 waiter (make <waiter> :query query :type type :notifier notifier) (set! (waiters-of ts) (cons waiter (waiters-of ts))) (when *debug* (print "\nwaiter+ " (inspect-waiters ts))))))) (define (tuplespace-init . args) (apply make <tuplespace> args)) (define (notify-waiters value ts) (with-locking-mutex (mutex-of ts) (lambda () (set! (waiters-of ts) (let loop ((waiters (waiters-of ts))) (if (null? waiters) '() (let1 waiter (car waiters) (if (matches? ts value (query-of waiter)) (begin ((notifier-of waiter) value) (when *debug* (print "\nwaiter- " (inspect-waiters ts))) (if (eq? (type-of waiter) 'read) (loop (cdr waiters)) (cdr waiters))) (begin (cons waiter (loop (cdr waiters)))))))))))) (define-method tuplespace-write ((ts <tuplespace>) value) (let1 value ((filter-of ts) value) (when *debug* (print "write " value "; " (ref ts 'tuples))) (slot-set! ts 'tuples (cons value (ref ts 'tuples))) (notify-waiters value ts) value)) (define (find-tuple ts query) (find (cut matches? ts <> query) (ref ts 'tuples))) (define-method tuplespace-readp ((ts <tuplespace>) query) (find-tuple ts query)) (define-method tuplespace-async ((ts <tuplespace>) query type notifier) (let1 found (find-tuple ts query) (if found (notifier found) (tuplespace-add-waiter ts query type notifier)))) (define-method tuplespace-read-async ((ts <tuplespace>) query notifier) (tuplespace-async ts query 'read notifier)) (define-method tuplespace-read ((ts <tuplespace>) query) (tuplespace-wait ts tuplespace-read-async query)) takep (define (remove-tuple! ts tuple) (slot-set! ts 'tuples (remove (cut eq? tuple <>) (ref ts 'tuples)))) (define-method tuplespace-takep ((ts <tuplespace>) query) (let1 found (find-tuple ts query) (when found (remove-tuple! ts found)) found)) (define-method tuplespace-take-async ((ts <tuplespace>) query notifier) (tuplespace-async ts query 'take (lambda (result) (remove-tuple! ts result) (when *debug* (print "took " result "; " (ref ts 'tuples))) (notifier result)))) (define-method tuplespace-take ((ts <tuplespace>) query) (tuplespace-wait ts tuplespace-take-async query)) (define-method tuplespace-wait ((ts <tuplespace>) ts-method query) (let1 mutex (make-mutex "mutex for tuplespace-wait") (mutex-lock! mutex) (ts-method ts query (mutex-specific-set! mutex result) (mutex-unlock! mutex))) (mutex-specific mutex))) (define-method tuplespace-dump ((ts <tuplespace>)) (x->string (ref ts 'tuples))) (define-method tuplespace-clear ((ts <tuplespace>)) (set! (tuples-of ts) '())) (provide "tuplespace")
1ac4708d78b58c7556de595f7c1fedb8c975bd0ce94f53fea28adaddd3095504
alan-j-hu/ocaml-textmate-language
tmLanguage.mli
type t * The collection of TextMate grammars . type grammar (** A TextMate grammar. *) exception Error of string [@ocaml.warn_on_literal_pattern] (** The error message is purely informational and is not to be matched on. *) type plist = [ `Bool of bool | `Data of string | `Date of float * float option | `Float of float | `Int of int | `String of string | `Array of plist list | `Dict of (string * plist) list ] * A plist document . This is the same type as [ t ] defined in the { { : -xml/ } [ plist - xml ] } package ( as of version 0.3.0 ) , but is reproduced here as not to depend on [ plist - xml ] . {{:-xml/} [plist-xml]} package (as of version 0.3.0), but is reproduced here as not to depend on [plist-xml]. *) type ezjsonm = [ `Null | `Bool of bool | `Float of float | `String of string | `A of ezjsonm list | `O of (string * ezjsonm) list ] (** A JSON document. This is the same type as [value] defined in the {{:/} [ezjsonm]} package (as of version 1.2.0), but is reproduced here as not to depend on [ezjsonm]. *) type yojson = [ `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * yojson) list | `List of yojson list ] * A JSON document . This is the same type as [ Basic.t ] defined in the { { : / } [ yojson ] } package ( as of version 1.7.0 ) , but is reproduced here as not to depend on [ yojson ] . {{:/} [yojson]} package (as of version 1.7.0), but is reproduced here as not to depend on [yojson]. *) val create : unit -> t (** Creates an empty collection of grammars. *) val add_grammar : t -> grammar -> unit (** Adds a grammar to the collection. *) val find_by_name : t -> string -> grammar option (** Finds a grammar by its [name] attribute. Case-insensitive. *) val find_by_scope_name : t -> string -> grammar option (** Finds a grammar by its [scopeName] attribute. Case-sensitive. *) val find_by_filetype : t -> string -> grammar option * Finds a grammar by matching one of the strings in its [ fileTypes ] attribute . Case - sensitive . attribute. Case-sensitive. *) val of_plist_exn : plist -> grammar * Reads a TextMate grammar from a PLIST file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) val of_ezjsonm_exn : ezjsonm -> grammar * Reads a TextMate grammar from a JSON file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) val of_yojson_exn : yojson -> grammar * Reads a TextMate grammar from a JSON file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) type stack (** The state of the tokenizer. *) val empty : stack (** The initial state of the tokenizer. *) type token (** A token of code. *) val ending : token -> int * One past the index of the last character of the token . If [ tok ] is the first token of the line , [ tok ] spans the substring within interval \[[0 ] , [ ending tok ] ) . If [ tok ] succeeds a token [ prev ] , [ tok ] spans the substring within interval \[[ending prev ] , [ ending tok ] ) . If [tok] is the first token of the line, [tok] spans the substring within interval \[[0], [ending tok]). If [tok] succeeds a token [prev], [tok] spans the substring within interval \[[ending prev], [ending tok]). *) val scopes : token -> string list * The token 's stack of TextMate grammar scopes . val tokenize_exn : t -> grammar -> stack -> string -> token list * stack * Usage : [ let tokens , stack = tokenize_exn t grammar stack line ] Tokenizes a line of code . Returns the list of tokens [ tokens ] and the updated tokenization state [ stack ] . Precondition : - [ line ] must be a single line , including the newline character at the end . Postconditions : - [ tokens ] is nonempty . - The ending positions of [ tokens ] are strictly increasing . - The [ ending ] of the last token in [ tokens ] is always [ String.length line ] . Raises { ! exception : Error } if it tries to match a malformed [ end ] or [ while ] regex . Raises { ! exception : Error } if it tries to access a local repository that does n't exist in the file . Currently , it silently ignores [ include]s of other grammars that do n't exist in [ t ] . Tokenizes a line of code. Returns the list of tokens [tokens] and the updated tokenization state [stack]. Precondition: - [line] must be a single line, including the newline character at the end. Postconditions: - [tokens] is nonempty. - The ending positions of [tokens] are strictly increasing. - The [ending] of the last token in [tokens] is always [String.length line]. Raises {!exception:Error} if it tries to match a malformed [end] or [while] regex. Raises {!exception:Error} if it tries to access a local repository that doesn't exist in the file. Currently, it silently ignores [include]s of other grammars that don't exist in [t]. *)
null
https://raw.githubusercontent.com/alan-j-hu/ocaml-textmate-language/4a75f7b8f41ab9d5f38598987f35a2991e0c3452/src/tmLanguage.mli
ocaml
* A TextMate grammar. * The error message is purely informational and is not to be matched on. * A JSON document. This is the same type as [value] defined in the {{:/} [ezjsonm]} package (as of version 1.2.0), but is reproduced here as not to depend on [ezjsonm]. * Creates an empty collection of grammars. * Adds a grammar to the collection. * Finds a grammar by its [name] attribute. Case-insensitive. * Finds a grammar by its [scopeName] attribute. Case-sensitive. * The state of the tokenizer. * The initial state of the tokenizer. * A token of code.
type t * The collection of TextMate grammars . type grammar exception Error of string [@ocaml.warn_on_literal_pattern] type plist = [ `Bool of bool | `Data of string | `Date of float * float option | `Float of float | `Int of int | `String of string | `Array of plist list | `Dict of (string * plist) list ] * A plist document . This is the same type as [ t ] defined in the { { : -xml/ } [ plist - xml ] } package ( as of version 0.3.0 ) , but is reproduced here as not to depend on [ plist - xml ] . {{:-xml/} [plist-xml]} package (as of version 0.3.0), but is reproduced here as not to depend on [plist-xml]. *) type ezjsonm = [ `Null | `Bool of bool | `Float of float | `String of string | `A of ezjsonm list | `O of (string * ezjsonm) list ] type yojson = [ `Null | `Bool of bool | `Int of int | `Float of float | `String of string | `Assoc of (string * yojson) list | `List of yojson list ] * A JSON document . This is the same type as [ Basic.t ] defined in the { { : / } [ yojson ] } package ( as of version 1.7.0 ) , but is reproduced here as not to depend on [ yojson ] . {{:/} [yojson]} package (as of version 1.7.0), but is reproduced here as not to depend on [yojson]. *) val create : unit -> t val add_grammar : t -> grammar -> unit val find_by_name : t -> string -> grammar option val find_by_scope_name : t -> string -> grammar option val find_by_filetype : t -> string -> grammar option * Finds a grammar by matching one of the strings in its [ fileTypes ] attribute . Case - sensitive . attribute. Case-sensitive. *) val of_plist_exn : plist -> grammar * Reads a TextMate grammar from a PLIST file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) val of_ezjsonm_exn : ezjsonm -> grammar * Reads a TextMate grammar from a JSON file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) val of_yojson_exn : yojson -> grammar * Reads a TextMate grammar from a JSON file . Raises { ! exception : Error } if the plist does not represent a valid TextMate grammar . the plist does not represent a valid TextMate grammar. *) type stack val empty : stack type token val ending : token -> int * One past the index of the last character of the token . If [ tok ] is the first token of the line , [ tok ] spans the substring within interval \[[0 ] , [ ending tok ] ) . If [ tok ] succeeds a token [ prev ] , [ tok ] spans the substring within interval \[[ending prev ] , [ ending tok ] ) . If [tok] is the first token of the line, [tok] spans the substring within interval \[[0], [ending tok]). If [tok] succeeds a token [prev], [tok] spans the substring within interval \[[ending prev], [ending tok]). *) val scopes : token -> string list * The token 's stack of TextMate grammar scopes . val tokenize_exn : t -> grammar -> stack -> string -> token list * stack * Usage : [ let tokens , stack = tokenize_exn t grammar stack line ] Tokenizes a line of code . Returns the list of tokens [ tokens ] and the updated tokenization state [ stack ] . Precondition : - [ line ] must be a single line , including the newline character at the end . Postconditions : - [ tokens ] is nonempty . - The ending positions of [ tokens ] are strictly increasing . - The [ ending ] of the last token in [ tokens ] is always [ String.length line ] . Raises { ! exception : Error } if it tries to match a malformed [ end ] or [ while ] regex . Raises { ! exception : Error } if it tries to access a local repository that does n't exist in the file . Currently , it silently ignores [ include]s of other grammars that do n't exist in [ t ] . Tokenizes a line of code. Returns the list of tokens [tokens] and the updated tokenization state [stack]. Precondition: - [line] must be a single line, including the newline character at the end. Postconditions: - [tokens] is nonempty. - The ending positions of [tokens] are strictly increasing. - The [ending] of the last token in [tokens] is always [String.length line]. Raises {!exception:Error} if it tries to match a malformed [end] or [while] regex. Raises {!exception:Error} if it tries to access a local repository that doesn't exist in the file. Currently, it silently ignores [include]s of other grammars that don't exist in [t]. *)
cf52808c781fdca7deef658e7ef097bdd28d9c9e54c1ac93c56d29b7f6562853
tonymorris/geo-gpx
MinlatL.hs
module Data.Geo.GPX.Lens.MinlatL where import Data.Geo.GPX.Type.Latitude import Data.Lens.Common class MinlatL a where minlatL :: Lens a Latitude
null
https://raw.githubusercontent.com/tonymorris/geo-gpx/526b59ec403293c810c2ba08d2c006dc526e8bf9/src/Data/Geo/GPX/Lens/MinlatL.hs
haskell
module Data.Geo.GPX.Lens.MinlatL where import Data.Geo.GPX.Type.Latitude import Data.Lens.Common class MinlatL a where minlatL :: Lens a Latitude
3e7b6eed7281eb9399a8a0de9492a29dca8e7889a3eff6838b3656f7205dd28c
andyhd/asteroids
asteroids.lisp
;;;; ASTeroids ; vim: ts=2 sts=2 sw=2 et ai (ql:quickload "lispbuilder-sdl") (ql:quickload "lispbuilder-sdl-gfx") (defpackage :asteroids (:use :cl :sdl) (:export main)) (in-package :asteroids) (defparameter *map-width* 640) (defparameter *map-height* 480) (defparameter *window* nil) (defparameter *window-width* 640) (defparameter *deceleration* 0.99) (defparameter *ticks* 0) (defparameter *powerup-max-age* 9) (defparameter *explosion-max-radius* 0.5) (defun vector-sum (a b) (mapcar #'+ a b)) (defun vector-scale (v factor) (mapcar #'* v (list factor factor))) (defun vector-subtract (a b) (mapcar #'- a b)) ;;; distance between point a and point b parameters must be lists of 2 numbers ( x y ) (defun my-distance (a b) (sqrt (apply #'+ (mapcar (lambda (x) (expt x 2)) (vector-subtract a b))))) (defun square-from-midpoint (point radius) (rectangle-from-midpoint-* (x point) (y point) (* radius 2) (* radius 2))) (defun deg->rad (degs) (* degs (/ pi 180))) (defun rad->deg (rads) (* rads (/ 180 pi))) (defun radial-point-from (p radius angle) (point :x (+ (* radius (sin (deg->rad angle))) (x p)) :y (+ (* radius (cos (deg->rad angle))) (y p)))) (defun get-ticks () (let ((ticks (shiftf *ticks* (sdl-get-ticks)))) (* (- *ticks* ticks) 0.001))) ;;; represents an object on the game map (defclass mob () ((pos :initarg :pos :initform '(0.5 0.5) :accessor pos) (radius :initarg :radius :accessor radius) (velocity :initarg :velocity :initform '(0 0) :accessor velocity))) (defclass asteroid (mob) ((size :initarg :size :initform 'big :reader size) (radii :initform nil :accessor radii) (rotation :initform (* (- (random 1.0) 0.5) 5) :reader rotation) (facing :initform 0 :accessor facing) (pos :initform `(,(random 1.0) ,(random 1.0))))) (defclass bullet (mob) ((radius :initform 0.005) (ship :initarg :ship :accessor ship))) (defclass explosion (mob) ((radius :initform 0))) (defclass powerup (mob) ((radius :initform 0.03) (age :initform 0 :accessor age))) (defclass bullet-powerup (powerup) ()) (defclass freeze-powerup (powerup) ()) (defclass shield-powerup (powerup) ()) (defclass ship (mob) ((timers :initform (make-hash-table) :accessor timers) (acceleration :initform '(0 0) :accessor acceleration) (facing :initform 0 :accessor facing) (radius :initform 0.04))) (defclass timer () ((remaining :initarg :seconds :initform 0 :accessor remaining))) (defclass world () ((mobs :initform nil :accessor mobs) (ship :initform nil :accessor ship) (bullet :initform nil :accessor bullet) (timers :initform (make-hash-table) :accessor timers) (level :initform 0 :accessor level) (num-asteroids :initform 0 :accessor num-asteroids) (score :initform 0 :accessor score) (max-level :initform 0 :accessor max-level) (high-score :initform 0 :accessor high-score) (lives :initform 0 :accessor lives))) (defmethod collide ((mob mob) (other mob) (world world)) t) (defmethod map-coords ((mob mob)) (destructuring-bind (x y) (pos mob) (point :x (round (* x *map-width*)) :y (round (* y *map-height*))))) (defun relative-coords (x y) (list (/ x *map-width*) (/ y *map-height*))) (defmethod map-radius ((mob mob)) (round (* (radius mob) *map-width*))) (defmethod update ((mob mob) time-delta (world world)) (setf (pos mob) (mapcar (lambda (x) (mod x 1)) (vector-sum (pos mob) (vector-scale (velocity mob) time-delta))))) (defmethod intersects-p ((mob mob) (other mob)) (< (my-distance (pos mob) (pos other)) (+ (radius mob) (radius other)))) (defmethod render ((mob mob)) (values)) (defmethod initialize-instance :after ((asteroid asteroid) &key) (let ((radius (cdr (assoc (size asteroid) '((big . 0.1) (medium . 0.075) (small . 0.05))))) (spd (cdr (assoc (size asteroid) '((big . 0.1) (medium . 0.15) (small . 0.25)))))) (setf (radius asteroid) radius) (setf (radii asteroid) (loop for i from 0 below 20 collect (round (* (+ 0.9 (random 0.2)) (map-radius asteroid))))) (setf (velocity asteroid) `(,(- (random (* 2 spd)) spd) ,(- (random (* 2 spd)) spd))))) (defun random-powerup (&key pos) (make-instance (case (random 3) (0 'bullet-powerup) (1 'freeze-powerup) (2 'shield-powerup)) :pos pos)) (defmethod break-down ((asteroid asteroid) (world world)) (with-slots ((pos pos) (size size)) asteroid (if (eq size 'small) ;; gradually reduce the probability of powerups appearing (if (< (random 100) (/ 100 (+ 4 (* (level world) 0.3)))) `(,(random-powerup :pos pos)) nil) (let ((smaller (cond ((eq size 'big) 'medium) ((eq size 'medium) 'small)))) `(,(make-instance 'asteroid :pos pos :size smaller) ,(make-instance 'asteroid :pos pos :size smaller)))))) (defmethod done ((timer timer)) (<= (ceiling (remaining timer)) 0)) (defmethod frozen-p ((world world)) (let ((timer (gethash 'freeze (timers world) nil))) (and timer (not (done timer))))) (defmethod update ((asteroid asteroid) time-delta (world world)) (declare (ignore time-delta)) (when (not (frozen-p world)) (incf (facing asteroid) (rotation asteroid)) (call-next-method))) (defmethod render ((asteroid asteroid)) (draw-polygon (loop for i from 0 for r in (radii asteroid) collect (radial-point-from (map-coords asteroid) r (+ (facing asteroid) (* i 18)))) :color *white*)) (defmethod remove-from-world ((world world) (mob mob)) (setf (mobs world) (remove mob (mobs world)))) (defmethod remove-from-world :after ((world world) (asteroid asteroid)) (decf (num-asteroids world))) (defmethod remove-from-world :after ((world world) (ship ship)) (setf (ship world) nil)) (defmethod update ((powerup powerup) time-delta (world world)) (when (> (ceiling (incf (age powerup) time-delta)) *powerup-max-age*) (remove-from-world world powerup))) (defmethod add-score ((world world) (score number)) (setf (high-score world) (max (incf (score world) score) (high-score world)))) (defmethod add-score ((world world) (powerup powerup)) (add-score world (* (level world) 10))) (defmethod add-score ((world world) (asteroid asteroid)) (add-score world (cdr (assoc (size asteroid) '((big . 1) (medium . 2) (small . 5)))))) (defmethod collide :before ((ship ship) (powerup powerup) (world world)) (remove-from-world world powerup) (add-score world powerup)) (defmethod powerup-active-p ((ship ship) powerup) (let ((timer (gethash powerup (timers ship) nil))) (and timer (not (done timer))))) (defmethod add-seconds ((timer timer) seconds) (incf (remaining timer) seconds)) (defmethod add-shield ((ship ship) &key (seconds 0)) (if (powerup-active-p ship 'shield) (add-seconds (gethash 'shield (timers ship)) seconds) (setf (gethash 'shield (timers ship)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup shield-powerup) (world world)) (add-shield ship :seconds 6)) (defmethod render ((powerup shield-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *green*) (draw-polygon `(,(radial-point-from coords (round (* radius 0.8)) 40) ,(radial-point-from coords (round (* radius 0.8)) 0) ,(radial-point-from coords (round (* radius 0.8)) -40) ,(radial-point-from coords (round (* radius 0.8)) -135) ,(radial-point-from coords (round (* radius 0.8)) 135)) :color *white*))) (defmethod add-super-bullets ((ship ship) &key (seconds 0)) (if (powerup-active-p ship 'super-bullets) (add-seconds (gethash 'super-bullets (timers ship)) seconds) (setf (gethash 'super-bullets (timers ship)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup bullet-powerup) (world world)) (add-super-bullets ship :seconds 6)) (defmethod render ((powerup bullet-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *magenta*) (draw-circle coords (round (* radius 0.3)) :color *white*))) (defmethod add-freeze ((world world) &key (seconds 0)) (if (frozen-p world) (add-seconds (gethash 'freeze (timers world)) seconds) (setf (gethash 'freeze (timers world)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup freeze-powerup) (world world)) (add-freeze world :seconds 6)) (defmethod render ((powerup freeze-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *cyan*) (draw-polygon (loop for i from 0 to 11 collect (radial-point-from coords (round (* radius (if (= (mod i 2) 0) 0.7 0.2))) (* i 30))) :color *white*))) (defmethod add-to-world ((world world) (mob mob)) (setf (mobs world) (cons mob (mobs world))) (values mob)) (defmethod collide :before ((ship ship) (asteroid asteroid) (world world)) (unless (powerup-active-p ship 'shield) (remove-from-world world ship) (add-to-world world (make-instance 'explosion :pos (pos ship))) (decf (lives world)))) (defmethod in-world-p ((world world) (mob mob)) (find mob (mobs world))) (defmethod ship-moved ((world world) (ship ship)) (dolist (mob (mobs world)) (when (and (not (eq ship mob)) (intersects-p ship mob)) (collide ship mob world)) ;; if a collision destroyed the ship, stop checking for collisions (when (not (in-world-p world ship)) (return ship)))) (defmethod update-timer ((timer timer) time-delta) (unless (done timer) (decf (remaining timer) time-delta))) (defmethod update :around ((ship ship) time-delta (world world)) (setf (velocity ship) (vector-scale (vector-sum (velocity ship) (acceleration ship)) *deceleration*)) (maphash (lambda (name timer) (declare (ignore name)) (update-timer timer time-delta)) (timers ship)) (call-next-method) (ship-moved world ship)) (defmethod thrust-at ((ship ship) coords) (setf (acceleration ship) (vector-sum (acceleration ship) (vector-scale (vector-subtract coords (pos ship)) 0.03)))) (defmethod stop-thrust ((ship ship)) (setf (acceleration ship) '(0 0))) (defmethod shoot-at ((ship ship) coords (world world)) (let ((bullet (make-instance 'bullet :pos (pos ship) :ship ship))) (setf (velocity bullet) (vector-scale (vector-subtract coords (pos bullet)) 3)) (add-to-world world bullet))) (defmethod render ((ship ship)) (let* ((coords (map-coords ship)) (radius (map-radius ship)) (facing (facing ship)) (nose (radial-point-from coords radius facing)) (left (radial-point-from coords radius (- facing 130))) (right (radial-point-from coords radius (+ facing 130))) (tail (radial-point-from coords (round (* radius 0.5)) (+ facing 180)))) (draw-polygon (list nose left tail right) :color *white*) (when (powerup-active-p ship 'shield) (draw-circle coords (round (+ radius (random 3))) :color *green*)))) (defmethod super-p ((bullet bullet)) (powerup-active-p (ship bullet) 'super-bullets)) (defmethod collide :before ((bullet bullet) (asteroid asteroid) (world world)) (remove-from-world world asteroid) (when (not (super-p bullet)) (remove-from-world world bullet)) (mapcar (lambda (mob) (add-to-world world mob)) (break-down asteroid world)) (add-to-world world (make-instance 'explosion :pos (pos asteroid))) (add-score world asteroid)) (defmethod render ((bullet bullet)) (let ((coords (map-coords bullet)) (radius (map-radius bullet))) (draw-circle coords radius :color *red*) (when (super-p bullet) (draw-circle coords (+ (random 3)) :color *magenta*)))) (defmethod bullet-moved ((world world) (bullet bullet)) (dolist (mob (mobs world)) (when (and (not (eq bullet mob)) (intersects-p bullet mob)) (collide bullet mob world)) (when (not (in-world-p world bullet)) (return bullet)))) (defmethod update ((bullet bullet) time-delta (world world)) (setf (pos bullet) (vector-sum (pos bullet) (vector-scale (velocity bullet) time-delta))) (destructuring-bind (x y) (pos bullet) (when (or (not (< 0 x *map-width*)) (not (< 0 y *map-height*))) (remove-from-world world bullet))) (bullet-moved world bullet)) (defmethod render ((explosion explosion)) (let ((coords (map-coords explosion)) (radius (map-radius explosion))) (draw-circle coords radius :color *red*) (draw-circle coords (+ radius (random 3)) :color *red*))) (defmethod update ((explosion explosion) time-delta (world world)) (when (> (incf (radius explosion) time-delta) *explosion-max-radius*) (remove-from-world world explosion))) (defmethod start-next-level ((world world)) (with-accessors ((level level) (max-level max-level) (mobs mobs) (timers timers) (ship ship)) world (incf level) (setf max-level (max max-level level)) (setf mobs nil) (setf timers (make-hash-table)) (dotimes (i level) (add-to-world world (make-instance 'asteroid))) (add-to-world world (or ship (make-instance 'ship))) (add-shield (ship world) :seconds 6))) (defmethod level-cleared-p ((world world)) (< (num-asteroids world) 1)) (defmethod after ((world world) timer-name &key (seconds 0) do) (multiple-value-bind (timer exists) (gethash timer-name (timers world)) (if exists (when (done timer) (remhash timer-name (timers world)) (when (functionp do) (funcall do))) (setf (gethash timer-name (timers world)) (make-instance 'timer :seconds seconds))))) (defmethod update-world ((world world) time-delta) (maphash (lambda (name timer) (declare (ignore name)) (update-timer timer time-delta)) (timers world)) (dolist (mob (mobs world)) (update mob time-delta world)) start next level 3 seconds after clearing (when (level-cleared-p world) (after world 'cleared :seconds 3 :do (lambda () (incf (lives world)) (start-next-level world)))) restart level 3 seconds after death - game over if no more lives (unless (ship world) (after world 'death :seconds 3 :do (lambda () (if (< (lives world) 1) (setf (level world) 0) ; game over (let ((ship (make-instance 'ship))) (add-to-world world ship) (add-shield ship :seconds 6))))))) (defmethod add-to-world :after ((world world) (asteroid asteroid)) (incf (num-asteroids world))) (defmethod add-to-world :after ((world world) (ship ship)) (setf (ship world) ship)) (defmethod render-world ((world world) paused) (clear-display *black*) hud (sdl-gfx:draw-string-solid-* (format nil "Level ~d" (level world)) 10 10 :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Lives ~d" (lives world)) 10 (- *map-height* 28) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Score ~d" (score world)) (- *map-width* 127) (- *map-height* 28) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "~a [Q]uit" (if (= (level world) 0) "[P]lay" "[P]ause")) (- *map-width* 127) 10 :color *green*) (if (= (level world) 0) ;; title screen (progn (sdl-gfx:draw-string-solid-* "ASTeroids" (round (* 1/2 (- *map-width* 81))) (round (* 1/4 (- *map-height* 18))) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "High score: ~d" (high-score world)) (round (* 1/2 (- *map-width* 171))) (round (* 1/2 (- *map-height* 18))) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Max level: ~d" (max-level world)) (round (* 1/2 (- *map-width* 135))) (round (* 3/4 (- *map-height* 18))) :color *green*)) (progn ;; game world (set-clip-rect (rectangle :x 0 :y 0 :w *map-width* :h *map-height*) :surface *default-display*) (dolist (mob (mobs world)) (render mob)) (set-clip-rect nil :surface *default-display*) ;; pause text (when paused (sdl-gfx:draw-string-solid-* "PAUSED" (round (* 1/2 (- *map-width* 54))) (round (* 1/2 (- *map-height* 18))) :color *green*))))) (defun calc-angle (a b) (destructuring-bind (x y) (vector-subtract b a) (rad->deg (atan x y)))) (defun main () (with-init () (setf *window* (window 640 480 :title-caption "ASTeroids" :icon-caption "ASTeroids")) (sdl-gfx:initialise-default-font sdl-gfx:*font-9x18*) (setf (frame-rate) 60) (clear-display *black*) (let ((world (make-instance 'world)) (paused nil)) (with-events () (:quit-event () t) (:mouse-motion-event (:x x :y y) (when (ship world) (setf (facing (ship world)) (calc-angle (pos (ship world)) (relative-coords x y))))) (:mouse-button-down-event (:x x :y y) (when (and (> (level world) 0) (ship world) (not paused)) (shoot-at (ship world) (relative-coords x y) world) (thrust-at (ship world) (relative-coords x y)))) (:mouse-button-up-event () (when (and (> (level world) 0) (ship world)) (stop-thrust (ship world)))) (:key-up-event (:key key) (case key (:sdl-key-escape (push-quit-event)) (:sdl-key-q (setf (level world) 0)) (:sdl-key-p (if (= (level world) 0) (progn (setf (score world) 0) (setf (lives world) 1) (setf *ticks* (sdl-get-ticks)) (start-next-level world)) (setf paused (not paused)))))) (:idle () (when (and (> (level world) 0) (not paused)) (update-world world (get-ticks))) (render-world world paused) (update-display))))))
null
https://raw.githubusercontent.com/andyhd/asteroids/1584646a21cdecfdcef38903d7cef6239ea5522a/asteroids.lisp
lisp
ASTeroids vim: ts=2 sts=2 sw=2 et ai distance between point a and point b represents an object on the game map gradually reduce the probability of powerups appearing if a collision destroyed the ship, stop checking for collisions game over title screen game world pause text
(ql:quickload "lispbuilder-sdl") (ql:quickload "lispbuilder-sdl-gfx") (defpackage :asteroids (:use :cl :sdl) (:export main)) (in-package :asteroids) (defparameter *map-width* 640) (defparameter *map-height* 480) (defparameter *window* nil) (defparameter *window-width* 640) (defparameter *deceleration* 0.99) (defparameter *ticks* 0) (defparameter *powerup-max-age* 9) (defparameter *explosion-max-radius* 0.5) (defun vector-sum (a b) (mapcar #'+ a b)) (defun vector-scale (v factor) (mapcar #'* v (list factor factor))) (defun vector-subtract (a b) (mapcar #'- a b)) parameters must be lists of 2 numbers ( x y ) (defun my-distance (a b) (sqrt (apply #'+ (mapcar (lambda (x) (expt x 2)) (vector-subtract a b))))) (defun square-from-midpoint (point radius) (rectangle-from-midpoint-* (x point) (y point) (* radius 2) (* radius 2))) (defun deg->rad (degs) (* degs (/ pi 180))) (defun rad->deg (rads) (* rads (/ 180 pi))) (defun radial-point-from (p radius angle) (point :x (+ (* radius (sin (deg->rad angle))) (x p)) :y (+ (* radius (cos (deg->rad angle))) (y p)))) (defun get-ticks () (let ((ticks (shiftf *ticks* (sdl-get-ticks)))) (* (- *ticks* ticks) 0.001))) (defclass mob () ((pos :initarg :pos :initform '(0.5 0.5) :accessor pos) (radius :initarg :radius :accessor radius) (velocity :initarg :velocity :initform '(0 0) :accessor velocity))) (defclass asteroid (mob) ((size :initarg :size :initform 'big :reader size) (radii :initform nil :accessor radii) (rotation :initform (* (- (random 1.0) 0.5) 5) :reader rotation) (facing :initform 0 :accessor facing) (pos :initform `(,(random 1.0) ,(random 1.0))))) (defclass bullet (mob) ((radius :initform 0.005) (ship :initarg :ship :accessor ship))) (defclass explosion (mob) ((radius :initform 0))) (defclass powerup (mob) ((radius :initform 0.03) (age :initform 0 :accessor age))) (defclass bullet-powerup (powerup) ()) (defclass freeze-powerup (powerup) ()) (defclass shield-powerup (powerup) ()) (defclass ship (mob) ((timers :initform (make-hash-table) :accessor timers) (acceleration :initform '(0 0) :accessor acceleration) (facing :initform 0 :accessor facing) (radius :initform 0.04))) (defclass timer () ((remaining :initarg :seconds :initform 0 :accessor remaining))) (defclass world () ((mobs :initform nil :accessor mobs) (ship :initform nil :accessor ship) (bullet :initform nil :accessor bullet) (timers :initform (make-hash-table) :accessor timers) (level :initform 0 :accessor level) (num-asteroids :initform 0 :accessor num-asteroids) (score :initform 0 :accessor score) (max-level :initform 0 :accessor max-level) (high-score :initform 0 :accessor high-score) (lives :initform 0 :accessor lives))) (defmethod collide ((mob mob) (other mob) (world world)) t) (defmethod map-coords ((mob mob)) (destructuring-bind (x y) (pos mob) (point :x (round (* x *map-width*)) :y (round (* y *map-height*))))) (defun relative-coords (x y) (list (/ x *map-width*) (/ y *map-height*))) (defmethod map-radius ((mob mob)) (round (* (radius mob) *map-width*))) (defmethod update ((mob mob) time-delta (world world)) (setf (pos mob) (mapcar (lambda (x) (mod x 1)) (vector-sum (pos mob) (vector-scale (velocity mob) time-delta))))) (defmethod intersects-p ((mob mob) (other mob)) (< (my-distance (pos mob) (pos other)) (+ (radius mob) (radius other)))) (defmethod render ((mob mob)) (values)) (defmethod initialize-instance :after ((asteroid asteroid) &key) (let ((radius (cdr (assoc (size asteroid) '((big . 0.1) (medium . 0.075) (small . 0.05))))) (spd (cdr (assoc (size asteroid) '((big . 0.1) (medium . 0.15) (small . 0.25)))))) (setf (radius asteroid) radius) (setf (radii asteroid) (loop for i from 0 below 20 collect (round (* (+ 0.9 (random 0.2)) (map-radius asteroid))))) (setf (velocity asteroid) `(,(- (random (* 2 spd)) spd) ,(- (random (* 2 spd)) spd))))) (defun random-powerup (&key pos) (make-instance (case (random 3) (0 'bullet-powerup) (1 'freeze-powerup) (2 'shield-powerup)) :pos pos)) (defmethod break-down ((asteroid asteroid) (world world)) (with-slots ((pos pos) (size size)) asteroid (if (eq size 'small) (if (< (random 100) (/ 100 (+ 4 (* (level world) 0.3)))) `(,(random-powerup :pos pos)) nil) (let ((smaller (cond ((eq size 'big) 'medium) ((eq size 'medium) 'small)))) `(,(make-instance 'asteroid :pos pos :size smaller) ,(make-instance 'asteroid :pos pos :size smaller)))))) (defmethod done ((timer timer)) (<= (ceiling (remaining timer)) 0)) (defmethod frozen-p ((world world)) (let ((timer (gethash 'freeze (timers world) nil))) (and timer (not (done timer))))) (defmethod update ((asteroid asteroid) time-delta (world world)) (declare (ignore time-delta)) (when (not (frozen-p world)) (incf (facing asteroid) (rotation asteroid)) (call-next-method))) (defmethod render ((asteroid asteroid)) (draw-polygon (loop for i from 0 for r in (radii asteroid) collect (radial-point-from (map-coords asteroid) r (+ (facing asteroid) (* i 18)))) :color *white*)) (defmethod remove-from-world ((world world) (mob mob)) (setf (mobs world) (remove mob (mobs world)))) (defmethod remove-from-world :after ((world world) (asteroid asteroid)) (decf (num-asteroids world))) (defmethod remove-from-world :after ((world world) (ship ship)) (setf (ship world) nil)) (defmethod update ((powerup powerup) time-delta (world world)) (when (> (ceiling (incf (age powerup) time-delta)) *powerup-max-age*) (remove-from-world world powerup))) (defmethod add-score ((world world) (score number)) (setf (high-score world) (max (incf (score world) score) (high-score world)))) (defmethod add-score ((world world) (powerup powerup)) (add-score world (* (level world) 10))) (defmethod add-score ((world world) (asteroid asteroid)) (add-score world (cdr (assoc (size asteroid) '((big . 1) (medium . 2) (small . 5)))))) (defmethod collide :before ((ship ship) (powerup powerup) (world world)) (remove-from-world world powerup) (add-score world powerup)) (defmethod powerup-active-p ((ship ship) powerup) (let ((timer (gethash powerup (timers ship) nil))) (and timer (not (done timer))))) (defmethod add-seconds ((timer timer) seconds) (incf (remaining timer) seconds)) (defmethod add-shield ((ship ship) &key (seconds 0)) (if (powerup-active-p ship 'shield) (add-seconds (gethash 'shield (timers ship)) seconds) (setf (gethash 'shield (timers ship)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup shield-powerup) (world world)) (add-shield ship :seconds 6)) (defmethod render ((powerup shield-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *green*) (draw-polygon `(,(radial-point-from coords (round (* radius 0.8)) 40) ,(radial-point-from coords (round (* radius 0.8)) 0) ,(radial-point-from coords (round (* radius 0.8)) -40) ,(radial-point-from coords (round (* radius 0.8)) -135) ,(radial-point-from coords (round (* radius 0.8)) 135)) :color *white*))) (defmethod add-super-bullets ((ship ship) &key (seconds 0)) (if (powerup-active-p ship 'super-bullets) (add-seconds (gethash 'super-bullets (timers ship)) seconds) (setf (gethash 'super-bullets (timers ship)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup bullet-powerup) (world world)) (add-super-bullets ship :seconds 6)) (defmethod render ((powerup bullet-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *magenta*) (draw-circle coords (round (* radius 0.3)) :color *white*))) (defmethod add-freeze ((world world) &key (seconds 0)) (if (frozen-p world) (add-seconds (gethash 'freeze (timers world)) seconds) (setf (gethash 'freeze (timers world)) (make-instance 'timer :seconds seconds)))) (defmethod collide :before ((ship ship) (powerup freeze-powerup) (world world)) (add-freeze world :seconds 6)) (defmethod render ((powerup freeze-powerup)) (let ((coords (map-coords powerup)) (radius (map-radius powerup))) (draw-circle coords radius :color *cyan*) (draw-polygon (loop for i from 0 to 11 collect (radial-point-from coords (round (* radius (if (= (mod i 2) 0) 0.7 0.2))) (* i 30))) :color *white*))) (defmethod add-to-world ((world world) (mob mob)) (setf (mobs world) (cons mob (mobs world))) (values mob)) (defmethod collide :before ((ship ship) (asteroid asteroid) (world world)) (unless (powerup-active-p ship 'shield) (remove-from-world world ship) (add-to-world world (make-instance 'explosion :pos (pos ship))) (decf (lives world)))) (defmethod in-world-p ((world world) (mob mob)) (find mob (mobs world))) (defmethod ship-moved ((world world) (ship ship)) (dolist (mob (mobs world)) (when (and (not (eq ship mob)) (intersects-p ship mob)) (collide ship mob world)) (when (not (in-world-p world ship)) (return ship)))) (defmethod update-timer ((timer timer) time-delta) (unless (done timer) (decf (remaining timer) time-delta))) (defmethod update :around ((ship ship) time-delta (world world)) (setf (velocity ship) (vector-scale (vector-sum (velocity ship) (acceleration ship)) *deceleration*)) (maphash (lambda (name timer) (declare (ignore name)) (update-timer timer time-delta)) (timers ship)) (call-next-method) (ship-moved world ship)) (defmethod thrust-at ((ship ship) coords) (setf (acceleration ship) (vector-sum (acceleration ship) (vector-scale (vector-subtract coords (pos ship)) 0.03)))) (defmethod stop-thrust ((ship ship)) (setf (acceleration ship) '(0 0))) (defmethod shoot-at ((ship ship) coords (world world)) (let ((bullet (make-instance 'bullet :pos (pos ship) :ship ship))) (setf (velocity bullet) (vector-scale (vector-subtract coords (pos bullet)) 3)) (add-to-world world bullet))) (defmethod render ((ship ship)) (let* ((coords (map-coords ship)) (radius (map-radius ship)) (facing (facing ship)) (nose (radial-point-from coords radius facing)) (left (radial-point-from coords radius (- facing 130))) (right (radial-point-from coords radius (+ facing 130))) (tail (radial-point-from coords (round (* radius 0.5)) (+ facing 180)))) (draw-polygon (list nose left tail right) :color *white*) (when (powerup-active-p ship 'shield) (draw-circle coords (round (+ radius (random 3))) :color *green*)))) (defmethod super-p ((bullet bullet)) (powerup-active-p (ship bullet) 'super-bullets)) (defmethod collide :before ((bullet bullet) (asteroid asteroid) (world world)) (remove-from-world world asteroid) (when (not (super-p bullet)) (remove-from-world world bullet)) (mapcar (lambda (mob) (add-to-world world mob)) (break-down asteroid world)) (add-to-world world (make-instance 'explosion :pos (pos asteroid))) (add-score world asteroid)) (defmethod render ((bullet bullet)) (let ((coords (map-coords bullet)) (radius (map-radius bullet))) (draw-circle coords radius :color *red*) (when (super-p bullet) (draw-circle coords (+ (random 3)) :color *magenta*)))) (defmethod bullet-moved ((world world) (bullet bullet)) (dolist (mob (mobs world)) (when (and (not (eq bullet mob)) (intersects-p bullet mob)) (collide bullet mob world)) (when (not (in-world-p world bullet)) (return bullet)))) (defmethod update ((bullet bullet) time-delta (world world)) (setf (pos bullet) (vector-sum (pos bullet) (vector-scale (velocity bullet) time-delta))) (destructuring-bind (x y) (pos bullet) (when (or (not (< 0 x *map-width*)) (not (< 0 y *map-height*))) (remove-from-world world bullet))) (bullet-moved world bullet)) (defmethod render ((explosion explosion)) (let ((coords (map-coords explosion)) (radius (map-radius explosion))) (draw-circle coords radius :color *red*) (draw-circle coords (+ radius (random 3)) :color *red*))) (defmethod update ((explosion explosion) time-delta (world world)) (when (> (incf (radius explosion) time-delta) *explosion-max-radius*) (remove-from-world world explosion))) (defmethod start-next-level ((world world)) (with-accessors ((level level) (max-level max-level) (mobs mobs) (timers timers) (ship ship)) world (incf level) (setf max-level (max max-level level)) (setf mobs nil) (setf timers (make-hash-table)) (dotimes (i level) (add-to-world world (make-instance 'asteroid))) (add-to-world world (or ship (make-instance 'ship))) (add-shield (ship world) :seconds 6))) (defmethod level-cleared-p ((world world)) (< (num-asteroids world) 1)) (defmethod after ((world world) timer-name &key (seconds 0) do) (multiple-value-bind (timer exists) (gethash timer-name (timers world)) (if exists (when (done timer) (remhash timer-name (timers world)) (when (functionp do) (funcall do))) (setf (gethash timer-name (timers world)) (make-instance 'timer :seconds seconds))))) (defmethod update-world ((world world) time-delta) (maphash (lambda (name timer) (declare (ignore name)) (update-timer timer time-delta)) (timers world)) (dolist (mob (mobs world)) (update mob time-delta world)) start next level 3 seconds after clearing (when (level-cleared-p world) (after world 'cleared :seconds 3 :do (lambda () (incf (lives world)) (start-next-level world)))) restart level 3 seconds after death - game over if no more lives (unless (ship world) (after world 'death :seconds 3 :do (lambda () (if (< (lives world) 1) (let ((ship (make-instance 'ship))) (add-to-world world ship) (add-shield ship :seconds 6))))))) (defmethod add-to-world :after ((world world) (asteroid asteroid)) (incf (num-asteroids world))) (defmethod add-to-world :after ((world world) (ship ship)) (setf (ship world) ship)) (defmethod render-world ((world world) paused) (clear-display *black*) hud (sdl-gfx:draw-string-solid-* (format nil "Level ~d" (level world)) 10 10 :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Lives ~d" (lives world)) 10 (- *map-height* 28) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Score ~d" (score world)) (- *map-width* 127) (- *map-height* 28) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "~a [Q]uit" (if (= (level world) 0) "[P]lay" "[P]ause")) (- *map-width* 127) 10 :color *green*) (if (= (level world) 0) (progn (sdl-gfx:draw-string-solid-* "ASTeroids" (round (* 1/2 (- *map-width* 81))) (round (* 1/4 (- *map-height* 18))) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "High score: ~d" (high-score world)) (round (* 1/2 (- *map-width* 171))) (round (* 1/2 (- *map-height* 18))) :color *green*) (sdl-gfx:draw-string-solid-* (format nil "Max level: ~d" (max-level world)) (round (* 1/2 (- *map-width* 135))) (round (* 3/4 (- *map-height* 18))) :color *green*)) (progn (set-clip-rect (rectangle :x 0 :y 0 :w *map-width* :h *map-height*) :surface *default-display*) (dolist (mob (mobs world)) (render mob)) (set-clip-rect nil :surface *default-display*) (when paused (sdl-gfx:draw-string-solid-* "PAUSED" (round (* 1/2 (- *map-width* 54))) (round (* 1/2 (- *map-height* 18))) :color *green*))))) (defun calc-angle (a b) (destructuring-bind (x y) (vector-subtract b a) (rad->deg (atan x y)))) (defun main () (with-init () (setf *window* (window 640 480 :title-caption "ASTeroids" :icon-caption "ASTeroids")) (sdl-gfx:initialise-default-font sdl-gfx:*font-9x18*) (setf (frame-rate) 60) (clear-display *black*) (let ((world (make-instance 'world)) (paused nil)) (with-events () (:quit-event () t) (:mouse-motion-event (:x x :y y) (when (ship world) (setf (facing (ship world)) (calc-angle (pos (ship world)) (relative-coords x y))))) (:mouse-button-down-event (:x x :y y) (when (and (> (level world) 0) (ship world) (not paused)) (shoot-at (ship world) (relative-coords x y) world) (thrust-at (ship world) (relative-coords x y)))) (:mouse-button-up-event () (when (and (> (level world) 0) (ship world)) (stop-thrust (ship world)))) (:key-up-event (:key key) (case key (:sdl-key-escape (push-quit-event)) (:sdl-key-q (setf (level world) 0)) (:sdl-key-p (if (= (level world) 0) (progn (setf (score world) 0) (setf (lives world) 1) (setf *ticks* (sdl-get-ticks)) (start-next-level world)) (setf paused (not paused)))))) (:idle () (when (and (> (level world) 0) (not paused)) (update-world world (get-ticks))) (render-world world paused) (update-display))))))
b6a31095ebc0a18f5bdbeaf39b6a408c1bcff54577b60ca927e995b8bfefde11
rudymatela/conjure
Conjure.hs
-- | -- Module : Conjure Copyright : ( c ) 2021 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > -- -- A library for Conjuring function implementations -- from tests or partial definitions. -- (a.k.a.: functional inductive programming) -- -- This is currently an experimental tool in its early stages, -- don't expect much from its current version. -- It is just a piece of curiosity in its current state. -- Step 1 : declare your partial function -- -- > square :: Int -> Int > square 0 = 0 > square 1 = 1 > square 2 = 4 -- Step 2 : declare a list with the potential building blocks : -- -- > primitives :: [Prim] -- > primitives = -- > [ pr (0::Int) -- > , pr (1::Int) -- > , prim "+" ((+) :: Int -> Int -> Int) -- > , prim "*" ((*) :: Int -> Int -> Int) -- > ] -- Step 3 : call conjure and see your generated function : -- -- > > conjure "square" square primitives -- > square :: Int -> Int > -- testing 3 combinations of argument values > -- pruning with 14/25 rules > -- looking through 3 candidates of size 1 > -- looking through 4 candidates of size 2 > -- looking through 9 candidates of size 3 -- > square x = x * x # LANGUAGE CPP # module Conjure ( -- * Basic use conjure , Prim , pr , prim , prif , primOrdCaseFor -- * Advanced use , conjureWithMaxSize , conjureWith , Args(..) , args , Expr , val , value -- * Conjuring from a specification , conjureFromSpec , conjureFromSpecWith -- * When using custom types , Conjurable (conjureExpress, conjureEquality, conjureTiers, conjureCases, conjureSubTypes, conjureSize) , reifyExpress , reifyEquality , reifyTiers , conjureType , Name (..) , Express (..) , deriveConjurable , deriveConjurableIfNeeded , deriveConjurableCascading -- * Pure interfaces , conjpure , conjpureWith -- * Helper test types , A, B, C, D, E, F ) where import Conjure.Engine import Conjure.Conjurable import Conjure.Prim import Conjure.Conjurable.Derive
null
https://raw.githubusercontent.com/rudymatela/conjure/9d2167e758e72b6be5970bc33f6b9e893fc5874f/src/Conjure.hs
haskell
| Module : Conjure A library for Conjuring function implementations from tests or partial definitions. (a.k.a.: functional inductive programming) This is currently an experimental tool in its early stages, don't expect much from its current version. It is just a piece of curiosity in its current state. > square :: Int -> Int > primitives :: [Prim] > primitives = > [ pr (0::Int) > , pr (1::Int) > , prim "+" ((+) :: Int -> Int -> Int) > , prim "*" ((*) :: Int -> Int -> Int) > ] > > conjure "square" square primitives > square :: Int -> Int testing 3 combinations of argument values pruning with 14/25 rules looking through 3 candidates of size 1 looking through 4 candidates of size 2 looking through 9 candidates of size 3 > square x = x * x * Basic use * Advanced use * Conjuring from a specification * When using custom types * Pure interfaces * Helper test types
Copyright : ( c ) 2021 License : 3 - Clause BSD ( see the file LICENSE ) Maintainer : < > Step 1 : declare your partial function > square 0 = 0 > square 1 = 1 > square 2 = 4 Step 2 : declare a list with the potential building blocks : Step 3 : call conjure and see your generated function : # LANGUAGE CPP # module Conjure ( conjure , Prim , pr , prim , prif , primOrdCaseFor , conjureWithMaxSize , conjureWith , Args(..) , args , Expr , val , value , conjureFromSpec , conjureFromSpecWith , Conjurable (conjureExpress, conjureEquality, conjureTiers, conjureCases, conjureSubTypes, conjureSize) , reifyExpress , reifyEquality , reifyTiers , conjureType , Name (..) , Express (..) , deriveConjurable , deriveConjurableIfNeeded , deriveConjurableCascading , conjpure , conjpureWith , A, B, C, D, E, F ) where import Conjure.Engine import Conjure.Conjurable import Conjure.Prim import Conjure.Conjurable.Derive
e15ecc378ede84e9bb1caaf5ad8d88fcee7049f25fcdaa78fdfe353e75848d81
lolepezy/rpki-prover
Time.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DerivingStrategies # # LANGUAGE DerivingVia # # LANGUAGE GeneralizedNewtypeDeriving # module RPKI.Time where import Data.Int import Data.Semigroup import Control.Monad.IO.Class (MonadIO, liftIO) import GHC.Generics (Generic) import Data.Hourglass import System.Hourglass (dateCurrent) import System.CPUTime import RPKI.Store.Base.Serialisation import RPKI.Orphans.Store newtype Instant = Instant DateTime deriving stock (Eq, Ord, Generic) deriving anyclass TheBinary instance Show Instant where show (Instant d) = timePrint ISO8601_DateAndTime d -- | Current time that is to be passed into the environment of validating functions newtype Now = Now { unNow :: Instant } deriving stock (Show, Eq, Ord) newtype TimeMs = TimeMs { unTimeMs :: Int64 } deriving stock (Eq, Ord, Generic) deriving anyclass (TheBinary) deriving newtype (Num) deriving Semigroup via Sum TimeMs deriving Monoid via Sum TimeMs newtype CPUTime = CPUTime { unCPUTime :: Integer } deriving stock (Eq, Ord, Generic) deriving anyclass (TheBinary) deriving newtype (Num) deriving Semigroup via Sum CPUTime deriving Monoid via Sum CPUTime instance Show TimeMs where show (TimeMs ms) = show ms instance Show CPUTime where show (CPUTime ms) = show ms thisInstant :: MonadIO m => m Now thisInstant = Now . Instant <$> liftIO dateCurrent getCpuTime :: MonadIO m => m CPUTime getCpuTime = do picos <- liftIO getCPUTime pure $ CPUTime $ picos `div` 1000_000_000 timed :: MonadIO m => m a -> m (a, Int64) timed action = do Now (Instant begin) <- thisInstant !z <- action Now (Instant end) <- thisInstant let (Seconds s, NanoSeconds ns) = timeDiffP end begin pure (z, s * nanosPerSecond + ns) timedMS :: MonadIO m => m a -> m (a, TimeMs) timedMS action = do (!z, ns) <- timed action pure (z, fromIntegral $! ns `div` microsecondsPerSecond) -- cpuTime :: nanosPerSecond :: Num p => p nanosPerSecond = 1000_000_000 # INLINE nanosPerSecond # microsecondsPerSecond :: Num p => p microsecondsPerSecond = 1000_000 # INLINE microsecondsPerSecond # toNanoseconds :: Instant -> Int64 toNanoseconds (Instant instant) = nanosPerSecond * seconds + nanos where ElapsedP (Elapsed (Seconds seconds)) (NanoSeconds nanos) = timeGetElapsedP instant asSeconds :: Instant -> Int64 asSeconds (Instant instant) = seconds where ElapsedP (Elapsed (Seconds seconds)) _ = timeGetElapsedP instant fromNanoseconds :: Int64 -> Instant fromNanoseconds totalNanos = Instant $ timeConvert elapsed where elapsed = ElapsedP (Elapsed (Seconds seconds)) (NanoSeconds nanos) (seconds, nanos) = totalNanos `divMod` nanosPerSecond closeEnoughMoments :: Instant -> Instant -> Seconds -> Bool closeEnoughMoments firstMoment secondMoment intervalSeconds = instantDiff secondMoment firstMoment < intervalSeconds instantDiff :: Instant -> Instant -> Seconds instantDiff (Instant firstMoment) (Instant secondMoment) = timeDiff firstMoment secondMoment uiDateFormat :: Instant -> String uiDateFormat (Instant d) = timePrint format d where format = TimeFormatString [ Format_Year, dash, Format_Month2, dash, Format_Day2, Format_Text ' ', Format_Hour, colon, Format_Minute, colon, Format_Second, Format_TimezoneName ] dash = Format_Text '-' colon = Format_Text ':' secondsToInt :: Seconds -> Int secondsToInt (Seconds s) = fromIntegral s cpuTimePerSecond :: CPUTime -> Instant -> Instant -> Double cpuTimePerSecond (CPUTime t) from to = let Seconds duration = instantDiff to from in (fromInteger t :: Double) / (fromIntegral duration :: Double)
null
https://raw.githubusercontent.com/lolepezy/rpki-prover/63ca8911d72ebac48f4c3df3fab95f9e0278e933/src/RPKI/Time.hs
haskell
# LANGUAGE DeriveAnyClass # | Current time that is to be passed into the environment of validating functions cpuTime ::
# LANGUAGE DerivingStrategies # # LANGUAGE DerivingVia # # LANGUAGE GeneralizedNewtypeDeriving # module RPKI.Time where import Data.Int import Data.Semigroup import Control.Monad.IO.Class (MonadIO, liftIO) import GHC.Generics (Generic) import Data.Hourglass import System.Hourglass (dateCurrent) import System.CPUTime import RPKI.Store.Base.Serialisation import RPKI.Orphans.Store newtype Instant = Instant DateTime deriving stock (Eq, Ord, Generic) deriving anyclass TheBinary instance Show Instant where show (Instant d) = timePrint ISO8601_DateAndTime d newtype Now = Now { unNow :: Instant } deriving stock (Show, Eq, Ord) newtype TimeMs = TimeMs { unTimeMs :: Int64 } deriving stock (Eq, Ord, Generic) deriving anyclass (TheBinary) deriving newtype (Num) deriving Semigroup via Sum TimeMs deriving Monoid via Sum TimeMs newtype CPUTime = CPUTime { unCPUTime :: Integer } deriving stock (Eq, Ord, Generic) deriving anyclass (TheBinary) deriving newtype (Num) deriving Semigroup via Sum CPUTime deriving Monoid via Sum CPUTime instance Show TimeMs where show (TimeMs ms) = show ms instance Show CPUTime where show (CPUTime ms) = show ms thisInstant :: MonadIO m => m Now thisInstant = Now . Instant <$> liftIO dateCurrent getCpuTime :: MonadIO m => m CPUTime getCpuTime = do picos <- liftIO getCPUTime pure $ CPUTime $ picos `div` 1000_000_000 timed :: MonadIO m => m a -> m (a, Int64) timed action = do Now (Instant begin) <- thisInstant !z <- action Now (Instant end) <- thisInstant let (Seconds s, NanoSeconds ns) = timeDiffP end begin pure (z, s * nanosPerSecond + ns) timedMS :: MonadIO m => m a -> m (a, TimeMs) timedMS action = do (!z, ns) <- timed action pure (z, fromIntegral $! ns `div` microsecondsPerSecond) nanosPerSecond :: Num p => p nanosPerSecond = 1000_000_000 # INLINE nanosPerSecond # microsecondsPerSecond :: Num p => p microsecondsPerSecond = 1000_000 # INLINE microsecondsPerSecond # toNanoseconds :: Instant -> Int64 toNanoseconds (Instant instant) = nanosPerSecond * seconds + nanos where ElapsedP (Elapsed (Seconds seconds)) (NanoSeconds nanos) = timeGetElapsedP instant asSeconds :: Instant -> Int64 asSeconds (Instant instant) = seconds where ElapsedP (Elapsed (Seconds seconds)) _ = timeGetElapsedP instant fromNanoseconds :: Int64 -> Instant fromNanoseconds totalNanos = Instant $ timeConvert elapsed where elapsed = ElapsedP (Elapsed (Seconds seconds)) (NanoSeconds nanos) (seconds, nanos) = totalNanos `divMod` nanosPerSecond closeEnoughMoments :: Instant -> Instant -> Seconds -> Bool closeEnoughMoments firstMoment secondMoment intervalSeconds = instantDiff secondMoment firstMoment < intervalSeconds instantDiff :: Instant -> Instant -> Seconds instantDiff (Instant firstMoment) (Instant secondMoment) = timeDiff firstMoment secondMoment uiDateFormat :: Instant -> String uiDateFormat (Instant d) = timePrint format d where format = TimeFormatString [ Format_Year, dash, Format_Month2, dash, Format_Day2, Format_Text ' ', Format_Hour, colon, Format_Minute, colon, Format_Second, Format_TimezoneName ] dash = Format_Text '-' colon = Format_Text ':' secondsToInt :: Seconds -> Int secondsToInt (Seconds s) = fromIntegral s cpuTimePerSecond :: CPUTime -> Instant -> Instant -> Double cpuTimePerSecond (CPUTime t) from to = let Seconds duration = instantDiff to from in (fromInteger t :: Double) / (fromIntegral duration :: Double)
b3c0f98f5f051f86c4673a32acdc11b0b523fd8099d6b0707287e39f430f3060
poroh/ersip
ersip_trans_se.erl
%% Copyright ( c ) 2017 , 2018 Dmitry Poroh %% All rights reserved. Distributed under the terms of the MIT License . See the LICENSE file . %% %% Side effects of transaction handlers %% -module(ersip_trans_se). -export([clear_trans/1, send_request/1, send_response/1, tu_result/1, set_timer/2 ]). -export_type([effect/0, clear_reason/0 ]). %%%=================================================================== %%% Types %%%=================================================================== -type effect() :: clear_trans() | tu_result() | send_request() | send_response() | set_timer(). -type clear_trans() :: {clear_trans, clear_reason()}. -type tu_result() :: {tu_result, ersip_sipmsg:sipmsg()}. -type send_request() :: {send_request, ersip_request:request()}. -type send_response() :: {send_response, ersip_sipmsg:sipmsg()}. -type set_timer() :: {set_timer, {timeout(), TimerEv :: timer_event()}}. -type timer_event() :: term(). -type clear_reason() :: normal | timeout | no_ack. %%%=================================================================== %%% API %%%=================================================================== %% @doc Delete transaction. Transaction must be removed if it saved %% somewhere. -spec clear_trans(clear_reason()) -> clear_trans(). clear_trans(Reason) -> {clear_trans, Reason}. %% @doc Inform transaction user about transaction result. -spec tu_result(ersip_sipmsg:sipmsg()) -> tu_result(). tu_result(SipMsg) -> {tu_result, SipMsg}. %% @doc Send request message. -spec send_request(Request) -> send_request() when Request :: ersip_request:request(). send_request(OutReq) -> {send_request, OutReq}. -spec send_response(Resp) -> send_response() when Resp :: ersip_sipmsg:sipmsg(). send_response(SipMsg) -> {send_response, SipMsg}. %% @doc Set timer for specified time interval. After timeout is expired TimerFun must be called to process timer event . -spec set_timer(timeout(), timer_event()) -> set_timer(). set_timer(Timeout, TimerEv) -> {set_timer, {Timeout, TimerEv}}.
null
https://raw.githubusercontent.com/poroh/ersip/f1b0d3c5713fb063a6cc327ea493f06cff6a6e5e/src/transaction/ersip_trans_se.erl
erlang
All rights reserved. Side effects of transaction handlers =================================================================== Types =================================================================== =================================================================== API =================================================================== @doc Delete transaction. Transaction must be removed if it saved somewhere. @doc Inform transaction user about transaction result. @doc Send request message. @doc Set timer for specified time interval. After timeout is
Copyright ( c ) 2017 , 2018 Dmitry Poroh Distributed under the terms of the MIT License . See the LICENSE file . -module(ersip_trans_se). -export([clear_trans/1, send_request/1, send_response/1, tu_result/1, set_timer/2 ]). -export_type([effect/0, clear_reason/0 ]). -type effect() :: clear_trans() | tu_result() | send_request() | send_response() | set_timer(). -type clear_trans() :: {clear_trans, clear_reason()}. -type tu_result() :: {tu_result, ersip_sipmsg:sipmsg()}. -type send_request() :: {send_request, ersip_request:request()}. -type send_response() :: {send_response, ersip_sipmsg:sipmsg()}. -type set_timer() :: {set_timer, {timeout(), TimerEv :: timer_event()}}. -type timer_event() :: term(). -type clear_reason() :: normal | timeout | no_ack. -spec clear_trans(clear_reason()) -> clear_trans(). clear_trans(Reason) -> {clear_trans, Reason}. -spec tu_result(ersip_sipmsg:sipmsg()) -> tu_result(). tu_result(SipMsg) -> {tu_result, SipMsg}. -spec send_request(Request) -> send_request() when Request :: ersip_request:request(). send_request(OutReq) -> {send_request, OutReq}. -spec send_response(Resp) -> send_response() when Resp :: ersip_sipmsg:sipmsg(). send_response(SipMsg) -> {send_response, SipMsg}. expired TimerFun must be called to process timer event . -spec set_timer(timeout(), timer_event()) -> set_timer(). set_timer(Timeout, TimerEv) -> {set_timer, {Timeout, TimerEv}}.
a7ab1ae2ecd89d48dbf7f19a55eb5d6c74c1e66ef2cd06104af180033ff50789
hengchu/tiger-haskell
tigercanon.hs
-- Much of the code in this file is adapted from the ML version at here : /~appel/modern/ml/chap8/canon.sml module TigerCanon ( linearize , basicblocks , tracesched , canonicalize ) where import qualified TigerTemp as Tmp import TigerITree import TigerGenSymLabTmp import qualified Data.Map as Map import Control.Monad.Identity import Prelude hiding (EQ, LT, GT) commute :: Stm -> Exp -> Bool commute (EXP(CONST _ _)) _ = True commute _ (NAME _) = True commute _ (CONST _ _) = True commute _ _ = False nop :: Stm nop = EXP(CONST 0 False) type Canon = GenSymLabTmp Identity combines two Stm , ignores nop (%) :: Stm -> Stm -> Stm s % (EXP(CONST _ _)) = s (EXP(CONST _ _)) % s = s a % b = SEQ(a, b) notrel :: Relop -> Relop notrel EQ = NE notrel NE = EQ notrel LT = GE notrel GT = LE notrel LE = GT notrel GE = LT notrel ULT = UGE notrel ULE = UGT notrel UGT = ULE notrel UGE = ULT notrel FEQ = FNE notrel FNE = FEQ notrel FLT = FGE notrel FLE = FGT notrel FGT = FLE notrel FGE = FLT linearize :: Stm -> Canon [Stm] linearize stmtobelinearized = let reorder dofunc (exps, build) = let f ((e@(CALL _ iscptr _)):rest) = do t <- newTemp iscptr f $ ESEQ(MOVE(TEMP t iscptr, e), TEMP t iscptr):rest f (a:rest) = do (stm0, e) <- dofunc a (stm1, el) <- f rest if commute stm1 e then return (stm0 % stm1, e:el) else do let iseptr = isExpPtr e t <- newTemp iseptr return (stm0 % MOVE(TEMP t iseptr, e) % stm1, TEMP t iseptr:el) f [] = return (nop, []) in do (stm0, el) <- f exps return (stm0, build el) expl :: [Exp] -> ([Exp] -> Exp) -> Canon (Stm, Exp) expl el f = reorder doexp (el, f) expl' :: [Exp] -> ([Exp] -> Stm) -> Canon Stm expl' el f = do (stm0, s) <- reorder doexp (el, f) return $ stm0 % s doexp :: Exp -> Canon (Stm, Exp) doexp (BINOP(p, a, b) isbptr) = expl [a, b] $ \[l, r] -> BINOP(p, l, r) isbptr doexp (CVTOP(p, a, s1, s2)) = expl [a] $ \[arg] -> CVTOP(p, arg, s1, s2) doexp (MEM(a, sz) ismemptr) = expl [a] $ \[arg] -> MEM(arg, sz) ismemptr doexp (ESEQ(s, e)) = do s' <- dostm s (s'', expr) <- expl [e] $ \[e'] -> e' return (s' % s'', expr) doexp (CALL(e, el) iscptr retlab) = expl (e:el) $ \(func:args) -> CALL(func, args) iscptr retlab doexp e = expl [] $ \[] -> e dostm :: Stm -> Canon Stm dostm (SEQ(a, b)) = do a' <- dostm a b' <- dostm b return $ a' % b' dostm (JUMP(e, labs)) = expl' [e] $ \[e'] -> JUMP(e', labs) dostm (CJUMP(TEST(p, a, b), t, f)) = expl' [a, b] $ \[a', b'] -> CJUMP(TEST(p, a', b'), t, f) dostm (MOVE(TEMP t istptr, CALL(e, el) iscptr retlab)) = expl' (e:el) $ \(func:args) -> MOVE(TEMP t istptr, CALL(func, args) iscptr retlab) dostm (MOVE(TEMP t istptr, b)) = expl' [b] $ \[src] -> MOVE(TEMP t istptr, src) dostm (MOVE(MEM(e, sz) ismemptr, src)) = expl' [e, src] $ \[e', src'] -> MOVE(MEM(e', sz) ismemptr, src') dostm (MOVE(ESEQ(s, e), src)) = do s' <- dostm s src' <- dostm $ MOVE(e, src) return $ s' % src' dostm (MOVE(a, b)) = expl' [a, b] $ \[a', b'] -> MOVE(a', b') dostm (EXP(CALL(e, el) iscptr retlab)) = expl' (e:el) $ \(func:arg) -> EXP(CALL(func, arg) iscptr retlab) dostm (EXP e) = expl' [e] $ \[e'] -> EXP e' dostm s = expl' [] $ \[] -> s linear (SEQ(a, b)) l = linear a $ linear b l linear s l = s : l in do stm' <- dostm stmtobelinearized return $ linear stm' [] basicblocks :: [Stm] -> Canon ([[Stm]], Tmp.Label) basicblocks stms0 = do done <- newLabel let blocks ((blkhead@(LABEL _)):blktail) blist = let next ((s@(JUMP _)):rest) thisblock = endblock rest $ s:thisblock next ((s@(CJUMP _)):rest) thisblock = endblock rest $ s:thisblock next (stms@(LABEL lab: _)) thisblock = next (JUMP(NAME lab, [lab]):stms) thisblock next (s:rest) thisblock = next rest $ s:thisblock next [] thisblock = next [JUMP(NAME done, [done])] thisblock endblock more thisblock = blocks more $ reverse thisblock:blist in next blktail [blkhead] blocks [] blist = return $ reverse blist blocks stms blist = do newlab <- newLabel blocks (LABEL newlab:stms) blist blks <- blocks stms0 [] return (blks, done) enterblock :: [Stm] -> Map.Map Tmp.Label [Stm] -> Map.Map Tmp.Label [Stm] enterblock b@(LABEL lab:_) table = Map.insert lab b table enterblock _ table = table splitlast :: [a] -> ([a], a) splitlast [x] = ([], x) splitlast (x:xs) = let (blktail, l) = splitlast xs in (x:blktail, l) splitlast _ = error "Compiler error: splitlast." trace :: Map.Map Tmp.Label [Stm] -> [Stm] -> [[Stm]] -> Canon [Stm] trace table b@(LABEL lab0:_) rest = let table1 = Map.insert lab0 [] table in case splitlast b of (most, JUMP(NAME lab, _)) -> case Map.lookup lab table1 of (Just b'@(_:_)) -> do t <- trace table1 b' rest return $ most ++ t _ -> do next <- getnext table1 rest return $ b ++ next (most, CJUMP(TEST(opr, x, y), t, f)) -> case (Map.lookup t table1, Map.lookup f table1) of (_, Just b'@(_:_)) -> do tr <- trace table1 b' rest return $ b ++ tr (Just b'@(_:_), _) -> do tc <- trace table1 b' rest let cjump = [CJUMP(TEST(notrel opr, x, y), f, t)] return $ most ++ cjump ++ tc _ -> do f' <- newLabel let cjump = [CJUMP(TEST(opr, x, y), t, f'), LABEL f', JUMP(NAME f, [f])] n <- getnext table1 rest return $ most ++ cjump ++ n (_, JUMP _) -> do next <- getnext table1 rest return $ b ++ next _ -> error "Compiler error: trace -> case splitlast b of." trace _ _ _ = error "Compiler error: trace." getnext :: Map.Map Tmp.Label [Stm] -> [[Stm]] -> Canon [Stm] getnext table (b@(LABEL lab:_):rest) = case Map.lookup lab table of Just (_:_) -> trace table b rest _ -> getnext table rest getnext _ [] = return [] getnext _ _ = error "Compiler error: getnext." tracesched :: ([[Stm]], Tmp.Label) -> Canon [Stm] tracesched (blocks, done) = do n <- getnext (foldr enterblock Map.empty blocks) blocks return $ n ++ [LABEL done] canonicalize :: Stm -> GenSymLabTmpState -> ([Stm], GenSymLabTmpState) canonicalize stm state = let monad = do stms <- linearize stm blocks <- basicblocks stms tracesched blocks result = (runIdentity . runGSLT state) monad in result
null
https://raw.githubusercontent.com/hengchu/tiger-haskell/ec6809500c245ea99d2329e8255a67bdb57cf579/src/tigercanon.hs
haskell
Much of the code in this file is adapted from
the ML version at here : /~appel/modern/ml/chap8/canon.sml module TigerCanon ( linearize , basicblocks , tracesched , canonicalize ) where import qualified TigerTemp as Tmp import TigerITree import TigerGenSymLabTmp import qualified Data.Map as Map import Control.Monad.Identity import Prelude hiding (EQ, LT, GT) commute :: Stm -> Exp -> Bool commute (EXP(CONST _ _)) _ = True commute _ (NAME _) = True commute _ (CONST _ _) = True commute _ _ = False nop :: Stm nop = EXP(CONST 0 False) type Canon = GenSymLabTmp Identity combines two Stm , ignores nop (%) :: Stm -> Stm -> Stm s % (EXP(CONST _ _)) = s (EXP(CONST _ _)) % s = s a % b = SEQ(a, b) notrel :: Relop -> Relop notrel EQ = NE notrel NE = EQ notrel LT = GE notrel GT = LE notrel LE = GT notrel GE = LT notrel ULT = UGE notrel ULE = UGT notrel UGT = ULE notrel UGE = ULT notrel FEQ = FNE notrel FNE = FEQ notrel FLT = FGE notrel FLE = FGT notrel FGT = FLE notrel FGE = FLT linearize :: Stm -> Canon [Stm] linearize stmtobelinearized = let reorder dofunc (exps, build) = let f ((e@(CALL _ iscptr _)):rest) = do t <- newTemp iscptr f $ ESEQ(MOVE(TEMP t iscptr, e), TEMP t iscptr):rest f (a:rest) = do (stm0, e) <- dofunc a (stm1, el) <- f rest if commute stm1 e then return (stm0 % stm1, e:el) else do let iseptr = isExpPtr e t <- newTemp iseptr return (stm0 % MOVE(TEMP t iseptr, e) % stm1, TEMP t iseptr:el) f [] = return (nop, []) in do (stm0, el) <- f exps return (stm0, build el) expl :: [Exp] -> ([Exp] -> Exp) -> Canon (Stm, Exp) expl el f = reorder doexp (el, f) expl' :: [Exp] -> ([Exp] -> Stm) -> Canon Stm expl' el f = do (stm0, s) <- reorder doexp (el, f) return $ stm0 % s doexp :: Exp -> Canon (Stm, Exp) doexp (BINOP(p, a, b) isbptr) = expl [a, b] $ \[l, r] -> BINOP(p, l, r) isbptr doexp (CVTOP(p, a, s1, s2)) = expl [a] $ \[arg] -> CVTOP(p, arg, s1, s2) doexp (MEM(a, sz) ismemptr) = expl [a] $ \[arg] -> MEM(arg, sz) ismemptr doexp (ESEQ(s, e)) = do s' <- dostm s (s'', expr) <- expl [e] $ \[e'] -> e' return (s' % s'', expr) doexp (CALL(e, el) iscptr retlab) = expl (e:el) $ \(func:args) -> CALL(func, args) iscptr retlab doexp e = expl [] $ \[] -> e dostm :: Stm -> Canon Stm dostm (SEQ(a, b)) = do a' <- dostm a b' <- dostm b return $ a' % b' dostm (JUMP(e, labs)) = expl' [e] $ \[e'] -> JUMP(e', labs) dostm (CJUMP(TEST(p, a, b), t, f)) = expl' [a, b] $ \[a', b'] -> CJUMP(TEST(p, a', b'), t, f) dostm (MOVE(TEMP t istptr, CALL(e, el) iscptr retlab)) = expl' (e:el) $ \(func:args) -> MOVE(TEMP t istptr, CALL(func, args) iscptr retlab) dostm (MOVE(TEMP t istptr, b)) = expl' [b] $ \[src] -> MOVE(TEMP t istptr, src) dostm (MOVE(MEM(e, sz) ismemptr, src)) = expl' [e, src] $ \[e', src'] -> MOVE(MEM(e', sz) ismemptr, src') dostm (MOVE(ESEQ(s, e), src)) = do s' <- dostm s src' <- dostm $ MOVE(e, src) return $ s' % src' dostm (MOVE(a, b)) = expl' [a, b] $ \[a', b'] -> MOVE(a', b') dostm (EXP(CALL(e, el) iscptr retlab)) = expl' (e:el) $ \(func:arg) -> EXP(CALL(func, arg) iscptr retlab) dostm (EXP e) = expl' [e] $ \[e'] -> EXP e' dostm s = expl' [] $ \[] -> s linear (SEQ(a, b)) l = linear a $ linear b l linear s l = s : l in do stm' <- dostm stmtobelinearized return $ linear stm' [] basicblocks :: [Stm] -> Canon ([[Stm]], Tmp.Label) basicblocks stms0 = do done <- newLabel let blocks ((blkhead@(LABEL _)):blktail) blist = let next ((s@(JUMP _)):rest) thisblock = endblock rest $ s:thisblock next ((s@(CJUMP _)):rest) thisblock = endblock rest $ s:thisblock next (stms@(LABEL lab: _)) thisblock = next (JUMP(NAME lab, [lab]):stms) thisblock next (s:rest) thisblock = next rest $ s:thisblock next [] thisblock = next [JUMP(NAME done, [done])] thisblock endblock more thisblock = blocks more $ reverse thisblock:blist in next blktail [blkhead] blocks [] blist = return $ reverse blist blocks stms blist = do newlab <- newLabel blocks (LABEL newlab:stms) blist blks <- blocks stms0 [] return (blks, done) enterblock :: [Stm] -> Map.Map Tmp.Label [Stm] -> Map.Map Tmp.Label [Stm] enterblock b@(LABEL lab:_) table = Map.insert lab b table enterblock _ table = table splitlast :: [a] -> ([a], a) splitlast [x] = ([], x) splitlast (x:xs) = let (blktail, l) = splitlast xs in (x:blktail, l) splitlast _ = error "Compiler error: splitlast." trace :: Map.Map Tmp.Label [Stm] -> [Stm] -> [[Stm]] -> Canon [Stm] trace table b@(LABEL lab0:_) rest = let table1 = Map.insert lab0 [] table in case splitlast b of (most, JUMP(NAME lab, _)) -> case Map.lookup lab table1 of (Just b'@(_:_)) -> do t <- trace table1 b' rest return $ most ++ t _ -> do next <- getnext table1 rest return $ b ++ next (most, CJUMP(TEST(opr, x, y), t, f)) -> case (Map.lookup t table1, Map.lookup f table1) of (_, Just b'@(_:_)) -> do tr <- trace table1 b' rest return $ b ++ tr (Just b'@(_:_), _) -> do tc <- trace table1 b' rest let cjump = [CJUMP(TEST(notrel opr, x, y), f, t)] return $ most ++ cjump ++ tc _ -> do f' <- newLabel let cjump = [CJUMP(TEST(opr, x, y), t, f'), LABEL f', JUMP(NAME f, [f])] n <- getnext table1 rest return $ most ++ cjump ++ n (_, JUMP _) -> do next <- getnext table1 rest return $ b ++ next _ -> error "Compiler error: trace -> case splitlast b of." trace _ _ _ = error "Compiler error: trace." getnext :: Map.Map Tmp.Label [Stm] -> [[Stm]] -> Canon [Stm] getnext table (b@(LABEL lab:_):rest) = case Map.lookup lab table of Just (_:_) -> trace table b rest _ -> getnext table rest getnext _ [] = return [] getnext _ _ = error "Compiler error: getnext." tracesched :: ([[Stm]], Tmp.Label) -> Canon [Stm] tracesched (blocks, done) = do n <- getnext (foldr enterblock Map.empty blocks) blocks return $ n ++ [LABEL done] canonicalize :: Stm -> GenSymLabTmpState -> ([Stm], GenSymLabTmpState) canonicalize stm state = let monad = do stms <- linearize stm blocks <- basicblocks stms tracesched blocks result = (runIdentity . runGSLT state) monad in result
8e4e32690afff1d9b3260de8ac96624004df01f8b0198826a46bb4adc642666e
VictorNicollet/Ohm
configure.mli
Ohm is © 2011 type path = [ `Log | `Templates | `Resources ] exception Locked of path * string val root : string val get : path -> string val set : path -> string -> unit val lock : path -> string
null
https://raw.githubusercontent.com/VictorNicollet/Ohm/ca90c162f6c49927c893114491f29d44aaf71feb/src/configure.mli
ocaml
Ohm is © 2011 type path = [ `Log | `Templates | `Resources ] exception Locked of path * string val root : string val get : path -> string val set : path -> string -> unit val lock : path -> string
2f7a166c328b3ef71f9528df88afe610972ccd2b8cccc01ccbef209e87821ec1
fosskers/aura
O.hs
-- | Module : . Commands . O Copyright : ( c ) , 2012 - 2021 -- License : GPL3 Maintainer : < > -- -- Handle all @-O@ flags - those which involve orphan packages. module Aura.Commands.O ( displayOrphans, adoptPkg ) where import Aura.Core (Env(..), orphans, sudo) import Aura.IO (putTextLn) import Aura.Pacman (pacman) import Aura.Settings import Aura.Types import RIO --- -- | Print the result of @pacman -Qqdt@ displayOrphans :: Environment -> IO () displayOrphans env = orphans env >>= traverse_ (putTextLn . pnName) -- | Identical to @-D --asexplicit@. adoptPkg :: NonEmpty PkgName -> RIO Env () adoptPkg pkgs = do env <- asks (envOf . settings) sudo . liftIO . pacman env $ ["-D", "--asexplicit"] <> asFlag pkgs
null
https://raw.githubusercontent.com/fosskers/aura/08cd46eaa598094f7395455d66690d3d8c59e965/haskell/aura/exec/Aura/Commands/O.hs
haskell
| License : GPL3 Handle all @-O@ flags - those which involve orphan packages. - | Print the result of @pacman -Qqdt@ | Identical to @-D --asexplicit@.
Module : . Commands . O Copyright : ( c ) , 2012 - 2021 Maintainer : < > module Aura.Commands.O ( displayOrphans, adoptPkg ) where import Aura.Core (Env(..), orphans, sudo) import Aura.IO (putTextLn) import Aura.Pacman (pacman) import Aura.Settings import Aura.Types import RIO displayOrphans :: Environment -> IO () displayOrphans env = orphans env >>= traverse_ (putTextLn . pnName) adoptPkg :: NonEmpty PkgName -> RIO Env () adoptPkg pkgs = do env <- asks (envOf . settings) sudo . liftIO . pacman env $ ["-D", "--asexplicit"] <> asFlag pkgs
74d049565b8516b3a3a1c2b531409b293e289165cea84dc7864a6c21abf5d369
brandonchinn178/persistent-migration
Postgres.hs
| Module : Database . Persist . Migration . Postgres Maintainer : < > Stability : experimental Portability : portable Defines the migration backend for PostgreSQL . Module : Database.Persist.Migration.Postgres Maintainer : Brandon Chinn <> Stability : experimental Portability : portable Defines the migration backend for PostgreSQL. -} # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # module Database.Persist.Migration.Postgres ( backend , getMigration , runMigration ) where import Data.Maybe (maybeToList) import Data.Text (Text) import qualified Data.Text as Text import Database.Persist.Migration import qualified Database.Persist.Migration.Core as Migration import Database.Persist.Sql (SqlPersistT) | Run a migration with the Postgres backend . runMigration :: MigrateSettings -> Migration -> SqlPersistT IO () runMigration = Migration.runMigration backend | Get a migration with the Postgres backend . getMigration :: MigrateSettings -> Migration -> SqlPersistT IO [MigrateSql] getMigration = Migration.getMigration backend | The migration backend for Postgres . backend :: MigrateBackend backend = MigrateBackend { getMigrationSql = getMigrationSql' } getMigrationSql' :: Operation -> SqlPersistT IO [MigrateSql] getMigrationSql' CreateTable{..} = fromMigrateSql $ mapSql (\sql -> Text.unwords ["CREATE TABLE IF NOT EXISTS", quote name, "(", sql, ")"]) $ concatSql uncommas tableDefs where tableDefs = map showColumn schema ++ map showTableConstraint constraints getMigrationSql' DropTable{..} = fromWords ["DROP TABLE IF EXISTS", quote table] getMigrationSql' RenameTable{..} = fromWords ["ALTER TABLE", quote from, "RENAME TO", quote to] getMigrationSql' AddConstraint{..} = fromWords ["ALTER TABLE", quote table, statement] where statement = case constraint of PrimaryKey cols -> Text.unwords ["ADD PRIMARY KEY (", uncommas' cols, ")"] Unique label cols -> Text.unwords ["ADD CONSTRAINT", quote label, "UNIQUE (", uncommas' cols, ")"] getMigrationSql' DropConstraint{..} = fromWords ["ALTER TABLE", quote table, "DROP CONSTRAINT", constraintName] getMigrationSql' AddColumn{..} = return $ createQuery : maybeToList alterQuery where Column{..} = column alterTable = Text.unwords ["ALTER TABLE", quote table] -- The CREATE query with the default specified by AddColumn{colDefault} withoutDefault = showColumn $ column { colProps = filter (not . isDefault) colProps } createDefault = case colDefault of Nothing -> MigrateSql "" [] Just def -> MigrateSql "DEFAULT ?" [def] createQuery = concatSql (\sqls -> Text.unwords $ [alterTable, "ADD COLUMN"] ++ sqls) [withoutDefault, createDefault] The ALTER query to drop / set the default ( if was set ) alterQuery = let action = case getDefault colProps of Nothing -> pureSql "DROP DEFAULT" Just v -> MigrateSql "SET DEFAULT ?" [v] alterQuery' = mapSql (\sql -> Text.unwords [alterTable, "ALTER COLUMN", quote colName, sql]) action in alterQuery' <$ colDefault getMigrationSql' RenameColumn{..} = fromWords ["ALTER TABLE", quote table, "RENAME COLUMN", quote from, "TO", quote to] getMigrationSql' DropColumn{..} = fromWords ["ALTER TABLE", quote tab, "DROP COLUMN", quote col] where (tab, col) = columnId getMigrationSql' RawOperation{..} = rawOp {- Helpers -} fromMigrateSql :: Monad m => MigrateSql -> m [MigrateSql] fromMigrateSql = return . pure fromWords :: Monad m => [Text] -> m [MigrateSql] fromWords = fromMigrateSql . pureSql . Text.unwords | True if the given ColumnProp sets a default . isDefault :: ColumnProp -> Bool isDefault (Default _) = True isDefault _ = False -- | Get the default value from the given ColumnProps. getDefault :: [ColumnProp] -> Maybe PersistValue getDefault [] = Nothing getDefault (Default v : _) = Just v getDefault (_:props) = getDefault props -- | Show a 'Column'. showColumn :: Column -> MigrateSql showColumn Column{..} = concatSql (\sqls -> Text.unwords $ [quote colName, sqlType] ++ sqls) $ map showColumnProp colProps where sqlType = case (AutoIncrement `elem` colProps, colType) of (True, SqlInt32) -> "SERIAL" (True, SqlInt64) -> "BIGSERIAL" _ -> showSqlType colType | Show a ' SqlType ' . See ` showSqlType ` from ` Database . Persist . Postgresql ` . showSqlType :: SqlType -> Text showSqlType = \case SqlString -> "VARCHAR" SqlInt32 -> "INT4" SqlInt64 -> "INT8" SqlReal -> "DOUBLE PRECISION" SqlNumeric s prec -> Text.concat ["NUMERIC(", showT s, ",", showT prec, ")"] SqlDay -> "DATE" SqlTime -> "TIME" SqlDayTime -> "TIMESTAMP WITH TIME ZONE" SqlBlob -> "BYTEA" SqlBool -> "BOOLEAN" SqlOther (Text.toLower -> "integer") -> "INT4" SqlOther t -> t where showT = Text.pack . show | Show a ' ColumnProp ' . showColumnProp :: ColumnProp -> MigrateSql showColumnProp = \case NotNull -> pureSql "NOT NULL" References (tab, col) -> pureSql $ Text.unwords ["REFERENCES", quote tab, "(", quote col, ")"] AutoIncrement -> pureSql "" Default v -> MigrateSql "DEFAULT ?" [v] | Show a ` TableConstraint ` . showTableConstraint :: TableConstraint -> MigrateSql showTableConstraint = pureSql . \case PrimaryKey cols -> Text.unwords ["PRIMARY KEY (", uncommas' cols, ")"] Unique name cols -> Text.unwords ["CONSTRAINT", quote name, "UNIQUE (", uncommas' cols, ")"]
null
https://raw.githubusercontent.com/brandonchinn178/persistent-migration/dd25379a9ba23e529dcaabc5947c3ad9a4f55110/src/Database/Persist/Migration/Postgres.hs
haskell
# LANGUAGE OverloadedStrings # The CREATE query with the default specified by AddColumn{colDefault} Helpers | Get the default value from the given ColumnProps. | Show a 'Column'.
| Module : Database . Persist . Migration . Postgres Maintainer : < > Stability : experimental Portability : portable Defines the migration backend for PostgreSQL . Module : Database.Persist.Migration.Postgres Maintainer : Brandon Chinn <> Stability : experimental Portability : portable Defines the migration backend for PostgreSQL. -} # LANGUAGE LambdaCase # # LANGUAGE RecordWildCards # # LANGUAGE ViewPatterns # module Database.Persist.Migration.Postgres ( backend , getMigration , runMigration ) where import Data.Maybe (maybeToList) import Data.Text (Text) import qualified Data.Text as Text import Database.Persist.Migration import qualified Database.Persist.Migration.Core as Migration import Database.Persist.Sql (SqlPersistT) | Run a migration with the Postgres backend . runMigration :: MigrateSettings -> Migration -> SqlPersistT IO () runMigration = Migration.runMigration backend | Get a migration with the Postgres backend . getMigration :: MigrateSettings -> Migration -> SqlPersistT IO [MigrateSql] getMigration = Migration.getMigration backend | The migration backend for Postgres . backend :: MigrateBackend backend = MigrateBackend { getMigrationSql = getMigrationSql' } getMigrationSql' :: Operation -> SqlPersistT IO [MigrateSql] getMigrationSql' CreateTable{..} = fromMigrateSql $ mapSql (\sql -> Text.unwords ["CREATE TABLE IF NOT EXISTS", quote name, "(", sql, ")"]) $ concatSql uncommas tableDefs where tableDefs = map showColumn schema ++ map showTableConstraint constraints getMigrationSql' DropTable{..} = fromWords ["DROP TABLE IF EXISTS", quote table] getMigrationSql' RenameTable{..} = fromWords ["ALTER TABLE", quote from, "RENAME TO", quote to] getMigrationSql' AddConstraint{..} = fromWords ["ALTER TABLE", quote table, statement] where statement = case constraint of PrimaryKey cols -> Text.unwords ["ADD PRIMARY KEY (", uncommas' cols, ")"] Unique label cols -> Text.unwords ["ADD CONSTRAINT", quote label, "UNIQUE (", uncommas' cols, ")"] getMigrationSql' DropConstraint{..} = fromWords ["ALTER TABLE", quote table, "DROP CONSTRAINT", constraintName] getMigrationSql' AddColumn{..} = return $ createQuery : maybeToList alterQuery where Column{..} = column alterTable = Text.unwords ["ALTER TABLE", quote table] withoutDefault = showColumn $ column { colProps = filter (not . isDefault) colProps } createDefault = case colDefault of Nothing -> MigrateSql "" [] Just def -> MigrateSql "DEFAULT ?" [def] createQuery = concatSql (\sqls -> Text.unwords $ [alterTable, "ADD COLUMN"] ++ sqls) [withoutDefault, createDefault] The ALTER query to drop / set the default ( if was set ) alterQuery = let action = case getDefault colProps of Nothing -> pureSql "DROP DEFAULT" Just v -> MigrateSql "SET DEFAULT ?" [v] alterQuery' = mapSql (\sql -> Text.unwords [alterTable, "ALTER COLUMN", quote colName, sql]) action in alterQuery' <$ colDefault getMigrationSql' RenameColumn{..} = fromWords ["ALTER TABLE", quote table, "RENAME COLUMN", quote from, "TO", quote to] getMigrationSql' DropColumn{..} = fromWords ["ALTER TABLE", quote tab, "DROP COLUMN", quote col] where (tab, col) = columnId getMigrationSql' RawOperation{..} = rawOp fromMigrateSql :: Monad m => MigrateSql -> m [MigrateSql] fromMigrateSql = return . pure fromWords :: Monad m => [Text] -> m [MigrateSql] fromWords = fromMigrateSql . pureSql . Text.unwords | True if the given ColumnProp sets a default . isDefault :: ColumnProp -> Bool isDefault (Default _) = True isDefault _ = False getDefault :: [ColumnProp] -> Maybe PersistValue getDefault [] = Nothing getDefault (Default v : _) = Just v getDefault (_:props) = getDefault props showColumn :: Column -> MigrateSql showColumn Column{..} = concatSql (\sqls -> Text.unwords $ [quote colName, sqlType] ++ sqls) $ map showColumnProp colProps where sqlType = case (AutoIncrement `elem` colProps, colType) of (True, SqlInt32) -> "SERIAL" (True, SqlInt64) -> "BIGSERIAL" _ -> showSqlType colType | Show a ' SqlType ' . See ` showSqlType ` from ` Database . Persist . Postgresql ` . showSqlType :: SqlType -> Text showSqlType = \case SqlString -> "VARCHAR" SqlInt32 -> "INT4" SqlInt64 -> "INT8" SqlReal -> "DOUBLE PRECISION" SqlNumeric s prec -> Text.concat ["NUMERIC(", showT s, ",", showT prec, ")"] SqlDay -> "DATE" SqlTime -> "TIME" SqlDayTime -> "TIMESTAMP WITH TIME ZONE" SqlBlob -> "BYTEA" SqlBool -> "BOOLEAN" SqlOther (Text.toLower -> "integer") -> "INT4" SqlOther t -> t where showT = Text.pack . show | Show a ' ColumnProp ' . showColumnProp :: ColumnProp -> MigrateSql showColumnProp = \case NotNull -> pureSql "NOT NULL" References (tab, col) -> pureSql $ Text.unwords ["REFERENCES", quote tab, "(", quote col, ")"] AutoIncrement -> pureSql "" Default v -> MigrateSql "DEFAULT ?" [v] | Show a ` TableConstraint ` . showTableConstraint :: TableConstraint -> MigrateSql showTableConstraint = pureSql . \case PrimaryKey cols -> Text.unwords ["PRIMARY KEY (", uncommas' cols, ")"] Unique name cols -> Text.unwords ["CONSTRAINT", quote name, "UNIQUE (", uncommas' cols, ")"]
cf71d42e3fff3e0e2c557c60b2f613061c25f1d9f66740acbd2997269e9f0847
deadpendency/deadpendency
PublishSimpleResultC.hs
module Common.Effect.PublishSimpleResult.Carrier.PublishSimpleResultC ( PublishSimpleResultIOC (..), ) where import Common.Effect.AppEventEmit.AppEventEmit import Common.Effect.AppEventEmit.Model.AppEventMessage import Common.Effect.PublishSimpleResult.Model.SimpleResult import Common.Effect.PublishSimpleResult.PublishSimpleResult (PublishSimpleResult (..)) import Common.Effect.QueueEventPublish.Model.QueueEventPublishRequest import Common.Effect.QueueEventPublish.Model.QueuePayload import Common.Effect.QueueEventPublish.Model.QueueTopicId import Common.Effect.QueueEventPublish.QueueEventPublish import Common.Model.Config.CommonConfig import Common.Model.Error.CommonError import Control.Algebra (Algebra (..), Has, (:+:) (..)) import Control.Effect.Reader (Reader, ask) import Control.Effect.Throw (Throw, liftEither) newtype PublishSimpleResultIOC (p :: Type) m a = PublishSimpleResultIOC {runPublishSimpleResultIOC :: m a} deriving newtype (Functor, Applicative, Monad, MonadIO) instance ( Algebra sig m, Has AppEventEmit sig m, Has (Reader CommonConfig) sig m, Has (Throw CommonError) sig m, Has QueueEventPublish sig m, MonadIO m ) => Algebra (PublishSimpleResult p :+: sig) (PublishSimpleResultIOC p m) where alg hdl sig ctx = case sig of (L (PublishSimpleResult (SimpleResult p))) -> do emitAppEventInfo (AppEventMessage "Started: Publish Simple Result") commonConfig <- ask @CommonConfig pubsubQueueTopicId <- (liftEither . maybeToRight PubSubPublishQueueIdConfigMissing . _downstreamPubSubQueueId) commonConfig let request = QueueEventPublishRequest { _topicId = QueueTopicId pubsubQueueTopicId, _payload = QueuePayload p } publishQueueEvent request emitAppEventInfo (AppEventMessage "Finished: Publish Simple Result") PublishSimpleResultIOC $ pure ctx (R other) -> PublishSimpleResultIOC $ alg (runPublishSimpleResultIOC . hdl) other ctx
null
https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/common/src/Common/Effect/PublishSimpleResult/Carrier/PublishSimpleResultC.hs
haskell
module Common.Effect.PublishSimpleResult.Carrier.PublishSimpleResultC ( PublishSimpleResultIOC (..), ) where import Common.Effect.AppEventEmit.AppEventEmit import Common.Effect.AppEventEmit.Model.AppEventMessage import Common.Effect.PublishSimpleResult.Model.SimpleResult import Common.Effect.PublishSimpleResult.PublishSimpleResult (PublishSimpleResult (..)) import Common.Effect.QueueEventPublish.Model.QueueEventPublishRequest import Common.Effect.QueueEventPublish.Model.QueuePayload import Common.Effect.QueueEventPublish.Model.QueueTopicId import Common.Effect.QueueEventPublish.QueueEventPublish import Common.Model.Config.CommonConfig import Common.Model.Error.CommonError import Control.Algebra (Algebra (..), Has, (:+:) (..)) import Control.Effect.Reader (Reader, ask) import Control.Effect.Throw (Throw, liftEither) newtype PublishSimpleResultIOC (p :: Type) m a = PublishSimpleResultIOC {runPublishSimpleResultIOC :: m a} deriving newtype (Functor, Applicative, Monad, MonadIO) instance ( Algebra sig m, Has AppEventEmit sig m, Has (Reader CommonConfig) sig m, Has (Throw CommonError) sig m, Has QueueEventPublish sig m, MonadIO m ) => Algebra (PublishSimpleResult p :+: sig) (PublishSimpleResultIOC p m) where alg hdl sig ctx = case sig of (L (PublishSimpleResult (SimpleResult p))) -> do emitAppEventInfo (AppEventMessage "Started: Publish Simple Result") commonConfig <- ask @CommonConfig pubsubQueueTopicId <- (liftEither . maybeToRight PubSubPublishQueueIdConfigMissing . _downstreamPubSubQueueId) commonConfig let request = QueueEventPublishRequest { _topicId = QueueTopicId pubsubQueueTopicId, _payload = QueuePayload p } publishQueueEvent request emitAppEventInfo (AppEventMessage "Finished: Publish Simple Result") PublishSimpleResultIOC $ pure ctx (R other) -> PublishSimpleResultIOC $ alg (runPublishSimpleResultIOC . hdl) other ctx
cd9d2229a30497287e909ec570bd58a4be813e9d099dc544a6e77e18c9762a58
elm-lang/elm-reactor
StaticFiles.hs
# OPTIONS_GHC -Wall # # LANGUAGE TemplateHaskell # module StaticFiles ( errors , index, indexPath , notFound, notFoundPath , favicon, faviconPath , waiting, waitingPath ) where import qualified Data.ByteString as BS import Data.FileEmbed (bsToExp) import Language.Haskell.TH (runIO) import System.FilePath ((</>)) import qualified StaticFiles.Build as Build -- PATHS faviconPath :: FilePath faviconPath = "favicon.ico" waitingPath :: FilePath waitingPath = "_reactor" </> "waiting.gif" indexPath :: FilePath indexPath = "_reactor" </> "index.js" notFoundPath :: FilePath notFoundPath = "_reactor" </> "notFound.js" -- RAW RESOURCES errors :: BS.ByteString errors = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "Errors.elm"))) index :: BS.ByteString index = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "Index.elm"))) notFound :: BS.ByteString notFound = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "NotFound.elm"))) favicon :: BS.ByteString favicon = $(bsToExp =<< runIO (BS.readFile ("assets" </> "favicon.ico"))) waiting :: BS.ByteString waiting = $(bsToExp =<< runIO (BS.readFile ("assets" </> "waiting.gif")))
null
https://raw.githubusercontent.com/elm-lang/elm-reactor/6f15395aa307aaaf287919a326f4ffb31bb5eb4a/src/backend/StaticFiles.hs
haskell
PATHS RAW RESOURCES
# OPTIONS_GHC -Wall # # LANGUAGE TemplateHaskell # module StaticFiles ( errors , index, indexPath , notFound, notFoundPath , favicon, faviconPath , waiting, waitingPath ) where import qualified Data.ByteString as BS import Data.FileEmbed (bsToExp) import Language.Haskell.TH (runIO) import System.FilePath ((</>)) import qualified StaticFiles.Build as Build faviconPath :: FilePath faviconPath = "favicon.ico" waitingPath :: FilePath waitingPath = "_reactor" </> "waiting.gif" indexPath :: FilePath indexPath = "_reactor" </> "index.js" notFoundPath :: FilePath notFoundPath = "_reactor" </> "notFound.js" errors :: BS.ByteString errors = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "Errors.elm"))) index :: BS.ByteString index = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "Index.elm"))) notFound :: BS.ByteString notFound = $(bsToExp =<< runIO (Build.compile ("src" </> "pages" </> "NotFound.elm"))) favicon :: BS.ByteString favicon = $(bsToExp =<< runIO (BS.readFile ("assets" </> "favicon.ico"))) waiting :: BS.ByteString waiting = $(bsToExp =<< runIO (BS.readFile ("assets" </> "waiting.gif")))
644869411bf874fc74dfdccfb905a4acd5a45c9cfffe666975ad58f86a1d7416
joinr/spork
primitive.clj
An implementation of segmented paths and primitive . Used as a ;;primitive facility for defining shapes and constructive geometry. Work in progress , should free us from J2d entirely ... (ns spork.graphics2d.primitive (:require [spork.util [vectors :as v]]) (:import [spork.util.vectors vec2 vec3])) (defn ^vec2 ->point ([^double x ^double y] (v/->vec2 x y)) ([p] (v/->vec2 (v/vec-nth p 0) (v/vec-nth p 1)))) (defn ^double point-x [p] (v/vec-nth p 0)) (defn ^double point-y [p] (v/vec-nth p 1)) (def origin (->point 0.0 0.0)) ;;adapted from j2d, not sure i'll need it though. (defn segment-type [^long id] (case id 0 :close 1 :cubic 2 :line 3 :quad 4 :move 5 :even 6 :nonzero)) (defprotocol ISegment (seg-id [s]) (seg-p1 [s]) (seg-p2 [s]) (seg-p3 [s])) (defmacro seg-op [name args body] (let [op-name (symbol (str "seg-" name))] `(defn ~name [~@args] (if (satisfies? ISegment ~'s) (~op-name ~'s) ~body)))) (seg-op id [s] (v/vec-nth s 0)) (seg-op p1 [s] (->point (v/vec-nth s 1) (v/vec-nth s 2))) (seg-op p2 [s] (->point (v/vec-nth s 2) (v/vec-nth s 3))) (seg-op p3 [s] (->point (v/vec-nth s 4) (v/vec-nth s 5))) (defrecord seg [^long id ^vec2 p1 ^vec2 p2 ^vec2 p3] ISegment (seg-id [s] id) (seg-p1 [s] p1) (seg-p2 [s] p2) (seg-p3 [s] p3)) (defn ^seg line-to [xy] (->seg 2 (->point xy) origin origin)) (defn ^seg curve-to [xy control1-xy control2-xy] (->seg 1 (->point xy) (->point control1-xy) (->point control2-xy))) (defn ^seg quad-to [xy control-xy] (->seg 3 (->point xy) (->point control-xy) origin)) (defn ^seg move-to [xy] (->seg 4 (->point xy) origin origin)) (def ^seg close (->seg 0 origin origin origin)) (defn quad-at [s] (p1 s)) (defn quad-through [s] (p2 s)) (defn cube-at [s] (p1 s)) (defn cube-left [s] (p2 s)) (defn cube-right [s] (p3 s)) (defn mid-point [p1 p2] (->point (/ (+ ^double (point-x p1) ^double (point-x p2)) 2.0) (/ (+ ^double (point-y p1) ^double (point-y p2)) 2.0))) (defn divide-quad "Divides a quad segment into two quad segments." [l ctrl r] (let [x1 (point-x l) y1 (point-y l) ctrlx (point-x ctrl) ctrly (point-y ctrl) x2 (point-x r) y2 (point-y r) lc (mid-point l ctrl) ctrlx1 (point-x lc) ctrly1 (point-y lc) cr (mid-point ctrl r) ctrlx2 (point-x cr) ctrly2 (point-y cr) new-ctrl (mid-point lc cr) new-ctrlx (point-x new-ctrl) new-ctrly (point-y new-ctrl)] [x1 y1 ctrlx1 ctrly1 new-ctrlx new-ctrly new-ctrlx new-ctrly ctrlx2 ctrly2 x2 y2])) (defn ^doubles seg->doubles [^seg s] (double-array (into [(:id s) (point-x (:p1 s)) (point-y (:p1 s)) (point-x (:p2 s)) (point-y (:p2 s)) (point-x (:p3 s)) (point-y (:p3 s))]))) (defn ^seg doubles->seg [^doubles xs] (assert (= (alength xs) 7) "Expected a seven-element array.") (->seg (aget xs 0) (->point (aget xs 1) (aget xs 2)) (->point (aget xs 3) (aget xs 4)) (->point (aget xs 5) (aget xs 6)))) ;;a path is defined as a sequence of segments. ;;so...anything can be a path if it can provide a sequence of ;;segments... (defprotocol IPath (get-path [s] "Return a sequence of segments that define the shape.")) (defrecord path [segments] IPath (get-path [s] segments)) (defn as-points [xs] (cond (number? (first xs)) (map #(apply ->point %) (partition 2 xs)) (satisfies? v/IDoubleVector (first xs)) xs :else (throw (Exception. (str "Cannot coerce to 2d point:" (first xs)))))) ;;In progress (comment (defn flatten-quadratic-segment "If s2 defines a segment that is a quad, then we generate a set of points. We recursively subdivide the quadratic curve between (p1 s1), until a desired flatness is achieved or a limit is reached." [limit s1 s2] (let [l (p1 s1) r (quad-at s2) ctrl (quad-through s2) divide-seg ] )) ) (comment ;;if p2 is a cubic, or a quad, we need to flatten it. (defn flatten-path [limit s1 s2] (case (segment-type s2) :cubic (flatten-cubic limit s1 s2) :quad (flatten-quadratic limit s1 s2) nil)) ) (defn ->polygon [coords] (let [pts (as-points coords)] (-> (reduce (fn [acc p] (conj! acc (line-to p))) (transient [(move-to (first pts))]) (rest pts)) (conj! close) (persistent!) (->path)))) ;;so a general path defines a shape like so: gp1 = new ( ) ; gp1.moveTo(50 , 10 ) ; gp1.lineTo(70 , 80 ) ; gp1.lineTo(90 , 40 ) ; gp1.lineTo(10 , 40 ) ; gp1.lineTo(50 , 80 ) ; ;gp1.closePath(); ;;analogously ( ->polygon [ 50 10 70 80 90 40 10 40 50 80 ] ) ;;so, all this came about as a result of trying to reify the existing ;;sketch api into something that can be interpreted into a scene ( for rendering in piccolo2d and friends ) . ;;The original api focused on elements defined in canvas/graphics. ;;around the graphicscontext protocol. ;;in truth, MOST of the drawing calls are fixed around calls to ;;supplemental functions in the canvas ns, ;;namely the with-[] series of graphics swaps. the existing api uses ( with - blah arg1 arg2 .... ) ;;so that we can pipeline the operations through. ;;If we use a protocol-defined context, then we ;;end up with (with-blah ctx arg1 arg2.....) etc. ;;The initial idea was to just implement these ;;with macros and define them per implementation. ;;Another option is to define some way of tagging ;;the graphics operation, via an annotation, so ;;that we can get all the good stuff. ;;Perhaps a better mechanism is just to generate the ;;ast directly, i.e. build the nodes (rather than ;;operate on the graphics canvas itself, recording ;;the instructions as output). ;;This would be more straightforward, and allow us to ;;port to more infrastructures (just define interpreters ;;for the ast to whatever backend). (defmacro swap-graphics [nm ctx-name f new-expr] (let [old (gensym (str "old-" nm)) get (symbol (str "spork.graphics2d.canvas/get-" nm)) set (symbol (str "spork.graphics2d.canvas/set-" nm)) ] `(let [~old (~get ~ctx-name)] (-> (~f (~set ~ctx-name ~new-expr)) (~set ~old))))) ;;original definitions (for now)... (defmacro with-color* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the color of the context if necessary, then reverts to the original color." [color ctx f] `(swap-graphics ~'color ~ctx ~f ~color)) (defmacro with-font* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the color of the context if necessary, then reverts to the original color." [font ctx f] `(swap-graphics ~'font ~ctx ~f (~'spork.graphics2d.font/get-font ~font))) (defmacro with-translation* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the translation of the context, applies f, then undoes the translation." [x y ctx f] `(-> (~f (spork.graphics2d.canvas/translate-2d ~ctx ~x ~y)) (spork.graphics2d.canvas/translate-2d (* -1 ~x) (* -1 ~y)))) (defmacro with-rotation* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the rotation of the context, applies f, then undoes the rotation." [theta ctx f] `(-> (~f (spork.graphics2d.canvas/rotate-2d ~ctx ~theta)) (spork.graphics2d.canvas/rotate-2d (* -1 ~theta)))) (defmacro with-scale* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the translation of the context, applies f, then undoes the translation." [xscale yscale ctx f] `(-> (~f (spork.graphics2d.canvas/scale-2d ~ctx (double ~xscale) (double ~yscale))) (spork.graphics2d.canvas/scale-2d (double (/ 1 ~xscale)) (double (/ 1 ~yscale))))) (defmacro with-transform* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the rotation of the context, applies f, then undoes the rotation." [xform ctx f] `(swap-graphics ~'transform ~ctx ~f ~xform)) (defmacro with-alpha* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the alpha blending of the context, applies f, then undoes the blend." [alpha ctx f] `(swap-graphics ~'alpha ~ctx ~f ~alpha)) (defmacro with-stroke* "Given a drawing function f, where f::IStroked->IStroked, temporarily changes the stroke of the context, applies f, then undoes the blend." [stroke ctx f] `(swap-graphics ~'stroke ~ctx ~f ~stroke)) (defn body [nm args] (let [ex (symbol (str nm "*"))] `(~nm [~@args] ~(macroexpand-1 (macroexpand-1 `(~ex ~@args)))))) (def default-graphics-implementation {:alpha (body 'with-font '[alpha ctx f]) :stroke (body 'with-stroke '[stroke ctx f]) :transform (body 'with-transform '[xform ctx f]) :rotation (body 'with-rotation '[theta ctx f]) :scale (body 'with-scale '[xscale yscale ctx f]) :translation (body 'with-translation '[x y ctx f]) :color (body 'with-color '[color ctx f]) :font (body 'with-font '[font ctx f])})
null
https://raw.githubusercontent.com/joinr/spork/bb80eddadf90bf92745bf5315217e25a99fbf9d6/src/spork/graphics2d/primitive.clj
clojure
primitive facility for defining shapes and constructive geometry. adapted from j2d, not sure i'll need it though. a path is defined as a sequence of segments. so...anything can be a path if it can provide a sequence of segments... In progress if p2 is a cubic, or a quad, we need to flatten it. so a general path defines a shape like so: gp1.closePath(); analogously so, all this came about as a result of trying to reify the existing sketch api into something that can be interpreted into a scene The original api focused on elements defined in canvas/graphics. around the graphicscontext protocol. in truth, MOST of the drawing calls are fixed around calls to supplemental functions in the canvas ns, namely the with-[] series of graphics swaps. so that we can pipeline the operations through. If we use a protocol-defined context, then we end up with (with-blah ctx arg1 arg2.....) etc. The initial idea was to just implement these with macros and define them per implementation. Another option is to define some way of tagging the graphics operation, via an annotation, so that we can get all the good stuff. Perhaps a better mechanism is just to generate the ast directly, i.e. build the nodes (rather than operate on the graphics canvas itself, recording the instructions as output). This would be more straightforward, and allow us to port to more infrastructures (just define interpreters for the ast to whatever backend). original definitions (for now)...
An implementation of segmented paths and primitive . Used as a Work in progress , should free us from J2d entirely ... (ns spork.graphics2d.primitive (:require [spork.util [vectors :as v]]) (:import [spork.util.vectors vec2 vec3])) (defn ^vec2 ->point ([^double x ^double y] (v/->vec2 x y)) ([p] (v/->vec2 (v/vec-nth p 0) (v/vec-nth p 1)))) (defn ^double point-x [p] (v/vec-nth p 0)) (defn ^double point-y [p] (v/vec-nth p 1)) (def origin (->point 0.0 0.0)) (defn segment-type [^long id] (case id 0 :close 1 :cubic 2 :line 3 :quad 4 :move 5 :even 6 :nonzero)) (defprotocol ISegment (seg-id [s]) (seg-p1 [s]) (seg-p2 [s]) (seg-p3 [s])) (defmacro seg-op [name args body] (let [op-name (symbol (str "seg-" name))] `(defn ~name [~@args] (if (satisfies? ISegment ~'s) (~op-name ~'s) ~body)))) (seg-op id [s] (v/vec-nth s 0)) (seg-op p1 [s] (->point (v/vec-nth s 1) (v/vec-nth s 2))) (seg-op p2 [s] (->point (v/vec-nth s 2) (v/vec-nth s 3))) (seg-op p3 [s] (->point (v/vec-nth s 4) (v/vec-nth s 5))) (defrecord seg [^long id ^vec2 p1 ^vec2 p2 ^vec2 p3] ISegment (seg-id [s] id) (seg-p1 [s] p1) (seg-p2 [s] p2) (seg-p3 [s] p3)) (defn ^seg line-to [xy] (->seg 2 (->point xy) origin origin)) (defn ^seg curve-to [xy control1-xy control2-xy] (->seg 1 (->point xy) (->point control1-xy) (->point control2-xy))) (defn ^seg quad-to [xy control-xy] (->seg 3 (->point xy) (->point control-xy) origin)) (defn ^seg move-to [xy] (->seg 4 (->point xy) origin origin)) (def ^seg close (->seg 0 origin origin origin)) (defn quad-at [s] (p1 s)) (defn quad-through [s] (p2 s)) (defn cube-at [s] (p1 s)) (defn cube-left [s] (p2 s)) (defn cube-right [s] (p3 s)) (defn mid-point [p1 p2] (->point (/ (+ ^double (point-x p1) ^double (point-x p2)) 2.0) (/ (+ ^double (point-y p1) ^double (point-y p2)) 2.0))) (defn divide-quad "Divides a quad segment into two quad segments." [l ctrl r] (let [x1 (point-x l) y1 (point-y l) ctrlx (point-x ctrl) ctrly (point-y ctrl) x2 (point-x r) y2 (point-y r) lc (mid-point l ctrl) ctrlx1 (point-x lc) ctrly1 (point-y lc) cr (mid-point ctrl r) ctrlx2 (point-x cr) ctrly2 (point-y cr) new-ctrl (mid-point lc cr) new-ctrlx (point-x new-ctrl) new-ctrly (point-y new-ctrl)] [x1 y1 ctrlx1 ctrly1 new-ctrlx new-ctrly new-ctrlx new-ctrly ctrlx2 ctrly2 x2 y2])) (defn ^doubles seg->doubles [^seg s] (double-array (into [(:id s) (point-x (:p1 s)) (point-y (:p1 s)) (point-x (:p2 s)) (point-y (:p2 s)) (point-x (:p3 s)) (point-y (:p3 s))]))) (defn ^seg doubles->seg [^doubles xs] (assert (= (alength xs) 7) "Expected a seven-element array.") (->seg (aget xs 0) (->point (aget xs 1) (aget xs 2)) (->point (aget xs 3) (aget xs 4)) (->point (aget xs 5) (aget xs 6)))) (defprotocol IPath (get-path [s] "Return a sequence of segments that define the shape.")) (defrecord path [segments] IPath (get-path [s] segments)) (defn as-points [xs] (cond (number? (first xs)) (map #(apply ->point %) (partition 2 xs)) (satisfies? v/IDoubleVector (first xs)) xs :else (throw (Exception. (str "Cannot coerce to 2d point:" (first xs)))))) (comment (defn flatten-quadratic-segment "If s2 defines a segment that is a quad, then we generate a set of points. We recursively subdivide the quadratic curve between (p1 s1), until a desired flatness is achieved or a limit is reached." [limit s1 s2] (let [l (p1 s1) r (quad-at s2) ctrl (quad-through s2) divide-seg ] )) ) (comment (defn flatten-path [limit s1 s2] (case (segment-type s2) :cubic (flatten-cubic limit s1 s2) :quad (flatten-quadratic limit s1 s2) nil)) ) (defn ->polygon [coords] (let [pts (as-points coords)] (-> (reduce (fn [acc p] (conj! acc (line-to p))) (transient [(move-to (first pts))]) (rest pts)) (conj! close) (persistent!) (->path)))) ( ->polygon [ 50 10 70 80 90 40 10 40 50 80 ] ) ( for rendering in piccolo2d and friends ) . the existing api uses ( with - blah arg1 arg2 .... ) (defmacro swap-graphics [nm ctx-name f new-expr] (let [old (gensym (str "old-" nm)) get (symbol (str "spork.graphics2d.canvas/get-" nm)) set (symbol (str "spork.graphics2d.canvas/set-" nm)) ] `(let [~old (~get ~ctx-name)] (-> (~f (~set ~ctx-name ~new-expr)) (~set ~old))))) (defmacro with-color* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the color of the context if necessary, then reverts to the original color." [color ctx f] `(swap-graphics ~'color ~ctx ~f ~color)) (defmacro with-font* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the color of the context if necessary, then reverts to the original color." [font ctx f] `(swap-graphics ~'font ~ctx ~f (~'spork.graphics2d.font/get-font ~font))) (defmacro with-translation* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the translation of the context, applies f, then undoes the translation." [x y ctx f] `(-> (~f (spork.graphics2d.canvas/translate-2d ~ctx ~x ~y)) (spork.graphics2d.canvas/translate-2d (* -1 ~x) (* -1 ~y)))) (defmacro with-rotation* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the rotation of the context, applies f, then undoes the rotation." [theta ctx f] `(-> (~f (spork.graphics2d.canvas/rotate-2d ~ctx ~theta)) (spork.graphics2d.canvas/rotate-2d (* -1 ~theta)))) (defmacro with-scale* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the translation of the context, applies f, then undoes the translation." [xscale yscale ctx f] `(-> (~f (spork.graphics2d.canvas/scale-2d ~ctx (double ~xscale) (double ~yscale))) (spork.graphics2d.canvas/scale-2d (double (/ 1 ~xscale)) (double (/ 1 ~yscale))))) (defmacro with-transform* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the rotation of the context, applies f, then undoes the rotation." [xform ctx f] `(swap-graphics ~'transform ~ctx ~f ~xform)) (defmacro with-alpha* "Given a drawing function f, where f::IGraphicsContext->IGraphicsContext, temporarily changes the alpha blending of the context, applies f, then undoes the blend." [alpha ctx f] `(swap-graphics ~'alpha ~ctx ~f ~alpha)) (defmacro with-stroke* "Given a drawing function f, where f::IStroked->IStroked, temporarily changes the stroke of the context, applies f, then undoes the blend." [stroke ctx f] `(swap-graphics ~'stroke ~ctx ~f ~stroke)) (defn body [nm args] (let [ex (symbol (str nm "*"))] `(~nm [~@args] ~(macroexpand-1 (macroexpand-1 `(~ex ~@args)))))) (def default-graphics-implementation {:alpha (body 'with-font '[alpha ctx f]) :stroke (body 'with-stroke '[stroke ctx f]) :transform (body 'with-transform '[xform ctx f]) :rotation (body 'with-rotation '[theta ctx f]) :scale (body 'with-scale '[xscale yscale ctx f]) :translation (body 'with-translation '[x y ctx f]) :color (body 'with-color '[color ctx f]) :font (body 'with-font '[font ctx f])})
8142caf18975405adc527d855f84d78e16ccd1e33a2d4177f519ef960597eb74
mpickering/eventlog-live
Main.hs
module Main where import qualified MyLib (someFunc) main :: IO () main = do putStrLn "Hello, Haskell!" MyLib.someFunc
null
https://raw.githubusercontent.com/mpickering/eventlog-live/e13f2bc32a9cc66a0a8b7c88241b70fe785dc5a7/ekg-eventlog-influxdb/Main.hs
haskell
module Main where import qualified MyLib (someFunc) main :: IO () main = do putStrLn "Hello, Haskell!" MyLib.someFunc
8c9c4a89d17c19bec76e8662cf4009ebe57dc75edbdec6a6482a965234e7a42e
emqx/emqx
emqx_connector_ldap.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_connector_ldap). -include("emqx_connector.hrl"). -include_lib("typerefl/include/types.hrl"). -include_lib("emqx/include/logger.hrl"). -export([roots/0, fields/1]). -behaviour(emqx_resource). %% callbacks of behaviour emqx_resource -export([ callback_mode/0, on_start/2, on_stop/2, on_query/3, on_get_status/2 ]). -export([connect/1]). -export([search/4]). %% port is not expected from configuration because %% all servers expected to use the same port number -define(LDAP_HOST_OPTIONS, #{no_port => true}). %%===================================================================== roots() -> ldap_fields() ++ emqx_connector_schema_lib:ssl_fields(). %% this schema has no sub-structs fields(_) -> []. %% =================================================================== callback_mode() -> always_sync. on_start( InstId, #{ servers := Servers0, port := Port, bind_dn := BindDn, bind_password := BindPassword, timeout := Timeout, pool_size := PoolSize, ssl := SSL } = Config ) -> ?SLOG(info, #{ msg => "starting_ldap_connector", connector => InstId, config => emqx_misc:redact(Config) }), Servers = emqx_schema:parse_servers(Servers0, ?LDAP_HOST_OPTIONS), SslOpts = case maps:get(enable, SSL) of true -> [ {ssl, true}, {sslopts, emqx_tls_lib:to_client_opts(SSL)} ]; false -> [{ssl, false}] end, Opts = [ {servers, Servers}, {port, Port}, {bind_dn, BindDn}, {bind_password, BindPassword}, {timeout, Timeout}, {pool_size, PoolSize}, {auto_reconnect, ?AUTO_RECONNECT_INTERVAL} ], PoolName = emqx_plugin_libs_pool:pool_name(InstId), case emqx_plugin_libs_pool:start_pool(PoolName, ?MODULE, Opts ++ SslOpts) of ok -> {ok, #{poolname => PoolName}}; {error, Reason} -> {error, Reason} end. on_stop(InstId, #{poolname := PoolName}) -> ?SLOG(info, #{ msg => "stopping_ldap_connector", connector => InstId }), emqx_plugin_libs_pool:stop_pool(PoolName). on_query(InstId, {search, Base, Filter, Attributes}, #{poolname := PoolName} = State) -> Request = {Base, Filter, Attributes}, ?TRACE( "QUERY", "ldap_connector_received", #{request => Request, connector => InstId, state => State} ), case Result = ecpool:pick_and_do( PoolName, {?MODULE, search, [Base, Filter, Attributes]}, no_handover ) of {error, Reason} -> ?SLOG(error, #{ msg => "ldap_connector_do_request_failed", request => Request, connector => InstId, reason => Reason }); _ -> ok end, Result. on_get_status(_InstId, _State) -> connected. search(Conn, Base, Filter, Attributes) -> eldap2:search(Conn, [ {base, Base}, {filter, Filter}, {attributes, Attributes}, {deref, eldap2:'derefFindingBaseObj'()} ]). %% =================================================================== connect(Opts) -> Servers = proplists:get_value(servers, Opts, ["localhost"]), Port = proplists:get_value(port, Opts, 389), Timeout = proplists:get_value(timeout, Opts, 30), BindDn = proplists:get_value(bind_dn, Opts), BindPassword = proplists:get_value(bind_password, Opts), SslOpts = case proplists:get_value(ssl, Opts, false) of true -> [{sslopts, proplists:get_value(sslopts, Opts, [])}, {ssl, true}]; false -> [{ssl, false}] end, LdapOpts = [ {port, Port}, {timeout, Timeout} ] ++ SslOpts, {ok, LDAP} = eldap2:open(Servers, LdapOpts), ok = eldap2:simple_bind(LDAP, BindDn, BindPassword), {ok, LDAP}. ldap_fields() -> [ {servers, servers()}, {port, fun port/1}, {pool_size, fun emqx_connector_schema_lib:pool_size/1}, {bind_dn, fun bind_dn/1}, {bind_password, fun emqx_connector_schema_lib:password/1}, {timeout, fun duration/1}, {auto_reconnect, fun emqx_connector_schema_lib:auto_reconnect/1} ]. servers() -> emqx_schema:servers_sc(#{}, ?LDAP_HOST_OPTIONS). bind_dn(type) -> binary(); bind_dn(default) -> 0; bind_dn(_) -> undefined. port(type) -> integer(); port(default) -> 389; port(_) -> undefined. duration(type) -> emqx_schema:duration_ms(); duration(_) -> undefined.
null
https://raw.githubusercontent.com/emqx/emqx/370b6b0d2f00c2fcc202104a5c117d8fd5a0e9da/apps/emqx_connector/src/emqx_connector_ldap.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. -------------------------------------------------------------------- callbacks of behaviour emqx_resource port is not expected from configuration because all servers expected to use the same port number ===================================================================== this schema has no sub-structs =================================================================== ===================================================================
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_connector_ldap). -include("emqx_connector.hrl"). -include_lib("typerefl/include/types.hrl"). -include_lib("emqx/include/logger.hrl"). -export([roots/0, fields/1]). -behaviour(emqx_resource). -export([ callback_mode/0, on_start/2, on_stop/2, on_query/3, on_get_status/2 ]). -export([connect/1]). -export([search/4]). -define(LDAP_HOST_OPTIONS, #{no_port => true}). roots() -> ldap_fields() ++ emqx_connector_schema_lib:ssl_fields(). fields(_) -> []. callback_mode() -> always_sync. on_start( InstId, #{ servers := Servers0, port := Port, bind_dn := BindDn, bind_password := BindPassword, timeout := Timeout, pool_size := PoolSize, ssl := SSL } = Config ) -> ?SLOG(info, #{ msg => "starting_ldap_connector", connector => InstId, config => emqx_misc:redact(Config) }), Servers = emqx_schema:parse_servers(Servers0, ?LDAP_HOST_OPTIONS), SslOpts = case maps:get(enable, SSL) of true -> [ {ssl, true}, {sslopts, emqx_tls_lib:to_client_opts(SSL)} ]; false -> [{ssl, false}] end, Opts = [ {servers, Servers}, {port, Port}, {bind_dn, BindDn}, {bind_password, BindPassword}, {timeout, Timeout}, {pool_size, PoolSize}, {auto_reconnect, ?AUTO_RECONNECT_INTERVAL} ], PoolName = emqx_plugin_libs_pool:pool_name(InstId), case emqx_plugin_libs_pool:start_pool(PoolName, ?MODULE, Opts ++ SslOpts) of ok -> {ok, #{poolname => PoolName}}; {error, Reason} -> {error, Reason} end. on_stop(InstId, #{poolname := PoolName}) -> ?SLOG(info, #{ msg => "stopping_ldap_connector", connector => InstId }), emqx_plugin_libs_pool:stop_pool(PoolName). on_query(InstId, {search, Base, Filter, Attributes}, #{poolname := PoolName} = State) -> Request = {Base, Filter, Attributes}, ?TRACE( "QUERY", "ldap_connector_received", #{request => Request, connector => InstId, state => State} ), case Result = ecpool:pick_and_do( PoolName, {?MODULE, search, [Base, Filter, Attributes]}, no_handover ) of {error, Reason} -> ?SLOG(error, #{ msg => "ldap_connector_do_request_failed", request => Request, connector => InstId, reason => Reason }); _ -> ok end, Result. on_get_status(_InstId, _State) -> connected. search(Conn, Base, Filter, Attributes) -> eldap2:search(Conn, [ {base, Base}, {filter, Filter}, {attributes, Attributes}, {deref, eldap2:'derefFindingBaseObj'()} ]). connect(Opts) -> Servers = proplists:get_value(servers, Opts, ["localhost"]), Port = proplists:get_value(port, Opts, 389), Timeout = proplists:get_value(timeout, Opts, 30), BindDn = proplists:get_value(bind_dn, Opts), BindPassword = proplists:get_value(bind_password, Opts), SslOpts = case proplists:get_value(ssl, Opts, false) of true -> [{sslopts, proplists:get_value(sslopts, Opts, [])}, {ssl, true}]; false -> [{ssl, false}] end, LdapOpts = [ {port, Port}, {timeout, Timeout} ] ++ SslOpts, {ok, LDAP} = eldap2:open(Servers, LdapOpts), ok = eldap2:simple_bind(LDAP, BindDn, BindPassword), {ok, LDAP}. ldap_fields() -> [ {servers, servers()}, {port, fun port/1}, {pool_size, fun emqx_connector_schema_lib:pool_size/1}, {bind_dn, fun bind_dn/1}, {bind_password, fun emqx_connector_schema_lib:password/1}, {timeout, fun duration/1}, {auto_reconnect, fun emqx_connector_schema_lib:auto_reconnect/1} ]. servers() -> emqx_schema:servers_sc(#{}, ?LDAP_HOST_OPTIONS). bind_dn(type) -> binary(); bind_dn(default) -> 0; bind_dn(_) -> undefined. port(type) -> integer(); port(default) -> 389; port(_) -> undefined. duration(type) -> emqx_schema:duration_ms(); duration(_) -> undefined.
f0c549c231fb44e4a530668b6615d878a056d018bf4610da01c34256e350d406
jjhenkel/lsee
executionTree.ml
open Abstractions;; open Expressions;; module SS = Set.Make(String) open BatString;; module ExecutionTree = struct type t = { mutable a: (Abstractions.t list); mutable pr: (int, SS.t) Hashtbl.t; d: int; i: Z.t; mutable c: (t list); mutable p: bool; } let empty () = { a = []; pr = Hashtbl.create 5012; d = 0; i = Z.zero; c = []; p = true; } let create a pr d i = { a = a; pr = pr; d; i; c = [ ]; p = true; } let currentpr t = let rec worker t' = if t'.p == true then Some t'.pr else match t'.c with | [] -> None | c -> List.fold_left ( fun acc t'' -> match (worker t'') with | Some v -> Some v | None -> acc ) None c in match (worker t) with | Some v -> v | None -> raise (Invalid_argument "Should be impossible") let push t c = let rec worker t' c' = if t'.p == true then let _ = t'.c <- c' :: t'.c in let _ = t'.p <- false in (c'.p <- true ; c'.pr <- t'.pr) else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' c') c in worker t c let append t c = let rec worker t' c' = if t'.p == true then (t'.a <- t'.a @ c'.a ; Hashtbl.iter (fun k a -> match Hashtbl.find_opt t'.pr k with | Some s -> Hashtbl.replace t'.pr k (SS.union s a) | None -> Hashtbl.add t'.pr k a ) c'.pr ) else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' c') c in worker t c let rec pop t = let rec worker t' l = if t'.p == true then let _ = t'.p <- false in let _ = l.p <- true May need to move more than one level up in if (List.length l.c) == l.d then pop t else () else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' t') c in worker t t let pprint tree = let print_abs a d = let _ = print_string ((String.make (2*d) ' ') ^ "+ ") in List.iteri (fun i x -> if i == 0 then Abstractions.pprint "" x else Abstractions.pprint (String.make (2*(d+1)) ' ') x ) a in let rec worker t' d = match t'.c with | [] -> print_abs t'.a d ; print_endline "" | c -> print_abs t'.a d ; print_endline "" ; List.iter (fun t'' -> worker t'' (d+1) ;) c in worker tree 0 let rec final_cleanup traces = match traces with | [] -> [] | x :: xs -> if (BatString.exists x "__builtin_unreachable") then (final_cleanup xs) else if (BatString.is_empty (BatString.trim x)) then (final_cleanup xs) else x :: (final_cleanup xs) (* Todo: try a version that only keeps N parents of context when writing a trace to disk. This will remove the crazy buildup of shared prefixes that can be detrimental to the models. *) Traces where we only keep data from one parent let traces1 tree = let rec worker t' trace = let temp = String.trim (List.fold_left (fun acc a -> acc ^ (Abstractions.to_string a) ^ " ") "" t'.a ) in match t'.c with | [] -> [ String.trim (trace ^ " " ^ temp)] | c -> [ String.trim (trace ^ " " ^ temp) ] @ List.flatten ( List.map (fun t'' -> worker t'' temp) c ) in let res = (worker tree "") in let final = (final_cleanup res) in match final with | [] -> () | xs -> List.iter (fun s -> print_endline (String.trim s)) xs let traces name tree = let rec worker t' trace = let temp = String.trim (List.fold_left (fun acc a -> acc ^ (Abstractions.to_string a) ^ " ") "" t'.a ) in match t'.c with | [] -> [ String.trim (trace ^ " " ^ temp) ] | c -> List.flatten (List.map (fun t'' -> worker t'' (String.trim (trace ^ " " ^ temp))) c) in let res = (worker tree "") in let final = (final_cleanup res) in let rgx = Str.regexp " +" in let clean s = (String.trim (Str.global_replace rgx " " s)) in match final with | [] -> () | xs -> List.iter (fun s -> print_endline (name ^ " " ^ (clean s))) xs end
null
https://raw.githubusercontent.com/jjhenkel/lsee/3255b4f61197e0fd816ac2e9ac1c97dbb72726a6/lib/executionTree.ml
ocaml
Todo: try a version that only keeps N parents of context when writing a trace to disk. This will remove the crazy buildup of shared prefixes that can be detrimental to the models.
open Abstractions;; open Expressions;; module SS = Set.Make(String) open BatString;; module ExecutionTree = struct type t = { mutable a: (Abstractions.t list); mutable pr: (int, SS.t) Hashtbl.t; d: int; i: Z.t; mutable c: (t list); mutable p: bool; } let empty () = { a = []; pr = Hashtbl.create 5012; d = 0; i = Z.zero; c = []; p = true; } let create a pr d i = { a = a; pr = pr; d; i; c = [ ]; p = true; } let currentpr t = let rec worker t' = if t'.p == true then Some t'.pr else match t'.c with | [] -> None | c -> List.fold_left ( fun acc t'' -> match (worker t'') with | Some v -> Some v | None -> acc ) None c in match (worker t) with | Some v -> v | None -> raise (Invalid_argument "Should be impossible") let push t c = let rec worker t' c' = if t'.p == true then let _ = t'.c <- c' :: t'.c in let _ = t'.p <- false in (c'.p <- true ; c'.pr <- t'.pr) else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' c') c in worker t c let append t c = let rec worker t' c' = if t'.p == true then (t'.a <- t'.a @ c'.a ; Hashtbl.iter (fun k a -> match Hashtbl.find_opt t'.pr k with | Some s -> Hashtbl.replace t'.pr k (SS.union s a) | None -> Hashtbl.add t'.pr k a ) c'.pr ) else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' c') c in worker t c let rec pop t = let rec worker t' l = if t'.p == true then let _ = t'.p <- false in let _ = l.p <- true May need to move more than one level up in if (List.length l.c) == l.d then pop t else () else match t'.c with | [] -> () | c -> List.iter (fun t'' -> worker t'' t') c in worker t t let pprint tree = let print_abs a d = let _ = print_string ((String.make (2*d) ' ') ^ "+ ") in List.iteri (fun i x -> if i == 0 then Abstractions.pprint "" x else Abstractions.pprint (String.make (2*(d+1)) ' ') x ) a in let rec worker t' d = match t'.c with | [] -> print_abs t'.a d ; print_endline "" | c -> print_abs t'.a d ; print_endline "" ; List.iter (fun t'' -> worker t'' (d+1) ;) c in worker tree 0 let rec final_cleanup traces = match traces with | [] -> [] | x :: xs -> if (BatString.exists x "__builtin_unreachable") then (final_cleanup xs) else if (BatString.is_empty (BatString.trim x)) then (final_cleanup xs) else x :: (final_cleanup xs) Traces where we only keep data from one parent let traces1 tree = let rec worker t' trace = let temp = String.trim (List.fold_left (fun acc a -> acc ^ (Abstractions.to_string a) ^ " ") "" t'.a ) in match t'.c with | [] -> [ String.trim (trace ^ " " ^ temp)] | c -> [ String.trim (trace ^ " " ^ temp) ] @ List.flatten ( List.map (fun t'' -> worker t'' temp) c ) in let res = (worker tree "") in let final = (final_cleanup res) in match final with | [] -> () | xs -> List.iter (fun s -> print_endline (String.trim s)) xs let traces name tree = let rec worker t' trace = let temp = String.trim (List.fold_left (fun acc a -> acc ^ (Abstractions.to_string a) ^ " ") "" t'.a ) in match t'.c with | [] -> [ String.trim (trace ^ " " ^ temp) ] | c -> List.flatten (List.map (fun t'' -> worker t'' (String.trim (trace ^ " " ^ temp))) c) in let res = (worker tree "") in let final = (final_cleanup res) in let rgx = Str.regexp " +" in let clean s = (String.trim (Str.global_replace rgx " " s)) in match final with | [] -> () | xs -> List.iter (fun s -> print_endline (name ^ " " ^ (clean s))) xs end
628b4ce6b2625ece9ec9a2aa25cff75a6035a411e66dfeff296a40f8dc5a4ed0
jamis/rtc-ocaml
RTCConic.ml
let parameters_of (shape:RTCShape.t) = match shape.shape with | Cylinder (minimum, maximum, closed) -> (minimum, maximum, closed) | Cone (minimum, maximum, closed) -> (minimum, maximum, closed) | _ -> failwith "expected a cylinder or cone" let intersect_caps trail shape min max closed (ray:RTCRay.t) radius_at xs = let check_cap t radius = let x = ray.origin.x +. t *. ray.direction.x and z = ray.origin.z +. t *. ray.direction.z in (x ** 2. +. z ** 2.) <= radius ** 2. in if (not closed) || ((abs_float ray.direction.y) < RTCConst.epsilon) then xs else let xs' = let t = (min -. ray.origin.y) /. ray.direction.y in if check_cap t (radius_at min) then (RTCIntersection.build t shape trail) :: xs else xs in let t = (max -. ray.origin.y) /. ray.direction.y in if check_cap t (radius_at max) then (RTCIntersection.build t shape trail) :: xs' else xs' let intersect (shape:RTCShape.t) ?(trail=[]) (r:RTCRay.t) afn bfn cfn radius_at = let (minimum, maximum, closed) = parameters_of shape in let a = afn r in let b = bfn r in let xs = if (abs_float a) < RTCConst.epsilon then if (abs_float b) < RTCConst.epsilon then [] else let c = cfn r in let t = (-.c) /. (2. *. b) in [ RTCIntersection.build t shape trail ] else let c = cfn r in let disc = b ** 2. -. 4. *. a *. c in if disc < 0. then [] else let root = sqrt disc in let t0 = (-.b -. root) /. (2. *. a) and t1 = (-.b +. root) /. (2. *. a) in let xs = let y = r.origin.y +. t1 *. r.direction.y in if minimum < y && y < maximum then [ RTCIntersection.build t1 shape trail ] else [] in let y = r.origin.y +. t0 *. r.direction.y in if minimum < y && y < maximum then (RTCIntersection.build t0 shape trail) :: xs else xs in RTCIntersection.list (intersect_caps trail shape minimum maximum closed r radius_at xs) let normal_at shape (point:RTCTuple.t) nfn = let (minimum, maximum, _) = parameters_of shape in let dist = point.x ** 2. +. point.z ** 2. in if dist < 1. && point.y >= maximum -. RTCConst.epsilon then RTCTuple.vector 0. 1. 0. else if dist < 1. && point.y <= minimum +. RTCConst.epsilon then RTCTuple.vector 0. (-1.) 0. else nfn point
null
https://raw.githubusercontent.com/jamis/rtc-ocaml/f5ba04e874ef0b54d100cdabfe9a67c2b80a643f/src/RTCConic.ml
ocaml
let parameters_of (shape:RTCShape.t) = match shape.shape with | Cylinder (minimum, maximum, closed) -> (minimum, maximum, closed) | Cone (minimum, maximum, closed) -> (minimum, maximum, closed) | _ -> failwith "expected a cylinder or cone" let intersect_caps trail shape min max closed (ray:RTCRay.t) radius_at xs = let check_cap t radius = let x = ray.origin.x +. t *. ray.direction.x and z = ray.origin.z +. t *. ray.direction.z in (x ** 2. +. z ** 2.) <= radius ** 2. in if (not closed) || ((abs_float ray.direction.y) < RTCConst.epsilon) then xs else let xs' = let t = (min -. ray.origin.y) /. ray.direction.y in if check_cap t (radius_at min) then (RTCIntersection.build t shape trail) :: xs else xs in let t = (max -. ray.origin.y) /. ray.direction.y in if check_cap t (radius_at max) then (RTCIntersection.build t shape trail) :: xs' else xs' let intersect (shape:RTCShape.t) ?(trail=[]) (r:RTCRay.t) afn bfn cfn radius_at = let (minimum, maximum, closed) = parameters_of shape in let a = afn r in let b = bfn r in let xs = if (abs_float a) < RTCConst.epsilon then if (abs_float b) < RTCConst.epsilon then [] else let c = cfn r in let t = (-.c) /. (2. *. b) in [ RTCIntersection.build t shape trail ] else let c = cfn r in let disc = b ** 2. -. 4. *. a *. c in if disc < 0. then [] else let root = sqrt disc in let t0 = (-.b -. root) /. (2. *. a) and t1 = (-.b +. root) /. (2. *. a) in let xs = let y = r.origin.y +. t1 *. r.direction.y in if minimum < y && y < maximum then [ RTCIntersection.build t1 shape trail ] else [] in let y = r.origin.y +. t0 *. r.direction.y in if minimum < y && y < maximum then (RTCIntersection.build t0 shape trail) :: xs else xs in RTCIntersection.list (intersect_caps trail shape minimum maximum closed r radius_at xs) let normal_at shape (point:RTCTuple.t) nfn = let (minimum, maximum, _) = parameters_of shape in let dist = point.x ** 2. +. point.z ** 2. in if dist < 1. && point.y >= maximum -. RTCConst.epsilon then RTCTuple.vector 0. 1. 0. else if dist < 1. && point.y <= minimum +. RTCConst.epsilon then RTCTuple.vector 0. (-1.) 0. else nfn point
32fc87b753738e3a08f40b22e6fef5b567c34b33bc5def4c03a00f8c9c9b30ee
ghc/nofib
Displacement.hs
Glasow Haskell 0.403 : FINITE ELEMENT PROGRAM V2 -- ********************************************************************** -- * * * FILE NAME : displacement.hs DATE : 13 - 3 - 1991 * -- * * -- * CONTENTS : Compute nodal displacement of the structure. * -- * * -- ********************************************************************** module Displacement ( uvw, getnuvw ) where import Basics import Vector import Matrix import VBmatrix import VBlldecomp import DB_interface import Degrees import Pre_assemble import Assemble_stiffness import Assemble_loadvec uvw :: (Array Int Int, Array Int Float) -> Vec Float getnuvw :: (Array Int Int, Array Int Float) -> Int -> Vec Float -> (Float, Float, Float) t_Ub s = vbllsolution (kdd s) (loadvec s) uvw s = incrvec initial_value index_value_assoc where initial_value = makevec ( 3 * (nnode s) ) ( \ i -> 0.0 ) index_value_assoc = concat (map f_s [1..(nnode s)]) f_s = f s tUb tUb = t_Ub s f s tUb node = azip [l,l+1,l+2] (map ff dgrs) where l = 3 * (node - 1) + 1 dgrs = getndgr s node ff i = if ( i == 0 ) then 0.0 else vecsub tUb i getnuvw s node uvw = (u,v,theta) where u = vecsub uvw index v = vecsub uvw (index+1) theta = vecsub uvw (index+2) index = 3 * (node - 1) + 1
null
https://raw.githubusercontent.com/ghc/nofib/f34b90b5a6ce46284693119a06d1133908b11856/real/fem/Displacement.hs
haskell
********************************************************************** * * * * * CONTENTS : Compute nodal displacement of the structure. * * * **********************************************************************
Glasow Haskell 0.403 : FINITE ELEMENT PROGRAM V2 * FILE NAME : displacement.hs DATE : 13 - 3 - 1991 * module Displacement ( uvw, getnuvw ) where import Basics import Vector import Matrix import VBmatrix import VBlldecomp import DB_interface import Degrees import Pre_assemble import Assemble_stiffness import Assemble_loadvec uvw :: (Array Int Int, Array Int Float) -> Vec Float getnuvw :: (Array Int Int, Array Int Float) -> Int -> Vec Float -> (Float, Float, Float) t_Ub s = vbllsolution (kdd s) (loadvec s) uvw s = incrvec initial_value index_value_assoc where initial_value = makevec ( 3 * (nnode s) ) ( \ i -> 0.0 ) index_value_assoc = concat (map f_s [1..(nnode s)]) f_s = f s tUb tUb = t_Ub s f s tUb node = azip [l,l+1,l+2] (map ff dgrs) where l = 3 * (node - 1) + 1 dgrs = getndgr s node ff i = if ( i == 0 ) then 0.0 else vecsub tUb i getnuvw s node uvw = (u,v,theta) where u = vecsub uvw index v = vecsub uvw (index+1) theta = vecsub uvw (index+2) index = 3 * (node - 1) + 1
ba9be9cb027b444d3009efd15b40795022dd91be45f551eb9e4ccfe0f98ae58d
rtoy/cmucl
move.lisp
;;; -*- Package: HPPA -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; (ext:file-comment "$Header: src/compiler/hppa/move.lisp $") ;;; ;;; ********************************************************************** ;;; ;;; This file contains the HPPA VM definition of operand loading/saving and the Move VOP . ;;; Written by . ;;; (in-package "HPPA") (define-move-function (load-immediate 1) (vop x y) ((null zero immediate) (any-reg descriptor-reg)) (let ((val (tn-value x))) (etypecase val (integer (inst li (fixnumize val) y)) (null (move null-tn y)) (symbol (load-symbol y val)) (character (inst li (logior (ash (char-code val) type-bits) base-char-type) y))))) (define-move-function (load-number 1) (vop x y) ((immediate zero) (signed-reg unsigned-reg)) (let ((x (tn-value x))) (inst li (if (>= x (ash 1 31)) (logior (ash -1 32) x) x) y))) (define-move-function (load-base-char 1) (vop x y) ((immediate) (base-char-reg)) (inst li (char-code (tn-value x)) y)) (define-move-function (load-system-area-pointer 1) (vop x y) ((immediate) (sap-reg)) (inst li (sap-int (tn-value x)) y)) (define-move-function (load-constant 5) (vop x y) ((constant) (descriptor-reg)) (loadw y code-tn (tn-offset x) other-pointer-type)) (define-move-function (load-stack 5) (vop x y) ((control-stack) (any-reg descriptor-reg)) (load-stack-tn y x)) (define-move-function (load-number-stack 5) (vop x y) ((base-char-stack) (base-char-reg) (sap-stack) (sap-reg) (signed-stack) (signed-reg) (unsigned-stack) (unsigned-reg)) (let ((nfp (current-nfp-tn vop))) (loadw y nfp (tn-offset x)))) (define-move-function (store-stack 5) (vop x y) ((any-reg descriptor-reg) (control-stack)) (store-stack-tn y x)) (define-move-function (store-number-stack 5) (vop x y) ((base-char-reg) (base-char-stack) (sap-reg) (sap-stack) (signed-reg) (signed-stack) (unsigned-reg) (unsigned-stack)) (let ((nfp (current-nfp-tn vop))) (storew x nfp (tn-offset y)))) The Move VOP : ;;; (define-vop (move) (:args (x :target y :scs (any-reg descriptor-reg) :load-if (not (location= x y)))) (:results (y :scs (any-reg descriptor-reg) :load-if (not (location= x y)))) (:effects) (:affected) (:generator 0 (move x y))) (define-move-vop move :move (any-reg descriptor-reg) (any-reg descriptor-reg)) Make Move the check VOP for T so that type check generation does n't think ;;; it is a hairy type. This also allows checking of a few of the values in a ;;; continuation to fall out. ;;; (primitive-type-vop move (:check) t) The Move - Argument VOP is used for moving descriptor values into another ;;; frame for argument or known value passing. ;;; (define-vop (move-argument) (:args (x :target y :scs (any-reg descriptor-reg)) (fp :scs (any-reg) :load-if (not (sc-is y any-reg descriptor-reg)))) (:results (y)) (:generator 0 (sc-case y ((any-reg descriptor-reg) (move x y)) (control-stack (storew x fp (tn-offset y)))))) ;;; (define-move-vop move-argument :move-argument (any-reg descriptor-reg) (any-reg descriptor-reg)) ;;;; ILLEGAL-MOVE This VOP exists just to begin the lifetime of a TN that could n't be written legally due to a type error . An error is signalled before this VOP is ;;; so we don't need to do anything (not that there would be anything sensible ;;; to do anyway.) ;;; (define-vop (illegal-move) (:args (x) (type)) (:results (y)) (:ignore y) (:vop-var vop) (:save-p :compute-only) (:generator 666 (error-call vop object-not-type-error x type))) ;;;; Moves and coercions: ;;; These MOVE-TO-WORD VOPs move a tagged integer to a raw full-word ;;; representation. Similarly, the MOVE-FROM-WORD VOPs converts a raw integer ;;; to a tagged bignum or fixnum. ;;; Arg is a fixnum, so just shift it. We need a type restriction because some ;;; possible arg SCs (control-stack) overlap with possible bignum arg SCs. ;;; (define-vop (move-to-word/fixnum) (:args (x :scs (any-reg descriptor-reg))) (:results (y :scs (signed-reg unsigned-reg))) (:arg-types tagged-num) (:note "fixnum untagging") (:generator 1 (inst sra x 2 y))) ;;; (define-move-vop move-to-word/fixnum :move (any-reg descriptor-reg) (signed-reg unsigned-reg)) ;;; Arg is a non-immediate constant, load it. (define-vop (move-to-word-c) (:args (x :scs (constant))) (:results (y :scs (signed-reg unsigned-reg))) (:note "constant load") (:generator 1 (inst li (tn-value x) y))) ;;; (define-move-vop move-to-word-c :move (constant) (signed-reg unsigned-reg)) ;;; Arg is a fixnum or bignum, figure out which and load if necessary. (define-vop (move-to-word/integer) (:args (x :scs (descriptor-reg))) (:results (y :scs (signed-reg unsigned-reg))) (:note "integer to untagged word coercion") (:generator 3 (inst extru x 31 2 zero-tn :<>) (inst sra x 2 y :tr) (loadw y x vm:bignum-digits-offset vm:other-pointer-type))) ;;; (define-move-vop move-to-word/integer :move (descriptor-reg) (signed-reg unsigned-reg)) ;;; Result is a fixnum, so we can just shift. We need the result type ;;; restriction because of the control-stack ambiguity noted above. ;;; (define-vop (move-from-word/fixnum) (:args (x :scs (signed-reg unsigned-reg))) (:results (y :scs (any-reg descriptor-reg))) (:result-types tagged-num) (:note "fixnum tagging") (:generator 1 (inst sll x 2 y))) ;;; (define-move-vop move-from-word/fixnum :move (signed-reg unsigned-reg) (any-reg descriptor-reg)) ;;; Result may be a bignum, so we have to check. Use a worst-case cost to make ;;; sure people know they may be number consing. ;;; (define-vop (move-from-signed) (:args (x :scs (signed-reg unsigned-reg) :to (:eval 1))) (:results (y :scs (any-reg descriptor-reg) :from (:eval 0))) (:temporary (:scs (non-descriptor-reg)) temp) (:note "signed word to integer coercion") (:generator 18 Extract the top three bits . (inst extrs x 2 3 temp :=) Invert them ( unless they are already zero ) . (inst uaddcm zero-tn temp temp) If we are left with zero , it will fit in a fixnum . So branch around ;; the bignum-construction, doing the shift in the delay slot. (inst comb := temp zero-tn done) (inst sll x 2 y) ;; Make a single-digit bignum. (with-fixed-allocation (y temp bignum-type (1+ bignum-digits-offset)) (storew x y bignum-digits-offset other-pointer-type)) DONE)) ;;; (define-move-vop move-from-signed :move (signed-reg) (descriptor-reg)) Check for fixnum , and possibly allocate one or two word bignum result . Use ;;; a worst-case cost to make sure people know they may be number consing. ;;; (define-vop (move-from-unsigned) (:args (x :scs (signed-reg unsigned-reg) :to (:eval 1))) (:results (y :scs (any-reg descriptor-reg) :from (:eval 0))) (:temporary (:scs (non-descriptor-reg)) temp) (:note "unsigned word to integer coercion") (:generator 20 Grab the top three bits . (inst extrs x 2 3 temp) If zero , it will fit as a fixnum . (inst comib := 0 temp done) (inst sll x 2 y) ;; Make a bignum. (pseudo-atomic (:extra (pad-data-block (1+ bignum-digits-offset))) ;; Create the result pointer. (inst move alloc-tn y) (inst dep other-pointer-type 31 3 y) ;; Check the high bit, and skip the next instruction it it's 0. (inst comclr x zero-tn zero-tn :>=) The high bit is set , so allocate enough space for a two - word bignum . ;; We always skip the following instruction, so it is only executed when we want one word . (inst addi (pad-data-block 1) alloc-tn alloc-tn :tr) Set up the header for one word . Use addi instead of so we can ;; skip the next instruction. (inst addi (logior (ash 1 type-bits) bignum-type) zero-tn temp :tr) Set up the header for two words . (inst li (logior (ash 2 type-bits) bignum-type) temp) ;; Store the header and the data. (storew temp y 0 other-pointer-type) (storew x y bignum-digits-offset other-pointer-type)) DONE)) ;;; (define-move-vop move-from-unsigned :move (unsigned-reg) (descriptor-reg)) ;;; Move untagged numbers. ;;; (define-vop (word-move) (:args (x :target y :scs (signed-reg unsigned-reg) :load-if (not (location= x y)))) (:results (y :scs (signed-reg unsigned-reg) :load-if (not (location= x y)))) (:effects) (:affected) (:note "word integer move") (:generator 0 (move x y))) ;;; (define-move-vop word-move :move (signed-reg unsigned-reg) (signed-reg unsigned-reg)) ;;; Move untagged number arguments/return-values. ;;; (define-vop (move-word-argument) (:args (x :target y :scs (signed-reg unsigned-reg)) (fp :scs (any-reg) :load-if (not (sc-is y sap-reg)))) (:results (y)) (:note "word integer argument move") (:generator 0 (sc-case y ((signed-reg unsigned-reg) (move x y)) ((signed-stack unsigned-stack) (storew x fp (tn-offset y)))))) ;;; (define-move-vop move-word-argument :move-argument (descriptor-reg any-reg signed-reg unsigned-reg) (signed-reg unsigned-reg)) ;;; Use standard MOVE-ARGUMENT + coercion to move an untagged number to a ;;; descriptor passing location. ;;; (define-move-vop move-argument :move-argument (signed-reg unsigned-reg) (any-reg descriptor-reg))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/compiler/hppa/move.lisp
lisp
-*- Package: HPPA -*- ********************************************************************** ********************************************************************** This file contains the HPPA VM definition of operand loading/saving and it is a hairy type. This also allows checking of a few of the values in a continuation to fall out. frame for argument or known value passing. ILLEGAL-MOVE so we don't need to do anything (not that there would be anything sensible to do anyway.) Moves and coercions: These MOVE-TO-WORD VOPs move a tagged integer to a raw full-word representation. Similarly, the MOVE-FROM-WORD VOPs converts a raw integer to a tagged bignum or fixnum. Arg is a fixnum, so just shift it. We need a type restriction because some possible arg SCs (control-stack) overlap with possible bignum arg SCs. Arg is a non-immediate constant, load it. Arg is a fixnum or bignum, figure out which and load if necessary. Result is a fixnum, so we can just shift. We need the result type restriction because of the control-stack ambiguity noted above. Result may be a bignum, so we have to check. Use a worst-case cost to make sure people know they may be number consing. the bignum-construction, doing the shift in the delay slot. Make a single-digit bignum. a worst-case cost to make sure people know they may be number consing. Make a bignum. Create the result pointer. Check the high bit, and skip the next instruction it it's 0. We always skip the following instruction, so it is only executed skip the next instruction. Store the header and the data. Move untagged numbers. Move untagged number arguments/return-values. Use standard MOVE-ARGUMENT + coercion to move an untagged number to a descriptor passing location.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . (ext:file-comment "$Header: src/compiler/hppa/move.lisp $") the Move VOP . Written by . (in-package "HPPA") (define-move-function (load-immediate 1) (vop x y) ((null zero immediate) (any-reg descriptor-reg)) (let ((val (tn-value x))) (etypecase val (integer (inst li (fixnumize val) y)) (null (move null-tn y)) (symbol (load-symbol y val)) (character (inst li (logior (ash (char-code val) type-bits) base-char-type) y))))) (define-move-function (load-number 1) (vop x y) ((immediate zero) (signed-reg unsigned-reg)) (let ((x (tn-value x))) (inst li (if (>= x (ash 1 31)) (logior (ash -1 32) x) x) y))) (define-move-function (load-base-char 1) (vop x y) ((immediate) (base-char-reg)) (inst li (char-code (tn-value x)) y)) (define-move-function (load-system-area-pointer 1) (vop x y) ((immediate) (sap-reg)) (inst li (sap-int (tn-value x)) y)) (define-move-function (load-constant 5) (vop x y) ((constant) (descriptor-reg)) (loadw y code-tn (tn-offset x) other-pointer-type)) (define-move-function (load-stack 5) (vop x y) ((control-stack) (any-reg descriptor-reg)) (load-stack-tn y x)) (define-move-function (load-number-stack 5) (vop x y) ((base-char-stack) (base-char-reg) (sap-stack) (sap-reg) (signed-stack) (signed-reg) (unsigned-stack) (unsigned-reg)) (let ((nfp (current-nfp-tn vop))) (loadw y nfp (tn-offset x)))) (define-move-function (store-stack 5) (vop x y) ((any-reg descriptor-reg) (control-stack)) (store-stack-tn y x)) (define-move-function (store-number-stack 5) (vop x y) ((base-char-reg) (base-char-stack) (sap-reg) (sap-stack) (signed-reg) (signed-stack) (unsigned-reg) (unsigned-stack)) (let ((nfp (current-nfp-tn vop))) (storew x nfp (tn-offset y)))) The Move VOP : (define-vop (move) (:args (x :target y :scs (any-reg descriptor-reg) :load-if (not (location= x y)))) (:results (y :scs (any-reg descriptor-reg) :load-if (not (location= x y)))) (:effects) (:affected) (:generator 0 (move x y))) (define-move-vop move :move (any-reg descriptor-reg) (any-reg descriptor-reg)) Make Move the check VOP for T so that type check generation does n't think (primitive-type-vop move (:check) t) The Move - Argument VOP is used for moving descriptor values into another (define-vop (move-argument) (:args (x :target y :scs (any-reg descriptor-reg)) (fp :scs (any-reg) :load-if (not (sc-is y any-reg descriptor-reg)))) (:results (y)) (:generator 0 (sc-case y ((any-reg descriptor-reg) (move x y)) (control-stack (storew x fp (tn-offset y)))))) (define-move-vop move-argument :move-argument (any-reg descriptor-reg) (any-reg descriptor-reg)) This VOP exists just to begin the lifetime of a TN that could n't be written legally due to a type error . An error is signalled before this VOP is (define-vop (illegal-move) (:args (x) (type)) (:results (y)) (:ignore y) (:vop-var vop) (:save-p :compute-only) (:generator 666 (error-call vop object-not-type-error x type))) (define-vop (move-to-word/fixnum) (:args (x :scs (any-reg descriptor-reg))) (:results (y :scs (signed-reg unsigned-reg))) (:arg-types tagged-num) (:note "fixnum untagging") (:generator 1 (inst sra x 2 y))) (define-move-vop move-to-word/fixnum :move (any-reg descriptor-reg) (signed-reg unsigned-reg)) (define-vop (move-to-word-c) (:args (x :scs (constant))) (:results (y :scs (signed-reg unsigned-reg))) (:note "constant load") (:generator 1 (inst li (tn-value x) y))) (define-move-vop move-to-word-c :move (constant) (signed-reg unsigned-reg)) (define-vop (move-to-word/integer) (:args (x :scs (descriptor-reg))) (:results (y :scs (signed-reg unsigned-reg))) (:note "integer to untagged word coercion") (:generator 3 (inst extru x 31 2 zero-tn :<>) (inst sra x 2 y :tr) (loadw y x vm:bignum-digits-offset vm:other-pointer-type))) (define-move-vop move-to-word/integer :move (descriptor-reg) (signed-reg unsigned-reg)) (define-vop (move-from-word/fixnum) (:args (x :scs (signed-reg unsigned-reg))) (:results (y :scs (any-reg descriptor-reg))) (:result-types tagged-num) (:note "fixnum tagging") (:generator 1 (inst sll x 2 y))) (define-move-vop move-from-word/fixnum :move (signed-reg unsigned-reg) (any-reg descriptor-reg)) (define-vop (move-from-signed) (:args (x :scs (signed-reg unsigned-reg) :to (:eval 1))) (:results (y :scs (any-reg descriptor-reg) :from (:eval 0))) (:temporary (:scs (non-descriptor-reg)) temp) (:note "signed word to integer coercion") (:generator 18 Extract the top three bits . (inst extrs x 2 3 temp :=) Invert them ( unless they are already zero ) . (inst uaddcm zero-tn temp temp) If we are left with zero , it will fit in a fixnum . So branch around (inst comb := temp zero-tn done) (inst sll x 2 y) (with-fixed-allocation (y temp bignum-type (1+ bignum-digits-offset)) (storew x y bignum-digits-offset other-pointer-type)) DONE)) (define-move-vop move-from-signed :move (signed-reg) (descriptor-reg)) Check for fixnum , and possibly allocate one or two word bignum result . Use (define-vop (move-from-unsigned) (:args (x :scs (signed-reg unsigned-reg) :to (:eval 1))) (:results (y :scs (any-reg descriptor-reg) :from (:eval 0))) (:temporary (:scs (non-descriptor-reg)) temp) (:note "unsigned word to integer coercion") (:generator 20 Grab the top three bits . (inst extrs x 2 3 temp) If zero , it will fit as a fixnum . (inst comib := 0 temp done) (inst sll x 2 y) (pseudo-atomic (:extra (pad-data-block (1+ bignum-digits-offset))) (inst move alloc-tn y) (inst dep other-pointer-type 31 3 y) (inst comclr x zero-tn zero-tn :>=) The high bit is set , so allocate enough space for a two - word bignum . when we want one word . (inst addi (pad-data-block 1) alloc-tn alloc-tn :tr) Set up the header for one word . Use addi instead of so we can (inst addi (logior (ash 1 type-bits) bignum-type) zero-tn temp :tr) Set up the header for two words . (inst li (logior (ash 2 type-bits) bignum-type) temp) (storew temp y 0 other-pointer-type) (storew x y bignum-digits-offset other-pointer-type)) DONE)) (define-move-vop move-from-unsigned :move (unsigned-reg) (descriptor-reg)) (define-vop (word-move) (:args (x :target y :scs (signed-reg unsigned-reg) :load-if (not (location= x y)))) (:results (y :scs (signed-reg unsigned-reg) :load-if (not (location= x y)))) (:effects) (:affected) (:note "word integer move") (:generator 0 (move x y))) (define-move-vop word-move :move (signed-reg unsigned-reg) (signed-reg unsigned-reg)) (define-vop (move-word-argument) (:args (x :target y :scs (signed-reg unsigned-reg)) (fp :scs (any-reg) :load-if (not (sc-is y sap-reg)))) (:results (y)) (:note "word integer argument move") (:generator 0 (sc-case y ((signed-reg unsigned-reg) (move x y)) ((signed-stack unsigned-stack) (storew x fp (tn-offset y)))))) (define-move-vop move-word-argument :move-argument (descriptor-reg any-reg signed-reg unsigned-reg) (signed-reg unsigned-reg)) (define-move-vop move-argument :move-argument (signed-reg unsigned-reg) (any-reg descriptor-reg))
ef381a48c7ccda11eeb5a9ff5ca2304dc60de8020a3ed82bb5b2f6eca210aea7
AlexeyRaga/azure-functions-haskell-worker
Utils.hs
module Templates.Utils where import Control.Monad (unless, when) import Data.Either.Combinators (fromRight') import Data.Text (Text) import qualified Data.Text.IO as Text import Prelude hiding (writeFile) import System.Directory (createDirectoryIfMissing, doesFileExist) import System.FilePath (takeDirectory) import Text.Glabrous (Template) import Text.Glabrous as Tpl writeFile :: FilePath -> Template -> [(Text, Text)] -> IO () writeFile file tpl vars = do createDirectoryIfMissing True (takeDirectory file) let content = Tpl.process tpl (Tpl.fromList vars) Text.writeFile file content writeFileIfNotExist :: FilePath -> Template -> [(Text, Text)] -> IO () writeFileIfNotExist file tpl vars = do ok <- doesFileExist file unless ok $ writeFile file tpl vars writeNewFile :: FilePath -> Template -> [(Text, Text)] -> IO () writeNewFile file tpl vars =do alreadyExists <- doesFileExist file when alreadyExists $ error $ "File already exists, will not overwrite: " <> file writeFile file tpl vars toTemplate :: String -> Text -> Template toTemplate name tpl = case Tpl.fromText tpl of Left err -> error $ "Unable to create template: " <> name <> ". Error: " <> err Right tpl' -> tpl'
null
https://raw.githubusercontent.com/AlexeyRaga/azure-functions-haskell-worker/a2fd35c5c4661e6255016bc004681c451b8beb46/azure-functions-tools/app/Templates/Utils.hs
haskell
module Templates.Utils where import Control.Monad (unless, when) import Data.Either.Combinators (fromRight') import Data.Text (Text) import qualified Data.Text.IO as Text import Prelude hiding (writeFile) import System.Directory (createDirectoryIfMissing, doesFileExist) import System.FilePath (takeDirectory) import Text.Glabrous (Template) import Text.Glabrous as Tpl writeFile :: FilePath -> Template -> [(Text, Text)] -> IO () writeFile file tpl vars = do createDirectoryIfMissing True (takeDirectory file) let content = Tpl.process tpl (Tpl.fromList vars) Text.writeFile file content writeFileIfNotExist :: FilePath -> Template -> [(Text, Text)] -> IO () writeFileIfNotExist file tpl vars = do ok <- doesFileExist file unless ok $ writeFile file tpl vars writeNewFile :: FilePath -> Template -> [(Text, Text)] -> IO () writeNewFile file tpl vars =do alreadyExists <- doesFileExist file when alreadyExists $ error $ "File already exists, will not overwrite: " <> file writeFile file tpl vars toTemplate :: String -> Text -> Template toTemplate name tpl = case Tpl.fromText tpl of Left err -> error $ "Unable to create template: " <> name <> ". Error: " <> err Right tpl' -> tpl'
15ad0c63e70539f2b9c7281046a9b3eafacd9dd65423a03584999b98bcac6eae
lspitzner/brittany
Test117.hs
func = case x of {}
null
https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test117.hs
haskell
func = case x of {}
6c8975caeadc8b8e236810fc33f1a504969c22ee7b8b7bf26e9a091bf7c0be04
mpickering/apply-refact
Default82.hs
main = let (first, rest) = (takeWhile p l, dropWhile p l) in rest
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default82.hs
haskell
main = let (first, rest) = (takeWhile p l, dropWhile p l) in rest
f80b85758f16ccec0bc00c1f631e9b91b6eea2a4e2712750f501bc5b2c97a008
facebookarchive/duckling_old
duration.clj
; Durations / Periods ( "seconde (unit-of-duration)" #"(?i)seg(undo)?s?" {:dim :unit-of-duration :grain :second} "minute (unit-of-duration)" #"(?i)min(uto)?s?" {:dim :unit-of-duration :grain :minute} "hour (unit-of-duration)" #"(?i)h(ora)?s?" {:dim :unit-of-duration :grain :hour} "day (unit-of-duration)" #"(?i)d(í|i)as?" {:dim :unit-of-duration :grain :day} "week (unit-of-duration)" #"(?i)semanas?" {:dim :unit-of-duration :grain :week} "month (unit-of-duration)" #"(?i)mes(es)?" {:dim :unit-of-duration :grain :month} "year (unit-of-duration)" #"(?i)a(n|ñ)os?" {:dim :unit-of-duration :grain :year} "<integer> <unit-of-duration>" [(integer 0) (dim :unit-of-duration)] ;prevent negative duration... {:dim :duration :value (duration (:grain %2) (:value %1))} " uno < unit - of - duration > " not sure we need that one ; [#"(?i)une?" (dim :unit-of-duration)] ; {:dim :duration : value ( duration (: grain % 2 ) 1 ) } "en <duration>" [#"(?i)en" (dim :duration)] (in-duration (:value %2)) "hace <duration>" [#"hace" (dim :duration)] (duration-ago (:value %2)) )
null
https://raw.githubusercontent.com/facebookarchive/duckling_old/bf5bb9758c36313b56e136a28ba401696eeff10b/resources/languages/es/rules/duration.clj
clojure
Durations / Periods prevent negative duration... [#"(?i)une?" (dim :unit-of-duration)] {:dim :duration
( "seconde (unit-of-duration)" #"(?i)seg(undo)?s?" {:dim :unit-of-duration :grain :second} "minute (unit-of-duration)" #"(?i)min(uto)?s?" {:dim :unit-of-duration :grain :minute} "hour (unit-of-duration)" #"(?i)h(ora)?s?" {:dim :unit-of-duration :grain :hour} "day (unit-of-duration)" #"(?i)d(í|i)as?" {:dim :unit-of-duration :grain :day} "week (unit-of-duration)" #"(?i)semanas?" {:dim :unit-of-duration :grain :week} "month (unit-of-duration)" #"(?i)mes(es)?" {:dim :unit-of-duration :grain :month} "year (unit-of-duration)" #"(?i)a(n|ñ)os?" {:dim :unit-of-duration :grain :year} "<integer> <unit-of-duration>" {:dim :duration :value (duration (:grain %2) (:value %1))} " uno < unit - of - duration > " not sure we need that one : value ( duration (: grain % 2 ) 1 ) } "en <duration>" [#"(?i)en" (dim :duration)] (in-duration (:value %2)) "hace <duration>" [#"hace" (dim :duration)] (duration-ago (:value %2)) )
d2aa7c506a2bd093c3439f10d7acf384a7ba4d4c872de231705049701456be52
prg-titech/baccaml
syntax.ml
type t = MinCamlの構文を表現するデータ型 ( caml2html : syntax_t ) | Unit | Bool of bool | Int of int | Float of float | String of string | Not of t | Neg of t | Add of t * t | Sub of t * t | Mul of t * t | Div of t * t | Mod of t * t | FNeg of t | FAdd of t * t | FSub of t * t | FMul of t * t | FDiv of t * t | Eq of t * t | LE of t * t | If of t * t * t | SIf of t * t * t | Let of (Id.t * Type.t) * t * t | Var of Id.t | LetRec of fundef * t | App of t * t list | Tuple of t list | LetTuple of (Id.t * Type.t) list * t * t | Array of t * t | Get of t * t | Put of t * t * t [@@deriving show] and fundef = { name : Id.t * Type.t ; args : (Id.t * Type.t) list ; body : t } [@@deriving show]
null
https://raw.githubusercontent.com/prg-titech/baccaml/a3b95e996a995b5004ca897a4b6419edfee590aa/base/syntax.ml
ocaml
type t = MinCamlの構文を表現するデータ型 ( caml2html : syntax_t ) | Unit | Bool of bool | Int of int | Float of float | String of string | Not of t | Neg of t | Add of t * t | Sub of t * t | Mul of t * t | Div of t * t | Mod of t * t | FNeg of t | FAdd of t * t | FSub of t * t | FMul of t * t | FDiv of t * t | Eq of t * t | LE of t * t | If of t * t * t | SIf of t * t * t | Let of (Id.t * Type.t) * t * t | Var of Id.t | LetRec of fundef * t | App of t * t list | Tuple of t list | LetTuple of (Id.t * Type.t) list * t * t | Array of t * t | Get of t * t | Put of t * t * t [@@deriving show] and fundef = { name : Id.t * Type.t ; args : (Id.t * Type.t) list ; body : t } [@@deriving show]
8870734cbf5be34aa579ad66de0573062593ccfac8fc47d2041b1209c6c4efbe
brendanhay/amazonka
SizeConstraintSetUpdate.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | Module : Amazonka . . SizeConstraintSetUpdate Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.WAF.Types.SizeConstraintSetUpdate where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.WAF.Types.ChangeAction import Amazonka.WAF.Types.SizeConstraint -- | This is __AWS WAF Classic__ documentation. For more information, see < -waf-chapter.html > -- in the developer guide. -- -- __For the latest version of AWS WAF__, use the AWS WAFV2 API and see the -- <-chapter.html AWS WAF Developer Guide>. -- With the latest version, AWS WAF has a single set of endpoints for -- regional and global use. -- -- Specifies the part of a web request that you want to inspect the size of -- and indicates whether you want to add the specification to a SizeConstraintSet or delete it from a @SizeConstraintSet@. -- /See:/ ' newSizeConstraintSetUpdate ' smart constructor . data SizeConstraintSetUpdate = SizeConstraintSetUpdate' { -- | Specify @INSERT@ to add a SizeConstraintSetUpdate to a SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ -- from a @SizeConstraintSet@. action :: ChangeAction, -- | Specifies a constraint on the size of a part of the web request. AWS WAF uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of -- @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is -- considered to match. sizeConstraint :: SizeConstraint } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) -- | -- Create a value of 'SizeConstraintSetUpdate' with all optional fields omitted. -- Use < -lens generic - lens > or < optics > to modify other optional fields . -- -- The following record fields are available, with the corresponding lenses provided -- for backwards compatibility: -- -- 'action', 'sizeConstraintSetUpdate_action' - Specify @INSERT@ to add a SizeConstraintSetUpdate to a SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ -- from a @SizeConstraintSet@. -- -- 'sizeConstraint', 'sizeConstraintSetUpdate_sizeConstraint' - Specifies a constraint on the size of a part of the web request. AWS WAF uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of -- @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is -- considered to match. newSizeConstraintSetUpdate :: -- | 'action' ChangeAction -> -- | 'sizeConstraint' SizeConstraint -> SizeConstraintSetUpdate newSizeConstraintSetUpdate pAction_ pSizeConstraint_ = SizeConstraintSetUpdate' { action = pAction_, sizeConstraint = pSizeConstraint_ } -- | Specify @INSERT@ to add a SizeConstraintSetUpdate to a SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ -- from a @SizeConstraintSet@. sizeConstraintSetUpdate_action :: Lens.Lens' SizeConstraintSetUpdate ChangeAction sizeConstraintSetUpdate_action = Lens.lens (\SizeConstraintSetUpdate' {action} -> action) (\s@SizeConstraintSetUpdate' {} a -> s {action = a} :: SizeConstraintSetUpdate) -- | Specifies a constraint on the size of a part of the web request. AWS WAF uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of -- @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is -- considered to match. sizeConstraintSetUpdate_sizeConstraint :: Lens.Lens' SizeConstraintSetUpdate SizeConstraint sizeConstraintSetUpdate_sizeConstraint = Lens.lens (\SizeConstraintSetUpdate' {sizeConstraint} -> sizeConstraint) (\s@SizeConstraintSetUpdate' {} a -> s {sizeConstraint = a} :: SizeConstraintSetUpdate) instance Prelude.Hashable SizeConstraintSetUpdate where hashWithSalt _salt SizeConstraintSetUpdate' {..} = _salt `Prelude.hashWithSalt` action `Prelude.hashWithSalt` sizeConstraint instance Prelude.NFData SizeConstraintSetUpdate where rnf SizeConstraintSetUpdate' {..} = Prelude.rnf action `Prelude.seq` Prelude.rnf sizeConstraint instance Data.ToJSON SizeConstraintSetUpdate where toJSON SizeConstraintSetUpdate' {..} = Data.object ( Prelude.catMaybes [ Prelude.Just ("Action" Data..= action), Prelude.Just ("SizeConstraint" Data..= sizeConstraint) ] )
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-waf/gen/Amazonka/WAF/Types/SizeConstraintSetUpdate.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated | This is __AWS WAF Classic__ documentation. For more information, see in the developer guide. __For the latest version of AWS WAF__, use the AWS WAFV2 API and see the <-chapter.html AWS WAF Developer Guide>. With the latest version, AWS WAF has a single set of endpoints for regional and global use. Specifies the part of a web request that you want to inspect the size of and indicates whether you want to add the specification to a | Specify @INSERT@ to add a SizeConstraintSetUpdate to a from a @SizeConstraintSet@. | Specifies a constraint on the size of a part of the web request. AWS WAF @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is considered to match. | Create a value of 'SizeConstraintSetUpdate' with all optional fields omitted. The following record fields are available, with the corresponding lenses provided for backwards compatibility: 'action', 'sizeConstraintSetUpdate_action' - Specify @INSERT@ to add a SizeConstraintSetUpdate to a from a @SizeConstraintSet@. 'sizeConstraint', 'sizeConstraintSetUpdate_sizeConstraint' - Specifies a constraint on the size of a part of the web request. AWS WAF @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is considered to match. | 'action' | 'sizeConstraint' | Specify @INSERT@ to add a SizeConstraintSetUpdate to a from a @SizeConstraintSet@. | Specifies a constraint on the size of a part of the web request. AWS WAF @FieldToMatch@\". If that expression is true, the @SizeConstraint@ is considered to match.
# LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE NamedFieldPuns # # LANGUAGE RecordWildCards # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # # OPTIONS_GHC -fno - warn - unused - matches # Derived from AWS service descriptions , licensed under Apache 2.0 . Module : Amazonka . . SizeConstraintSetUpdate Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.WAF.Types.SizeConstraintSetUpdate where import qualified Amazonka.Core as Core import qualified Amazonka.Core.Lens.Internal as Lens import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude import Amazonka.WAF.Types.ChangeAction import Amazonka.WAF.Types.SizeConstraint < -waf-chapter.html > SizeConstraintSet or delete it from a @SizeConstraintSet@. /See:/ ' newSizeConstraintSetUpdate ' smart constructor . data SizeConstraintSetUpdate = SizeConstraintSetUpdate' SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ action :: ChangeAction, uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of sizeConstraint :: SizeConstraint } deriving (Prelude.Eq, Prelude.Read, Prelude.Show, Prelude.Generic) Use < -lens generic - lens > or < optics > to modify other optional fields . SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of newSizeConstraintSetUpdate :: ChangeAction -> SizeConstraint -> SizeConstraintSetUpdate newSizeConstraintSetUpdate pAction_ pSizeConstraint_ = SizeConstraintSetUpdate' { action = pAction_, sizeConstraint = pSizeConstraint_ } SizeConstraintSet . Use @DELETE@ to remove a @SizeConstraintSetUpdate@ sizeConstraintSetUpdate_action :: Lens.Lens' SizeConstraintSetUpdate ChangeAction sizeConstraintSetUpdate_action = Lens.lens (\SizeConstraintSetUpdate' {action} -> action) (\s@SizeConstraintSetUpdate' {} a -> s {action = a} :: SizeConstraintSetUpdate) uses the @Size@ , @ComparisonOperator@ , and @FieldToMatch@ to build an expression in the form of \"@Size@ @ComparisonOperator@ size in bytes of sizeConstraintSetUpdate_sizeConstraint :: Lens.Lens' SizeConstraintSetUpdate SizeConstraint sizeConstraintSetUpdate_sizeConstraint = Lens.lens (\SizeConstraintSetUpdate' {sizeConstraint} -> sizeConstraint) (\s@SizeConstraintSetUpdate' {} a -> s {sizeConstraint = a} :: SizeConstraintSetUpdate) instance Prelude.Hashable SizeConstraintSetUpdate where hashWithSalt _salt SizeConstraintSetUpdate' {..} = _salt `Prelude.hashWithSalt` action `Prelude.hashWithSalt` sizeConstraint instance Prelude.NFData SizeConstraintSetUpdate where rnf SizeConstraintSetUpdate' {..} = Prelude.rnf action `Prelude.seq` Prelude.rnf sizeConstraint instance Data.ToJSON SizeConstraintSetUpdate where toJSON SizeConstraintSetUpdate' {..} = Data.object ( Prelude.catMaybes [ Prelude.Just ("Action" Data..= action), Prelude.Just ("SizeConstraint" Data..= sizeConstraint) ] )
6ca20f5ee5531dd783b4d8182b9887472ccbdf7f7b426dcb5ef6e2442627b214
awslabs/s2n-bignum
bignum_tomont_p256k1_alt.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) Conversion of a 4 - word ( 256 - bit ) bignum to Montgomery form mod p_256k1 . (* ========================================================================= *) (**** print_literal_from_elf "x86/secp256k1/bignum_tomont_p256k1_alt.o";; ****) let bignum_tomont_p256k1_alt_mc = define_assert_from_elf "bignum_tomont_p256k1_alt_mc" "x86/secp256k1/bignum_tomont_p256k1_alt.o" [ 0x48; 0xb9; 0xd1; 0x03; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00; MOV ( % rcx ) ( Imm64 ( word 4294968273 ) ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( % rcx ) MOV ( % r8 ) ( % rax ) MOV ( % r9 ) ( % rdx ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) 0x4d; 0x31; 0xd2; (* XOR (% r10) (% r10) *) MUL2 ( % rdx,% rax ) ( % rcx ) 0x49; 0x01; 0xc1; (* ADD (% r9) (% rax) *) 0x49; 0x11; 0xd2; (* ADC (% r10) (% rdx) *) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( % rcx ) 0x49; 0x01; 0xc2; (* ADD (% r10) (% rax) *) ADC ( % rdx ) ( Imm8 ( word 0 ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MOV ( % rsi ) ( % rdx ) MUL2 ( % rdx,% rax ) ( % rcx ) 0x48; 0x01; 0xc6; (* ADD (% rsi) (% rax) *) ADC ( % rdx ) ( Imm8 ( word 0 ) ) ( % rax ) ( % % ( rdx,1 ) ) MUL2 ( % rdx,% rax ) ( % rcx ) 0x49; 0x01; 0xc0; (* ADD (% r8) (% rax) *) 0x49; 0x11; 0xd1; (* ADC (% r9) (% rdx) *) 0x49; 0x83; 0xd2; 0x00; (* ADC (% r10) (Imm8 (word 0)) *) 0x48; 0x83; 0xd6; 0x00; (* ADC (% rsi) (Imm8 (word 0)) *) 0x48; 0xc7; 0xc0; 0x00; 0x00; 0x00; 0x00; MOV ( % rax ) ( Imm32 ( word 0 ) ) CMOVB ( % rcx ) ( % rax ) 0x49; 0x29; 0xc8; (* SUB (% r8) (% rcx) *) MOV ( ( % % ( rdi,0 ) ) ) ( % r8 ) SBB ( % r9 ) ( % rax ) MOV ( ( % % ( rdi,8 ) ) ) ( % r9 ) SBB ( % r10 ) ( % rax ) MOV ( ( % % ( rdi,16 ) ) ) ( % r10 ) SBB ( % rsi ) ( % rax ) MOV ( ( % % ( ) ) ) ( % rsi ) RET ];; let BIGNUM_TOMONT_P256K1_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_tomont_p256k1_alt_mc;; (* ------------------------------------------------------------------------- *) (* Proof. *) (* ------------------------------------------------------------------------- *) let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let p256k1redlemma = prove (`!n. n <= (2 EXP 64 - 1) * (p_256k1 - 1) ==> let q = n DIV 2 EXP 256 + 1 in q < 2 EXP 64 /\ q * p_256k1 <= n + p_256k1 /\ n < q * p_256k1 + p_256k1`, CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN REWRITE_TAC[p_256k1] THEN ARITH_TAC);; let BIGNUM_TOMONT_P256K1_ALT_CORRECT = time prove (`!z x a pc. nonoverlapping (word pc,0x81) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_tomont_p256k1_alt_mc) /\ read RIP s = word pc /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = word (pc + 0x80) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `a:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN (*** Reduce to a variant of bignum_cmul_p256k1 ***) SUBGOAL_THEN `(2 EXP 256 * a) MOD p_256k1 = (4294968273 * a) MOD p_256k1` SUBST1_TAC THENL [ONCE_REWRITE_TAC[GSYM MOD_MULT_LMOD] THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV; ALL_TAC] THEN (*** Instantiate the quotient approximation lemma ***) MP_TAC(SPEC `4294968273 * a` p256k1redlemma) THEN ANTS_TAC THENL [EXPAND_TAC "a" THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV THEN BOUNDER_TAC[]; CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN STRIP_TAC] THEN (*** Intermediate result from initial multiply ***) X86_ACCSTEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC (1--19) (1--19) THEN ABBREV_TAC `ca = bignum_of_wordlist [mullo_s3; sum_s9; sum_s13; sum_s18; sum_s19]` THEN SUBGOAL_THEN `4294968273 * a = ca` SUBST_ALL_TAC THENL [MAP_EVERY EXPAND_TAC ["a"; "ca"] THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC; REPEAT(FIRST_X_ASSUM(K ALL_TAC o check((fun l -> not(l = [])) o intersect [`a:num`; `x:int64`; `c:int64`] o frees o concl))) THEN ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN (*** Quotient estimate computation ***) SUBGOAL_THEN `ca DIV 2 EXP 256 = val(sum_s19:int64)` SUBST_ALL_TAC THENL [EXPAND_TAC "ca" THEN CONV_TAC(LAND_CONV BIGNUM_OF_WORDLIST_DIV_CONV) THEN REFL_TAC; FIRST_ASSUM(ASSUME_TAC o MATCH_MP (ARITH_RULE `n + 1 < 2 EXP 64 ==> n < 2 EXP 64 - 1`))] THEN X86_STEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC [20] THEN ABBREV_TAC `q:int64 = word_add sum_s19 (word 1)` THEN SUBGOAL_THEN `val(sum_s19:int64) + 1 = val(q:int64)` SUBST_ALL_TAC THENL [EXPAND_TAC "q" THEN REWRITE_TAC[VAL_WORD_ADD; VAL_WORD_1] THEN ASM_SIMP_TAC[DIMINDEX_64; MOD_LT]; ALL_TAC] THEN (*** The rest of the computation ***) X86_ACCSTEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC [21;22;23;24;25;26;28;30;32;34] (21--35) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC MOD_UNIQ_BALANCED_REAL THEN MAP_EVERY EXISTS_TAC [`val(q:int64)`; `256`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN (*** Comparison computation and then the rest is easy ***) SUBGOAL_THEN `ca < val(q:int64) * p_256k1 <=> ~carry_s25` SUBST1_TAC THENL [CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `256` THEN EXPAND_TAC "ca" THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN SUBGOAL_THEN `&(val(sum_s19:int64)):real = &(val(q:int64)) - &1` SUBST1_TAC THENL [FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `n < 2 EXP 64 - 1 ==> n + 1 < 2 EXP 64`)) THEN UNDISCH_THEN `word_add sum_s19 (word 1):int64 = q` (SUBST1_TAC o SYM) THEN SIMP_TAC[VAL_WORD_ADD; VAL_WORD_1; DIMINDEX_64; MOD_LT] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]]; EXPAND_TAC "ca" THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN RULE_ASSUM_TAC(REWRITE_RULE[WORD_UNMASK_64]) THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN ASM_CASES_TAC `carry_s25:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC]);; let BIGNUM_TOMONT_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word pc,0x81) (z,8 * 4) /\ nonoverlapping (stackpointer,8) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_tomont_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSP; RSI; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_NOSTACK_TAC bignum_tomont_p256k1_alt_mc BIGNUM_TOMONT_P256K1_ALT_CORRECT);; (* ------------------------------------------------------------------------- *) (* Correctness of Windows ABI version. *) (* ------------------------------------------------------------------------- *) let windows_bignum_tomont_p256k1_alt_mc = define_from_elf "windows_bignum_tomont_p256k1_alt_mc" "x86/secp256k1/bignum_tomont_p256k1_alt.obj";; let WINDOWS_BIGNUM_TOMONT_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. ALL (nonoverlapping (word_sub stackpointer (word 16),16)) [(word pc,0x8b); (x,8 * 4)] /\ nonoverlapping (word pc,0x8b) (z,8 * 4) /\ nonoverlapping (word_sub stackpointer (word 16),24) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_tomont_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSP; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 16),16)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_NOSTACK_TAC windows_bignum_tomont_p256k1_alt_mc bignum_tomont_p256k1_alt_mc BIGNUM_TOMONT_P256K1_ALT_CORRECT);;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/x86/proofs/bignum_tomont_p256k1_alt.ml
ocaml
========================================================================= ========================================================================= *** print_literal_from_elf "x86/secp256k1/bignum_tomont_p256k1_alt.o";; *** XOR (% r10) (% r10) ADD (% r9) (% rax) ADC (% r10) (% rdx) ADD (% r10) (% rax) ADD (% rsi) (% rax) ADD (% r8) (% rax) ADC (% r9) (% rdx) ADC (% r10) (Imm8 (word 0)) ADC (% rsi) (Imm8 (word 0)) SUB (% r8) (% rcx) ------------------------------------------------------------------------- Proof. ------------------------------------------------------------------------- ** Reduce to a variant of bignum_cmul_p256k1 ** ** Instantiate the quotient approximation lemma ** ** Intermediate result from initial multiply ** ** Quotient estimate computation ** ** The rest of the computation ** ** Comparison computation and then the rest is easy ** ------------------------------------------------------------------------- Correctness of Windows ABI version. -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) Conversion of a 4 - word ( 256 - bit ) bignum to Montgomery form mod p_256k1 . let bignum_tomont_p256k1_alt_mc = define_assert_from_elf "bignum_tomont_p256k1_alt_mc" "x86/secp256k1/bignum_tomont_p256k1_alt.o" [ 0x48; 0xb9; 0xd1; 0x03; 0x00; 0x00; 0x01; 0x00; 0x00; 0x00; MOV ( % rcx ) ( Imm64 ( word 4294968273 ) ) MOV ( % rax ) ( ( % % ( rsi,0 ) ) ) MUL2 ( % rdx,% rax ) ( % rcx ) MOV ( % r8 ) ( % rax ) MOV ( % r9 ) ( % rdx ) MOV ( % rax ) ( ( % % ( rsi,8 ) ) ) MUL2 ( % rdx,% rax ) ( % rcx ) MOV ( % rax ) ( ( % % ( rsi,16 ) ) ) MUL2 ( % rdx,% rax ) ( % rcx ) ADC ( % rdx ) ( Imm8 ( word 0 ) ) MOV ( % rax ) ( ( % % ( rsi,24 ) ) ) MOV ( % rsi ) ( % rdx ) MUL2 ( % rdx,% rax ) ( % rcx ) ADC ( % rdx ) ( Imm8 ( word 0 ) ) ( % rax ) ( % % ( rdx,1 ) ) MUL2 ( % rdx,% rax ) ( % rcx ) 0x48; 0xc7; 0xc0; 0x00; 0x00; 0x00; 0x00; MOV ( % rax ) ( Imm32 ( word 0 ) ) CMOVB ( % rcx ) ( % rax ) MOV ( ( % % ( rdi,0 ) ) ) ( % r8 ) SBB ( % r9 ) ( % rax ) MOV ( ( % % ( rdi,8 ) ) ) ( % r9 ) SBB ( % r10 ) ( % rax ) MOV ( ( % % ( rdi,16 ) ) ) ( % r10 ) SBB ( % rsi ) ( % rax ) MOV ( ( % % ( ) ) ) ( % rsi ) RET ];; let BIGNUM_TOMONT_P256K1_ALT_EXEC = X86_MK_CORE_EXEC_RULE bignum_tomont_p256k1_alt_mc;; let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let p256k1redlemma = prove (`!n. n <= (2 EXP 64 - 1) * (p_256k1 - 1) ==> let q = n DIV 2 EXP 256 + 1 in q < 2 EXP 64 /\ q * p_256k1 <= n + p_256k1 /\ n < q * p_256k1 + p_256k1`, CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN REWRITE_TAC[p_256k1] THEN ARITH_TAC);; let BIGNUM_TOMONT_P256K1_ALT_CORRECT = time prove (`!z x a pc. nonoverlapping (word pc,0x81) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) (BUTLAST bignum_tomont_p256k1_alt_mc) /\ read RIP s = word pc /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = word (pc + 0x80) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSI; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `a:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_DIGITIZE_TAC "x_" `bignum_from_memory (x,4) s0` THEN SUBGOAL_THEN `(2 EXP 256 * a) MOD p_256k1 = (4294968273 * a) MOD p_256k1` SUBST1_TAC THENL [ONCE_REWRITE_TAC[GSYM MOD_MULT_LMOD] THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV; ALL_TAC] THEN MP_TAC(SPEC `4294968273 * a` p256k1redlemma) THEN ANTS_TAC THENL [EXPAND_TAC "a" THEN REWRITE_TAC[p_256k1] THEN CONV_TAC NUM_REDUCE_CONV THEN BOUNDER_TAC[]; CONV_TAC(TOP_DEPTH_CONV let_CONV) THEN STRIP_TAC] THEN X86_ACCSTEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC (1--19) (1--19) THEN ABBREV_TAC `ca = bignum_of_wordlist [mullo_s3; sum_s9; sum_s13; sum_s18; sum_s19]` THEN SUBGOAL_THEN `4294968273 * a = ca` SUBST_ALL_TAC THENL [MAP_EVERY EXPAND_TAC ["a"; "ca"] THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN REAL_ARITH_TAC; REPEAT(FIRST_X_ASSUM(K ALL_TAC o check((fun l -> not(l = [])) o intersect [`a:num`; `x:int64`; `c:int64`] o frees o concl))) THEN ACCUMULATOR_POP_ASSUM_LIST(K ALL_TAC)] THEN SUBGOAL_THEN `ca DIV 2 EXP 256 = val(sum_s19:int64)` SUBST_ALL_TAC THENL [EXPAND_TAC "ca" THEN CONV_TAC(LAND_CONV BIGNUM_OF_WORDLIST_DIV_CONV) THEN REFL_TAC; FIRST_ASSUM(ASSUME_TAC o MATCH_MP (ARITH_RULE `n + 1 < 2 EXP 64 ==> n < 2 EXP 64 - 1`))] THEN X86_STEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC [20] THEN ABBREV_TAC `q:int64 = word_add sum_s19 (word 1)` THEN SUBGOAL_THEN `val(sum_s19:int64) + 1 = val(q:int64)` SUBST_ALL_TAC THENL [EXPAND_TAC "q" THEN REWRITE_TAC[VAL_WORD_ADD; VAL_WORD_1] THEN ASM_SIMP_TAC[DIMINDEX_64; MOD_LT]; ALL_TAC] THEN X86_ACCSTEPS_TAC BIGNUM_TOMONT_P256K1_ALT_EXEC [21;22;23;24;25;26;28;30;32;34] (21--35) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC MOD_UNIQ_BALANCED_REAL THEN MAP_EVERY EXISTS_TAC [`val(q:int64)`; `256`] THEN ASM_REWRITE_TAC[] THEN CONJ_TAC THENL [REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC] THEN CONJ_TAC THENL [BOUNDER_TAC[]; ALL_TAC] THEN SUBGOAL_THEN `ca < val(q:int64) * p_256k1 <=> ~carry_s25` SUBST1_TAC THENL [CONV_TAC SYM_CONV THEN MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `256` THEN EXPAND_TAC "ca" THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN SUBGOAL_THEN `&(val(sum_s19:int64)):real = &(val(q:int64)) - &1` SUBST1_TAC THENL [FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `n < 2 EXP 64 - 1 ==> n + 1 < 2 EXP 64`)) THEN UNDISCH_THEN `word_add sum_s19 (word 1):int64 = q` (SUBST1_TAC o SYM) THEN SIMP_TAC[VAL_WORD_ADD; VAL_WORD_1; DIMINDEX_64; MOD_LT] THEN REWRITE_TAC[GSYM REAL_OF_NUM_CLAUSES] THEN REAL_ARITH_TAC; ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]]; EXPAND_TAC "ca" THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN RULE_ASSUM_TAC(REWRITE_RULE[WORD_UNMASK_64]) THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DESUM_RULE) THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN ASM_CASES_TAC `carry_s25:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THEN CONV_TAC WORD_REDUCE_CONV THEN REAL_INTEGER_TAC]);; let BIGNUM_TOMONT_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. nonoverlapping (word pc,0x81) (z,8 * 4) /\ nonoverlapping (stackpointer,8) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) bignum_tomont_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSP; RSI; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4)] ,, MAYCHANGE SOME_FLAGS)`, X86_PROMOTE_RETURN_NOSTACK_TAC bignum_tomont_p256k1_alt_mc BIGNUM_TOMONT_P256K1_ALT_CORRECT);; let windows_bignum_tomont_p256k1_alt_mc = define_from_elf "windows_bignum_tomont_p256k1_alt_mc" "x86/secp256k1/bignum_tomont_p256k1_alt.obj";; let WINDOWS_BIGNUM_TOMONT_P256K1_ALT_SUBROUTINE_CORRECT = time prove (`!z x a pc stackpointer returnaddress. ALL (nonoverlapping (word_sub stackpointer (word 16),16)) [(word pc,0x8b); (x,8 * 4)] /\ nonoverlapping (word pc,0x8b) (z,8 * 4) /\ nonoverlapping (word_sub stackpointer (word 16),24) (z,8 * 4) ==> ensures x86 (\s. bytes_loaded s (word pc) windows_bignum_tomont_p256k1_alt_mc /\ read RIP s = word pc /\ read RSP s = stackpointer /\ read (memory :> bytes64 stackpointer) s = returnaddress /\ WINDOWS_C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = a) (\s. read RIP s = returnaddress /\ read RSP s = word_add stackpointer (word 8) /\ bignum_from_memory (z,4) s = (2 EXP 256 * a) MOD p_256k1) (MAYCHANGE [RIP; RSP; RAX; RDX; RCX; R8; R9; R10] ,, MAYCHANGE [memory :> bytes(z,8 * 4); memory :> bytes(word_sub stackpointer (word 16),16)] ,, MAYCHANGE SOME_FLAGS)`, WINDOWS_X86_WRAP_NOSTACK_TAC windows_bignum_tomont_p256k1_alt_mc bignum_tomont_p256k1_alt_mc BIGNUM_TOMONT_P256K1_ALT_CORRECT);;
304fd2d1d88362e64c9fbd547726591f52a3101b3f480762e551df0d3cc1689d
babashka/sci.configs
test.cljs
(ns sci.configs.clojure.test (:require [sci.configs.impl.clojure.test :as t] [sci.core :as sci])) (def tns t/tns) ;; TODO: 'test-all-vars 'test-ns #_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]} (defn new-var [var-sym f] (sci/new-var var-sym f {:ns tns})) (def clojure-test-namespace {:obj tns 'async (sci/copy-var t/async tns) '-async-test (sci/copy-var t/-async-test tns) '*load-tests* t/load-tests '*stack-trace-depth* t/stack-trace-depth '*report-counters* t/report-counters '*initial-report-counters* t/initial-report-counters '*testing-vars* t/testing-vars '*testing-contexts* t/testing-contexts 'testing-vars-str (sci/copy-var t/testing-vars-str tns) 'testing-contexts-str (sci/copy-var t/testing-contexts-str tns) 'inc-report-counter! (sci/copy-var t/inc-report-counter! tns) 'report t/report 'do-report (sci/copy-var t/do-report tns) ;; assertion utilities 'function? (sci/copy-var t/function? tns) 'assert-predicate (sci/copy-var t/assert-predicate tns) 'assert-any (sci/copy-var t/assert-any tns) ;; assertion methods 'assert-expr (sci/copy-var t/assert-expr tns) 'try-expr (sci/copy-var t/try-expr tns) ;; assertion macros 'is (sci/copy-var t/is tns) 'are (sci/copy-var t/are tns) 'testing (sci/copy-var t/testing tns) ;; defining tests 'with-test (sci/copy-var t/with-test tns) 'deftest (sci/copy-var t/deftest tns) 'deftest- (sci/copy-var t/deftest- tns) 'set-test (sci/copy-var t/set-test tns) ;; fixtures 'use-fixtures (sci/copy-var t/use-fixtures tns) 'compose-fixtures (sci/copy-var t/compose-fixtures tns) 'join-fixtures (sci/copy-var t/join-fixtures tns) ;; running tests: low level 'test-var t/test-var 'test-vars (sci/copy-var t/test-vars tns) 'get-current-env (sci/copy-var t/get-current-env tns) ;; TODO: ;;'test-all-vars (new-var 'test-all-vars (contextualize t/test-all-vars)) ;; TODO: ;;'test-ns (new-var 'test-ns (contextualize t/test-ns)) ;; running tests: high level 'run-tests (sci/copy-var t/run-tests tns) ;; 'run-all-tests (sci/copy-var t/run-all-tests tns) 'successful? (sci/copy-var t/successful? tns)}) (def namespaces {'cljs.test clojure-test-namespace 'clojure.test clojure-test-namespace}) (def config {:namespaces namespaces})
null
https://raw.githubusercontent.com/babashka/sci.configs/2bdbd4a65b2b7db738d9f580eea69a1f4c8fba17/src/sci/configs/clojure/test.cljs
clojure
TODO: 'test-all-vars 'test-ns assertion utilities assertion methods assertion macros defining tests fixtures running tests: low level TODO: 'test-all-vars (new-var 'test-all-vars (contextualize t/test-all-vars)) TODO: 'test-ns (new-var 'test-ns (contextualize t/test-ns)) running tests: high level 'run-all-tests (sci/copy-var t/run-all-tests tns)
(ns sci.configs.clojure.test (:require [sci.configs.impl.clojure.test :as t] [sci.core :as sci])) (def tns t/tns) #_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]} (defn new-var [var-sym f] (sci/new-var var-sym f {:ns tns})) (def clojure-test-namespace {:obj tns 'async (sci/copy-var t/async tns) '-async-test (sci/copy-var t/-async-test tns) '*load-tests* t/load-tests '*stack-trace-depth* t/stack-trace-depth '*report-counters* t/report-counters '*initial-report-counters* t/initial-report-counters '*testing-vars* t/testing-vars '*testing-contexts* t/testing-contexts 'testing-vars-str (sci/copy-var t/testing-vars-str tns) 'testing-contexts-str (sci/copy-var t/testing-contexts-str tns) 'inc-report-counter! (sci/copy-var t/inc-report-counter! tns) 'report t/report 'do-report (sci/copy-var t/do-report tns) 'function? (sci/copy-var t/function? tns) 'assert-predicate (sci/copy-var t/assert-predicate tns) 'assert-any (sci/copy-var t/assert-any tns) 'assert-expr (sci/copy-var t/assert-expr tns) 'try-expr (sci/copy-var t/try-expr tns) 'is (sci/copy-var t/is tns) 'are (sci/copy-var t/are tns) 'testing (sci/copy-var t/testing tns) 'with-test (sci/copy-var t/with-test tns) 'deftest (sci/copy-var t/deftest tns) 'deftest- (sci/copy-var t/deftest- tns) 'set-test (sci/copy-var t/set-test tns) 'use-fixtures (sci/copy-var t/use-fixtures tns) 'compose-fixtures (sci/copy-var t/compose-fixtures tns) 'join-fixtures (sci/copy-var t/join-fixtures tns) 'test-var t/test-var 'test-vars (sci/copy-var t/test-vars tns) 'get-current-env (sci/copy-var t/get-current-env tns) 'run-tests (sci/copy-var t/run-tests tns) 'successful? (sci/copy-var t/successful? tns)}) (def namespaces {'cljs.test clojure-test-namespace 'clojure.test clojure-test-namespace}) (def config {:namespaces namespaces})
95de47c138c07ebb725d0217f49fe9e7da22ea30838ed2a5c179b6e798355166
robert-stuttaford/bridge
edit.clj
(ns bridge.event.data.edit (:require [bridge.data.datomic :as datomic] [bridge.data.edit :as data.edit] [bridge.event.spec :as event.spec])) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; Edit (def event-for-editing-pull-spec [:event/id :event/title :event/slug :event/status {:event/chapter [:chapter/slug]} {:event/organisers [:person/name]} :event/start-date :event/end-date :event/registration-close-date :event/details-markdown :event/notes-markdown]) (defn event-for-editing [db event-id] (datomic/pull db event-for-editing-pull-spec event-id)) (def edit-whitelist #{:event/title :event/slug :event/status :event/organisers :event/start-date :event/end-date :event/registration-close-date :event/details-markdown :event/notes-markdown}) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Field validations ;;; :event/status (defmethod data.edit/check-custom-validation :event/status [db {:field/keys [entity-id value]}] (let [current-status (datomic/attr db entity-id :event/status) possible-next-status (some-> (get event.spec/status->valid-next-status current-status) set)] (cond (nil? possible-next-status) {:error :bridge.event.error/status-may-not-change} (not (contains? possible-next-status value)) {:error :bridge.event.error/invalid-next-status :event/status value :possible-next-status possible-next-status}))) ;;; :event/organisers (defmethod data.edit/check-custom-validation :event/organisers [db {:field/keys [entity-id value retract?]}] (cond (and retract? (= 1 (count (datomic/attr db entity-id :event/organisers)))) {:error :bridge.event.error/event-can-not-have-no-organisers :field/retract? true :event/organisers value}))
null
https://raw.githubusercontent.com/robert-stuttaford/bridge/867d81354457c600cc5c25917de267a8e267c853/src/bridge/event/data/edit.clj
clojure
Edit :event/status :event/organisers
(ns bridge.event.data.edit (:require [bridge.data.datomic :as datomic] [bridge.data.edit :as data.edit] [bridge.event.spec :as event.spec])) (def event-for-editing-pull-spec [:event/id :event/title :event/slug :event/status {:event/chapter [:chapter/slug]} {:event/organisers [:person/name]} :event/start-date :event/end-date :event/registration-close-date :event/details-markdown :event/notes-markdown]) (defn event-for-editing [db event-id] (datomic/pull db event-for-editing-pull-spec event-id)) (def edit-whitelist #{:event/title :event/slug :event/status :event/organisers :event/start-date :event/end-date :event/registration-close-date :event/details-markdown :event/notes-markdown}) Field validations (defmethod data.edit/check-custom-validation :event/status [db {:field/keys [entity-id value]}] (let [current-status (datomic/attr db entity-id :event/status) possible-next-status (some-> (get event.spec/status->valid-next-status current-status) set)] (cond (nil? possible-next-status) {:error :bridge.event.error/status-may-not-change} (not (contains? possible-next-status value)) {:error :bridge.event.error/invalid-next-status :event/status value :possible-next-status possible-next-status}))) (defmethod data.edit/check-custom-validation :event/organisers [db {:field/keys [entity-id value retract?]}] (cond (and retract? (= 1 (count (datomic/attr db entity-id :event/organisers)))) {:error :bridge.event.error/event-can-not-have-no-organisers :field/retract? true :event/organisers value}))
0870d27d772c62a2a36b884a751eb423566d045b20f93e6d872fe51b6c3c9dc4
racehub/om-bootstrap
disabled.cljs
#_ (:require [om-bootstrap.pagination :as pg]) (pg/pagination {} (pg/previous {:disabled? true}) (pg/page {} "1") (pg/page {} "2") (pg/page {} "3") (pg/next {}))
null
https://raw.githubusercontent.com/racehub/om-bootstrap/18fb7f67c306d208bcb012a1b765ac1641d7a00b/dev/snippets/pagination/disabled.cljs
clojure
#_ (:require [om-bootstrap.pagination :as pg]) (pg/pagination {} (pg/previous {:disabled? true}) (pg/page {} "1") (pg/page {} "2") (pg/page {} "3") (pg/next {}))
7a9d636144362d81d2da44a9519cfd074b2a96a82e681ba3f4ce6c9d05207fd8
twosigma/Cook
cors.clj
(ns cook.test.rest.cors (:require [clojure.string :as str] [clojure.test :refer :all] [cook.rest.cors :as cors])) (deftest test-is-preflight? (is (cors/preflight? {:request-method :options})) (is (not (cors/preflight? {:request-method :get}))) (is (not (cors/preflight? {:request-method :put})))) (deftest test-same-origin? (is (cors/same-origin? {:headers {"host" "example.com" "origin" ""} :scheme :http})) (is (cors/same-origin? {:headers {"host" "example.com" "origin" "" "x-forwarded-proto" "https"} :scheme :http})) (is (not (cors/same-origin? {:headers {"host" "example.com" "origin" "" "x-forwarded-proto" "http"} :scheme :https}))) (is (not (cors/same-origin? {:headers {"host" "example.com"} :scheme :http}))) (is (not (cors/same-origin? {:headers {"origin" "" "host" "example.com"} :scheme :http}))) (is (not (cors/same-origin? {:headers {"origin" "" "host" "example.com"} :scheme :https})))) (deftest test-request-allowed? (let [allowed-orgins [#"^https?$" #"^"] origin-allowed? (fn [origin] (cors/request-allowed? {:headers {"origin" origin "host" "other.example.com"}} allowed-orgins))] (is (origin-allowed? "")) (is (origin-allowed? "")) (is (origin-allowed? "")) (is (not (origin-allowed? ""))) (is (cors/request-allowed? {:headers {"origin" "" "host" "same.example.com"} :scheme :http} [])))) (deftest test-wrap-preflight (let [default-resp {:status 200 :body "default"} allowed-origins [#""] handler (cors/wrap-preflight (fn [_] default-resp) allowed-origins)] (testing "passes through non-preflight requests" (is (= default-resp (handler {:request-method :get :headers {"origin" ""}})))) (testing "denies disallowed preflight requests" (let [{:keys [status body]} (handler {:request-method :options :headers {"origin" ""}})] (is (= 403 status)) (is (str/includes? body "")))) (testing "allows valid preflight requests" (let [{:keys [status headers]} (handler {:request-method :options :headers {"origin" "" "access-control-request-headers" "foo,bar"}})] (is (= 200 status)) (is (= "" (headers "Access-Control-Allow-Origin"))) (is (= "foo,bar" (headers "Access-Control-Allow-Headers"))) (is (every? #(str/includes? (headers "Access-Control-Allow-Methods") %) ["PUT" "GET" "OPTIONS" "DELETE"])) (is (= "true" (headers "Access-Control-Allow-Credentials"))) (is (= "86400" (headers "Access-Control-Max-Age"))))))) (deftest test-wrap-cors (let [default-resp {:status 200 :body "default"} allowed-origins [#""] handler (cors/wrap-cors (fn [{:keys [headers]}] (assoc default-resp :headers headers)) allowed-origins)] (testing "reqeusts without origin pass through" (let [{:keys [status body headers]} (handler {:request-method :get :headers {"foo" "bar"}})] (is (= 200 status)) (is (= "default" body)) (is (= {"foo" "bar"} headers)))) (testing "deny requests from disallowed origin" (let [{:keys [status body]} (handler {:request-method :get :headers {"origin" ""}})] (is (= 403 status)) (is (str/includes? body "")))) (testing "adds cors headers on requests from allowed origin" (let [req-headers {"foo" "bar" "origin" ""} {:keys [status body headers]} (handler {:request-method :get :headers req-headers})] (is (= 200 status)) (is (= "default" body)) (is (= (assoc req-headers "Access-Control-Allow-Origin" "" "Access-Control-Allow-Credentials" "true")))))))
null
https://raw.githubusercontent.com/twosigma/Cook/9e561b847827adf2a775220d1fc435d8089fc41d/scheduler/test/cook/test/rest/cors.clj
clojure
(ns cook.test.rest.cors (:require [clojure.string :as str] [clojure.test :refer :all] [cook.rest.cors :as cors])) (deftest test-is-preflight? (is (cors/preflight? {:request-method :options})) (is (not (cors/preflight? {:request-method :get}))) (is (not (cors/preflight? {:request-method :put})))) (deftest test-same-origin? (is (cors/same-origin? {:headers {"host" "example.com" "origin" ""} :scheme :http})) (is (cors/same-origin? {:headers {"host" "example.com" "origin" "" "x-forwarded-proto" "https"} :scheme :http})) (is (not (cors/same-origin? {:headers {"host" "example.com" "origin" "" "x-forwarded-proto" "http"} :scheme :https}))) (is (not (cors/same-origin? {:headers {"host" "example.com"} :scheme :http}))) (is (not (cors/same-origin? {:headers {"origin" "" "host" "example.com"} :scheme :http}))) (is (not (cors/same-origin? {:headers {"origin" "" "host" "example.com"} :scheme :https})))) (deftest test-request-allowed? (let [allowed-orgins [#"^https?$" #"^"] origin-allowed? (fn [origin] (cors/request-allowed? {:headers {"origin" origin "host" "other.example.com"}} allowed-orgins))] (is (origin-allowed? "")) (is (origin-allowed? "")) (is (origin-allowed? "")) (is (not (origin-allowed? ""))) (is (cors/request-allowed? {:headers {"origin" "" "host" "same.example.com"} :scheme :http} [])))) (deftest test-wrap-preflight (let [default-resp {:status 200 :body "default"} allowed-origins [#""] handler (cors/wrap-preflight (fn [_] default-resp) allowed-origins)] (testing "passes through non-preflight requests" (is (= default-resp (handler {:request-method :get :headers {"origin" ""}})))) (testing "denies disallowed preflight requests" (let [{:keys [status body]} (handler {:request-method :options :headers {"origin" ""}})] (is (= 403 status)) (is (str/includes? body "")))) (testing "allows valid preflight requests" (let [{:keys [status headers]} (handler {:request-method :options :headers {"origin" "" "access-control-request-headers" "foo,bar"}})] (is (= 200 status)) (is (= "" (headers "Access-Control-Allow-Origin"))) (is (= "foo,bar" (headers "Access-Control-Allow-Headers"))) (is (every? #(str/includes? (headers "Access-Control-Allow-Methods") %) ["PUT" "GET" "OPTIONS" "DELETE"])) (is (= "true" (headers "Access-Control-Allow-Credentials"))) (is (= "86400" (headers "Access-Control-Max-Age"))))))) (deftest test-wrap-cors (let [default-resp {:status 200 :body "default"} allowed-origins [#""] handler (cors/wrap-cors (fn [{:keys [headers]}] (assoc default-resp :headers headers)) allowed-origins)] (testing "reqeusts without origin pass through" (let [{:keys [status body headers]} (handler {:request-method :get :headers {"foo" "bar"}})] (is (= 200 status)) (is (= "default" body)) (is (= {"foo" "bar"} headers)))) (testing "deny requests from disallowed origin" (let [{:keys [status body]} (handler {:request-method :get :headers {"origin" ""}})] (is (= 403 status)) (is (str/includes? body "")))) (testing "adds cors headers on requests from allowed origin" (let [req-headers {"foo" "bar" "origin" ""} {:keys [status body headers]} (handler {:request-method :get :headers req-headers})] (is (= 200 status)) (is (= "default" body)) (is (= (assoc req-headers "Access-Control-Allow-Origin" "" "Access-Control-Allow-Credentials" "true")))))))
b9c0c231ea14ca722b2df74b44b38a3d3c0fbd4bb3d5981d1ec51e9571d0401f
denibertovic/denv
LibSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Test.Lib.LibSpec where import RIO import Data.List (isPrefixOf) import qualified Data.Text as T import qualified Data.Text.IO as TIO import System.Environment (setEnv) import System.FilePath ((</>)) import System.Directory (setCurrentDirectory, createDirectory) import Test.Hspec (Spec, describe, it, shouldBe) import Denv.Lib import Denv.Types import Denv.Utils -- | Required for auto-discovery spec :: Spec spec = describe "Lib" $ do it "Tests kube env" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f Nothing cont <- TIO.readFile (d </> ".denv") let config = "export KUBECONFIG=" <> T.pack f <> ";" let short = "export KUBECONFIG_SHORT=foobar;" let namespace = "export KUBECTL_NAMESPACE=default;" let ls = T.lines cont (config `elem` ls) `shouldBe` True (namespace `elem` ls) `shouldBe` True (short `elem` ls) `shouldBe` True it "Tests kube env sets denv vars" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f Nothing cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"k8s|n:$KUBECTL_NAMESPACE|$KUBECONFIG_SHORT \";" let denvSetVars = "export _DENV_SET_VARS=KUBECONFIG,KUBECONFIG_SHORT,KUBECTL_NAMESPACE,_OLD_DENV_PS1,_DENV_PROMPT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests kube env with namespace" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f (Just "kube-system") cont <- TIO.readFile (d </> ".denv") let config = "export KUBECONFIG=" <> T.pack f <> ";" let short = "export KUBECONFIG_SHORT=foobar;" let namespace = "export KUBECTL_NAMESPACE=kube-system;" let ls = T.lines cont (config `elem` ls) `shouldBe` True (namespace `elem` ls) `shouldBe` True (short `elem` ls) `shouldBe` True it "Tests vault env" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testVaultConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests vault env sets denv vars" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"raw|$RAW_ENV_FILE \";" let denvSetVars = "export _DENV_SET_VARS=_OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,VAULT_SKIP_VERIFY,VAULT_TOKEN,VAULT_ADDR,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests sourcing env file" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testVaultConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests pass env" $ do withRandomTempFile $ \d _ -> do setEnv "HOME" d _ <- mkPassEnv (Just d) cont <- TIO.readFile (d </> ".denv") let ret = [ "export PASSWORD_STORE_DIR=" <> T.pack d <> ";" , "export PASSWORD_STORE_DIR_SHORT=" <> (T.pack $ mkNameShort d) <> ";" ] (ret `isPrefixOf` T.lines cont) `shouldBe` True it "Tests pass env sets denv vars" $ do withRandomTempFile $ \d _ -> do setEnv "HOME" d _ <- mkPassEnv (Just d) cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"pass|$PASSWORD_STORE_DIR_SHORT \";" let denvSetVars = "export _DENV_SET_VARS=PASSWORD_STORE_DIR,PASSWORD_STORE_DIR_SHORT,_OLD_DENV_PS1,_DENV_PROMPT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests tf env" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testTerraformConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests tf env sets denv vars" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"raw|$RAW_ENV_FILE \";" let denvSetVars = "export _DENV_SET_VARS=_OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,TF_VAR_foo,CLUSTER_NAME,ENVIRONMENT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests FISH set transformation" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let ls = T.lines $ fishify cont let f1 = "set -x -g CLUSTER_NAME foo" let f2 = "set -x -g ENVIRONMENT prod" let f3 = "set -x -g TF_VAR_foo bar" let prompt = "set -x -g PS1 $_DENV_PROMPT$PS1;" let oldPrompt = "set -x -g _OLD_DENV_PS1 \"$PS1\";" let denvPrompt = "set -x -g _DENV_PROMPT \"raw|$RAW_ENV_FILE \";" let denvSetVars = "set -x -g _DENV_SET_VARS _OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,TF_VAR_foo,CLUSTER_NAME,ENVIRONMENT,_DENV_SET_VARS;" (f1 `elem` ls) `shouldBe` True (f2 `elem` ls) `shouldBe` True (f3 `elem` ls) `shouldBe` True (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests deactivate env" $ do withTempTerraformConfig $ \d _ -> do setEnv "HOME" d setEnv "_DENV_SET_VARS" "FOO,BAR,_DENV_SET_VARS" _ <- deactivateEnv cont <- TIO.readFile (d </> ".denv") let expected = "export PS1=\"$_OLD_DENV_PS1\";\nunset \"FOO\";\nunset \"BAR\";\nunset \"_DENV_SET_VARS\";\n" (expected == cont) `shouldBe` True it "Tests deactivate env with FISH" $ do withTempTerraformConfig $ \d _ -> do setEnv "HOME" d setEnv "_DENV_SET_VARS" "FOO,BAR,_DENV_SET_VARS" _ <- deactivateEnv cont <- TIO.readFile (d </> ".denv") let expected = "set -x -g PS1 \"$_OLD_DENV_PS1\";\nset -e -g \"FOO\";\nset -e -g \"BAR\";\nset -e -g \"_DENV_SET_VARS\";\n" (expected == (fishify cont)) `shouldBe` True it "Tests tracking vars works" $ do let env = [ Set OldPrompt ps1 , Set KubeConfig "foobar" , Set Prompt $ mkEscapedText "bar | $PS1" ] let expected = Set DenvSetVars "_OLD_DENV_PS1,KUBECONFIG,_DENV_SET_VARS" let ret = withVarTracking Nothing env (expected `elem` ret) `shouldBe` True let predefined = "FOO," let ret2 = withVarTracking (Just predefined) env let expected2 = Set DenvSetVars "_OLD_DENV_PS1,KUBECONFIG,FOO,_DENV_SET_VARS" (expected2 `elem` ret2) `shouldBe` True withRandomTempFile :: (FilePath -> FilePath -> IO a) -> IO a withRandomTempFile f = do withSystemTempDirectory "denv--" $ \d -> do let c = d </> "foobar" TIO.writeFile c "content doesn't matter" f d c testVaultConfig :: [T.Text] testVaultConfig = [ "export VAULT_ADDR=" , "export VAULT_TOKEN=secret" , "export VAULT_SKIP_VERIFY=true" ] testTerraformConfig :: [T.Text] testTerraformConfig = [ "export ENVIRONMENT=prod" , "export CLUSTER_NAME=foo" , "export TF_VAR_foo=bar" ] withTempVaultConfig :: (FilePath -> FilePath -> IO a) -> IO a withTempVaultConfig f = do withSystemTempDirectory "denv--" $ \d -> do let c = d </> "testvault" TIO.writeFile (d </> c) ((T.intercalate "\n" testVaultConfig) <> "\n") f d c withTempTerraformConfig :: (FilePath -> FilePath -> IO a) -> IO a withTempTerraformConfig f = do withSystemTempDirectory "denv--" $ \d -> do createDirectory (d </> "prod") let c = d </> "prod" </> "env" TIO.writeFile (d </> c) ((T.intercalate "\n" testTerraformConfig) <> "\n") f d c
null
https://raw.githubusercontent.com/denibertovic/denv/86a3d612d8207daad75ad38a1711ad048e8f6113/test/Test/Lib/LibSpec.hs
haskell
# LANGUAGE OverloadedStrings # | Required for auto-discovery
module Test.Lib.LibSpec where import RIO import Data.List (isPrefixOf) import qualified Data.Text as T import qualified Data.Text.IO as TIO import System.Environment (setEnv) import System.FilePath ((</>)) import System.Directory (setCurrentDirectory, createDirectory) import Test.Hspec (Spec, describe, it, shouldBe) import Denv.Lib import Denv.Types import Denv.Utils spec :: Spec spec = describe "Lib" $ do it "Tests kube env" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f Nothing cont <- TIO.readFile (d </> ".denv") let config = "export KUBECONFIG=" <> T.pack f <> ";" let short = "export KUBECONFIG_SHORT=foobar;" let namespace = "export KUBECTL_NAMESPACE=default;" let ls = T.lines cont (config `elem` ls) `shouldBe` True (namespace `elem` ls) `shouldBe` True (short `elem` ls) `shouldBe` True it "Tests kube env sets denv vars" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f Nothing cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"k8s|n:$KUBECTL_NAMESPACE|$KUBECONFIG_SHORT \";" let denvSetVars = "export _DENV_SET_VARS=KUBECONFIG,KUBECONFIG_SHORT,KUBECTL_NAMESPACE,_OLD_DENV_PS1,_DENV_PROMPT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests kube env with namespace" $ do withRandomTempFile $ \d f -> do setEnv "HOME" d _ <- mkKubeEnv f (Just "kube-system") cont <- TIO.readFile (d </> ".denv") let config = "export KUBECONFIG=" <> T.pack f <> ";" let short = "export KUBECONFIG_SHORT=foobar;" let namespace = "export KUBECTL_NAMESPACE=kube-system;" let ls = T.lines cont (config `elem` ls) `shouldBe` True (namespace `elem` ls) `shouldBe` True (short `elem` ls) `shouldBe` True it "Tests vault env" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testVaultConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests vault env sets denv vars" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"raw|$RAW_ENV_FILE \";" let denvSetVars = "export _DENV_SET_VARS=_OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,VAULT_SKIP_VERIFY,VAULT_TOKEN,VAULT_ADDR,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests sourcing env file" $ do withTempVaultConfig $ \d f -> do setEnv "HOME" d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testVaultConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests pass env" $ do withRandomTempFile $ \d _ -> do setEnv "HOME" d _ <- mkPassEnv (Just d) cont <- TIO.readFile (d </> ".denv") let ret = [ "export PASSWORD_STORE_DIR=" <> T.pack d <> ";" , "export PASSWORD_STORE_DIR_SHORT=" <> (T.pack $ mkNameShort d) <> ";" ] (ret `isPrefixOf` T.lines cont) `shouldBe` True it "Tests pass env sets denv vars" $ do withRandomTempFile $ \d _ -> do setEnv "HOME" d _ <- mkPassEnv (Just d) cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"pass|$PASSWORD_STORE_DIR_SHORT \";" let denvSetVars = "export _DENV_SET_VARS=PASSWORD_STORE_DIR,PASSWORD_STORE_DIR_SHORT,_OLD_DENV_PS1,_DENV_PROMPT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests tf env" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") (testTerraformConfig `isPrefixOf` T.lines cont) `shouldBe` True it "Tests tf env sets denv vars" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let prompt = "export PS1=$_DENV_PROMPT$PS1;" let oldPrompt = "export _OLD_DENV_PS1=\"$PS1\";" let denvPrompt = "export _DENV_PROMPT=\"raw|$RAW_ENV_FILE \";" let denvSetVars = "export _DENV_SET_VARS=_OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,TF_VAR_foo,CLUSTER_NAME,ENVIRONMENT,_DENV_SET_VARS;" let ls = T.lines cont (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests FISH set transformation" $ do withTempTerraformConfig $ \d f -> do setEnv "HOME" d setCurrentDirectory d _ <- mkRawEnv Nothing f cont <- TIO.readFile (d </> ".denv") let ls = T.lines $ fishify cont let f1 = "set -x -g CLUSTER_NAME foo" let f2 = "set -x -g ENVIRONMENT prod" let f3 = "set -x -g TF_VAR_foo bar" let prompt = "set -x -g PS1 $_DENV_PROMPT$PS1;" let oldPrompt = "set -x -g _OLD_DENV_PS1 \"$PS1\";" let denvPrompt = "set -x -g _DENV_PROMPT \"raw|$RAW_ENV_FILE \";" let denvSetVars = "set -x -g _DENV_SET_VARS _OLD_DENV_PS1,RAW_ENV_FILE,_DENV_PROMPT,TF_VAR_foo,CLUSTER_NAME,ENVIRONMENT,_DENV_SET_VARS;" (f1 `elem` ls) `shouldBe` True (f2 `elem` ls) `shouldBe` True (f3 `elem` ls) `shouldBe` True (prompt `elem` ls) `shouldBe` True (oldPrompt `elem` ls) `shouldBe` True (denvPrompt `elem` ls) `shouldBe` True (denvSetVars `elem` ls) `shouldBe` True it "Tests deactivate env" $ do withTempTerraformConfig $ \d _ -> do setEnv "HOME" d setEnv "_DENV_SET_VARS" "FOO,BAR,_DENV_SET_VARS" _ <- deactivateEnv cont <- TIO.readFile (d </> ".denv") let expected = "export PS1=\"$_OLD_DENV_PS1\";\nunset \"FOO\";\nunset \"BAR\";\nunset \"_DENV_SET_VARS\";\n" (expected == cont) `shouldBe` True it "Tests deactivate env with FISH" $ do withTempTerraformConfig $ \d _ -> do setEnv "HOME" d setEnv "_DENV_SET_VARS" "FOO,BAR,_DENV_SET_VARS" _ <- deactivateEnv cont <- TIO.readFile (d </> ".denv") let expected = "set -x -g PS1 \"$_OLD_DENV_PS1\";\nset -e -g \"FOO\";\nset -e -g \"BAR\";\nset -e -g \"_DENV_SET_VARS\";\n" (expected == (fishify cont)) `shouldBe` True it "Tests tracking vars works" $ do let env = [ Set OldPrompt ps1 , Set KubeConfig "foobar" , Set Prompt $ mkEscapedText "bar | $PS1" ] let expected = Set DenvSetVars "_OLD_DENV_PS1,KUBECONFIG,_DENV_SET_VARS" let ret = withVarTracking Nothing env (expected `elem` ret) `shouldBe` True let predefined = "FOO," let ret2 = withVarTracking (Just predefined) env let expected2 = Set DenvSetVars "_OLD_DENV_PS1,KUBECONFIG,FOO,_DENV_SET_VARS" (expected2 `elem` ret2) `shouldBe` True withRandomTempFile :: (FilePath -> FilePath -> IO a) -> IO a withRandomTempFile f = do withSystemTempDirectory "denv--" $ \d -> do let c = d </> "foobar" TIO.writeFile c "content doesn't matter" f d c testVaultConfig :: [T.Text] testVaultConfig = [ "export VAULT_ADDR=" , "export VAULT_TOKEN=secret" , "export VAULT_SKIP_VERIFY=true" ] testTerraformConfig :: [T.Text] testTerraformConfig = [ "export ENVIRONMENT=prod" , "export CLUSTER_NAME=foo" , "export TF_VAR_foo=bar" ] withTempVaultConfig :: (FilePath -> FilePath -> IO a) -> IO a withTempVaultConfig f = do withSystemTempDirectory "denv--" $ \d -> do let c = d </> "testvault" TIO.writeFile (d </> c) ((T.intercalate "\n" testVaultConfig) <> "\n") f d c withTempTerraformConfig :: (FilePath -> FilePath -> IO a) -> IO a withTempTerraformConfig f = do withSystemTempDirectory "denv--" $ \d -> do createDirectory (d </> "prod") let c = d </> "prod" </> "env" TIO.writeFile (d </> c) ((T.intercalate "\n" testTerraformConfig) <> "\n") f d c
99311f0150a152ad010e037281318b59babb988ea7e57bbd305654e8d181b1cd
jumarko/clojure-experiments
intro_to_sequences.clj
(ns four-clojure.intro-to-sequences) (= 3 (first '(3 2 1))) (= 3 (second [2 3 4])) (= 3 (last (list 1 2 3)))
null
https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/four_clojure/intro_to_sequences.clj
clojure
(ns four-clojure.intro-to-sequences) (= 3 (first '(3 2 1))) (= 3 (second [2 3 4])) (= 3 (last (list 1 2 3)))
188e5222d1ac252548c5fad43fa63330d34c0411306eb34cefa6ab75ac20e73d
sgbj/MaximaSharp
dqwgts.lisp
;;; Compiled by f2cl version: ( " f2cl1.l , v 46c1f6a93b0d 2012/05/03 04:40:28 toy $ " " f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " ;;; "f2cl5.l,v 46c1f6a93b0d 2012/05/03 04:40:28 toy $" " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v fceac530ef0c 2011/11/26 04:02:26 toy $ " ) Using Lisp CMU Common Lisp snapshot-2012 - 04 ( ) ;;; ;;; Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) ;;; (:coerce-assigns :as-needed) (:array-type ':array) ;;; (:array-slicing t) (:declare-common nil) ;;; (:float-format double-float)) (in-package :slatec) (defun dqwgts (x a b alfa beta integr) (declare (type (f2cl-lib:integer4) integr) (type (double-float) beta alfa b a x)) (prog ((bmx 0.0) (xma 0.0) (dqwgts 0.0)) (declare (type (double-float) dqwgts xma bmx)) (setf xma (- x a)) (setf bmx (- b x)) (setf dqwgts (* (expt xma alfa) (expt bmx beta))) (f2cl-lib:computed-goto (label40 label10 label20 label30) integr) label10 (setf dqwgts (* dqwgts (f2cl-lib:flog xma))) (go label40) label20 (setf dqwgts (* dqwgts (f2cl-lib:flog bmx))) (go label40) label30 (setf dqwgts (* dqwgts (f2cl-lib:flog xma) (f2cl-lib:flog bmx))) label40 (go end_label) end_label (return (values dqwgts nil nil nil nil nil nil)))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dqwgts fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float) (double-float) (double-float) (double-float) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil) :calls 'nil)))
null
https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/numerical/slatec/dqwgts.lisp
lisp
Compiled by f2cl version: "f2cl5.l,v 46c1f6a93b0d 2012/05/03 04:40:28 toy $" Options: ((:prune-labels nil) (:auto-save t) (:relaxed-array-decls t) (:coerce-assigns :as-needed) (:array-type ':array) (:array-slicing t) (:declare-common nil) (:float-format double-float))
( " f2cl1.l , v 46c1f6a93b0d 2012/05/03 04:40:28 toy $ " " f2cl2.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl3.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl4.l , v 96616d88fb7e 2008/02/22 22:19:34 rtoy $ " " f2cl6.l , v 1d5cbacbb977 2008/08/24 00:56:27 rtoy $ " " macros.l , v fceac530ef0c 2011/11/26 04:02:26 toy $ " ) Using Lisp CMU Common Lisp snapshot-2012 - 04 ( ) (in-package :slatec) (defun dqwgts (x a b alfa beta integr) (declare (type (f2cl-lib:integer4) integr) (type (double-float) beta alfa b a x)) (prog ((bmx 0.0) (xma 0.0) (dqwgts 0.0)) (declare (type (double-float) dqwgts xma bmx)) (setf xma (- x a)) (setf bmx (- b x)) (setf dqwgts (* (expt xma alfa) (expt bmx beta))) (f2cl-lib:computed-goto (label40 label10 label20 label30) integr) label10 (setf dqwgts (* dqwgts (f2cl-lib:flog xma))) (go label40) label20 (setf dqwgts (* dqwgts (f2cl-lib:flog bmx))) (go label40) label30 (setf dqwgts (* dqwgts (f2cl-lib:flog xma) (f2cl-lib:flog bmx))) label40 (go end_label) end_label (return (values dqwgts nil nil nil nil nil nil)))) (in-package #-gcl #:cl-user #+gcl "CL-USER") #+#.(cl:if (cl:find-package '#:f2cl) '(and) '(or)) (eval-when (:load-toplevel :compile-toplevel :execute) (setf (gethash 'fortran-to-lisp::dqwgts fortran-to-lisp::*f2cl-function-info*) (fortran-to-lisp::make-f2cl-finfo :arg-types '((double-float) (double-float) (double-float) (double-float) (double-float) (fortran-to-lisp::integer4)) :return-values '(nil nil nil nil nil nil) :calls 'nil)))
fdfb1799f4108d7cb85b2b3e6463d5f61267d1c241aebdb0f72fd0de6c6e7e15
xapi-project/xen-api
gen_api_main.ml
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) Front end around the API code generator . Central place for filtering open Datamodel_types let filter = ref None let filterinternal = ref false module Field = struct let filter_internal x = if !filterinternal then not x.internal_only else true let opensource x = List.mem "3.0.3" x.release.opensource && filter_internal x let closed x = List.mem "closed" x.release.internal && filter_internal x let debug x = List.mem "debug" x.release.internal && filter_internal x let nothing x = filter_internal x end module Message = struct let filter_internal x = if !filterinternal then not x.msg_db_only else true let opensource x = List.mem "3.0.3" x.msg_release.opensource && filter_internal x let closed x = List.mem "closed" x.msg_release.internal && filter_internal x let debug x = List.mem "debug" x.msg_release.internal && filter_internal x let nothing x = filter_internal x end let filter_api () = let api_used = Datamodel.all_api in (* Add all implicit messages to the API directly *) let api_used = Datamodel_utils.add_implicit_messages api_used in let filterfn = Dm_api.filter (fun _ -> true) in match !filter with | None -> api_used | Some "opensource" -> filterfn Field.opensource Message.opensource api_used | Some "closed" -> filterfn Field.closed Message.closed api_used | Some "debug" -> filterfn Field.debug Message.debug api_used | Some "nothing" -> filterfn Field.nothing Message.nothing api_used | Some x -> Printf.eprintf "Unknown filter mode: %s\n" x ; api_used let set_gendebug () = Gen_server.enable_debugging := true let mode = ref None let _ = Arg.parse [ ( "-mode" , Arg.Symbol ( ["client"; "server"; "api"; "db"; "actions"; "sql"; "rbac"; "test"] , fun x -> mode := Some x ) , "Choose which file to output" ) ; ( "-filter" , Arg.Symbol ( ["opensource"; "closed"; "debug"; "nothing"] , fun x -> filter := Some x ) , "Apply a filter to the API" ) ; ( "-filterinternal" , Arg.Bool (fun x -> filterinternal := x) , "Filter internal fields and messages" ) ; ( "-gendebug" , Arg.Unit (fun _ -> set_gendebug ()) , "Add debugging code to generated output" ) ; ( "-output" , Arg.String (fun s -> ( try Unix.mkdir (Filename.dirname s) 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> () ) ; Gen_api.oc := open_out s ) , "Output to the specified file" ) ] (fun x -> Printf.eprintf "Ignoring argument: %s\n" x) "Generate ocaml code from the datamodel. See -help" ; let api = filter_api () in match !mode with | None -> Printf.eprintf "Must select an output type with -mode\n" | Some "client" -> Gen_api.gen_client api | Some "api" -> Gen_api.gen_client_types api | Some "server" -> Gen_api.gen_server api | Some "db" -> Gen_api.gen_db_actions api | Some "actions" -> Gen_api.gen_custom_actions api | Some "rbac" -> Gen_api.gen_rbac api | Some "test" -> Gen_test.gen_test api | Some x -> Printf.eprintf "Didn't recognise mode: %s\n" x
null
https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/idl/ocaml_backend/gen_api_main.ml
ocaml
Add all implicit messages to the API directly
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc. * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation ; version 2.1 only . with the special * exception on linking described in file LICENSE . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * Copyright (C) 2006-2009 Citrix Systems Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; version 2.1 only. with the special * exception on linking described in file LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. *) Front end around the API code generator . Central place for filtering open Datamodel_types let filter = ref None let filterinternal = ref false module Field = struct let filter_internal x = if !filterinternal then not x.internal_only else true let opensource x = List.mem "3.0.3" x.release.opensource && filter_internal x let closed x = List.mem "closed" x.release.internal && filter_internal x let debug x = List.mem "debug" x.release.internal && filter_internal x let nothing x = filter_internal x end module Message = struct let filter_internal x = if !filterinternal then not x.msg_db_only else true let opensource x = List.mem "3.0.3" x.msg_release.opensource && filter_internal x let closed x = List.mem "closed" x.msg_release.internal && filter_internal x let debug x = List.mem "debug" x.msg_release.internal && filter_internal x let nothing x = filter_internal x end let filter_api () = let api_used = Datamodel.all_api in let api_used = Datamodel_utils.add_implicit_messages api_used in let filterfn = Dm_api.filter (fun _ -> true) in match !filter with | None -> api_used | Some "opensource" -> filterfn Field.opensource Message.opensource api_used | Some "closed" -> filterfn Field.closed Message.closed api_used | Some "debug" -> filterfn Field.debug Message.debug api_used | Some "nothing" -> filterfn Field.nothing Message.nothing api_used | Some x -> Printf.eprintf "Unknown filter mode: %s\n" x ; api_used let set_gendebug () = Gen_server.enable_debugging := true let mode = ref None let _ = Arg.parse [ ( "-mode" , Arg.Symbol ( ["client"; "server"; "api"; "db"; "actions"; "sql"; "rbac"; "test"] , fun x -> mode := Some x ) , "Choose which file to output" ) ; ( "-filter" , Arg.Symbol ( ["opensource"; "closed"; "debug"; "nothing"] , fun x -> filter := Some x ) , "Apply a filter to the API" ) ; ( "-filterinternal" , Arg.Bool (fun x -> filterinternal := x) , "Filter internal fields and messages" ) ; ( "-gendebug" , Arg.Unit (fun _ -> set_gendebug ()) , "Add debugging code to generated output" ) ; ( "-output" , Arg.String (fun s -> ( try Unix.mkdir (Filename.dirname s) 0o755 with Unix.Unix_error (Unix.EEXIST, _, _) -> () ) ; Gen_api.oc := open_out s ) , "Output to the specified file" ) ] (fun x -> Printf.eprintf "Ignoring argument: %s\n" x) "Generate ocaml code from the datamodel. See -help" ; let api = filter_api () in match !mode with | None -> Printf.eprintf "Must select an output type with -mode\n" | Some "client" -> Gen_api.gen_client api | Some "api" -> Gen_api.gen_client_types api | Some "server" -> Gen_api.gen_server api | Some "db" -> Gen_api.gen_db_actions api | Some "actions" -> Gen_api.gen_custom_actions api | Some "rbac" -> Gen_api.gen_rbac api | Some "test" -> Gen_test.gen_test api | Some x -> Printf.eprintf "Didn't recognise mode: %s\n" x
05e99c1db9072cb8d996233bcf6d80948b5a6638c4141430515886ba6f7d0e59
Bannerets/camlproto
Types.ml
open! Base type tl_section = Functions | Types type name_with_loc = Ast.name Loc.annot and tl_type_ident' = | TypeIdBoxed of Ast.name | TypeIdBare of Ast.name and tl_type_ident = tl_type_ident' Loc.annot and tl_type_param = ParamNat of string | ParamType of string and tl_type = Type of Ast.name * tl_type_param list and tl_builtin_type = | BuiltinType | BuiltinNat and tl_constr_ref = | ConstrRef of int [@@unboxed] and tl_type_ref = | TypeRef of (int * tl_constr_ref option) Loc.annot (* TODO: remove loc? *) | TypeRefUnd of tl_type_ident | TypeRefBuiltin of tl_builtin_type and tl_var_ref = | VarRef of int * string option | VarRefUnd of string and tl_expr = | ExprNat of tl_nat_expr | ExprType of tl_type_expr and tl_nat_expr' = | NatConst of int | NatVar of tl_var_ref | NatPlus of tl_nat_expr * tl_nat_expr and tl_nat_expr = tl_nat_expr' Loc.annot and tl_type_expr' = | TypeExpr of tl_type_ref * tl_expr list | TypeRepeat of tl_nat_expr * tl_repeat_arg list | TypeVar of tl_var_ref | TypeBare of tl_type_expr and tl_type_expr = tl_type_expr' Loc.annot and tl_modifier = ModBang and modified_type_expr' = Modified of tl_modifier option * tl_type_expr and modified_type_expr = modified_type_expr' Loc.annot and tl_cond' = Cond of tl_var_ref * int and tl_cond = tl_cond' Loc.annot and tl_arg_id = string Loc.annot and tl_repeat_arg' = { r_arg_id: tl_arg_id option; r_arg_type: tl_type_expr; } and tl_repeat_arg = tl_repeat_arg' Loc.annot and tl_opt_arg_kind = [ `ResultBang | `ArgBang ] and tl_arg' = { arg_id: tl_arg_id option; arg_ref: int; arg_cond: tl_cond option; arg_type: modified_type_expr; arg_opt: tl_opt_arg_kind option; } and tl_arg = tl_arg' Loc.annot (* TODO: merge tl_constructor and tl_function? *) and tl_constructor' = { c_id: name_with_loc; c_magic: int32 [@printer fun fmt -> fprintf fmt "0x%lXl"]; c_args: tl_arg list; c_ref: int; c_result_type: int; c_builtin: bool; } and tl_constructor = tl_constructor' Loc.annot and tl_function' = { f_id: name_with_loc; f_magic: int32 [@printer fun fmt -> fprintf fmt "0x%lXl"]; f_args: tl_arg list; f_result_type: tl_type_expr; f_builtin: bool; } and tl_function = tl_function' Loc.annot [@@deriving show { with_path = false }, equal, compare, sexp, hash] let gen_type_id' = function | TypeIdBoxed n | TypeIdBare n -> Ast.gen_name n let gen_type_id (_, id : tl_type_ident) = gen_type_id' id let is_boxed_type_id l = Loc.value_map_annot l @@ function | TypeIdBoxed _ -> true | TypeIdBare _ -> false let is_boxed_type_ref = function | TypeRef (_, (_, Some _)) -> false | TypeRef (_, (_, None)) -> true | TypeRefBuiltin BuiltinType -> true | TypeRefBuiltin BuiltinNat -> false | TypeRefUnd id -> is_boxed_type_id id let is_bare_type_ref r = not @@ is_boxed_type_ref r let ref_Type = TypeRefBuiltin BuiltinType let ref_nat = TypeRefBuiltin BuiltinNat let show_builtin_type : tl_builtin_type -> string = function | BuiltinType -> "Type" | BuiltinNat -> "nat" let show_param_type = function | ParamType _ -> "Type" | ParamNat _ -> "nat" let get_expr_loc : tl_expr -> Loc.t = function | ExprNat (l, _) -> l | ExprType (l, _) -> l let unwrap_modified : modified_type_expr -> tl_type_expr = function | _, Modified (_, texpr) -> texpr module TypeRefCmp = struct type t = tl_type_ref [@@deriving compare, sexp_of, hash] include (val Comparator.make ~compare ~sexp_of_t) end
null
https://raw.githubusercontent.com/Bannerets/camlproto/0b31083b8c0103079ec2881176f63f8cb12abb73/src/tl/lib/Types.ml
ocaml
TODO: remove loc? TODO: merge tl_constructor and tl_function?
open! Base type tl_section = Functions | Types type name_with_loc = Ast.name Loc.annot and tl_type_ident' = | TypeIdBoxed of Ast.name | TypeIdBare of Ast.name and tl_type_ident = tl_type_ident' Loc.annot and tl_type_param = ParamNat of string | ParamType of string and tl_type = Type of Ast.name * tl_type_param list and tl_builtin_type = | BuiltinType | BuiltinNat and tl_constr_ref = | ConstrRef of int [@@unboxed] and tl_type_ref = | TypeRefUnd of tl_type_ident | TypeRefBuiltin of tl_builtin_type and tl_var_ref = | VarRef of int * string option | VarRefUnd of string and tl_expr = | ExprNat of tl_nat_expr | ExprType of tl_type_expr and tl_nat_expr' = | NatConst of int | NatVar of tl_var_ref | NatPlus of tl_nat_expr * tl_nat_expr and tl_nat_expr = tl_nat_expr' Loc.annot and tl_type_expr' = | TypeExpr of tl_type_ref * tl_expr list | TypeRepeat of tl_nat_expr * tl_repeat_arg list | TypeVar of tl_var_ref | TypeBare of tl_type_expr and tl_type_expr = tl_type_expr' Loc.annot and tl_modifier = ModBang and modified_type_expr' = Modified of tl_modifier option * tl_type_expr and modified_type_expr = modified_type_expr' Loc.annot and tl_cond' = Cond of tl_var_ref * int and tl_cond = tl_cond' Loc.annot and tl_arg_id = string Loc.annot and tl_repeat_arg' = { r_arg_id: tl_arg_id option; r_arg_type: tl_type_expr; } and tl_repeat_arg = tl_repeat_arg' Loc.annot and tl_opt_arg_kind = [ `ResultBang | `ArgBang ] and tl_arg' = { arg_id: tl_arg_id option; arg_ref: int; arg_cond: tl_cond option; arg_type: modified_type_expr; arg_opt: tl_opt_arg_kind option; } and tl_arg = tl_arg' Loc.annot and tl_constructor' = { c_id: name_with_loc; c_magic: int32 [@printer fun fmt -> fprintf fmt "0x%lXl"]; c_args: tl_arg list; c_ref: int; c_result_type: int; c_builtin: bool; } and tl_constructor = tl_constructor' Loc.annot and tl_function' = { f_id: name_with_loc; f_magic: int32 [@printer fun fmt -> fprintf fmt "0x%lXl"]; f_args: tl_arg list; f_result_type: tl_type_expr; f_builtin: bool; } and tl_function = tl_function' Loc.annot [@@deriving show { with_path = false }, equal, compare, sexp, hash] let gen_type_id' = function | TypeIdBoxed n | TypeIdBare n -> Ast.gen_name n let gen_type_id (_, id : tl_type_ident) = gen_type_id' id let is_boxed_type_id l = Loc.value_map_annot l @@ function | TypeIdBoxed _ -> true | TypeIdBare _ -> false let is_boxed_type_ref = function | TypeRef (_, (_, Some _)) -> false | TypeRef (_, (_, None)) -> true | TypeRefBuiltin BuiltinType -> true | TypeRefBuiltin BuiltinNat -> false | TypeRefUnd id -> is_boxed_type_id id let is_bare_type_ref r = not @@ is_boxed_type_ref r let ref_Type = TypeRefBuiltin BuiltinType let ref_nat = TypeRefBuiltin BuiltinNat let show_builtin_type : tl_builtin_type -> string = function | BuiltinType -> "Type" | BuiltinNat -> "nat" let show_param_type = function | ParamType _ -> "Type" | ParamNat _ -> "nat" let get_expr_loc : tl_expr -> Loc.t = function | ExprNat (l, _) -> l | ExprType (l, _) -> l let unwrap_modified : modified_type_expr -> tl_type_expr = function | _, Modified (_, texpr) -> texpr module TypeRefCmp = struct type t = tl_type_ref [@@deriving compare, sexp_of, hash] include (val Comparator.make ~compare ~sexp_of_t) end
4c952c6e7898daa26f6bac104bc9766c34f922bd61efadcaf15a5b24fa3bc50f
thheller/shadow-cljs
bootstrap_script.cljs
(ns demo.bootstrap-script (:require [cljs.js :as cljs] [cljs.env :as env] [shadow.cljs.bootstrap.node :as boot])) (defn print-result [{:keys [error value] :as result}] (prn [:result result])) (def code "(prn ::foo) (+ 1 2)") (defonce compile-state-ref (env/default-compiler-env)) (defn compile-it [] (cljs/eval-str compile-state-ref code "[test]" {:eval cljs/js-eval :load (partial boot/load compile-state-ref)} print-result)) (defn main [& args] (boot/init compile-state-ref {} compile-it))
null
https://raw.githubusercontent.com/thheller/shadow-cljs/ba0a02aec050c6bc8db1932916009400f99d3cce/src/dev/demo/bootstrap_script.cljs
clojure
(ns demo.bootstrap-script (:require [cljs.js :as cljs] [cljs.env :as env] [shadow.cljs.bootstrap.node :as boot])) (defn print-result [{:keys [error value] :as result}] (prn [:result result])) (def code "(prn ::foo) (+ 1 2)") (defonce compile-state-ref (env/default-compiler-env)) (defn compile-it [] (cljs/eval-str compile-state-ref code "[test]" {:eval cljs/js-eval :load (partial boot/load compile-state-ref)} print-result)) (defn main [& args] (boot/init compile-state-ref {} compile-it))
dccb4c4e155d277970b765fbe4a9b00a1058e20bf0ed2cb707ffe7883403865e
muyinliu/cl-fswatch
cl-fswatch.lisp
(in-package :fsw) ;;; condition (define-condition fsw-status-error (error) ((code :initarg :code :reader code)) (:report (lambda (condition stream) (format stream "fswatch C function returned error ~S(~A)" (cffi:foreign-enum-keyword '%fsw-error-codes (code condition)) (code condition)))) (:documentation "Signalled when a fswatch function return a status code other than FSW-OK")) (defmacro with-fsw-error-code-handler (form) "Handle foreign call to libfswatch." `(let ((handle ,form)) (if (zerop handle) t (error 'fsw-status-error :code handle)))) ;;; fswatch-session (defclass fswatch-session () ((handle :initarg :handle :reader handle :type integer :initform (error "Must pass an integer as value of slot :hanle.")) (path-list :initarg :path-list :accessor path-list) (property-list :initarg :property-list :accessor property-list) (allow-overflow-p :initarg :allow-overflow-p :accessor allow-overflow-p) (callback :initarg :callback :accessor callback) (latency :initarg :latency :accessor latency) (recursive-p :initarg :recursive-p :accessor recursive-p) (directory-only-p :initarg :directory-only-p :accessor directory-only-p) (follow-symlinks-p :initarg :follow-symlinks-p :accessor follow-symlinks-p) (event-type-filter-list :initarg :event-type-filter-list :accessor event-type-filter-list) (filter-list :initarg :filter-list :accessor filter-list) (thread :initarg :thread :accessor thread)) (:default-initargs :path-list nil :property-list nil :allow-overflow-p nil :callback nil :latency nil :recursive-p t :directory-only-p nil :follow-symlinks-p nil :event-type-filter-list nil :filter-list nil :thread nil)) (defmethod initialize-instance :after ((session fswatch-session) &key) (set-latency session 0.1) (setf (latency session) 0.1)) (defmethod print-object ((session fswatch-session) stream) (with-slots (handle path-list property-list allow-overflow-p callback latency recursive-p directory-only-p follow-symlinks-p event-type-filter-list filter-list thread) session (print-unreadable-object (session stream :type t :identity t) (format stream ":handle ~S ~% :path-list '(~{~S~^, ~}) ~% :property-list '(~{~S~^, ~}) ~% :allow-overflow-p ~S ~% :callback ~S ~% :latency ~S :recursive-p ~S :directory-only-p ~S :follow-symlinks-p ~S ~% :event-type-filter-list '(~{~S~^, ~}) ~% :filter-list '(~{~S~^, ~}) ~% :thread ~S" handle path-list property-list allow-overflow-p callback latency recursive-p directory-only-p follow-symlinks-p event-type-filter-list filter-list thread)))) (defmethod add-path ((session fswatch-session) pathspec) (setf pathspec (namestring (pathname pathspec))) (with-fsw-error-code-handler (%fsw-add-path (handle session) pathspec)) (push pathspec (path-list session))) (defmethod add-property ((session fswatch-session) name value) (with-fsw-error-code-handler (%fsw-add-property (handle session) name value)) (push (cons name value) (property-list session))) (defmethod set-allow-overflow ((session fswatch-session) allow-overflow-p) (with-fsw-error-code-handler (%fsw-set-allow-overflow (handle session) (cffi:convert-to-foreign allow-overflow-p :boolean))) (setf (allow-overflow-p session) allow-overflow-p)) (defmacro fsw-set-callback (handle callback) "Macro to generate callback function pointer and set to fsw." (let ((callback-name (gensym "fsw-cevent-callback"))) `(progn ;; /** * A function pointer of type FSW_CEVENT_CALLBACK is used by the API as a ;; * callback to provide information about received events. The callback is ;; * passed the following arguments: ;; * - events, a const pointer to an array of events of type const fsw_cevent. ;; * - event_num, the size of the *events array. ;; * - data, optional persisted data for a callback. ;; * ;; * The memory used by the fsw_cevent objects will be freed at the end of the ;; * callback invocation. A callback should copy such data instead of storing ;; * a pointer to it. ;; */ ;; typedef void (*FSW_CEVENT_CALLBACK) (fsw_cevent const *const events, ;; const unsigned int event_num, ;; void *data); (cffi:defcallback ,callback-name :void ((events :pointer) (event_num :unsigned-int) (data :pointer)) (declare (ignore data)) (funcall ,callback (loop for i below event_num collect (cffi:with-foreign-slots ((path evt_time flags flags_num) (cffi:mem-aptr events '(:struct %fsw-cevent) i) (:struct %fsw-cevent)) (list path (unix-time->universal-time evt_time) (loop for j below flags_num collect (cffi:foreign-enum-keyword '%fsw-event-flag (cffi:mem-aref flags :int j)))))))) TODO data , optional persisted data for a callback . (cffi:with-foreign-pointer (data 32) (with-fsw-error-code-handler (%fsw-set-callback ,handle (cffi:callback ,callback-name) data)))))) (defmethod set-callback ((session fswatch-session) callback) (fsw-set-callback (handle session) callback) (setf (callback session) callback)) (defmethod set-latency ((session fswatch-session) latency) "Set fswatch event delay time." (with-fsw-error-code-handler (%fsw-set-latency (handle session) (cffi:convert-to-foreign (coerce latency 'double-float) :double))) (setf (latency session) latency)) (defmethod set-recursive ((session fswatch-session) recursive-p) (with-fsw-error-code-handler (%fsw-set-recursive (handle session) (cffi:convert-to-foreign recursive-p :boolean))) (setf (recursive-p session) recursive-p)) (defmethod set-directory-only ((session fswatch-session) directory-only-p) (with-fsw-error-code-handler (%fsw-set-directory-only (handle session) (cffi:convert-to-foreign directory-only-p :boolean))) (setf (directory-only-p session) directory-only-p)) (defmethod set-follow-symlinks ((session fswatch-session) follow-symlinks-p) (with-fsw-error-code-handler (%fsw-set-follow-symlinks (handle session) (cffi:convert-to-foreign follow-symlinks-p :boolean))) (setf (follow-symlinks-p session) follow-symlinks-p)) (defmethod add-event-type-filter ((session fswatch-session) event-type) (assert (member event-type '(:Created :Updated :Removed :Rename :OwnerModified :AttributeModified :MovedFrom :MoveTo :IsFile :IsDir :IsSymLink :Link :Overflow))) (cffi:with-foreign-object (pointer '(:struct %fsw-event-type-filter)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-event-type-filter) 'flag) (cffi:foreign-enum-value '%fsw-event-flag event-type)) (with-fsw-error-code-handler (%fsw-add-event-type-filter (handle session) pointer)))) (defmethod add-filter ((session fswatch-session) text type case-sensitive-p extended-p) (check-type text string) (assert (member type '(:filter_include :filter_exclude))) (cffi:with-foreign-object (pointer '(:struct %fsw-cmonitor-filter)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'text) text) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'type) (cffi:foreign-enum-value '%fsw-filter-type type)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'case_sensitive) (cffi:convert-to-foreign case-sensitive-p :boolean)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'extended) (cffi:convert-to-foreign extended-p :boolean)) (with-fsw-error-code-handler (%fsw-add-filter (handle session) pointer)))) (defmethod start-monitor ((session fswatch-session)) (unless (and (path-list session) (callback session)) (error "A path to watch and a callback function are required.")) (let ((thread (bt:make-thread #'(lambda () (with-fsw-error-code-handler (%fsw-start-monitor (handle session)))) :name (format nil "fswatch thread(handle: ~S)" (handle session))))) (setf (thread session) thread))) (defun destroy (session) (check-type session fswatch-session) (let ((thread (thread session))) (when thread (bt:destroy-thread thread) (bt:make-thread #'(lambda () (with-fsw-error-code-handler (%fsw-destroy-session (handle session))))) (setf (thread session) nil) (remove-session session) (setf session nil) t))) ;;; fswatch (defvar *session-list* nil) (defun init-library () (with-fsw-error-code-handler (%fsw-init-library))) ;; initial library automatically (init-library) (define-condition fsw-init-session-error (error) ((code :initarg :code :reader code)) (:report (lambda (condition stream) (format stream "fswatch C function fsw_init_session returned error ~:[UNKNOWN~;:FSW-INVALID-HANDLE~](~A)" (equal %fsw-invalid-handle (code condition)) (code condition))))) (defun init-session (&optional (monitor-type (cffi:foreign-enum-value '%fsw-monitor-type :system-default-monitor-type))) (let* ((handle (%fsw-init-session monitor-type))) (when (< handle 0) (error 'fsw-init-session-error :code handle)) (let ((session (make-instance 'fswatch-session :handle handle))) (push session *session-list*) session))) (defun all-sessions () "List all sessions." *session-list*) (defun get-session (handle) "Get fswatch session with handle(integer)." (loop for session in *session-list* do (when (eq handle (handle session)) (return-from get-session session)))) (defun remove-session (session) (setf *session-list* (remove-if #'(lambda (item) (equal (handle session) (handle item))) *session-list*))) (defun last-error () (with-fsw-error-code-handler (%fsw-last-error))) (defun verbose-p () (cffi:convert-from-foreign (%fsw-is-verbose) :boolean)) (defun set-verbose (verbose-p) (%fsw-set-verbose (cffi:convert-to-foreign verbose-p :boolean)))
null
https://raw.githubusercontent.com/muyinliu/cl-fswatch/b39120ff0cf94b20717da6196e36245c2cf89741/cl-fswatch.lisp
lisp
condition fswatch-session /** * callback to provide information about received events. The callback is * passed the following arguments: * - events, a const pointer to an array of events of type const fsw_cevent. * - event_num, the size of the *events array. * - data, optional persisted data for a callback. * * The memory used by the fsw_cevent objects will be freed at the end of the * callback invocation. A callback should copy such data instead of storing * a pointer to it. */ typedef void (*FSW_CEVENT_CALLBACK) (fsw_cevent const *const events, const unsigned int event_num, void *data); fswatch initial library automatically
(in-package :fsw) (define-condition fsw-status-error (error) ((code :initarg :code :reader code)) (:report (lambda (condition stream) (format stream "fswatch C function returned error ~S(~A)" (cffi:foreign-enum-keyword '%fsw-error-codes (code condition)) (code condition)))) (:documentation "Signalled when a fswatch function return a status code other than FSW-OK")) (defmacro with-fsw-error-code-handler (form) "Handle foreign call to libfswatch." `(let ((handle ,form)) (if (zerop handle) t (error 'fsw-status-error :code handle)))) (defclass fswatch-session () ((handle :initarg :handle :reader handle :type integer :initform (error "Must pass an integer as value of slot :hanle.")) (path-list :initarg :path-list :accessor path-list) (property-list :initarg :property-list :accessor property-list) (allow-overflow-p :initarg :allow-overflow-p :accessor allow-overflow-p) (callback :initarg :callback :accessor callback) (latency :initarg :latency :accessor latency) (recursive-p :initarg :recursive-p :accessor recursive-p) (directory-only-p :initarg :directory-only-p :accessor directory-only-p) (follow-symlinks-p :initarg :follow-symlinks-p :accessor follow-symlinks-p) (event-type-filter-list :initarg :event-type-filter-list :accessor event-type-filter-list) (filter-list :initarg :filter-list :accessor filter-list) (thread :initarg :thread :accessor thread)) (:default-initargs :path-list nil :property-list nil :allow-overflow-p nil :callback nil :latency nil :recursive-p t :directory-only-p nil :follow-symlinks-p nil :event-type-filter-list nil :filter-list nil :thread nil)) (defmethod initialize-instance :after ((session fswatch-session) &key) (set-latency session 0.1) (setf (latency session) 0.1)) (defmethod print-object ((session fswatch-session) stream) (with-slots (handle path-list property-list allow-overflow-p callback latency recursive-p directory-only-p follow-symlinks-p event-type-filter-list filter-list thread) session (print-unreadable-object (session stream :type t :identity t) (format stream ":handle ~S ~% :path-list '(~{~S~^, ~}) ~% :property-list '(~{~S~^, ~}) ~% :allow-overflow-p ~S ~% :callback ~S ~% :latency ~S :recursive-p ~S :directory-only-p ~S :follow-symlinks-p ~S ~% :event-type-filter-list '(~{~S~^, ~}) ~% :filter-list '(~{~S~^, ~}) ~% :thread ~S" handle path-list property-list allow-overflow-p callback latency recursive-p directory-only-p follow-symlinks-p event-type-filter-list filter-list thread)))) (defmethod add-path ((session fswatch-session) pathspec) (setf pathspec (namestring (pathname pathspec))) (with-fsw-error-code-handler (%fsw-add-path (handle session) pathspec)) (push pathspec (path-list session))) (defmethod add-property ((session fswatch-session) name value) (with-fsw-error-code-handler (%fsw-add-property (handle session) name value)) (push (cons name value) (property-list session))) (defmethod set-allow-overflow ((session fswatch-session) allow-overflow-p) (with-fsw-error-code-handler (%fsw-set-allow-overflow (handle session) (cffi:convert-to-foreign allow-overflow-p :boolean))) (setf (allow-overflow-p session) allow-overflow-p)) (defmacro fsw-set-callback (handle callback) "Macro to generate callback function pointer and set to fsw." (let ((callback-name (gensym "fsw-cevent-callback"))) `(progn * A function pointer of type FSW_CEVENT_CALLBACK is used by the API as a (cffi:defcallback ,callback-name :void ((events :pointer) (event_num :unsigned-int) (data :pointer)) (declare (ignore data)) (funcall ,callback (loop for i below event_num collect (cffi:with-foreign-slots ((path evt_time flags flags_num) (cffi:mem-aptr events '(:struct %fsw-cevent) i) (:struct %fsw-cevent)) (list path (unix-time->universal-time evt_time) (loop for j below flags_num collect (cffi:foreign-enum-keyword '%fsw-event-flag (cffi:mem-aref flags :int j)))))))) TODO data , optional persisted data for a callback . (cffi:with-foreign-pointer (data 32) (with-fsw-error-code-handler (%fsw-set-callback ,handle (cffi:callback ,callback-name) data)))))) (defmethod set-callback ((session fswatch-session) callback) (fsw-set-callback (handle session) callback) (setf (callback session) callback)) (defmethod set-latency ((session fswatch-session) latency) "Set fswatch event delay time." (with-fsw-error-code-handler (%fsw-set-latency (handle session) (cffi:convert-to-foreign (coerce latency 'double-float) :double))) (setf (latency session) latency)) (defmethod set-recursive ((session fswatch-session) recursive-p) (with-fsw-error-code-handler (%fsw-set-recursive (handle session) (cffi:convert-to-foreign recursive-p :boolean))) (setf (recursive-p session) recursive-p)) (defmethod set-directory-only ((session fswatch-session) directory-only-p) (with-fsw-error-code-handler (%fsw-set-directory-only (handle session) (cffi:convert-to-foreign directory-only-p :boolean))) (setf (directory-only-p session) directory-only-p)) (defmethod set-follow-symlinks ((session fswatch-session) follow-symlinks-p) (with-fsw-error-code-handler (%fsw-set-follow-symlinks (handle session) (cffi:convert-to-foreign follow-symlinks-p :boolean))) (setf (follow-symlinks-p session) follow-symlinks-p)) (defmethod add-event-type-filter ((session fswatch-session) event-type) (assert (member event-type '(:Created :Updated :Removed :Rename :OwnerModified :AttributeModified :MovedFrom :MoveTo :IsFile :IsDir :IsSymLink :Link :Overflow))) (cffi:with-foreign-object (pointer '(:struct %fsw-event-type-filter)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-event-type-filter) 'flag) (cffi:foreign-enum-value '%fsw-event-flag event-type)) (with-fsw-error-code-handler (%fsw-add-event-type-filter (handle session) pointer)))) (defmethod add-filter ((session fswatch-session) text type case-sensitive-p extended-p) (check-type text string) (assert (member type '(:filter_include :filter_exclude))) (cffi:with-foreign-object (pointer '(:struct %fsw-cmonitor-filter)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'text) text) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'type) (cffi:foreign-enum-value '%fsw-filter-type type)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'case_sensitive) (cffi:convert-to-foreign case-sensitive-p :boolean)) (setf (cffi:foreign-slot-value pointer '(:struct %fsw-cmonitor-filter) 'extended) (cffi:convert-to-foreign extended-p :boolean)) (with-fsw-error-code-handler (%fsw-add-filter (handle session) pointer)))) (defmethod start-monitor ((session fswatch-session)) (unless (and (path-list session) (callback session)) (error "A path to watch and a callback function are required.")) (let ((thread (bt:make-thread #'(lambda () (with-fsw-error-code-handler (%fsw-start-monitor (handle session)))) :name (format nil "fswatch thread(handle: ~S)" (handle session))))) (setf (thread session) thread))) (defun destroy (session) (check-type session fswatch-session) (let ((thread (thread session))) (when thread (bt:destroy-thread thread) (bt:make-thread #'(lambda () (with-fsw-error-code-handler (%fsw-destroy-session (handle session))))) (setf (thread session) nil) (remove-session session) (setf session nil) t))) (defvar *session-list* nil) (defun init-library () (with-fsw-error-code-handler (%fsw-init-library))) (init-library) (define-condition fsw-init-session-error (error) ((code :initarg :code :reader code)) (:report (lambda (condition stream) (format stream "fswatch C function fsw_init_session returned error ~:[UNKNOWN~;:FSW-INVALID-HANDLE~](~A)" (equal %fsw-invalid-handle (code condition)) (code condition))))) (defun init-session (&optional (monitor-type (cffi:foreign-enum-value '%fsw-monitor-type :system-default-monitor-type))) (let* ((handle (%fsw-init-session monitor-type))) (when (< handle 0) (error 'fsw-init-session-error :code handle)) (let ((session (make-instance 'fswatch-session :handle handle))) (push session *session-list*) session))) (defun all-sessions () "List all sessions." *session-list*) (defun get-session (handle) "Get fswatch session with handle(integer)." (loop for session in *session-list* do (when (eq handle (handle session)) (return-from get-session session)))) (defun remove-session (session) (setf *session-list* (remove-if #'(lambda (item) (equal (handle session) (handle item))) *session-list*))) (defun last-error () (with-fsw-error-code-handler (%fsw-last-error))) (defun verbose-p () (cffi:convert-from-foreign (%fsw-is-verbose) :boolean)) (defun set-verbose (verbose-p) (%fsw-set-verbose (cffi:convert-to-foreign verbose-p :boolean)))
41950100206d93ab585f3eea335d0350033939237276acac10113a0c72bb595d
yesodweb/yesod
English.hs
{-# LANGUAGE OverloadedStrings #-} module Yesod.Form.I18n.English where import Yesod.Form.Types (FormMessage (..)) import Data.Monoid (mappend) import Data.Text (Text) englishFormMessage :: FormMessage -> Text englishFormMessage (MsgInvalidInteger t) = "Invalid integer: " `Data.Monoid.mappend` t englishFormMessage (MsgInvalidNumber t) = "Invalid number: " `mappend` t englishFormMessage (MsgInvalidEntry t) = "Invalid entry: " `mappend` t englishFormMessage MsgInvalidTimeFormat = "Invalid time, must be in HH:MM[:SS] format" englishFormMessage MsgInvalidDay = "Invalid day, must be in YYYY-MM-DD format" englishFormMessage (MsgInvalidUrl t) = "Invalid URL: " `mappend` t englishFormMessage (MsgInvalidEmail t) = "Invalid e-mail address: " `mappend` t englishFormMessage (MsgInvalidHour t) = "Invalid hour: " `mappend` t englishFormMessage (MsgInvalidMinute t) = "Invalid minute: " `mappend` t englishFormMessage (MsgInvalidSecond t) = "Invalid second: " `mappend` t englishFormMessage MsgCsrfWarning = "As a protection against cross-site request forgery attacks, please confirm your form submission." englishFormMessage MsgValueRequired = "Value is required" englishFormMessage (MsgInputNotFound t) = "Input not found: " `mappend` t englishFormMessage MsgSelectNone = "<None>" englishFormMessage (MsgInvalidBool t) = "Invalid boolean: " `mappend` t englishFormMessage MsgBoolYes = "Yes" englishFormMessage MsgBoolNo = "No" englishFormMessage MsgDelete = "Delete?" englishFormMessage (MsgInvalidHexColorFormat t) = "Invalid color, must be in #rrggbb hexadecimal format: " `mappend` t
null
https://raw.githubusercontent.com/yesodweb/yesod/48d05fd6ab12ad440e1f2aa32684ed08b23f0613/yesod-form/Yesod/Form/I18n/English.hs
haskell
# LANGUAGE OverloadedStrings #
module Yesod.Form.I18n.English where import Yesod.Form.Types (FormMessage (..)) import Data.Monoid (mappend) import Data.Text (Text) englishFormMessage :: FormMessage -> Text englishFormMessage (MsgInvalidInteger t) = "Invalid integer: " `Data.Monoid.mappend` t englishFormMessage (MsgInvalidNumber t) = "Invalid number: " `mappend` t englishFormMessage (MsgInvalidEntry t) = "Invalid entry: " `mappend` t englishFormMessage MsgInvalidTimeFormat = "Invalid time, must be in HH:MM[:SS] format" englishFormMessage MsgInvalidDay = "Invalid day, must be in YYYY-MM-DD format" englishFormMessage (MsgInvalidUrl t) = "Invalid URL: " `mappend` t englishFormMessage (MsgInvalidEmail t) = "Invalid e-mail address: " `mappend` t englishFormMessage (MsgInvalidHour t) = "Invalid hour: " `mappend` t englishFormMessage (MsgInvalidMinute t) = "Invalid minute: " `mappend` t englishFormMessage (MsgInvalidSecond t) = "Invalid second: " `mappend` t englishFormMessage MsgCsrfWarning = "As a protection against cross-site request forgery attacks, please confirm your form submission." englishFormMessage MsgValueRequired = "Value is required" englishFormMessage (MsgInputNotFound t) = "Input not found: " `mappend` t englishFormMessage MsgSelectNone = "<None>" englishFormMessage (MsgInvalidBool t) = "Invalid boolean: " `mappend` t englishFormMessage MsgBoolYes = "Yes" englishFormMessage MsgBoolNo = "No" englishFormMessage MsgDelete = "Delete?" englishFormMessage (MsgInvalidHexColorFormat t) = "Invalid color, must be in #rrggbb hexadecimal format: " `mappend` t
76b16f8bda7070cf2923a38d6cca22cd5213ed444964d2277fae3a5664918c36
dgiot/dgiot
emqx_broker_helper.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2018 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_broker_helper). -behaviour(gen_server). -include("logger.hrl"). -include("types.hrl"). -logger_header("[Broker Helper]"). -export([start_link/0]). %% APIs -export([ register_sub/2 , lookup_subid/1 , lookup_subpid/1 , get_sub_shard/2 , create_seq/1 , reclaim_seq/1 ]). %% gen_server callbacks -export([ init/1 , handle_call/3 , handle_cast/2 , handle_info/2 , terminate/2 , code_change/3 ]). -ifdef(TEST). -compile(export_all). -compile(nowarn_export_all). -endif. -define(HELPER, ?MODULE). -define(SUBID, emqx_subid). -define(SUBMON, emqx_submon). -define(SUBSEQ, emqx_subseq). -define(SHARD, 1024). -define(BATCH_SIZE, 100000). -spec(start_link() -> startlink_ret()). start_link() -> gen_server:start_link({local, ?HELPER}, ?MODULE, [], []). -spec(register_sub(pid(), emqx_types:subid()) -> ok). register_sub(SubPid, SubId) when is_pid(SubPid) -> case ets:lookup(?SUBMON, SubPid) of [] -> gen_server:cast(?HELPER, {register_sub, SubPid, SubId}); [{_, SubId}] -> ok; _Other -> error(subid_conflict) end. -spec(lookup_subid(pid()) -> maybe(emqx_types:subid())). lookup_subid(SubPid) when is_pid(SubPid) -> emqx_tables:lookup_value(?SUBMON, SubPid). -spec(lookup_subpid(emqx_types:subid()) -> maybe(pid())). lookup_subpid(SubId) -> emqx_tables:lookup_value(?SUBID, SubId). -spec(get_sub_shard(pid(), emqx_topic:topic()) -> non_neg_integer()). get_sub_shard(SubPid, Topic) -> case create_seq(Topic) of Seq when Seq =< ?SHARD -> 0; _ -> erlang:phash2(SubPid, shards_num()) + 1 end. -spec(shards_num() -> pos_integer()). shards_num() -> %% Dynamic sharding later... ets:lookup_element(?HELPER, shards, 2). -spec(create_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). create_seq(Topic) -> emqx_sequence:nextval(?SUBSEQ, Topic). -spec(reclaim_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). reclaim_seq(Topic) -> emqx_sequence:reclaim(?SUBSEQ, Topic). %%-------------------------------------------------------------------- %% gen_server callbacks %%-------------------------------------------------------------------- init([]) -> %% Helper table ok = emqx_tables:new(?HELPER, [{read_concurrency, true}]), Shards : CPU * 32 true = ets:insert(?HELPER, {shards, emqx_vm:schedulers() * 32}), SubSeq : Topic - > SeqId ok = emqx_sequence:create(?SUBSEQ), %% SubId: SubId -> SubPid ok = emqx_tables:new(?SUBID, [public, {read_concurrency, true}, {write_concurrency, true}]), SubMon : SubPid - > SubId ok = emqx_tables:new(?SUBMON, [public, {read_concurrency, true}, {write_concurrency, true}]), %% Stats timer ok = emqx_stats:update_interval(broker_stats, fun emqx_broker:stats_fun/0), {ok, #{pmon => emqx_pmon:new()}}. handle_call(Req, _From, State) -> ?LOG(error, "Unexpected call: ~p", [Req]), {reply, ignored, State}. handle_cast({register_sub, SubPid, SubId}, State = #{pmon := PMon}) -> true = (SubId =:= undefined) orelse ets:insert(?SUBID, {SubId, SubPid}), true = ets:insert(?SUBMON, {SubPid, SubId}), {noreply, State#{pmon := emqx_pmon:monitor(SubPid, PMon)}}; handle_cast(Msg, State) -> ?LOG(error, "Unexpected cast: ~p", [Msg]), {noreply, State}. handle_info({'DOWN', _MRef, process, SubPid, _Reason}, State = #{pmon := PMon}) -> SubPids = [SubPid | emqx_misc:drain_down(?BATCH_SIZE)], ok = emqx_pool:async_submit( fun lists:foreach/2, [fun clean_down/1, SubPids]), {_, PMon1} = emqx_pmon:erase_all(SubPids, PMon), {noreply, State#{pmon := PMon1}}; handle_info(Info, State) -> ?LOG(error, "Unexpected info: ~p", [Info]), {noreply, State}. terminate(_Reason, _State) -> true = emqx_sequence:delete(?SUBSEQ), emqx_stats:cancel_update(broker_stats). code_change(_OldVsn, State, _Extra) -> {ok, State}. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- clean_down(SubPid) -> case ets:lookup(?SUBMON, SubPid) of [{_, SubId}] -> true = ets:delete(?SUBMON, SubPid), true = (SubId =:= undefined) orelse ets:delete_object(?SUBID, {SubId, SubPid}), emqx_broker:subscriber_down(SubPid); [] -> ok end.
null
https://raw.githubusercontent.com/dgiot/dgiot/c601555e45f38d02aafc308b18a9e28c543b6f2c/src/emqx_broker_helper.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. -------------------------------------------------------------------- APIs gen_server callbacks Dynamic sharding later... -------------------------------------------------------------------- gen_server callbacks -------------------------------------------------------------------- Helper table SubId: SubId -> SubPid Stats timer -------------------------------------------------------------------- --------------------------------------------------------------------
Copyright ( c ) 2018 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_broker_helper). -behaviour(gen_server). -include("logger.hrl"). -include("types.hrl"). -logger_header("[Broker Helper]"). -export([start_link/0]). -export([ register_sub/2 , lookup_subid/1 , lookup_subpid/1 , get_sub_shard/2 , create_seq/1 , reclaim_seq/1 ]). -export([ init/1 , handle_call/3 , handle_cast/2 , handle_info/2 , terminate/2 , code_change/3 ]). -ifdef(TEST). -compile(export_all). -compile(nowarn_export_all). -endif. -define(HELPER, ?MODULE). -define(SUBID, emqx_subid). -define(SUBMON, emqx_submon). -define(SUBSEQ, emqx_subseq). -define(SHARD, 1024). -define(BATCH_SIZE, 100000). -spec(start_link() -> startlink_ret()). start_link() -> gen_server:start_link({local, ?HELPER}, ?MODULE, [], []). -spec(register_sub(pid(), emqx_types:subid()) -> ok). register_sub(SubPid, SubId) when is_pid(SubPid) -> case ets:lookup(?SUBMON, SubPid) of [] -> gen_server:cast(?HELPER, {register_sub, SubPid, SubId}); [{_, SubId}] -> ok; _Other -> error(subid_conflict) end. -spec(lookup_subid(pid()) -> maybe(emqx_types:subid())). lookup_subid(SubPid) when is_pid(SubPid) -> emqx_tables:lookup_value(?SUBMON, SubPid). -spec(lookup_subpid(emqx_types:subid()) -> maybe(pid())). lookup_subpid(SubId) -> emqx_tables:lookup_value(?SUBID, SubId). -spec(get_sub_shard(pid(), emqx_topic:topic()) -> non_neg_integer()). get_sub_shard(SubPid, Topic) -> case create_seq(Topic) of Seq when Seq =< ?SHARD -> 0; _ -> erlang:phash2(SubPid, shards_num()) + 1 end. -spec(shards_num() -> pos_integer()). shards_num() -> ets:lookup_element(?HELPER, shards, 2). -spec(create_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). create_seq(Topic) -> emqx_sequence:nextval(?SUBSEQ, Topic). -spec(reclaim_seq(emqx_topic:topic()) -> emqx_sequence:seqid()). reclaim_seq(Topic) -> emqx_sequence:reclaim(?SUBSEQ, Topic). init([]) -> ok = emqx_tables:new(?HELPER, [{read_concurrency, true}]), Shards : CPU * 32 true = ets:insert(?HELPER, {shards, emqx_vm:schedulers() * 32}), SubSeq : Topic - > SeqId ok = emqx_sequence:create(?SUBSEQ), ok = emqx_tables:new(?SUBID, [public, {read_concurrency, true}, {write_concurrency, true}]), SubMon : SubPid - > SubId ok = emqx_tables:new(?SUBMON, [public, {read_concurrency, true}, {write_concurrency, true}]), ok = emqx_stats:update_interval(broker_stats, fun emqx_broker:stats_fun/0), {ok, #{pmon => emqx_pmon:new()}}. handle_call(Req, _From, State) -> ?LOG(error, "Unexpected call: ~p", [Req]), {reply, ignored, State}. handle_cast({register_sub, SubPid, SubId}, State = #{pmon := PMon}) -> true = (SubId =:= undefined) orelse ets:insert(?SUBID, {SubId, SubPid}), true = ets:insert(?SUBMON, {SubPid, SubId}), {noreply, State#{pmon := emqx_pmon:monitor(SubPid, PMon)}}; handle_cast(Msg, State) -> ?LOG(error, "Unexpected cast: ~p", [Msg]), {noreply, State}. handle_info({'DOWN', _MRef, process, SubPid, _Reason}, State = #{pmon := PMon}) -> SubPids = [SubPid | emqx_misc:drain_down(?BATCH_SIZE)], ok = emqx_pool:async_submit( fun lists:foreach/2, [fun clean_down/1, SubPids]), {_, PMon1} = emqx_pmon:erase_all(SubPids, PMon), {noreply, State#{pmon := PMon1}}; handle_info(Info, State) -> ?LOG(error, "Unexpected info: ~p", [Info]), {noreply, State}. terminate(_Reason, _State) -> true = emqx_sequence:delete(?SUBSEQ), emqx_stats:cancel_update(broker_stats). code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions clean_down(SubPid) -> case ets:lookup(?SUBMON, SubPid) of [{_, SubId}] -> true = ets:delete(?SUBMON, SubPid), true = (SubId =:= undefined) orelse ets:delete_object(?SUBID, {SubId, SubPid}), emqx_broker:subscriber_down(SubPid); [] -> ok end.
21182b74bb0e5f24b65de954083255014dadd52aab685b90805b1c41cf34793c
broom-lang/broom
ToJs.mli
val emit : bool -> Cfg.Program.t -> PPrint.document
null
https://raw.githubusercontent.com/broom-lang/broom/e817d0588ae7ac881f61654503910852238d6297/compiler/lib/Js/ToJs.mli
ocaml
val emit : bool -> Cfg.Program.t -> PPrint.document
0c514bbbdfeb42cdbca4a797f957a91886e064766d5eff344e5d3306e5f8cc91
dgiot/dgiot
emqx_access_control.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2017 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(emqx_access_control). -include("emqx.hrl"). -export([authenticate/1]). -export([ check_acl/3 ]). -type(result() :: #{auth_result := emqx_types:auth_result(), anonymous := boolean() }). %%-------------------------------------------------------------------- %% APIs %%-------------------------------------------------------------------- -spec(authenticate(emqx_types:clientinfo()) -> {ok, result()} | {error, term()}). authenticate(ClientInfo = #{zone := Zone}) -> ok = emqx_metrics:inc('client.authenticate'), Username = maps:get(username, ClientInfo, undefined), {MaybeStop, AuthResult} = default_auth_result(Username, Zone), case MaybeStop of stop -> return_auth_result(AuthResult); continue -> return_auth_result(emqx_hooks:run_fold('client.authenticate', [ClientInfo], AuthResult)) end. %% @doc Check ACL -spec(check_acl(emqx_types:clientinfo(), emqx_types:pubsub(), emqx_types:topic()) -> allow | deny). check_acl(ClientInfo, PubSub, Topic) -> Result = case emqx_acl_cache:is_enabled() of true -> check_acl_cache(ClientInfo, PubSub, Topic); false -> do_check_acl(ClientInfo, PubSub, Topic) end, inc_acl_metrics(Result), Result. %%-------------------------------------------------------------------- Internal functions %%-------------------------------------------------------------------- %% ACL check_acl_cache(ClientInfo, PubSub, Topic) -> case emqx_acl_cache:get_acl_cache(PubSub, Topic) of not_found -> AclResult = do_check_acl(ClientInfo, PubSub, Topic), emqx_acl_cache:put_acl_cache(PubSub, Topic, AclResult), AclResult; AclResult -> inc_acl_metrics(cache_hit), emqx:run_hook('client.check_acl_complete', [ClientInfo, PubSub, Topic, AclResult, true]), AclResult end. do_check_acl(ClientInfo = #{zone := Zone}, PubSub, Topic) -> Default = emqx_zone:get_env(Zone, acl_nomatch, deny), ok = emqx_metrics:inc('client.check_acl'), Result = case emqx_hooks:run_fold('client.check_acl', [ClientInfo, PubSub, Topic], Default) of allow -> allow; _Other -> deny end, emqx:run_hook('client.check_acl_complete', [ClientInfo, PubSub, Topic, Result, false]), Result. -compile({inline, [inc_acl_metrics/1]}). inc_acl_metrics(allow) -> emqx_metrics:inc('client.acl.allow'); inc_acl_metrics(deny) -> emqx_metrics:inc('client.acl.deny'); inc_acl_metrics(cache_hit) -> emqx_metrics:inc('client.acl.cache_hit'). Auth default_auth_result(Username, Zone) -> IsAnonymous = (Username =:= undefined orelse Username =:= <<>>), AllowAnonymous = emqx_zone:get_env(Zone, allow_anonymous, false), Bypass = emqx_zone:get_env(Zone, bypass_auth_plugins, false), %% the `anonymous` field in auth result does not mean the client is %% connected without username, but if the auth result is based on %% allowing anonymous access. IsResultBasedOnAllowAnonymous = case AllowAnonymous of true -> true; _ -> false end, Result = case AllowAnonymous of true -> #{auth_result => success, anonymous => IsResultBasedOnAllowAnonymous}; _ -> #{auth_result => not_authorized, anonymous => IsResultBasedOnAllowAnonymous} end, case {IsAnonymous, AllowAnonymous} of {true, false_quick_deny} -> {stop, Result}; _ when Bypass -> {stop, Result}; _ -> {continue, Result} end. -compile({inline, [return_auth_result/1]}). return_auth_result(AuthResult = #{auth_result := success}) -> inc_auth_success_metrics(AuthResult), {ok, AuthResult}; return_auth_result(AuthResult) -> emqx_metrics:inc('client.auth.failure'), {error, maps:get(auth_result, AuthResult, unknown_error)}. -compile({inline, [inc_auth_success_metrics/1]}). inc_auth_success_metrics(AuthResult) -> is_anonymous(AuthResult) andalso emqx_metrics:inc('client.auth.success.anonymous'), emqx_metrics:inc('client.auth.success'). is_anonymous(#{anonymous := true}) -> true; is_anonymous(_AuthResult) -> false.
null
https://raw.githubusercontent.com/dgiot/dgiot/c601555e45f38d02aafc308b18a9e28c543b6f2c/src/emqx_access_control.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. -------------------------------------------------------------------- -------------------------------------------------------------------- APIs -------------------------------------------------------------------- @doc Check ACL -------------------------------------------------------------------- -------------------------------------------------------------------- ACL the `anonymous` field in auth result does not mean the client is connected without username, but if the auth result is based on allowing anonymous access.
Copyright ( c ) 2017 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(emqx_access_control). -include("emqx.hrl"). -export([authenticate/1]). -export([ check_acl/3 ]). -type(result() :: #{auth_result := emqx_types:auth_result(), anonymous := boolean() }). -spec(authenticate(emqx_types:clientinfo()) -> {ok, result()} | {error, term()}). authenticate(ClientInfo = #{zone := Zone}) -> ok = emqx_metrics:inc('client.authenticate'), Username = maps:get(username, ClientInfo, undefined), {MaybeStop, AuthResult} = default_auth_result(Username, Zone), case MaybeStop of stop -> return_auth_result(AuthResult); continue -> return_auth_result(emqx_hooks:run_fold('client.authenticate', [ClientInfo], AuthResult)) end. -spec(check_acl(emqx_types:clientinfo(), emqx_types:pubsub(), emqx_types:topic()) -> allow | deny). check_acl(ClientInfo, PubSub, Topic) -> Result = case emqx_acl_cache:is_enabled() of true -> check_acl_cache(ClientInfo, PubSub, Topic); false -> do_check_acl(ClientInfo, PubSub, Topic) end, inc_acl_metrics(Result), Result. Internal functions check_acl_cache(ClientInfo, PubSub, Topic) -> case emqx_acl_cache:get_acl_cache(PubSub, Topic) of not_found -> AclResult = do_check_acl(ClientInfo, PubSub, Topic), emqx_acl_cache:put_acl_cache(PubSub, Topic, AclResult), AclResult; AclResult -> inc_acl_metrics(cache_hit), emqx:run_hook('client.check_acl_complete', [ClientInfo, PubSub, Topic, AclResult, true]), AclResult end. do_check_acl(ClientInfo = #{zone := Zone}, PubSub, Topic) -> Default = emqx_zone:get_env(Zone, acl_nomatch, deny), ok = emqx_metrics:inc('client.check_acl'), Result = case emqx_hooks:run_fold('client.check_acl', [ClientInfo, PubSub, Topic], Default) of allow -> allow; _Other -> deny end, emqx:run_hook('client.check_acl_complete', [ClientInfo, PubSub, Topic, Result, false]), Result. -compile({inline, [inc_acl_metrics/1]}). inc_acl_metrics(allow) -> emqx_metrics:inc('client.acl.allow'); inc_acl_metrics(deny) -> emqx_metrics:inc('client.acl.deny'); inc_acl_metrics(cache_hit) -> emqx_metrics:inc('client.acl.cache_hit'). Auth default_auth_result(Username, Zone) -> IsAnonymous = (Username =:= undefined orelse Username =:= <<>>), AllowAnonymous = emqx_zone:get_env(Zone, allow_anonymous, false), Bypass = emqx_zone:get_env(Zone, bypass_auth_plugins, false), IsResultBasedOnAllowAnonymous = case AllowAnonymous of true -> true; _ -> false end, Result = case AllowAnonymous of true -> #{auth_result => success, anonymous => IsResultBasedOnAllowAnonymous}; _ -> #{auth_result => not_authorized, anonymous => IsResultBasedOnAllowAnonymous} end, case {IsAnonymous, AllowAnonymous} of {true, false_quick_deny} -> {stop, Result}; _ when Bypass -> {stop, Result}; _ -> {continue, Result} end. -compile({inline, [return_auth_result/1]}). return_auth_result(AuthResult = #{auth_result := success}) -> inc_auth_success_metrics(AuthResult), {ok, AuthResult}; return_auth_result(AuthResult) -> emqx_metrics:inc('client.auth.failure'), {error, maps:get(auth_result, AuthResult, unknown_error)}. -compile({inline, [inc_auth_success_metrics/1]}). inc_auth_success_metrics(AuthResult) -> is_anonymous(AuthResult) andalso emqx_metrics:inc('client.auth.success.anonymous'), emqx_metrics:inc('client.auth.success'). is_anonymous(#{anonymous := true}) -> true; is_anonymous(_AuthResult) -> false.
bc4adef27c5aef4da73b76c0e239b94e68e522853129528e0dc668c868c2f034
brendanhay/amazonka
DuplicateRegistrationAction.hs
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # {-# LANGUAGE StrictData #-} # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # Derived from AWS service descriptions , licensed under Apache 2.0 . -- | Module : Amazonka . VoiceId . Types . DuplicateRegistrationAction Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > -- Stability : auto-generated Portability : non - portable ( GHC extensions ) module Amazonka.VoiceId.Types.DuplicateRegistrationAction ( DuplicateRegistrationAction ( .., DuplicateRegistrationAction_REGISTER_AS_NEW, DuplicateRegistrationAction_SKIP ), ) where import qualified Amazonka.Core as Core import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude newtype DuplicateRegistrationAction = DuplicateRegistrationAction' { fromDuplicateRegistrationAction :: Data.Text } deriving stock ( Prelude.Show, Prelude.Read, Prelude.Eq, Prelude.Ord, Prelude.Generic ) deriving newtype ( Prelude.Hashable, Prelude.NFData, Data.FromText, Data.ToText, Data.ToByteString, Data.ToLog, Data.ToHeader, Data.ToQuery, Data.FromJSON, Data.FromJSONKey, Data.ToJSON, Data.ToJSONKey, Data.FromXML, Data.ToXML ) pattern DuplicateRegistrationAction_REGISTER_AS_NEW :: DuplicateRegistrationAction pattern DuplicateRegistrationAction_REGISTER_AS_NEW = DuplicateRegistrationAction' "REGISTER_AS_NEW" pattern DuplicateRegistrationAction_SKIP :: DuplicateRegistrationAction pattern DuplicateRegistrationAction_SKIP = DuplicateRegistrationAction' "SKIP" {-# COMPLETE DuplicateRegistrationAction_REGISTER_AS_NEW, DuplicateRegistrationAction_SKIP, DuplicateRegistrationAction' #-}
null
https://raw.githubusercontent.com/brendanhay/amazonka/09f52b75d2cfdff221b439280d3279d22690d6a6/lib/services/amazonka-voice-id/gen/Amazonka/VoiceId/Types/DuplicateRegistrationAction.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE StrictData # | Stability : auto-generated # COMPLETE DuplicateRegistrationAction_REGISTER_AS_NEW, DuplicateRegistrationAction_SKIP, DuplicateRegistrationAction' #
# LANGUAGE DeriveGeneric # # LANGUAGE DerivingStrategies # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE PatternSynonyms # # LANGUAGE NoImplicitPrelude # # OPTIONS_GHC -fno - warn - unused - imports # Derived from AWS service descriptions , licensed under Apache 2.0 . Module : Amazonka . VoiceId . Types . DuplicateRegistrationAction Copyright : ( c ) 2013 - 2023 License : Mozilla Public License , v. 2.0 . Maintainer : < brendan.g.hay+ > Portability : non - portable ( GHC extensions ) module Amazonka.VoiceId.Types.DuplicateRegistrationAction ( DuplicateRegistrationAction ( .., DuplicateRegistrationAction_REGISTER_AS_NEW, DuplicateRegistrationAction_SKIP ), ) where import qualified Amazonka.Core as Core import qualified Amazonka.Data as Data import qualified Amazonka.Prelude as Prelude newtype DuplicateRegistrationAction = DuplicateRegistrationAction' { fromDuplicateRegistrationAction :: Data.Text } deriving stock ( Prelude.Show, Prelude.Read, Prelude.Eq, Prelude.Ord, Prelude.Generic ) deriving newtype ( Prelude.Hashable, Prelude.NFData, Data.FromText, Data.ToText, Data.ToByteString, Data.ToLog, Data.ToHeader, Data.ToQuery, Data.FromJSON, Data.FromJSONKey, Data.ToJSON, Data.ToJSONKey, Data.FromXML, Data.ToXML ) pattern DuplicateRegistrationAction_REGISTER_AS_NEW :: DuplicateRegistrationAction pattern DuplicateRegistrationAction_REGISTER_AS_NEW = DuplicateRegistrationAction' "REGISTER_AS_NEW" pattern DuplicateRegistrationAction_SKIP :: DuplicateRegistrationAction pattern DuplicateRegistrationAction_SKIP = DuplicateRegistrationAction' "SKIP"
aa3fa57c667a7dc0bdf86879c54704e16dc059f8ba7aa03c9c3e53889bcc529c
softwarelanguageslab/maf
R5RS_ad_qsort-5.scm
; Changes: * removed : 1 * added : 3 * swaps : 0 * negated predicates : 1 ; * swapped branches: 0 * calls to i d fun : 3 (letrec ((quick-sort (lambda (vector) (letrec ((swap (lambda (v index1 index2) (let ((temp (vector-ref v index1))) (vector-set! v index1 (vector-ref v index2)) (vector-set! v index2 temp)))) (quick-sort-aux (lambda (low high) (<change> (letrec ((quick-sort-aux-iter (lambda (mid-value from to) (letrec ((quick-right (lambda (index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2)))))) (if (< low high) (let ((middle (quotient (+ low high) 2)) (pivot-index (+ low 1))) (swap vector middle pivot-index) (if (> (vector-ref vector pivot-index) (vector-ref vector high)) (swap vector pivot-index high) #f) (if (> (vector-ref vector low) (vector-ref vector high)) (swap vector low high) #f) (if (< (vector-ref vector pivot-index) (vector-ref vector low)) (swap vector pivot-index low) #f) (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (quick-sort-aux (+ mid-index 1) high))) #f)) ((lambda (x) x) (letrec ((quick-sort-aux-iter (lambda (mid-value from to) (<change> (letrec ((quick-right (lambda (index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2))) ((lambda (x) x) (letrec ((quick-right (lambda (index1) (<change> () index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (<change> (> index2 low) (not (> index2 low))) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2)))))))) (if (< low high) (let ((middle (quotient (+ low high) 2)) (pivot-index (+ low 1))) (swap vector middle pivot-index) (if (> (vector-ref vector pivot-index) (vector-ref vector high)) (swap vector pivot-index high) #f) (if (> (vector-ref vector low) (vector-ref vector high)) (swap vector low high) #f) (<change> (if (< (vector-ref vector pivot-index) (vector-ref vector low)) (swap vector pivot-index low) #f) ()) (<change> (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (quick-sort-aux (+ mid-index 1) high)) ((lambda (x) x) (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (<change> () vector) (<change> () (display +)) (quick-sort-aux (+ mid-index 1) high))))) #f))))))) (quick-sort-aux 0 (- (vector-length vector) 1))))) (test3 (vector 8 3 6 6 1 5 4 2 9 6))) (quick-sort test3) (equal? test3 (vector 1 2 3 4 5 6 6 6 8 9)))
null
https://raw.githubusercontent.com/softwarelanguageslab/maf/11acedf56b9bf0c8e55ddb6aea754b6766d8bb40/test/changes/scheme/generated/R5RS_ad_qsort-5.scm
scheme
Changes: * swapped branches: 0
* removed : 1 * added : 3 * swaps : 0 * negated predicates : 1 * calls to i d fun : 3 (letrec ((quick-sort (lambda (vector) (letrec ((swap (lambda (v index1 index2) (let ((temp (vector-ref v index1))) (vector-set! v index1 (vector-ref v index2)) (vector-set! v index2 temp)))) (quick-sort-aux (lambda (low high) (<change> (letrec ((quick-sort-aux-iter (lambda (mid-value from to) (letrec ((quick-right (lambda (index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2)))))) (if (< low high) (let ((middle (quotient (+ low high) 2)) (pivot-index (+ low 1))) (swap vector middle pivot-index) (if (> (vector-ref vector pivot-index) (vector-ref vector high)) (swap vector pivot-index high) #f) (if (> (vector-ref vector low) (vector-ref vector high)) (swap vector low high) #f) (if (< (vector-ref vector pivot-index) (vector-ref vector low)) (swap vector pivot-index low) #f) (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (quick-sort-aux (+ mid-index 1) high))) #f)) ((lambda (x) x) (letrec ((quick-sort-aux-iter (lambda (mid-value from to) (<change> (letrec ((quick-right (lambda (index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (> index2 low) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2))) ((lambda (x) x) (letrec ((quick-right (lambda (index1) (<change> () index1) (if (if (< index1 high) (< (vector-ref vector index1) mid-value) #f) (quick-right (+ index1 1)) index1))) (quick-left (lambda (index2) (if (if (<change> (> index2 low) (not (> index2 low))) (> (vector-ref vector index2) mid-value) #f) (quick-left (- index2 1)) index2)))) (let ((index1 (quick-right (+ from 1))) (index2 (quick-left to))) (if (< index1 index2) (begin (swap vector index1 index2) (quick-sort-aux-iter mid-value index1 index2)) index2)))))))) (if (< low high) (let ((middle (quotient (+ low high) 2)) (pivot-index (+ low 1))) (swap vector middle pivot-index) (if (> (vector-ref vector pivot-index) (vector-ref vector high)) (swap vector pivot-index high) #f) (if (> (vector-ref vector low) (vector-ref vector high)) (swap vector low high) #f) (<change> (if (< (vector-ref vector pivot-index) (vector-ref vector low)) (swap vector pivot-index low) #f) ()) (<change> (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (quick-sort-aux (+ mid-index 1) high)) ((lambda (x) x) (let ((mid-index (quick-sort-aux-iter (vector-ref vector pivot-index) (+ low 1) high))) (swap vector mid-index pivot-index) (quick-sort-aux low (- mid-index 1)) (<change> () vector) (<change> () (display +)) (quick-sort-aux (+ mid-index 1) high))))) #f))))))) (quick-sort-aux 0 (- (vector-length vector) 1))))) (test3 (vector 8 3 6 6 1 5 4 2 9 6))) (quick-sort test3) (equal? test3 (vector 1 2 3 4 5 6 6 6 8 9)))
7db0f97df6ac0091f776bee5a01724ef74d4830c796267df4f4edd8175e968c1
tweag/asterius
T5785.hs
module Main where import Data.Int import Data.Word Test case for bug # 5785 . The cause of this was that the backend converted all Int constants using ( fromInteger : : Int ) and so on 32bit a Int64 or would be truncated to 32bit ! value before printing out . main :: IO () main = do first two should print as big numbers ( as unsigned ) print (-1 :: Word8) print (-1 :: Word16) print (-1 :: Word32) print (-1 :: Word64) print (-1 :: Int8) print (-1 :: Int16) print (-1 :: Int32) print (-1 :: Int64) only requires 32 bits ( unsigned ) print (2316287658 :: Word8) print (2316287658 :: Word16) print (2316287658 :: Word32) print (2316287658 :: Word64) print (2316287658 :: Int8) print (2316287658 :: Int16) print (2316287658 :: Int32) print (2316287658 :: Int64) this requries a 64 ( unsigned ) bit word to store correctly print (32342316287658 :: Word8) print (32342316287658 :: Word16) print (32342316287658 :: Word32) print (32342316287658 :: Word64) print (32342316287658 :: Int8) print (32342316287658 :: Int16) print (32342316287658 :: Int32) print (32342316287658 :: Int64)
null
https://raw.githubusercontent.com/tweag/asterius/e7b823c87499656860f87b9b468eb0567add1de8/asterius/test/ghc-testsuite/codeGen/T5785.hs
haskell
module Main where import Data.Int import Data.Word Test case for bug # 5785 . The cause of this was that the backend converted all Int constants using ( fromInteger : : Int ) and so on 32bit a Int64 or would be truncated to 32bit ! value before printing out . main :: IO () main = do first two should print as big numbers ( as unsigned ) print (-1 :: Word8) print (-1 :: Word16) print (-1 :: Word32) print (-1 :: Word64) print (-1 :: Int8) print (-1 :: Int16) print (-1 :: Int32) print (-1 :: Int64) only requires 32 bits ( unsigned ) print (2316287658 :: Word8) print (2316287658 :: Word16) print (2316287658 :: Word32) print (2316287658 :: Word64) print (2316287658 :: Int8) print (2316287658 :: Int16) print (2316287658 :: Int32) print (2316287658 :: Int64) this requries a 64 ( unsigned ) bit word to store correctly print (32342316287658 :: Word8) print (32342316287658 :: Word16) print (32342316287658 :: Word32) print (32342316287658 :: Word64) print (32342316287658 :: Int8) print (32342316287658 :: Int16) print (32342316287658 :: Int32) print (32342316287658 :: Int64)
0c37a2768a67fde55ef687c4345250bd6fa4c8b50a25f07e390dff7ab505b266
exercism/racket
acronym-test.rkt
#lang racket/base Tests adapted from ` problem - specifications / canonical - data.json v1.7.0 (require "acronym.rkt") (module+ test (require rackunit rackunit/text-ui) (define suite (test-suite "acronym tests" (test-equal? "basic" (acronym "Portable Network Graphics") "PNG") (test-equal? "lowercase words" (acronym "Ruby on Rails") "ROR") (test-equal? "punctuation" (acronym "First In, First Out") "FIFO") (test-equal? "all caps word" (acronym "GNU Image Manipulation Program") "GIMP") (test-equal? "punctuation without whitespace" (acronym "Complementary metal-oxide semiconductor") "CMOS") (test-equal? "very long abbreviation" (acronym "Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me") "ROTFLSHTMDCOALM") (test-equal? "consecutive delimiters" (acronym "Something - I made up from thin air") "SIMUFTA") (test-equal? "apostrophes" (acronym "Halley's Comet") "HC") (test-equal? "underscore emphasis" (acronym "The Road _Not_ Taken") "TRNT"))) (run-tests suite))
null
https://raw.githubusercontent.com/exercism/racket/4110268ed331b1b4dac8888550f05d0dacb1865b/exercises/practice/acronym/acronym-test.rkt
racket
#lang racket/base Tests adapted from ` problem - specifications / canonical - data.json v1.7.0 (require "acronym.rkt") (module+ test (require rackunit rackunit/text-ui) (define suite (test-suite "acronym tests" (test-equal? "basic" (acronym "Portable Network Graphics") "PNG") (test-equal? "lowercase words" (acronym "Ruby on Rails") "ROR") (test-equal? "punctuation" (acronym "First In, First Out") "FIFO") (test-equal? "all caps word" (acronym "GNU Image Manipulation Program") "GIMP") (test-equal? "punctuation without whitespace" (acronym "Complementary metal-oxide semiconductor") "CMOS") (test-equal? "very long abbreviation" (acronym "Rolling On The Floor Laughing So Hard That My Dogs Came Over And Licked Me") "ROTFLSHTMDCOALM") (test-equal? "consecutive delimiters" (acronym "Something - I made up from thin air") "SIMUFTA") (test-equal? "apostrophes" (acronym "Halley's Comet") "HC") (test-equal? "underscore emphasis" (acronym "The Road _Not_ Taken") "TRNT"))) (run-tests suite))
cb02268803858a13c550d3966cccd60c43022eb0d505a0de1460549be6061635
BinaryAnalysisPlatform/bap
graphlib_regular.mli
open Core_kernel[@@warning "-D"] open Regular.Std open Graphlib_intf open Graphlib_graph open Graphlib_regular_intf module Make(Node : Opaque.S)(Label : T) : Graph with type node = Node.t and type Node.label = Node.t and type Edge.label = Label.t module Labeled(Node : Opaque.S)(NL : T)(EL : T) : Graph with type node = (Node.t, NL.t) labeled and type Node.label = (Node.t, NL.t) labeled and type Edge.label = EL.t module Aux(M : sig include Pretty_printer.S val module_name : string end) : Aux with type node := M.t
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap/253afc171bbfd0fe1b34f6442795dbf4b1798348/lib/graphlib/graphlib_regular.mli
ocaml
open Core_kernel[@@warning "-D"] open Regular.Std open Graphlib_intf open Graphlib_graph open Graphlib_regular_intf module Make(Node : Opaque.S)(Label : T) : Graph with type node = Node.t and type Node.label = Node.t and type Edge.label = Label.t module Labeled(Node : Opaque.S)(NL : T)(EL : T) : Graph with type node = (Node.t, NL.t) labeled and type Node.label = (Node.t, NL.t) labeled and type Edge.label = EL.t module Aux(M : sig include Pretty_printer.S val module_name : string end) : Aux with type node := M.t
14f27be1e22847d9a8d2c951b16339ba3b82dad50f3542e88669b392a3e9cfd2
libguestfs/supermin
mode_build.mli
supermin 5 * Copyright ( C ) 2009 - 2016 Red Hat Inc. * * 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. , 51 Franklin Street , Fifth Floor , Boston , USA * Copyright (C) 2009-2016 Red Hat Inc. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) (** Implements the [--build] subcommand. *) val build : int -> (bool * Types.format * string * string option * string * bool * int64 option * bool) -> string list -> string -> unit (** [build debug (args...) inputs outputdir] performs the [supermin --build] subcommand. *) val get_outputs : (bool * Types.format * string * string option * string * bool * int64 option * bool) -> string list -> string list (** [get_outputs (args...) inputs] gets the potential outputs for the appliance. *)
null
https://raw.githubusercontent.com/libguestfs/supermin/fd9f17c7eb63979af882533a0d234bfc8ca42de3/src/mode_build.mli
ocaml
* Implements the [--build] subcommand. * [build debug (args...) inputs outputdir] performs the [supermin --build] subcommand. * [get_outputs (args...) inputs] gets the potential outputs for the appliance.
supermin 5 * Copyright ( C ) 2009 - 2016 Red Hat Inc. * * 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. , 51 Franklin Street , Fifth Floor , Boston , USA * Copyright (C) 2009-2016 Red Hat Inc. * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *) val build : int -> (bool * Types.format * string * string option * string * bool * int64 option * bool) -> string list -> string -> unit val get_outputs : (bool * Types.format * string * string option * string * bool * int64 option * bool) -> string list -> string list
c253c8dff1e1ba6486ab1dd9a943c3ce69ea97759a1ade06cc3ebc761e3a2f57
bortexz/graphcom
graphcom_test.cljc
(ns bortexz.graphcom-test (:require [clojure.test :refer [deftest is testing]] [bortexz.graphcom :as g])) (deftest base-test (let [input (g/input-node) sum-node (g/compute-node {:source input} (fn [val {:keys [source]}] (+ (or val 0) source))) graph (g/graph {:input input :sum sum-node}) context (g/context graph)] (testing "Correct value after processing graph context" (is (= 10 (g/value (g/process context {:input 10}) :sum)))) (testing "Correctly inputs current value on handler" (is (= 20 (-> context (g/process {:input 10}) (g/process {:input 10}) (g/value :sum))))) (testing "Precompile works" (is (= (:compilations (g/precompile context #{:input})) (:compilations (g/process context {:input 10}))))))) (defn relay-node [source] (g/compute-node {:source source} (fn [_ {:keys [source]}] source))) (deftest hidden-nodes (let [input (g/input-node) hidden-node (relay-node input) final-node (relay-node hidden-node) graph (g/graph {:input input :node final-node}) context (g/context graph)] (testing "Doesn't ignore hidden nodes" (is (= 10 (g/value (g/process context {:input 10}) :node)))))) (defn test-processor [processor] (let [input1 (g/input-node) input2 (g/input-node) relay1 (relay-node input1) relay2 (relay-node input2) sum-node (g/compute-node {:input1 relay1 :input2 relay2} (fn [_ {:keys [input1 input2]}] (+ input1 input2))) graph (g/graph {:input1 input1 :input2 input2 :sum sum-node}) context (g/context graph processor)] (testing "Works fine on all inputs being passed" (is (= 20 (g/value (g/process context {:input1 10 :input2 10}) :sum)))) (testing "Inputs that are not specified do not propagate nil value, and intermediary compute node keeps old value" (is (= 30 (-> context (g/process {:input1 10 :input2 10}) (g/process {:input1 20}) (g/value :sum))))) (testing "Input values are ephemeral and cannot be retrieved with value or values" (let [processed (-> context (g/process {:input1 10 :input2 10}))] (is (nil? (g/value processed :input1))) (is (nil? (:input1 (g/values processed)))))) (testing "Exception paths is correct" (let [i (g/input-node) c (g/compute-node {:input i} (fn [_ _] (throw (ex-info "" {})))) c1 (g/compute-node {:source c} (fn [_ _])) c2 (g/compute-node {:source c} (fn [_ _])) c3 (g/compute-node {:c1 c1 :c2 c2} (fn [_ _])) ctx (g/context (g/graph {:input i :compute c3})) ex-paths (try (g/process ctx {:input true}) (catch #?(:clj Exception :cljs js/Error) e (:paths (ex-data e))))] (is (true? (contains? ex-paths [:compute :c1 :source]))) (is (true? (contains? ex-paths [:compute :c2 :source]))))))) (deftest processor (testing "Sequential processor" (test-processor (g/sequential-processor)) #?(:clj (test-processor (g/parallel-processor)))))
null
https://raw.githubusercontent.com/bortexz/graphcom/5679e4c3562b8d968eb74b18272a1962efa82c81/test/bortexz/graphcom_test.cljc
clojure
(ns bortexz.graphcom-test (:require [clojure.test :refer [deftest is testing]] [bortexz.graphcom :as g])) (deftest base-test (let [input (g/input-node) sum-node (g/compute-node {:source input} (fn [val {:keys [source]}] (+ (or val 0) source))) graph (g/graph {:input input :sum sum-node}) context (g/context graph)] (testing "Correct value after processing graph context" (is (= 10 (g/value (g/process context {:input 10}) :sum)))) (testing "Correctly inputs current value on handler" (is (= 20 (-> context (g/process {:input 10}) (g/process {:input 10}) (g/value :sum))))) (testing "Precompile works" (is (= (:compilations (g/precompile context #{:input})) (:compilations (g/process context {:input 10}))))))) (defn relay-node [source] (g/compute-node {:source source} (fn [_ {:keys [source]}] source))) (deftest hidden-nodes (let [input (g/input-node) hidden-node (relay-node input) final-node (relay-node hidden-node) graph (g/graph {:input input :node final-node}) context (g/context graph)] (testing "Doesn't ignore hidden nodes" (is (= 10 (g/value (g/process context {:input 10}) :node)))))) (defn test-processor [processor] (let [input1 (g/input-node) input2 (g/input-node) relay1 (relay-node input1) relay2 (relay-node input2) sum-node (g/compute-node {:input1 relay1 :input2 relay2} (fn [_ {:keys [input1 input2]}] (+ input1 input2))) graph (g/graph {:input1 input1 :input2 input2 :sum sum-node}) context (g/context graph processor)] (testing "Works fine on all inputs being passed" (is (= 20 (g/value (g/process context {:input1 10 :input2 10}) :sum)))) (testing "Inputs that are not specified do not propagate nil value, and intermediary compute node keeps old value" (is (= 30 (-> context (g/process {:input1 10 :input2 10}) (g/process {:input1 20}) (g/value :sum))))) (testing "Input values are ephemeral and cannot be retrieved with value or values" (let [processed (-> context (g/process {:input1 10 :input2 10}))] (is (nil? (g/value processed :input1))) (is (nil? (:input1 (g/values processed)))))) (testing "Exception paths is correct" (let [i (g/input-node) c (g/compute-node {:input i} (fn [_ _] (throw (ex-info "" {})))) c1 (g/compute-node {:source c} (fn [_ _])) c2 (g/compute-node {:source c} (fn [_ _])) c3 (g/compute-node {:c1 c1 :c2 c2} (fn [_ _])) ctx (g/context (g/graph {:input i :compute c3})) ex-paths (try (g/process ctx {:input true}) (catch #?(:clj Exception :cljs js/Error) e (:paths (ex-data e))))] (is (true? (contains? ex-paths [:compute :c1 :source]))) (is (true? (contains? ex-paths [:compute :c2 :source]))))))) (deftest processor (testing "Sequential processor" (test-processor (g/sequential-processor)) #?(:clj (test-processor (g/parallel-processor)))))
d85af65efc5b95a9a95d0bb95e779057ed2d1c035af3379df7e48c2af5f06d3d
wingo/fibers
timers.scm
;; Fibers: cooperative, event-driven user-space threads. Copyright ( C ) 2016 Free Software Foundation , Inc. ;;;; ;;;; This library is free software; you can redistribute it and/or ;;;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;;;; ;;;; This library is distributed in the hope that it will be useful, ;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;;;; Lesser General Public License for more details. ;;;; You should have received a copy of the GNU Lesser General Public License ;;;; along with this program. If not, see </>. ;;;; (define-module (fibers timers) #:use-module (fibers scheduler) #:use-module (fibers operations) #:use-module (ice-9 atomic) #:use-module (ice-9 match) #:use-module (ice-9 threads) #:export (sleep-operation timer-operation) #:replace (sleep)) (define *timer-sched* (make-atomic-box #f)) (define (timer-sched) (or (atomic-box-ref *timer-sched*) (let ((sched (make-scheduler))) (cond ((atomic-box-compare-and-swap! *timer-sched* #f sched)) (else ;; FIXME: Would be nice to clean up this thread at some point. (call-with-new-thread (lambda () (define (finished?) #f) (run-scheduler sched finished?))) sched))))) (define (timer-operation expiry) "Make an operation that will succeed when the current time is greater than or equal to @var{expiry}, expressed in internal time units. The operation will succeed with no values." (make-base-operation #f (lambda () (and (< expiry (get-internal-real-time)) values)) (lambda (flag sched resume) (define (timer) (match (atomic-box-compare-and-swap! flag 'W 'S) ('W (resume values)) ('C (timer)) ('S #f))) (if sched (schedule-task-at-time sched expiry timer) (schedule-task (timer-sched) (lambda () (perform-operation (timer-operation expiry)) (timer))))))) (define (sleep-operation seconds) "Make an operation that will succeed with no values when @var{seconds} have elapsed." (timer-operation (+ (get-internal-real-time) (inexact->exact (round (* seconds internal-time-units-per-second)))))) (define (sleep seconds) "Block the calling fiber until @var{seconds} have elapsed." (perform-operation (sleep-operation seconds)))
null
https://raw.githubusercontent.com/wingo/fibers/8f4ce08cd009926061d6ebfc55e4fa1e0b80ddd3/fibers/timers.scm
scheme
Fibers: cooperative, event-driven user-space threads. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. along with this program. If not, see </>. FIXME: Would be nice to clean up this thread at some point.
Copyright ( C ) 2016 Free Software Foundation , Inc. version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public License (define-module (fibers timers) #:use-module (fibers scheduler) #:use-module (fibers operations) #:use-module (ice-9 atomic) #:use-module (ice-9 match) #:use-module (ice-9 threads) #:export (sleep-operation timer-operation) #:replace (sleep)) (define *timer-sched* (make-atomic-box #f)) (define (timer-sched) (or (atomic-box-ref *timer-sched*) (let ((sched (make-scheduler))) (cond ((atomic-box-compare-and-swap! *timer-sched* #f sched)) (else (call-with-new-thread (lambda () (define (finished?) #f) (run-scheduler sched finished?))) sched))))) (define (timer-operation expiry) "Make an operation that will succeed when the current time is greater than or equal to @var{expiry}, expressed in internal time units. The operation will succeed with no values." (make-base-operation #f (lambda () (and (< expiry (get-internal-real-time)) values)) (lambda (flag sched resume) (define (timer) (match (atomic-box-compare-and-swap! flag 'W 'S) ('W (resume values)) ('C (timer)) ('S #f))) (if sched (schedule-task-at-time sched expiry timer) (schedule-task (timer-sched) (lambda () (perform-operation (timer-operation expiry)) (timer))))))) (define (sleep-operation seconds) "Make an operation that will succeed with no values when @var{seconds} have elapsed." (timer-operation (+ (get-internal-real-time) (inexact->exact (round (* seconds internal-time-units-per-second)))))) (define (sleep seconds) "Block the calling fiber until @var{seconds} have elapsed." (perform-operation (sleep-operation seconds)))
167e017566462d02198ae143c4586042a3c02159e74c03947c74d0ca2d00ab53
pangloss/pattern
predicator.clj
(ns pattern.match.predicator (:require [clojure.walk :as walk])) (def ^:dynamic *pattern-replace* "Add maps used by postwalk-replace or functions that return a transformed pattern here, and they will be applied to each rule pattern with [[do-pattern-replace]] before the rule is compiled." []) (defn match-abbr [abbr] (let [p0 (re-pattern (str "(\\?+)([^?\\w]*)(" (name abbr) ":)([a-zA-Z]\\S*)")) p1 (re-pattern (str "(\\?+)([^?\\w]*)()(" (name abbr) "[*+0123456789]*)"))] (fn symbol-matcher [x] (when (symbol? x) (or (re-matches p0 (name x)) (re-matches p1 (name x))))))) (defn apply-predicator [{:keys [abbr predicate metadata]} pattern] (let [mode (when metadata "$") symbol-matcher (match-abbr abbr)] (walk/postwalk (fn [x] (if-let [[m ? -> p n] (symbol-matcher x)] (list* (symbol (str ? -> mode)) (with-meta (symbol (str p n)) metadata) (when predicate [predicate])) x)) pattern))) (defn apply-replacements [pattern replacements] (reduce (fn [pattern pr] (cond (:predicator pr) (apply-predicator pr pattern) (ifn? pr) (pr pattern) (map? pr) (walk/postwalk-replace pr pattern) :else (throw (ex-info "Unknown *pattern-replace* object" {:pr pr})))) pattern replacements)) (defn var-abbr [prefix n] (if prefix (symbol prefix) (when n (when-let [[_ abbr :as x] (re-matches #"[^?\w]*(\w+?)[*+0123456789]*" (name n))] (symbol abbr))))) (defn make-abbr-predicator "Create a function that when applied to a pattern, will add the given predicate to any short-form var that has the given `abbr` as the main component of its name, or if it has a prefix, that matches the prefix. Actually just captures the data to build it. The function itself can be built on demand and this way it's more inspectable. Example: (make-abbr-predicator 'sym symbol?) As applied to various patterns: ?sym => (? sym ~symbol?) ?sym*0 => (? sym*0 ~symbol?) ??sym => (?? sym ~symbol?) ??->sym+ => (??-> sym+ ~symbol?) ?<-$!sym:name => (?<-$! sym:name ~symbol?) ;; abbr must match, and matcher must be short-form: ?x => ?x (? sym) => (? sym) If `metadata` is provided, it will be attached to the matcher name, and the matcher will be marked with a `$` mode character. ?sym => (?$ ~(with-meta 'sym metadata) ~symbol)" ([abbr predicate] (make-abbr-predicator nil abbr predicate)) ([metadata abbr predicate] (when (or predicate metadata) {:predicator true :abbr abbr :predicate predicate :metadata metadata}))) (defn with-predicates* [pred-map body-fn] (with-bindings* {#'*pattern-replace* (concat *pattern-replace* (map (fn [[k v]] (make-abbr-predicator k v)) pred-map))} body-fn)) (defmacro with-predicates [pred-map & forms] `(with-predicates* ~pred-map (fn [] ~@forms)))
null
https://raw.githubusercontent.com/pangloss/pattern/6d0c7130bf6f9e74610223fc2f1a4c0fd97b01fa/src/pattern/match/predicator.clj
clojure
abbr must match, and matcher must be short-form:
(ns pattern.match.predicator (:require [clojure.walk :as walk])) (def ^:dynamic *pattern-replace* "Add maps used by postwalk-replace or functions that return a transformed pattern here, and they will be applied to each rule pattern with [[do-pattern-replace]] before the rule is compiled." []) (defn match-abbr [abbr] (let [p0 (re-pattern (str "(\\?+)([^?\\w]*)(" (name abbr) ":)([a-zA-Z]\\S*)")) p1 (re-pattern (str "(\\?+)([^?\\w]*)()(" (name abbr) "[*+0123456789]*)"))] (fn symbol-matcher [x] (when (symbol? x) (or (re-matches p0 (name x)) (re-matches p1 (name x))))))) (defn apply-predicator [{:keys [abbr predicate metadata]} pattern] (let [mode (when metadata "$") symbol-matcher (match-abbr abbr)] (walk/postwalk (fn [x] (if-let [[m ? -> p n] (symbol-matcher x)] (list* (symbol (str ? -> mode)) (with-meta (symbol (str p n)) metadata) (when predicate [predicate])) x)) pattern))) (defn apply-replacements [pattern replacements] (reduce (fn [pattern pr] (cond (:predicator pr) (apply-predicator pr pattern) (ifn? pr) (pr pattern) (map? pr) (walk/postwalk-replace pr pattern) :else (throw (ex-info "Unknown *pattern-replace* object" {:pr pr})))) pattern replacements)) (defn var-abbr [prefix n] (if prefix (symbol prefix) (when n (when-let [[_ abbr :as x] (re-matches #"[^?\w]*(\w+?)[*+0123456789]*" (name n))] (symbol abbr))))) (defn make-abbr-predicator "Create a function that when applied to a pattern, will add the given predicate to any short-form var that has the given `abbr` as the main component of its name, or if it has a prefix, that matches the prefix. Actually just captures the data to build it. The function itself can be built on demand and this way it's more inspectable. Example: (make-abbr-predicator 'sym symbol?) As applied to various patterns: ?sym => (? sym ~symbol?) ?sym*0 => (? sym*0 ~symbol?) ??sym => (?? sym ~symbol?) ??->sym+ => (??-> sym+ ~symbol?) ?<-$!sym:name => (?<-$! sym:name ~symbol?) ?x => ?x (? sym) => (? sym) If `metadata` is provided, it will be attached to the matcher name, and the matcher will be marked with a `$` mode character. ?sym => (?$ ~(with-meta 'sym metadata) ~symbol)" ([abbr predicate] (make-abbr-predicator nil abbr predicate)) ([metadata abbr predicate] (when (or predicate metadata) {:predicator true :abbr abbr :predicate predicate :metadata metadata}))) (defn with-predicates* [pred-map body-fn] (with-bindings* {#'*pattern-replace* (concat *pattern-replace* (map (fn [[k v]] (make-abbr-predicator k v)) pred-map))} body-fn)) (defmacro with-predicates [pred-map & forms] `(with-predicates* ~pred-map (fn [] ~@forms)))
fd8257ac6863c9a33af1f66a56b76d601b03b13915203ed255f0af43878eb7e5
k-bx/protocol-buffers
Main.hs
module Main where import Test.QuickCheck import Arb.UnittestProto main :: IO () main = do cs mapM_ (\(name,test) -> putStrLn name >> quickCheck test) tests_TestAllExtensions mapM_ (\(name,test) -> putStrLn name >> quickCheck test) tests_TestAllTypes
null
https://raw.githubusercontent.com/k-bx/protocol-buffers/89425795ac2d560c5d690714e7d206ba9f97aff2/tests/Main.hs
haskell
module Main where import Test.QuickCheck import Arb.UnittestProto main :: IO () main = do cs mapM_ (\(name,test) -> putStrLn name >> quickCheck test) tests_TestAllExtensions mapM_ (\(name,test) -> putStrLn name >> quickCheck test) tests_TestAllTypes
ace5fa931245fb549571d86414f9f5ae6a15ce0e0ba3395df84219192ad0651b
jrh13/hol-light
integer.ml
(* ========================================================================= *) (* Basic divisibility notions over the integers. *) (* *) This is similar to stuff in Library / prime.ml etc . for natural numbers . (* ========================================================================= *) prioritize_int();; (* ------------------------------------------------------------------------- *) (* Basic properties of divisibility. *) (* ------------------------------------------------------------------------- *) let INT_DIVIDES_REFL = INTEGER_RULE `!d. d divides d`;; let INT_DIVIDES_TRANS = INTEGER_RULE `!x y z. x divides y /\ y divides z ==> x divides z`;; let INT_DIVIDES_ADD = INTEGER_RULE `!d a b. d divides a /\ d divides b ==> d divides (a + b)`;; let INT_DIVIDES_SUB = INTEGER_RULE `!d a b. d divides a /\ d divides b ==> d divides (a - b)`;; let INT_DIVIDES_0 = INTEGER_RULE `!d. d divides &0`;; let INT_DIVIDES_ZERO = INTEGER_RULE `!x. &0 divides x <=> x = &0`;; let INT_DIVIDES_LNEG = INTEGER_RULE `!d x. (--d) divides x <=> d divides x`;; let INT_DIVIDES_RNEG = INTEGER_RULE `!d x. d divides (--x) <=> d divides x`;; let INT_DIVIDES_RMUL = INTEGER_RULE `!d x y. d divides x ==> d divides (x * y)`;; let INT_DIVIDES_LMUL = INTEGER_RULE `!d x y. d divides y ==> d divides (x * y)`;; let INT_DIVIDES_1 = INTEGER_RULE `!x. &1 divides x`;; let INT_DIVIDES_ADD_REVR = INTEGER_RULE `!d a b. d divides a /\ d divides (a + b) ==> d divides b`;; let INT_DIVIDES_ADD_REVL = INTEGER_RULE `!d a b. d divides b /\ d divides (a + b) ==> d divides a`;; let INT_DIVIDES_MUL_L = INTEGER_RULE `!a b c. a divides b ==> (c * a) divides (c * b)`;; let INT_DIVIDES_MUL_R = INTEGER_RULE `!a b c. a divides b ==> (a * c) divides (b * c)`;; let INT_DIVIDES_LMUL2 = INTEGER_RULE `!d a x. (x * d) divides a ==> d divides a`;; let INT_DIVIDES_RMUL2 = INTEGER_RULE `!d a x. (d * x) divides a ==> d divides a`;; let INT_DIVIDES_CMUL2 = INTEGER_RULE `!a b c. (c * a) divides (c * b) /\ ~(c = &0) ==> a divides b`;; let INT_DIVIDES_LMUL2_EQ = INTEGER_RULE `!a b c. ~(c = &0) ==> ((c * a) divides (c * b) <=> a divides b)`;; let INT_DIVIDES_RMUL2_EQ = INTEGER_RULE `!a b c. ~(c = &0) ==> ((a * c) divides (b * c) <=> a divides b)`;; let INT_DIVIDES_MUL2 = INTEGER_RULE `!a b c d. a divides b /\ c divides d ==> (a * c) divides (b * d)`;; let INT_DIVIDES_POW = prove (`!x y n. x divides y ==> (x pow n) divides (y pow n)`, REWRITE_TAC[int_divides] THEN MESON_TAC[INT_POW_MUL]);; let INT_DIVIDES_POW2 = prove (`!n x y. ~(n = 0) /\ (x pow n) divides y ==> x divides y`, INDUCT_TAC THEN REWRITE_TAC[NOT_SUC; INT_POW] THEN INTEGER_TAC);; let INT_DIVIDES_RPOW = prove (`!x y n. x divides y /\ ~(n = 0) ==> x divides (y pow n)`, GEN_TAC THEN GEN_TAC THEN INDUCT_TAC THEN SIMP_TAC[INT_DIVIDES_RMUL; INT_POW]);; let INT_DIVIDES_RPOW_SUC = prove (`!x y n. x divides y ==> x divides (y pow (SUC n))`, SIMP_TAC[INT_DIVIDES_RPOW; NOT_SUC]);; let INT_DIVIDES_POW_LE_IMP = prove (`!(p:int) m n. m <= n ==> p pow m divides p pow n`, SIMP_TAC[LE_EXISTS; INT_POW_ADD; LEFT_IMP_EXISTS_THM] THEN CONV_TAC INTEGER_RULE);; let INT_DIVIDES_ANTISYM_DIVISORS = prove (`!a b:int. a divides b /\ b divides a <=> !d. d divides a <=> d divides b`, MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_DIVIDES_ANTISYM_MULTIPLES = prove (`!a b. a divides b /\ b divides a <=> !d. a divides d <=> b divides d`, MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; (* ------------------------------------------------------------------------- *) (* Now carefully distinguish signs. *) (* ------------------------------------------------------------------------- *) let INT_DIVIDES_ONE_POS = prove (`!x. &0 <= x ==> (x divides &1 <=> x = &1)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [REWRITE_TAC[int_divides]; INTEGER_TAC] THEN DISCH_THEN(CHOOSE_THEN(MP_TAC o AP_TERM `abs` o SYM)) THEN SIMP_TAC[INT_ABS_NUM; INT_ABS_MUL_1] THEN ASM_SIMP_TAC[INT_ABS]);; let INT_DIVIDES_ONE_ABS = prove (`!d. d divides &1 <=> abs(d) = &1`, MESON_TAC[INT_DIVIDES_LABS; INT_DIVIDES_ONE_POS; INT_ABS_POS]);; let INT_DIVIDES_ONE = prove (`!d. d divides &1 <=> d = &1 \/ d = -- &1`, REWRITE_TAC[INT_DIVIDES_ONE_ABS] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_ASSOCIATED = prove (`!x y. x divides y /\ y divides x <=> ?u. u divides &1 /\ x = y * u`, REPEAT GEN_TAC THEN EQ_TAC THENL [ALL_TAC; INTEGER_TAC] THEN ASM_CASES_TAC `x = &0` THEN ASM_SIMP_TAC[INT_DIVIDES_ZERO; INT_MUL_LZERO] THEN ASM_MESON_TAC[int_divides; INT_DIVIDES_REFL; INTEGER_RULE `y = x * d /\ x = y * e /\ ~(y = &0) ==> d divides &1`]);; let INT_DIVIDES_ANTISYM = prove (`!x y. x divides y /\ y divides x <=> x = y \/ x = --y`, REWRITE_TAC[INT_DIVIDES_ANTISYM_ASSOCIATED; INT_DIVIDES_ONE] THEN REWRITE_TAC[RIGHT_OR_DISTRIB; EXISTS_OR_THM; UNWIND_THM2] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_ABS = prove (`!x y. x divides y /\ y divides x <=> abs(x) = abs(y)`, REWRITE_TAC[INT_DIVIDES_ANTISYM] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_POS = prove (`!x y. &0 <= x /\ &0 <= y ==> (x divides y /\ y divides x <=> x = y)`, REWRITE_TAC[INT_DIVIDES_ANTISYM_ABS] THEN INT_ARITH_TAC);; (* ------------------------------------------------------------------------- *) Lemmas about GCDs . (* ------------------------------------------------------------------------- *) let INT_GCD_POS = prove (`!a b. &0 <= gcd(a,b)`, REWRITE_TAC[int_gcd]);; let INT_ABS_GCD = prove (`!a b. abs(gcd(a,b)) = gcd(a,b)`, REWRITE_TAC[INT_ABS; INT_GCD_POS]);; let INT_GCD_DIVIDES = prove (`!a b. gcd(a,b) divides a /\ gcd(a,b) divides b`, INTEGER_TAC);; let INT_COPRIME_GCD = prove (`!a b. coprime(a,b) <=> gcd(a,b) = &1`, SIMP_TAC[GSYM INT_DIVIDES_ONE_POS; INT_GCD_POS] THEN INTEGER_TAC);; let INT_GCD_BEZOUT = prove (`!a b. ?x y. gcd(a,b) = a * x + b * y`, INTEGER_TAC);; let INT_DIVIDES_GCD = prove (`!a b d. d divides gcd(a,b) <=> d divides a /\ d divides b`, INTEGER_TAC);; let INT_GCD = INTEGER_RULE `!a b. (gcd(a,b) divides a /\ gcd(a,b) divides b) /\ (!e. e divides a /\ e divides b ==> e divides gcd(a,b))`;; let INT_GCD_UNIQUE = prove (`!a b d. gcd(a,b) = d <=> &0 <= d /\ d divides a /\ d divides b /\ !e. e divides a /\ e divides b ==> e divides d`, REPEAT GEN_TAC THEN EQ_TAC THENL [MESON_TAC[INT_GCD; INT_GCD_POS]; ALL_TAC] THEN ASM_SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS; INT_DIVIDES_GCD] THEN REPEAT STRIP_TAC THEN FIRST_X_ASSUM MATCH_MP_TAC THEN INTEGER_TAC);; let INT_GCD_UNIQUE_ABS = prove (`!a b d. gcd(a,b) = abs(d) <=> d divides a /\ d divides b /\ !e. e divides a /\ e divides b ==> e divides d`, REWRITE_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS]);; let INT_GCD_REFL = prove (`!a. gcd(a,a) = abs(a)`, REWRITE_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_SYM = prove (`!a b. gcd(a,b) = gcd(b,a)`, SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS] THEN INTEGER_TAC);; let INT_GCD_ASSOC = prove (`!a b c. gcd(a,gcd(b,c)) = gcd(gcd(a,b),c)`, SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS] THEN INTEGER_TAC);; let INT_GCD_1 = prove (`!a. gcd(a,&1) = &1 /\ gcd(&1,a) = &1`, SIMP_TAC[INT_GCD_UNIQUE; INT_POS; INT_DIVIDES_1]);; let INT_GCD_0 = prove (`!a. gcd(a,&0) = abs(a) /\ gcd(&0,a) = abs(a)`, SIMP_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_EQ_0 = prove (`!a b. gcd(a,b) = &0 <=> a = &0 /\ b = &0`, INTEGER_TAC);; let INT_GCD_ABS = prove (`!a b. gcd(abs(a),b) = gcd(a,b) /\ gcd(a,abs(b)) = gcd(a,b)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_DIVIDES_ABS; INT_GCD_POS; INT_GCD]);; let INT_GCD_MULTIPLE = (`!a b. gcd(a,a * b) = abs(a) /\ gcd(b,a * b) = abs(b)`, REWRITE_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_ADD = prove (`(!a b. gcd(a + b,b) = gcd(a,b)) /\ (!a b. gcd(b + a,b) = gcd(a,b)) /\ (!a b. gcd(a,a + b) = gcd(a,b)) /\ (!a b. gcd(a,b + a) = gcd(a,b))`, SIMP_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_GCD_SUB = prove (`(!a b. gcd(a - b,b) = gcd(a,b)) /\ (!a b. gcd(b - a,b) = gcd(a,b)) /\ (!a b. gcd(a,a - b) = gcd(a,b)) /\ (!a b. gcd(a,b - a) = gcd(a,b))`, SIMP_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_DIVIDES_GCD_LEFT = prove (`!m n:int. m divides n <=> gcd(m,n) = abs m`, SIMP_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS; INT_DIVIDES_REFL] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_DIVIDES_GCD_RIGHT = prove (`!m n:int. n divides m <=> gcd(m,n) = abs n`, SIMP_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS; INT_DIVIDES_REFL] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_GCD_EQ = prove (`!x y u v:int. (!d. d divides x /\ d divides y <=> d divides u /\ d divides v) ==> gcd(x,y) = gcd(u,v)`, REPEAT STRIP_TAC THEN SIMP_TAC[GSYM INT_DIVIDES_ANTISYM_POS; INT_GCD_POS] THEN ASM_REWRITE_TAC[INT_DIVIDES_GCD; INT_GCD_DIVIDES] THEN FIRST_X_ASSUM(fun th -> REWRITE_TAC[GSYM th]) THEN REWRITE_TAC[INT_GCD_DIVIDES]);; let INT_GCD_LNEG = prove (`!a b:int. gcd(--a,b) = gcd(a,b)`, REPEAT GEN_TAC THEN MATCH_MP_TAC INT_GCD_EQ THEN INTEGER_TAC);; let INT_GCD_RNEG = prove (`!a b:int. gcd(a,--b) = gcd(a,b)`, REPEAT GEN_TAC THEN MATCH_MP_TAC INT_GCD_EQ THEN INTEGER_TAC);; let INT_GCD_NEG = prove (`(!a b. gcd(--a,b) = gcd(a,b)) /\ (!a b. gcd(a,--b) = gcd(a,b))`, REWRITE_TAC[INT_GCD_LNEG; INT_GCD_RNEG]);; let INT_GCD_LABS = prove (`!a b. gcd(abs a,b) = gcd(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_GCD_LNEG]);; let INT_GCD_RABS = prove (`!a b. gcd(a,abs b) = gcd(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_GCD_RNEG]);; let INT_GCD_ABS = prove (`(!a b. gcd(abs a,b) = gcd(a,b)) /\ (!a b. gcd(a,abs b) = gcd(a,b))`, REWRITE_TAC[INT_GCD_LABS; INT_GCD_RABS]);; let INT_GCD_LMUL = prove (`!a b c:int. gcd(c * a,c * b) = abs c * gcd(a,b)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_RMUL = prove (`!a b c:int. gcd(a * c,b * c) = gcd(a,b) * abs c`, ONCE_REWRITE_TAC[INT_MUL_SYM] THEN REWRITE_TAC[INT_GCD_LMUL]);; let INT_GCD_COPRIME_LMUL = prove (`!a b c:int. coprime(a,b) ==> gcd(a * b,c) = gcd(a,c) * gcd(b,c)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_COPRIME_RMUL = prove (`!a b c:int. coprime(b,c) ==> gcd(a, b * c) = gcd(a,b) * gcd(a,c)`, ONCE_REWRITE_TAC[INT_GCD_SYM] THEN REWRITE_TAC[INT_GCD_COPRIME_LMUL]);; let INT_GCD_COPRIME_DIVIDES_LMUL = prove (`!a b c:int. coprime(a,b) /\ a divides c ==> gcd(a * b,c) = abs a * gcd(b,c)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_COPRIME_DIVIDES_RMUL = prove (`!a b c:int. coprime(b,c) /\ b divides a ==> gcd(a,b * c) = abs b * gcd(a,c)`, ONCE_REWRITE_TAC[INT_GCD_SYM] THEN REWRITE_TAC[INT_GCD_COPRIME_DIVIDES_LMUL]);; let INT_GCD_COPRIME_EXISTS = prove (`!a b. ?a' b'. a = a' * gcd(a,b) /\ b = b' * gcd(a,b) /\ coprime(a',b')`, REPEAT GEN_TAC THEN ASM_CASES_TAC `gcd(a,b):int = &0` THENL [ALL_TAC; POP_ASSUM MP_TAC THEN CONV_TAC INTEGER_RULE] THEN RULE_ASSUM_TAC(REWRITE_RULE[INT_GCD_EQ_0]) THEN REPEAT(EXISTS_TAC `&1:int`) THEN ASM_REWRITE_TAC[INT_GCD_0] THEN CONV_TAC INT_REDUCE_CONV THEN CONV_TAC INTEGER_RULE);; (* ------------------------------------------------------------------------- *) Lemmas about lcms . (* ------------------------------------------------------------------------- *) let INT_ABS_LCM = prove (`!a b. abs(lcm(a,b)) = lcm(a,b)`, REWRITE_TAC[INT_ABS; INT_LCM_POS]);; let INT_LCM_EQ_0 = prove (`!m n. lcm(m,n) = &0 <=> m = &0 \/ n = &0`, REWRITE_TAC[INTEGER_RULE `n:int = &0 <=> &0 divides n`] THEN REWRITE_TAC[INT_DIVIDES_LCM_GCD] THEN INTEGER_TAC);; let INT_DIVIDES_LCM = prove (`!m n r. r divides m \/ r divides n ==> r divides lcm(m,n)`, REWRITE_TAC[INT_DIVIDES_LCM_GCD] THEN INTEGER_TAC);; let INT_LCM_0 = prove (`(!n. lcm(&0,n) = &0) /\ (!n. lcm(n,&0) = &0)`, REWRITE_TAC[INT_LCM_EQ_0]);; let INT_LCM_1 = prove (`(!n. lcm(&1,n) = abs n) /\ (!n. lcm(n,&1) = abs n)`, SIMP_TAC[int_lcm; INT_MUL_LID; INT_MUL_RID; INT_GCD_1] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_DIV_1; INT_ABS_NUM]);; let INT_LCM_UNIQUE_ABS = prove (`!a b m. lcm(a,b) = abs m <=> a divides m /\ b divides m /\ (!n. a divides n /\ b divides n ==> m divides n)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN REWRITE_TAC[INT_LCM_DIVIDES] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_LCM_UNIQUE = prove (`!a b m. lcm(a,b) = m <=> &0 <= m /\ a divides m /\ b divides m /\ (!n. a divides n /\ b divides n ==> m divides n)`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM INT_LCM_UNIQUE_ABS] THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_LCM_POS) THEN INT_ARITH_TAC);; let INT_LCM_EQ = prove (`!x y u v. (!m. x divides m /\ y divides m <=> u divides m /\ v divides m) ==> lcm(x,y) = lcm(u,v)`, REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN ASM_REWRITE_TAC[INT_LCM_DIVIDES]);; let INT_LCM_REFL = prove (`!n. lcm(n,n) = abs n`, REWRITE_TAC[int_lcm; INT_GCD_REFL; INT_ENTIRE] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_ABS_NUM; INT_ABS_MUL] THEN ASM_SIMP_TAC[INT_DIV_MUL; INT_ABS_ZERO]);; let INT_LCM_SYM = prove (`!m n. lcm(m,n) = lcm(n,m)`, REWRITE_TAC[int_lcm; INT_GCD_SYM; INT_MUL_SYM]);; let INT_LCM_ASSOC = prove (`!m n p. lcm(m,lcm(n,p)) = lcm(lcm(m,n),p)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN REWRITE_TAC[INT_LCM_DIVIDES] THEN REWRITE_TAC[CONJ_ASSOC]);; let INT_LCM_LNEG = prove (`!a b:int. lcm(--a,b) = lcm(a,b)`, SIMP_TAC[int_lcm; INT_MUL_LNEG; INT_ABS_NEG; INT_GCD_LNEG; INT_NEG_EQ_0]);; let INT_LCM_RNEG = prove (`!a b:int. lcm(a,--b) = lcm(a,b)`, SIMP_TAC[int_lcm; INT_MUL_RNEG; INT_ABS_NEG; INT_GCD_RNEG; INT_NEG_EQ_0]);; let INT_LCM_NEG = prove (`(!a b. lcm(--a,b) = lcm(a,b)) /\ (!a b. lcm(a,--b) = lcm(a,b))`, REWRITE_TAC[INT_LCM_LNEG; INT_LCM_RNEG]);; let INT_LCM_LABS = prove (`!a b. lcm(abs a,b) = lcm(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_LCM_LNEG]);; let INT_LCM_RABS = prove (`!a b. lcm(a,abs b) = lcm(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_LCM_RNEG]);; let INT_LCM_ABS = prove (`(!a b. lcm(abs a,b) = lcm(a,b)) /\ (!a b. lcm(a,abs b) = lcm(a,b))`, REWRITE_TAC[INT_LCM_LABS; INT_LCM_RABS]);; let INT_LCM_LMUL = prove (`!a b c:int. lcm(c * a,c * b) = abs c * lcm(a,b)`, REPEAT GEN_TAC THEN MAP_EVERY ASM_CASES_TAC [`a:int = &0`; `b:int = &0`; `c:int = &0`] THEN ASM_REWRITE_TAC[INT_MUL_LZERO; INT_MUL_RZERO; INT_ABS_NUM; INT_LCM_0] THEN MATCH_MP_TAC(INT_RING `!x:int. ~(x = &0) /\ a * x = b * x ==> a = b`) THEN EXISTS_TAC `gcd(c * a:int,c * b)` THEN ASM_REWRITE_TAC[INT_GCD_EQ_0; INT_ENTIRE; INT_MUL_LCM_GCD] THEN REWRITE_TAC[INT_GCD_LMUL; INT_MUL_LCM_GCD; INT_ARITH `(x * a) * x * b:int = x * x * a * b`] THEN REWRITE_TAC[INT_ABS_MUL; INT_MUL_AC]);; let INT_LCM_RMUL = prove (`!a b c:int. lcm(a * c,b * c) = lcm(a,b) * abs c`, ONCE_REWRITE_TAC[INT_MUL_SYM] THEN REWRITE_TAC[INT_LCM_LMUL]);; (* ------------------------------------------------------------------------- *) (* More lemmas about coprimality. *) (* ------------------------------------------------------------------------- *) let INT_COPRIME = prove (`!a b. coprime(a,b) <=> !d. d divides a /\ d divides b ==> d divides &1`, REWRITE_TAC[INT_COPRIME_GCD; INT_GCD_UNIQUE; INT_POS; INT_DIVIDES_1]);; let INT_COPRIME_ALT = prove (`!a b. coprime(a,b) <=> !d. d divides a /\ d divides b <=> d divides &1`, MESON_TAC[INT_DIVIDES_1; INT_DIVIDES_TRANS; INT_COPRIME]);; let INT_COPRIME_SYM = prove (`!a b. coprime(a,b) <=> coprime(b,a)`, INTEGER_TAC);; let INT_COPRIME_DIVPROD = prove (`!d a b. d divides (a * b) /\ coprime(d,a) ==> d divides b`, INTEGER_TAC);; let INT_COPRIME_1 = prove (`!a. coprime(a,&1) /\ coprime(&1,a)`, INTEGER_TAC);; let INT_GCD_COPRIME = prove (`!a b a' b'. ~(gcd(a,b) = &0) /\ a = a' * gcd(a,b) /\ b = b' * gcd(a,b) ==> coprime(a',b')`, INTEGER_TAC);; let INT_COPRIME_0 = prove (`(!a. coprime(a,&0) <=> a divides &1) /\ (!a. coprime(&0,a) <=> a divides &1)`, INTEGER_TAC);; let INT_COPRIME_MUL = prove (`!d a b. coprime(d,a) /\ coprime(d,b) ==> coprime(d,a * b)`, INTEGER_TAC);; let INT_COPRIME_LMUL2 = prove (`!d a b. coprime(d,a * b) ==> coprime(d,b)`, INTEGER_TAC);; let INT_COPRIME_RMUL2 = prove (`!d a b. coprime(d,a * b) ==> coprime(d,a)`, INTEGER_TAC);; let INT_COPRIME_LMUL = prove (`!d a b. coprime(a * b,d) <=> coprime(a,d) /\ coprime(b,d)`, INTEGER_TAC);; let INT_COPRIME_RMUL = prove (`!d a b. coprime(d,a * b) <=> coprime(d,a) /\ coprime(d,b)`, INTEGER_TAC);; let INT_COPRIME_REFL = prove (`!n. coprime(n,n) <=> n divides &1`, INTEGER_TAC);; let INT_COPRIME_PLUS1 = prove (`!n. coprime(n + &1,n) /\ coprime(n,n + &1)`, INTEGER_TAC);; let INT_COPRIME_MINUS1 = prove (`!n. coprime(n - &1,n) /\ coprime(n,n - &1)`, INTEGER_TAC);; let INT_COPRIME_RPOW = prove (`!m n k. coprime(m,n pow k) <=> coprime(m,n) \/ k = 0`, GEN_TAC THEN GEN_TAC THEN INDUCT_TAC THEN ASM_SIMP_TAC[INT_POW; INT_COPRIME_1; INT_COPRIME_RMUL; NOT_SUC] THEN CONV_TAC TAUT);; let INT_COPRIME_LPOW = prove (`!m n k. coprime(m pow k,n) <=> coprime(m,n) \/ k = 0`, ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN REWRITE_TAC[INT_COPRIME_RPOW]);; let INT_COPRIME_POW2 = prove (`!m n k. coprime(m pow k,n pow k) <=> coprime(m,n) \/ k = 0`, REWRITE_TAC[INT_COPRIME_RPOW; INT_COPRIME_LPOW; DISJ_ACI]);; let INT_COPRIME_POW = prove (`!n a d. coprime(d,a) ==> coprime(d,a pow n)`, SIMP_TAC[INT_COPRIME_RPOW]);; let INT_COPRIME_POW_IMP = prove (`!n a b. coprime(a,b) ==> coprime(a pow n,b pow n)`, MESON_TAC[INT_COPRIME_POW; INT_COPRIME_SYM]);; let INT_GCD_POW = prove (`!(a:int) b n. gcd(a pow n,b pow n) = gcd(a,b) pow n`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_GCD_COPRIME_EXISTS) THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`a':int`; `b':int`] THEN STRIP_TAC THEN ONCE_ASM_REWRITE_TAC[] THEN REWRITE_TAC[INT_POW_MUL; INT_GCD_RMUL; INT_ABS_POW] THEN ASM_SIMP_TAC[fst(EQ_IMP_RULE(SPEC_ALL INT_COPRIME_GCD)); INT_COPRIME_POW2; INT_POW_ONE]);; let INT_LCM_POW = prove (`!(a:int) b n. lcm(a pow n,b pow n) = lcm(a,b) pow n`, REPEAT GEN_TAC THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[INT_POW; INT_LCM_1; INT_POW_ONE; INT_ABS_NUM] THEN MAP_EVERY ASM_CASES_TAC [`a:int = &0`; `b:int = &0`] THEN ASM_REWRITE_TAC[INT_POW_ZERO; INT_LCM_0] THEN MATCH_MP_TAC(INT_RING `!x:int. ~(x = &0) /\ a * x = b * x ==> a = b`) THEN EXISTS_TAC `gcd((a:int) pow n,b pow n)` THEN ASM_REWRITE_TAC[INT_GCD_EQ_0; INT_POW_EQ_0; INT_MUL_LCM_GCD] THEN REWRITE_TAC[INT_GCD_POW; GSYM INT_POW_MUL] THEN REWRITE_TAC[INT_MUL_LCM_GCD; INT_ABS_POW]);; let INT_DIVISION_DECOMP = prove (`!a b c. a divides (b * c) ==> ?b' c'. (a = b' * c') /\ b' divides b /\ c' divides c`, REPEAT STRIP_TAC THEN EXISTS_TAC `gcd(a,b)` THEN ASM_CASES_TAC `gcd(a,b) = &0` THEN REPEAT(POP_ASSUM MP_TAC) THENL [SIMP_TAC[INT_GCD_EQ_0; INT_GCD_0; INT_ABS_NUM]; INTEGER_TAC] THEN REWRITE_TAC[INT_MUL_LZERO] THEN MESON_TAC[INT_DIVIDES_REFL]);; let INT_DIVIDES_MUL = prove (`!m n r. m divides r /\ n divides r /\ coprime(m,n) ==> (m * n) divides r`, INTEGER_TAC);; let INT_CHINESE_REMAINDER = prove (`!a b u v. coprime(a,b) /\ ~(a = &0) /\ ~(b = &0) ==> ?x q1 q2. (x = u + q1 * a) /\ (x = v + q2 * b)`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_USUAL = prove (`!a b u v. coprime(a,b) ==> ?x. (x == u) (mod a) /\ (x == v) (mod b)`, INTEGER_TAC);; let INT_COPRIME_DIVISORS = prove (`!a b d e. d divides a /\ e divides b /\ coprime(a,b) ==> coprime(d,e)`, INTEGER_TAC);; let INT_COPRIME_LNEG = prove (`!a b. coprime(--a,b) <=> coprime(a,b)`, INTEGER_TAC);; let INT_COPRIME_RNEG = prove (`!a b. coprime(a,--b) <=> coprime(a,b)`, INTEGER_TAC);; let INT_COPRIME_NEG = prove (`(!a b. coprime(--a,b) <=> coprime(a,b)) /\ (!a b. coprime(a,--b) <=> coprime(a,b))`, INTEGER_TAC);; let INT_COPRIME_LABS = prove (`!a b. coprime(abs a,b) <=> coprime(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_COPRIME_LNEG]);; let INT_COPRIME_RABS = prove (`!a b. coprime(a,abs b) <=> coprime(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_COPRIME_RNEG]);; let INT_COPRIME_ABS = prove (`(!a b. coprime(abs a,b) <=> coprime(a,b)) /\ (!a b. coprime(a,abs b) <=> coprime(a,b))`, REWRITE_TAC[INT_COPRIME_LABS; INT_COPRIME_RABS]);; (* ------------------------------------------------------------------------- *) (* More lemmas about congruences. *) (* ------------------------------------------------------------------------- *) let INT_CONG_MOD_0 = prove (`!x y. (x == y) (mod &0) <=> (x = y)`, INTEGER_TAC);; let INT_CONG_MOD_1 = prove (`!x y. (x == y) (mod &1)`, INTEGER_TAC);; let INT_CONG = prove (`!x y n. (x == y) (mod n) <=> n divides (x - y)`, INTEGER_TAC);; let INT_CONG_MOD_ABS = prove (`!a b n:int. (a == b) (mod (abs n)) <=> (a == b) (mod n)`, REWRITE_TAC[INT_CONG; INT_DIVIDES_LABS]);; let INT_CONG_MUL_LCANCEL = prove (`!a n x y. coprime(a,n) /\ (a * x == a * y) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_MUL_RCANCEL = prove (`!a n x y. coprime(a,n) /\ (x * a == y * a) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_MULT_LCANCEL_ALL = INTEGER_RULE `!a x y n:int. (a * x == a * y) (mod (a * n)) <=> a = &0 \/ (x == y) (mod n)`;; let INT_CONG_LMUL = INTEGER_RULE `!a x y n:int. (x == y) (mod n) ==> (a * x == a * y) (mod n)`;; let INT_CONG_RMUL = INTEGER_RULE `!x y a n:int. (x == y) (mod n) ==> (x * a == y * a) (mod n)`;; let INT_CONG_REFL = prove (`!x n. (x == x) (mod n)`, INTEGER_TAC);; let INT_EQ_IMP_CONG = prove (`!a b n. a = b ==> (a == b) (mod n)`, INTEGER_TAC);; let INT_CONG_SYM = prove (`!x y n. (x == y) (mod n) <=> (y == x) (mod n)`, INTEGER_TAC);; let INT_CONG_TRANS = prove (`!x y z n. (x == y) (mod n) /\ (y == z) (mod n) ==> (x == z) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x + y == x' + y') (mod n)`, INTEGER_TAC);; let INT_CONG_SUB = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x - y == x' - y') (mod n)`, INTEGER_TAC);; let INT_CONG_MUL = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x * y == x' * y') (mod n)`, INTEGER_TAC);; let INT_CONG_POW = prove (`!n k x y. (x == y) (mod n) ==> (x pow k == y pow k) (mod n)`, GEN_TAC THEN INDUCT_TAC THEN ASM_SIMP_TAC[INT_CONG_MUL; INT_POW; INT_CONG_REFL]);; let INT_CONG_MUL_1 = prove (`!n x y:int. (x == &1) (mod n) /\ (y == &1) (mod n) ==> (x * y == &1) (mod n)`, MESON_TAC[INT_CONG_MUL; INT_MUL_LID]);; let INT_CONG_POW_1 = prove (`!a k n:int. (a == &1) (mod n) ==> (a pow k == &1) (mod n)`, MESON_TAC[INT_CONG_POW; INT_POW_ONE]);; let INT_CONG_MUL_LCANCEL_EQ = prove (`!a n x y. coprime(a,n) ==> ((a * x == a * y) (mod n) <=> (x == y) (mod n))`, INTEGER_TAC);; let INT_CONG_MUL_RCANCEL_EQ = prove (`!a n x y. coprime(a,n) ==> ((x * a == y * a) (mod n) <=> (x == y) (mod n))`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL_EQ = prove (`!a n x y. (a + x == a + y) (mod n) <=> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL_EQ = prove (`!a n x y. (x + a == y + a) (mod n) <=> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL = prove (`!a n x y. (x + a == y + a) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL = prove (`!a n x y. (a + x == a + y) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL_EQ_0 = prove (`!a n x y. (a + x == a) (mod n) <=> (x == &0) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL_EQ_0 = prove (`!a n x y. (x + a == a) (mod n) <=> (x == &0) (mod n)`, INTEGER_TAC);; let INT_CONG_INT_DIVIDES_MODULUS = prove (`!x y m n. (x == y) (mod m) /\ n divides m ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_0_DIVIDES = prove (`!n x. (x == &0) (mod n) <=> n divides x`, INTEGER_TAC);; let INT_CONG_1_DIVIDES = prove (`!n x. (x == &1) (mod n) ==> n divides (x - &1)`, INTEGER_TAC);; let INT_CONG_DIVIDES = prove (`!x y n. (x == y) (mod n) ==> (n divides x <=> n divides y)`, INTEGER_TAC);; let INT_CONG_COPRIME = prove (`!x y n. (x == y) (mod n) ==> (coprime(n,x) <=> coprime(n,y))`, INTEGER_TAC);; let INT_COPRIME_RREM = prove (`!m n. coprime(m,n rem m) <=> coprime(m,n)`, MESON_TAC[INT_CONG_COPRIME; INT_CONG_RREM; INT_CONG_REFL]);; let INT_COPRIME_LREM = prove (`!a b. coprime(a rem n,n) <=> coprime(a,n)`, MESON_TAC[INT_COPRIME_RREM; INT_COPRIME_SYM]);; let INT_CONG_MOD_MULT = prove (`!x y m n. (x == y) (mod n) /\ m divides n ==> (x == y) (mod m)`, INTEGER_TAC);; let INT_CONG_GCD_RIGHT = prove (`!x y n. (x == y) (mod n) ==> gcd(n,x) = gcd(n,y)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_CONG_GCD_LEFT = prove (`!x y n. (x == y) (mod n) ==> gcd(x,n) = gcd(y,n)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_CONG_TO_1 = prove (`!a n. (a == &1) (mod n) <=> ?m. a = &1 + m * n`, INTEGER_TAC);; let INT_CONG_SOLVE = prove (`!a b n. coprime(a,n) ==> ?x. (a * x == b) (mod n)`, INTEGER_TAC);; let INT_CONG_SOLVE_EQ = prove (`!n a b:int. (?x. (a * x == b) (mod n)) <=> gcd(a,n) divides b`, INTEGER_TAC);; let INT_CONG_SOLVE_UNIQUE = prove (`!a b n. coprime(a,n) ==> !x y. (a * x == b) (mod n) /\ (a * y == b) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_CHINESE = prove (`coprime(a,b) /\ (x == y) (mod a) /\ (x == y) (mod b) ==> (x == y) (mod (a * b))`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_COPRIME = prove (`!a b m n. coprime(a,b) /\ ~(a = &0) /\ ~(b = &0) /\ coprime(m,a) /\ coprime(n,b) ==> ?x. coprime(x,a * b) /\ (x == m) (mod a) /\ (x == n) (mod b)`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_COPRIME_UNIQUE = prove (`!a b m n x y. coprime(a,b) /\ (x == m) (mod a) /\ (x == n) (mod b) /\ (y == m) (mod a) /\ (y == n) (mod b) ==> (x == y) (mod (a * b))`, INTEGER_TAC);; let SOLVABLE_GCD = prove (`!a b n. gcd(a,n) divides b ==> ?x. (a * x == b) (mod n)`, INTEGER_TAC);; let INT_LINEAR_CONG_POS = prove (`!n a x:int. ~(n = &0) ==> ?y. &0 <= y /\ (a * x == a * y) (mod n)`, REPEAT STRIP_TAC THEN EXISTS_TAC `x + abs(x * n):int` THEN CONJ_TAC THENL [MATCH_MP_TAC(INT_ARITH `abs(x:int) * &1 <= y ==> &0 <= x + y`) THEN REWRITE_TAC[INT_ABS_MUL] THEN MATCH_MP_TAC INT_LE_LMUL THEN ASM_INT_ARITH_TAC; MATCH_MP_TAC(INTEGER_RULE `n divides y ==> (a * x:int == a * (x + y)) (mod n)`) THEN REWRITE_TAC[INT_DIVIDES_RABS] THEN INTEGER_TAC]);; let INT_CONG_SOLVE_POS = prove (`!a b n:int. coprime(a,n) /\ ~(n = &0 /\ abs a = &1) ==> ?x. &0 <= x /\ (a * x == b) (mod n)`, REPEAT GEN_TAC THEN ASM_CASES_TAC `n:int = &0` THEN ASM_REWRITE_TAC[INT_COPRIME_0; INT_DIVIDES_ONE] THENL [INT_ARITH_TAC; ASM_MESON_TAC[INT_LINEAR_CONG_POS; INT_CONG_SOLVE; INT_CONG_TRANS; INT_CONG_SYM]]);; let INT_CONG_IMP_EQ = prove (`!x y n:int. abs(x - y) < n /\ (x == y) (mod n) ==> x = y`, REPEAT GEN_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN ONCE_REWRITE_TAC[int_congruent; GSYM INT_SUB_0] THEN DISCH_THEN(X_CHOOSE_THEN `q:int` SUBST_ALL_TAC) THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `abs(n * q) < n ==> abs(n * q) < abs n * &1`)) THEN REWRITE_TAC[INT_ABS_MUL; INT_ENTIRE] THEN REWRITE_TAC[INT_ARITH `abs n * (q:int) < abs n * &1 <=> ~(&0 <= abs n * (q - &1))`] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[DE_MORGAN_THM] THEN STRIP_TAC THEN MATCH_MP_TAC INT_LE_MUL THEN ASM_INT_ARITH_TAC);; let INT_CONG_DIV = prove (`!m n a b. ~(m = &0) /\ (a == m * b) (mod (m * n)) ==> (a div m == b) (mod n)`, METIS_TAC[INT_CONG_DIV2; INT_DIV_MUL; INT_LT_LE]);; let INT_CONG_DIV_COPRIME = prove (`!m n a b:int. coprime(m,n) /\ m divides a /\ (a == m * b) (mod n) ==> (a div m == b) (mod n)`, REPEAT GEN_TAC THEN ASM_CASES_TAC `m:int = &0` THEN ASM_SIMP_TAC[INT_COPRIME_0; INT_CONG_MOD_1] THENL [INTEGER_TAC; STRIP_TAC] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC INT_CONG_DIV THEN REPEAT(POP_ASSUM MP_TAC) THEN CONV_TAC INTEGER_RULE);; (* ------------------------------------------------------------------------- *) (* A stronger form of the CRT. *) (* ------------------------------------------------------------------------- *) let INT_CRT_STRONG = prove (`!a1 a2 n1 n2:int. (a1 == a2) (mod (gcd(n1,n2))) ==> ?x. (x == a1) (mod n1) /\ (x == a2) (mod n2)`, INTEGER_TAC);; let INT_CRT_STRONG_IFF = prove (`!a1 a2 n1 n2:int. (?x. (x == a1) (mod n1) /\ (x == a2) (mod n2)) <=> (a1 == a2) (mod (gcd(n1,n2)))`, INTEGER_TAC);; (* ------------------------------------------------------------------------- *) (* Other miscellaneous lemmas. *) (* ------------------------------------------------------------------------- *) let EVEN_SQUARE_MOD4 = prove (`((&2 * n) pow 2 == &0) (mod &4)`, INTEGER_TAC);; let ODD_SQUARE_MOD4 = prove (`((&2 * n + &1) pow 2 == &1) (mod &4)`, INTEGER_TAC);; let INT_DIVIDES_LE = prove (`!x y. x divides y ==> abs(x) <= abs(y) \/ y = &0`, REWRITE_TAC[int_divides; LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`x:int`; `y:int`; `z:int`] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[INT_ABS_MUL; INT_ENTIRE] THEN REWRITE_TAC[INT_ARITH `x <= x * z <=> &0 <= x * (z - &1)`] THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `z = &0` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC INT_LE_MUL THEN ASM_INT_ARITH_TAC);; let INT_DIVIDES_POW_LE = prove (`!p m n. &2 <= abs p ==> ((p pow m) divides (p pow n) <=> m <= n)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_ARITH `&2 <= abs p ==> ~(p = &0)`] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[INT_NOT_LE; NOT_LE; INT_ABS_POW] THEN ASM_MESON_TAC[INT_POW_MONO_LT; ARITH_RULE `&2 <= x ==> &1 < x`]; SIMP_TAC[LE_EXISTS; LEFT_IMP_EXISTS_THM; INT_POW_ADD] THEN INTEGER_TAC]);; (* ------------------------------------------------------------------------- *) Integer primality / irreducibility . (* ------------------------------------------------------------------------- *) let int_prime = new_definition `int_prime p <=> abs(p) > &1 /\ !x. x divides p ==> abs(x) = &1 \/ abs(x) = abs(p)`;; let INT_PRIME_NEG = prove (`!p. int_prime(--p) <=> int_prime p`, REWRITE_TAC[int_prime; INT_DIVIDES_RNEG; INT_ABS_NEG]);; let INT_PRIME_ABS = prove (`!p. int_prime(abs p) <=> int_prime p`, GEN_TAC THEN REWRITE_TAC[INT_ABS] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_PRIME_NEG]);; let INT_PRIME_GE_2 = prove (`!p. int_prime p ==> &2 <= abs(p)`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_0 = prove (`~(int_prime(&0))`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_1 = prove (`~(int_prime(&1))`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_2 = prove (`int_prime(&2)`, REWRITE_TAC[int_prime] THEN CONV_TAC INT_REDUCE_CONV THEN X_GEN_TAC `x:int` THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[INT_DIVIDES_ZERO] THEN CONV_TAC INT_REDUCE_CONV THEN DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC);; let INT_PRIME_FACTOR = prove (`!x. ~(abs x = &1) ==> ?p. int_prime p /\ p divides x`, MATCH_MP_TAC WF_INT_MEASURE THEN EXISTS_TAC `abs` THEN REWRITE_TAC[INT_ABS_POS] THEN X_GEN_TAC `x:int` THEN REPEAT STRIP_TAC THEN ASM_CASES_TAC `int_prime x` THENL [EXISTS_TAC `x:int` THEN ASM_REWRITE_TAC[] THEN REPEAT(POP_ASSUM MP_TAC) THEN INTEGER_TAC; ALL_TAC] THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[] THENL [EXISTS_TAC `&2` THEN ASM_REWRITE_TAC[INT_PRIME_2; INT_DIVIDES_0]; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE RAND_CONV [int_prime]) THEN ASM_SIMP_TAC[INT_ARITH `~(x = &0) /\ ~(abs x = &1) ==> abs x > &1`] THEN REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; DE_MORGAN_THM] THEN DISCH_THEN(X_CHOOSE_THEN `y:int` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o SPEC `y:int`) THEN ASM_REWRITE_TAC[] THEN ANTS_TAC THENL [FIRST_X_ASSUM(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC; MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC THEN SIMP_TAC[] THEN UNDISCH_TAC `y divides x` THEN INTEGER_TAC]);; let INT_PRIME_FACTOR_LT = prove (`!n m p. int_prime(p) /\ ~(n = &0) /\ n = p * m ==> abs m < abs n`, REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[INT_ABS_MUL] THEN MATCH_MP_TAC(INT_ARITH `&0 < m * (p - &1) ==> m < p * m`) THEN MATCH_MP_TAC INT_LT_MUL THEN UNDISCH_TAC `~(n = &0)` THEN ASM_CASES_TAC `m = &0` THEN ASM_REWRITE_TAC[INT_MUL_RZERO] THEN DISCH_THEN(K ALL_TAC) THEN CONJ_TAC THENL [ASM_INT_ARITH_TAC; ALL_TAC] THEN FIRST_ASSUM(MP_TAC o MATCH_MP INT_PRIME_GE_2) THEN INT_ARITH_TAC);; let INT_PRIME_FACTOR_INDUCT = prove (`!P. P(&0) /\ P(&1) /\ P(-- &1) /\ (!p n. int_prime p /\ ~(n = &0) /\ P n ==> P(p * n)) ==> !n. P n`, GEN_TAC THEN STRIP_TAC THEN MATCH_MP_TAC WF_INT_MEASURE THEN EXISTS_TAC `abs` THEN REWRITE_TAC[INT_ABS_POS] THEN X_GEN_TAC `n:int` THEN DISCH_TAC THEN ASM_CASES_TAC `n = &0` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `abs n = &1` THENL [ASM_MESON_TAC[INT_ARITH `abs x = &a <=> x = &a \/ x = -- &a`]; ALL_TAC] THEN FIRST_ASSUM(X_CHOOSE_THEN `p:int` STRIP_ASSUME_TAC o MATCH_MP INT_PRIME_FACTOR) THEN FIRST_X_ASSUM(X_CHOOSE_THEN `d:int` SUBST_ALL_TAC o GEN_REWRITE_RULE I [int_divides]) THEN FIRST_X_ASSUM(MP_TAC o SPECL [`p:int`; `d:int`]) THEN RULE_ASSUM_TAC(REWRITE_RULE[INT_ENTIRE; DE_MORGAN_THM]) THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_MESON_TAC[INT_PRIME_FACTOR_LT; INT_ENTIRE]);; (* ------------------------------------------------------------------------- *) Infinitude . (* ------------------------------------------------------------------------- *) let INT_DIVIDES_FACT = prove (`!n x. &1 <= abs(x) /\ abs(x) <= &n ==> x divides &(FACT n)`, INDUCT_TAC THENL [INT_ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[FACT; INT_ARITH `x <= &n <=> x = &n \/ x < &n`] THEN REWRITE_TAC[GSYM INT_OF_NUM_SUC; INT_ARITH `x < &m + &1 <=> x <= &m`] THEN REWRITE_TAC[INT_OF_NUM_SUC; GSYM INT_OF_NUM_MUL] THEN REPEAT STRIP_TAC THEN ASM_SIMP_TAC[INT_DIVIDES_LMUL] THEN MATCH_MP_TAC INT_DIVIDES_RMUL THEN ASM_MESON_TAC[INT_DIVIDES_LABS; INT_DIVIDES_REFL]);; let INT_EUCLID_BOUND = prove (`!n. ?p. int_prime(p) /\ &n < p /\ p <= &(FACT n) + &1`, GEN_TAC THEN MP_TAC(SPEC `&(FACT n) + &1` INT_PRIME_FACTOR) THEN REWRITE_TAC[INT_OF_NUM_ADD; INT_ABS_NUM; INT_OF_NUM_EQ] THEN REWRITE_TAC[EQ_ADD_RCANCEL_0; FACT_NZ; GSYM INT_OF_NUM_ADD] THEN DISCH_THEN(X_CHOOSE_THEN `p:int` STRIP_ASSUME_TAC) THEN EXISTS_TAC `abs p` THEN ASM_REWRITE_TAC[INT_PRIME_ABS] THEN CONJ_TAC THENL [ALL_TAC; FIRST_ASSUM(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN REWRITE_TAC[GSYM INT_OF_NUM_ADD; GSYM INT_OF_NUM_SUC] THEN INT_ARITH_TAC] THEN REWRITE_TAC[GSYM INT_NOT_LE] THEN DISCH_TAC THEN MP_TAC(SPECL [`n:num`; `p:int`] INT_DIVIDES_FACT) THEN ASM_SIMP_TAC[INT_PRIME_GE_2; INT_ARITH `&2 <= p ==> &1 <= p`] THEN DISCH_TAC THEN SUBGOAL_THEN `p divides &1` MP_TAC THENL [REPEAT(POP_ASSUM MP_TAC) THEN INTEGER_TAC; REWRITE_TAC[INT_DIVIDES_ONE] THEN ASM_MESON_TAC[INT_PRIME_NEG; INT_PRIME_1]]);; let INT_EUCLID = prove (`!n. ?p. int_prime(p) /\ p > n`, MP_TAC INT_IMAGE THEN MATCH_MP_TAC MONO_FORALL THEN X_GEN_TAC `n:int` THEN REWRITE_TAC[INT_GT] THEN ASM_REWRITE_TAC[OR_EXISTS_THM; LEFT_IMP_EXISTS_THM] THEN MP_TAC INT_EUCLID_BOUND THEN MATCH_MP_TAC MONO_FORALL THEN X_GEN_TAC `m:num` THEN DISCH_THEN(fun th -> DISCH_TAC THEN MP_TAC th) THEN MATCH_MP_TAC MONO_EXISTS THEN SIMP_TAC[] THEN FIRST_X_ASSUM(DISJ_CASES_THEN SUBST1_TAC) THEN INT_ARITH_TAC);; let INT_PRIMES_INFINITE = prove (`INFINITE {p | int_prime p}`, SUBGOAL_THEN `INFINITE {n | int_prime(&n)}` MP_TAC THEN REWRITE_TAC[INFINITE; CONTRAPOS_THM] THENL [REWRITE_TAC[num_FINITE; IN_ELIM_THM] THEN REWRITE_TAC[NOT_EXISTS_THM; NOT_FORALL_THM; NOT_IMP; NOT_LE] THEN REWRITE_TAC[GSYM INT_OF_NUM_LT; INT_EXISTS_POS] THEN MP_TAC INT_EUCLID_BOUND THEN MATCH_MP_TAC MONO_FORALL THEN GEN_TAC THEN MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC THEN SIMP_TAC[] THEN INT_ARITH_TAC; MP_TAC(ISPECL [`&`; `{p | int_prime p}`] FINITE_IMAGE_INJ) THEN REWRITE_TAC[INT_OF_NUM_EQ; IN_ELIM_THM]]);; let INT_COPRIME_PRIME = prove (`!p a b. coprime(a,b) ==> ~(int_prime(p) /\ p divides a /\ p divides b)`, REWRITE_TAC[INT_COPRIME] THEN MESON_TAC[INT_DIVIDES_ONE; INT_PRIME_NEG; INT_PRIME_1]);; let INT_COPRIME_PRIME_EQ = prove (`!a b. coprime(a,b) <=> !p. ~(int_prime(p) /\ p divides a /\ p divides b)`, REPEAT GEN_TAC THEN EQ_TAC THENL [MESON_TAC[INT_COPRIME_PRIME]; ALL_TAC] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[INT_COPRIME; INT_DIVIDES_ONE_ABS] THEN ONCE_REWRITE_TAC[NOT_FORALL_THM] THEN REWRITE_TAC[NOT_IMP] THEN DISCH_THEN(X_CHOOSE_THEN `d:int` STRIP_ASSUME_TAC) THEN FIRST_ASSUM(X_CHOOSE_TAC `p:int` o MATCH_MP INT_PRIME_FACTOR) THEN EXISTS_TAC `p:int` THEN ASM_MESON_TAC[INT_DIVIDES_TRANS]);; let INT_PRIME_COPRIME = prove (`!x p. int_prime(p) ==> p divides x \/ coprime(p,x)`, REPEAT STRIP_TAC THEN REWRITE_TAC[INT_COPRIME] THEN MATCH_MP_TAC(TAUT `(~b ==> a) ==> a \/ b`) THEN REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; INT_DIVIDES_ONE_ABS] THEN DISCH_THEN(X_CHOOSE_THEN `d:int` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [int_prime]) THEN DISCH_THEN(MP_TAC o SPEC `d:int` o CONJUNCT2) THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[INT_DIVIDES_TRANS; INT_DIVIDES_LABS; INT_DIVIDES_RABS]);; let INT_PRIME_COPRIME_EQ = prove (`!p n. int_prime p ==> (coprime(p,n) <=> ~(p divides n))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC(TAUT `(b \/ a) /\ ~(a /\ b) ==> (a <=> ~b)`) THEN ASM_SIMP_TAC[INT_PRIME_COPRIME; INT_COPRIME; INT_DIVIDES_ONE_ABS] THEN ASM_MESON_TAC[INT_DIVIDES_REFL; INT_PRIME_1; INT_PRIME_ABS]);; let INT_COPRIME_PRIMEPOW = prove (`!p k m. int_prime p /\ ~(k = 0) ==> (coprime(m,p pow k) <=> ~(p divides m))`, SIMP_TAC[INT_COPRIME_RPOW] THEN ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN SIMP_TAC[INT_PRIME_COPRIME_EQ]);; let INT_COPRIME_BEZOUT = prove (`!a b. coprime(a,b) <=> ?x y. a * x + b * y = &1`, INTEGER_TAC);; let INT_COPRIME_BEZOUT_ALT = prove (`!a b. coprime(a,b) ==> ?x y. a * x = b * y + &1`, INTEGER_TAC);; let INT_BEZOUT_PRIME = prove (`!a p. int_prime p /\ ~(p divides a) ==> ?x y. a * x = p * y + &1`, MESON_TAC[INT_COPRIME_BEZOUT_ALT; INT_COPRIME_SYM; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_DIVPROD = prove (`!p a b. int_prime(p) /\ p divides (a * b) ==> p divides a \/ p divides b`, ONCE_REWRITE_TAC[TAUT `a /\ b ==> c \/ d <=> a ==> (~c /\ ~d ==> ~b)`] THEN SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ] THEN INTEGER_TAC);; let INT_PRIME_DIVPROD_EQ = prove (`!p a b. int_prime(p) ==> (p divides (a * b) <=> p divides a \/ p divides b)`, MESON_TAC[INT_PRIME_DIVPROD; INT_DIVIDES_LMUL; INT_DIVIDES_RMUL]);; let INT_PRIME_DIVPOW = prove (`!n p x. int_prime(p) /\ p divides (x pow n) ==> p divides x`, REPEAT GEN_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ; INT_COPRIME_POW]);; let INT_PRIME_DIVPOW_N = prove (`!n p x. int_prime p /\ p divides (x pow n) ==> (p pow n) divides (x pow n)`, MESON_TAC[INT_PRIME_DIVPOW; INT_DIVIDES_POW]);; let INT_COPRIME_SOS = prove (`!x y. coprime(x,y) ==> coprime(x * y,x pow 2 + y pow 2)`, INTEGER_TAC);; let INT_PRIME_IMP_NZ = prove (`!p. int_prime p ==> ~(p = &0)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP INT_PRIME_GE_2) THEN INT_ARITH_TAC);; let INT_DISTINCT_PRIME_COPRIME = prove (`!p q. int_prime p /\ int_prime q /\ ~(abs p = abs q) ==> coprime(p,q)`, REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN MESON_TAC[INT_COPRIME_SYM; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_COPRIME_LT = prove (`!x p. int_prime p /\ &0 < abs x /\ abs x < abs p ==> coprime(x,p)`, ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN SIMP_TAC[INT_PRIME_COPRIME_EQ] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC);; let INT_DIVIDES_PRIME_PRIME = prove (`!p q. int_prime p /\ int_prime q ==> (p divides q <=> abs p = abs q)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ; INT_DISTINCT_PRIME_COPRIME]; SIMP_TAC[GSYM INT_DIVIDES_ANTISYM_ABS]]);; let INT_COPRIME_POW_DIVPROD = prove (`!d a b. (d pow n) divides (a * b) /\ coprime(d,a) ==> (d pow n) divides b`, MESON_TAC[INT_COPRIME_DIVPROD; INT_COPRIME_POW; INT_COPRIME_SYM]);; let INT_PRIME_COPRIME_CASES = prove (`!p a b. int_prime p /\ coprime(a,b) ==> coprime(p,a) \/ coprime(p,b)`, MESON_TAC[INT_COPRIME_PRIME; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_DIVPROD_POW = prove (`!n p a b. int_prime(p) /\ coprime(a,b) /\ (p pow n) divides (a * b) ==> (p pow n) divides a \/ (p pow n) divides b`, MESON_TAC[INT_COPRIME_POW_DIVPROD; INT_PRIME_COPRIME_CASES; INT_MUL_SYM]);; let INT_DIVIDES_POW2_REV = prove (`!n a b. (a pow n) divides (b pow n) /\ ~(n = 0) ==> a divides b`, REPEAT GEN_TAC THEN ASM_CASES_TAC `gcd(a,b) = &0` THENL [ASM_MESON_TAC[INT_GCD_EQ_0; INT_DIVIDES_REFL]; ALL_TAC] THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_GCD_COPRIME_EXISTS) THEN STRIP_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN ONCE_ASM_REWRITE_TAC[] THEN REWRITE_TAC[INT_POW_MUL] THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_DIVIDES_RMUL2_EQ] THEN DISCH_THEN(MP_TAC o MATCH_MP (INTEGER_RULE `a divides b ==> coprime(a,b) ==> a divides &1`)) THEN ASM_SIMP_TAC[INT_COPRIME_POW2] THEN ASM_MESON_TAC[INT_DIVIDES_POW2; INT_DIVIDES_TRANS; INT_DIVIDES_1]);; let INT_DIVIDES_POW2_EQ = prove (`!n a b. ~(n = 0) ==> ((a pow n) divides (b pow n) <=> a divides b)`, MESON_TAC[INT_DIVIDES_POW2_REV; INT_DIVIDES_POW]);; let INT_POW_MUL_EXISTS = prove (`!m n p k. ~(m = &0) /\ m pow k * n = p pow k ==> ?q. n = q pow k`, REPEAT GEN_TAC THEN ASM_CASES_TAC `k = 0` THEN ASM_SIMP_TAC[INT_POW; INT_MUL_LID] THEN STRIP_TAC THEN MP_TAC(SPECL [`k:num`; `m:int`; `p:int`] INT_DIVIDES_POW2_REV) THEN ASM_REWRITE_TAC[] THEN ANTS_TAC THENL [ASM_MESON_TAC[int_divides; INT_MUL_SYM]; ALL_TAC] THEN REWRITE_TAC[int_divides] THEN DISCH_THEN(CHOOSE_THEN SUBST_ALL_TAC) THEN FIRST_X_ASSUM(MP_TAC o SYM) THEN ASM_SIMP_TAC[INT_POW_MUL; INT_EQ_MUL_LCANCEL; INT_POW_EQ_0] THEN MESON_TAC[]);; let INT_COPRIME_POW_ABS = prove (`!n a b c. coprime(a,b) /\ a * b = c pow n ==> ?r s. abs a = r pow n /\ abs b = s pow n`, GEN_TAC THEN GEN_REWRITE_TAC BINDER_CONV [SWAP_FORALL_THM] THEN GEN_REWRITE_TAC I [SWAP_FORALL_THM] THEN ASM_CASES_TAC `n = 0` THENL [ASM_REWRITE_TAC[INT_POW] THEN MESON_TAC[INT_ABS_MUL_1; INT_ABS_NUM]; ALL_TAC] THEN MATCH_MP_TAC INT_PRIME_FACTOR_INDUCT THEN REPEAT CONJ_TAC THENL [REPEAT GEN_TAC THEN ASM_REWRITE_TAC[INT_POW_ZERO; INT_ENTIRE] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC DISJ_CASES_TAC) THEN ASM_SIMP_TAC[INT_COPRIME_0; INT_DIVIDES_ONE_ABS; INT_ABS_NUM] THEN ASM_MESON_TAC[INT_POW_ONE; INT_POW_ZERO]; REPEAT STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o AP_TERM `abs:int->int`) THEN SIMP_TAC[INT_POW_ONE; INT_ABS_NUM; INT_ABS_MUL_1] THEN MESON_TAC[INT_POW_ONE]; REPEAT STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o AP_TERM `abs:int->int`) THEN SIMP_TAC[INT_POW_ONE; INT_ABS_POW; INT_ABS_NEG; INT_ABS_NUM; INT_ABS_MUL_1] THEN MESON_TAC[INT_POW_ONE]; REWRITE_TAC[INT_POW_MUL] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `p pow n divides a \/ p pow n divides b` MP_TAC THENL [ASM_MESON_TAC[INT_PRIME_DIVPROD_POW; int_divides]; ALL_TAC] THEN REWRITE_TAC[int_divides] THEN DISCH_THEN(DISJ_CASES_THEN(X_CHOOSE_THEN `d:int` SUBST_ALL_TAC)) THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [INT_COPRIME_SYM]) THEN ASM_SIMP_TAC[INT_COPRIME_RMUL; INT_COPRIME_LMUL; INT_COPRIME_LPOW; INT_COPRIME_RPOW] THEN STRIP_TAC THENL [FIRST_X_ASSUM(MP_TAC o SPECL [`b:int`; `d:int`]); FIRST_X_ASSUM(MP_TAC o SPECL [`d:int`; `a:int`])] THEN ASM_REWRITE_TAC[] THEN (ANTS_TAC THENL [MATCH_MP_TAC(INT_RING `!p. ~(p = &0) /\ a * p = b * p ==> a = b`) THEN EXISTS_TAC `p pow n` THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_PRIME_IMP_NZ] THEN FIRST_X_ASSUM(MP_TAC o SYM) THEN CONV_TAC INT_RING; STRIP_TAC THEN ASM_REWRITE_TAC[INT_ABS_POW; GSYM INT_POW_MUL; INT_ABS_MUL] THEN MESON_TAC[]])]);; let INT_COPRIME_POW_ODD = prove (`!n a b c. ODD n /\ coprime(a,b) /\ a * b = c pow n ==> ?r s. a = r pow n /\ b = s pow n`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`n:num`; `a:int`; `b:int`; `c:int`] INT_COPRIME_POW_ABS) THEN ASM_REWRITE_TAC[INT_ABS] THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM; LEFT_EXISTS_AND_THM] THEN MATCH_MP_TAC MONO_AND THEN REWRITE_TAC[INT_ABS] THEN ASM_MESON_TAC[INT_POW_NEG; INT_NEG_NEG; NOT_ODD]);; let INT_DIVIDES_PRIME_POW_LE = prove (`!p q m n. int_prime p /\ int_prime q ==> ((p pow m) divides (q pow n) <=> m = 0 \/ abs p = abs q /\ m <= n)`, REPEAT STRIP_TAC THEN ASM_CASES_TAC `m = 0` THEN ASM_REWRITE_TAC[INT_POW; INT_DIVIDES_1] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_LABS] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_RABS] THEN REWRITE_TAC[INT_ABS_POW] THEN EQ_TAC THENL [DISCH_TAC THEN MATCH_MP_TAC(TAUT `a /\ (a ==> b) ==> a /\ b`); ALL_TAC] THEN ASM_MESON_TAC[INT_DIVIDES_POW_LE; INT_PRIME_GE_2; INT_PRIME_DIVPOW; INT_ABS_ABS; INT_PRIME_ABS; INT_DIVIDES_POW2; INT_DIVIDES_PRIME_PRIME]);; let INT_EQ_PRIME_POW_ABS = prove (`!p q m n. int_prime p /\ int_prime q ==> (abs p pow m = abs q pow n <=> m = 0 /\ n = 0 \/ abs p = abs q /\ m = n)`, REPEAT STRIP_TAC THEN REWRITE_TAC[GSYM INT_ABS_POW] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_ANTISYM_ABS] THEN ASM_SIMP_TAC[INT_DIVIDES_PRIME_POW_LE; INT_PRIME_ABS] THEN ASM_CASES_TAC `abs p = abs q` THEN ASM_REWRITE_TAC[] THEN ARITH_TAC);; let INT_EQ_PRIME_POW_POS = prove (`!p q m n. int_prime p /\ int_prime q /\ &0 <= p /\ &0 <= q ==> (p pow m = q pow n <=> m = 0 /\ n = 0 \/ p = q /\ m = n)`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`p:int`; `q:int`; `m:num`; `n:num`] INT_EQ_PRIME_POW_ABS) THEN ASM_SIMP_TAC[INT_ABS]);; let INT_DIVIDES_FACT_PRIME = prove (`!p. int_prime p ==> !n. p divides &(FACT n) <=> abs p <= &n`, GEN_TAC THEN DISCH_TAC THEN INDUCT_TAC THEN REWRITE_TAC[FACT] THENL [REWRITE_TAC[INT_ARITH `abs x <= &0 <=> x = &0`] THEN ASM_MESON_TAC[INT_DIVIDES_ONE; INT_PRIME_NEG; INT_PRIME_0; INT_PRIME_1]; ASM_SIMP_TAC[INT_PRIME_DIVPROD_EQ; GSYM INT_OF_NUM_MUL] THEN REWRITE_TAC[GSYM INT_OF_NUM_SUC] THEN ASM_MESON_TAC[INT_DIVIDES_LE; INT_ARITH `x <= n ==> x <= n + &1`; INT_DIVIDES_REFL; INT_DIVIDES_LABS; INT_ARITH `p <= n + &1 ==> p <= n \/ p = n + &1`; INT_ARITH `~(&n + &1 = &0)`; INT_ARITH `abs(&n + &1) = &n + &1`]]);;
null
https://raw.githubusercontent.com/jrh13/hol-light/f25b1592a72d8c1c2666231645cff4809aed1ce4/Library/integer.ml
ocaml
========================================================================= Basic divisibility notions over the integers. ========================================================================= ------------------------------------------------------------------------- Basic properties of divisibility. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Now carefully distinguish signs. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- More lemmas about coprimality. ------------------------------------------------------------------------- ------------------------------------------------------------------------- More lemmas about congruences. ------------------------------------------------------------------------- ------------------------------------------------------------------------- A stronger form of the CRT. ------------------------------------------------------------------------- ------------------------------------------------------------------------- Other miscellaneous lemmas. ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- ------------------------------------------------------------------------- -------------------------------------------------------------------------
This is similar to stuff in Library / prime.ml etc . for natural numbers . prioritize_int();; let INT_DIVIDES_REFL = INTEGER_RULE `!d. d divides d`;; let INT_DIVIDES_TRANS = INTEGER_RULE `!x y z. x divides y /\ y divides z ==> x divides z`;; let INT_DIVIDES_ADD = INTEGER_RULE `!d a b. d divides a /\ d divides b ==> d divides (a + b)`;; let INT_DIVIDES_SUB = INTEGER_RULE `!d a b. d divides a /\ d divides b ==> d divides (a - b)`;; let INT_DIVIDES_0 = INTEGER_RULE `!d. d divides &0`;; let INT_DIVIDES_ZERO = INTEGER_RULE `!x. &0 divides x <=> x = &0`;; let INT_DIVIDES_LNEG = INTEGER_RULE `!d x. (--d) divides x <=> d divides x`;; let INT_DIVIDES_RNEG = INTEGER_RULE `!d x. d divides (--x) <=> d divides x`;; let INT_DIVIDES_RMUL = INTEGER_RULE `!d x y. d divides x ==> d divides (x * y)`;; let INT_DIVIDES_LMUL = INTEGER_RULE `!d x y. d divides y ==> d divides (x * y)`;; let INT_DIVIDES_1 = INTEGER_RULE `!x. &1 divides x`;; let INT_DIVIDES_ADD_REVR = INTEGER_RULE `!d a b. d divides a /\ d divides (a + b) ==> d divides b`;; let INT_DIVIDES_ADD_REVL = INTEGER_RULE `!d a b. d divides b /\ d divides (a + b) ==> d divides a`;; let INT_DIVIDES_MUL_L = INTEGER_RULE `!a b c. a divides b ==> (c * a) divides (c * b)`;; let INT_DIVIDES_MUL_R = INTEGER_RULE `!a b c. a divides b ==> (a * c) divides (b * c)`;; let INT_DIVIDES_LMUL2 = INTEGER_RULE `!d a x. (x * d) divides a ==> d divides a`;; let INT_DIVIDES_RMUL2 = INTEGER_RULE `!d a x. (d * x) divides a ==> d divides a`;; let INT_DIVIDES_CMUL2 = INTEGER_RULE `!a b c. (c * a) divides (c * b) /\ ~(c = &0) ==> a divides b`;; let INT_DIVIDES_LMUL2_EQ = INTEGER_RULE `!a b c. ~(c = &0) ==> ((c * a) divides (c * b) <=> a divides b)`;; let INT_DIVIDES_RMUL2_EQ = INTEGER_RULE `!a b c. ~(c = &0) ==> ((a * c) divides (b * c) <=> a divides b)`;; let INT_DIVIDES_MUL2 = INTEGER_RULE `!a b c d. a divides b /\ c divides d ==> (a * c) divides (b * d)`;; let INT_DIVIDES_POW = prove (`!x y n. x divides y ==> (x pow n) divides (y pow n)`, REWRITE_TAC[int_divides] THEN MESON_TAC[INT_POW_MUL]);; let INT_DIVIDES_POW2 = prove (`!n x y. ~(n = 0) /\ (x pow n) divides y ==> x divides y`, INDUCT_TAC THEN REWRITE_TAC[NOT_SUC; INT_POW] THEN INTEGER_TAC);; let INT_DIVIDES_RPOW = prove (`!x y n. x divides y /\ ~(n = 0) ==> x divides (y pow n)`, GEN_TAC THEN GEN_TAC THEN INDUCT_TAC THEN SIMP_TAC[INT_DIVIDES_RMUL; INT_POW]);; let INT_DIVIDES_RPOW_SUC = prove (`!x y n. x divides y ==> x divides (y pow (SUC n))`, SIMP_TAC[INT_DIVIDES_RPOW; NOT_SUC]);; let INT_DIVIDES_POW_LE_IMP = prove (`!(p:int) m n. m <= n ==> p pow m divides p pow n`, SIMP_TAC[LE_EXISTS; INT_POW_ADD; LEFT_IMP_EXISTS_THM] THEN CONV_TAC INTEGER_RULE);; let INT_DIVIDES_ANTISYM_DIVISORS = prove (`!a b:int. a divides b /\ b divides a <=> !d. d divides a <=> d divides b`, MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_DIVIDES_ANTISYM_MULTIPLES = prove (`!a b. a divides b /\ b divides a <=> !d. a divides d <=> b divides d`, MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_DIVIDES_ONE_POS = prove (`!x. &0 <= x ==> (x divides &1 <=> x = &1)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [REWRITE_TAC[int_divides]; INTEGER_TAC] THEN DISCH_THEN(CHOOSE_THEN(MP_TAC o AP_TERM `abs` o SYM)) THEN SIMP_TAC[INT_ABS_NUM; INT_ABS_MUL_1] THEN ASM_SIMP_TAC[INT_ABS]);; let INT_DIVIDES_ONE_ABS = prove (`!d. d divides &1 <=> abs(d) = &1`, MESON_TAC[INT_DIVIDES_LABS; INT_DIVIDES_ONE_POS; INT_ABS_POS]);; let INT_DIVIDES_ONE = prove (`!d. d divides &1 <=> d = &1 \/ d = -- &1`, REWRITE_TAC[INT_DIVIDES_ONE_ABS] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_ASSOCIATED = prove (`!x y. x divides y /\ y divides x <=> ?u. u divides &1 /\ x = y * u`, REPEAT GEN_TAC THEN EQ_TAC THENL [ALL_TAC; INTEGER_TAC] THEN ASM_CASES_TAC `x = &0` THEN ASM_SIMP_TAC[INT_DIVIDES_ZERO; INT_MUL_LZERO] THEN ASM_MESON_TAC[int_divides; INT_DIVIDES_REFL; INTEGER_RULE `y = x * d /\ x = y * e /\ ~(y = &0) ==> d divides &1`]);; let INT_DIVIDES_ANTISYM = prove (`!x y. x divides y /\ y divides x <=> x = y \/ x = --y`, REWRITE_TAC[INT_DIVIDES_ANTISYM_ASSOCIATED; INT_DIVIDES_ONE] THEN REWRITE_TAC[RIGHT_OR_DISTRIB; EXISTS_OR_THM; UNWIND_THM2] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_ABS = prove (`!x y. x divides y /\ y divides x <=> abs(x) = abs(y)`, REWRITE_TAC[INT_DIVIDES_ANTISYM] THEN INT_ARITH_TAC);; let INT_DIVIDES_ANTISYM_POS = prove (`!x y. &0 <= x /\ &0 <= y ==> (x divides y /\ y divides x <=> x = y)`, REWRITE_TAC[INT_DIVIDES_ANTISYM_ABS] THEN INT_ARITH_TAC);; Lemmas about GCDs . let INT_GCD_POS = prove (`!a b. &0 <= gcd(a,b)`, REWRITE_TAC[int_gcd]);; let INT_ABS_GCD = prove (`!a b. abs(gcd(a,b)) = gcd(a,b)`, REWRITE_TAC[INT_ABS; INT_GCD_POS]);; let INT_GCD_DIVIDES = prove (`!a b. gcd(a,b) divides a /\ gcd(a,b) divides b`, INTEGER_TAC);; let INT_COPRIME_GCD = prove (`!a b. coprime(a,b) <=> gcd(a,b) = &1`, SIMP_TAC[GSYM INT_DIVIDES_ONE_POS; INT_GCD_POS] THEN INTEGER_TAC);; let INT_GCD_BEZOUT = prove (`!a b. ?x y. gcd(a,b) = a * x + b * y`, INTEGER_TAC);; let INT_DIVIDES_GCD = prove (`!a b d. d divides gcd(a,b) <=> d divides a /\ d divides b`, INTEGER_TAC);; let INT_GCD = INTEGER_RULE `!a b. (gcd(a,b) divides a /\ gcd(a,b) divides b) /\ (!e. e divides a /\ e divides b ==> e divides gcd(a,b))`;; let INT_GCD_UNIQUE = prove (`!a b d. gcd(a,b) = d <=> &0 <= d /\ d divides a /\ d divides b /\ !e. e divides a /\ e divides b ==> e divides d`, REPEAT GEN_TAC THEN EQ_TAC THENL [MESON_TAC[INT_GCD; INT_GCD_POS]; ALL_TAC] THEN ASM_SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS; INT_DIVIDES_GCD] THEN REPEAT STRIP_TAC THEN FIRST_X_ASSUM MATCH_MP_TAC THEN INTEGER_TAC);; let INT_GCD_UNIQUE_ABS = prove (`!a b d. gcd(a,b) = abs(d) <=> d divides a /\ d divides b /\ !e. e divides a /\ e divides b ==> e divides d`, REWRITE_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS]);; let INT_GCD_REFL = prove (`!a. gcd(a,a) = abs(a)`, REWRITE_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_SYM = prove (`!a b. gcd(a,b) = gcd(b,a)`, SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS] THEN INTEGER_TAC);; let INT_GCD_ASSOC = prove (`!a b c. gcd(a,gcd(b,c)) = gcd(gcd(a,b),c)`, SIMP_TAC[INT_GCD_POS; GSYM INT_DIVIDES_ANTISYM_POS] THEN INTEGER_TAC);; let INT_GCD_1 = prove (`!a. gcd(a,&1) = &1 /\ gcd(&1,a) = &1`, SIMP_TAC[INT_GCD_UNIQUE; INT_POS; INT_DIVIDES_1]);; let INT_GCD_0 = prove (`!a. gcd(a,&0) = abs(a) /\ gcd(&0,a) = abs(a)`, SIMP_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_EQ_0 = prove (`!a b. gcd(a,b) = &0 <=> a = &0 /\ b = &0`, INTEGER_TAC);; let INT_GCD_ABS = prove (`!a b. gcd(abs(a),b) = gcd(a,b) /\ gcd(a,abs(b)) = gcd(a,b)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_DIVIDES_ABS; INT_GCD_POS; INT_GCD]);; let INT_GCD_MULTIPLE = (`!a b. gcd(a,a * b) = abs(a) /\ gcd(b,a * b) = abs(b)`, REWRITE_TAC[INT_GCD_UNIQUE_ABS] THEN INTEGER_TAC);; let INT_GCD_ADD = prove (`(!a b. gcd(a + b,b) = gcd(a,b)) /\ (!a b. gcd(b + a,b) = gcd(a,b)) /\ (!a b. gcd(a,a + b) = gcd(a,b)) /\ (!a b. gcd(a,b + a) = gcd(a,b))`, SIMP_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_GCD_SUB = prove (`(!a b. gcd(a - b,b) = gcd(a,b)) /\ (!a b. gcd(b - a,b) = gcd(a,b)) /\ (!a b. gcd(a,a - b) = gcd(a,b)) /\ (!a b. gcd(a,b - a) = gcd(a,b))`, SIMP_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_DIVIDES_GCD_LEFT = prove (`!m n:int. m divides n <=> gcd(m,n) = abs m`, SIMP_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS; INT_DIVIDES_REFL] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_DIVIDES_GCD_RIGHT = prove (`!m n:int. n divides m <=> gcd(m,n) = abs n`, SIMP_TAC[INT_GCD_UNIQUE; INT_ABS_POS; INT_DIVIDES_ABS; INT_DIVIDES_REFL] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_GCD_EQ = prove (`!x y u v:int. (!d. d divides x /\ d divides y <=> d divides u /\ d divides v) ==> gcd(x,y) = gcd(u,v)`, REPEAT STRIP_TAC THEN SIMP_TAC[GSYM INT_DIVIDES_ANTISYM_POS; INT_GCD_POS] THEN ASM_REWRITE_TAC[INT_DIVIDES_GCD; INT_GCD_DIVIDES] THEN FIRST_X_ASSUM(fun th -> REWRITE_TAC[GSYM th]) THEN REWRITE_TAC[INT_GCD_DIVIDES]);; let INT_GCD_LNEG = prove (`!a b:int. gcd(--a,b) = gcd(a,b)`, REPEAT GEN_TAC THEN MATCH_MP_TAC INT_GCD_EQ THEN INTEGER_TAC);; let INT_GCD_RNEG = prove (`!a b:int. gcd(a,--b) = gcd(a,b)`, REPEAT GEN_TAC THEN MATCH_MP_TAC INT_GCD_EQ THEN INTEGER_TAC);; let INT_GCD_NEG = prove (`(!a b. gcd(--a,b) = gcd(a,b)) /\ (!a b. gcd(a,--b) = gcd(a,b))`, REWRITE_TAC[INT_GCD_LNEG; INT_GCD_RNEG]);; let INT_GCD_LABS = prove (`!a b. gcd(abs a,b) = gcd(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_GCD_LNEG]);; let INT_GCD_RABS = prove (`!a b. gcd(a,abs b) = gcd(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_GCD_RNEG]);; let INT_GCD_ABS = prove (`(!a b. gcd(abs a,b) = gcd(a,b)) /\ (!a b. gcd(a,abs b) = gcd(a,b))`, REWRITE_TAC[INT_GCD_LABS; INT_GCD_RABS]);; let INT_GCD_LMUL = prove (`!a b c:int. gcd(c * a,c * b) = abs c * gcd(a,b)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_RMUL = prove (`!a b c:int. gcd(a * c,b * c) = gcd(a,b) * abs c`, ONCE_REWRITE_TAC[INT_MUL_SYM] THEN REWRITE_TAC[INT_GCD_LMUL]);; let INT_GCD_COPRIME_LMUL = prove (`!a b c:int. coprime(a,b) ==> gcd(a * b,c) = gcd(a,c) * gcd(b,c)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_COPRIME_RMUL = prove (`!a b c:int. coprime(b,c) ==> gcd(a, b * c) = gcd(a,b) * gcd(a,c)`, ONCE_REWRITE_TAC[INT_GCD_SYM] THEN REWRITE_TAC[INT_GCD_COPRIME_LMUL]);; let INT_GCD_COPRIME_DIVIDES_LMUL = prove (`!a b c:int. coprime(a,b) /\ a divides c ==> gcd(a * b,c) = abs a * gcd(b,c)`, ONCE_REWRITE_TAC[GSYM INT_ABS_GCD] THEN REWRITE_TAC[GSYM INT_ABS_MUL] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN CONV_TAC INTEGER_RULE);; let INT_GCD_COPRIME_DIVIDES_RMUL = prove (`!a b c:int. coprime(b,c) /\ b divides a ==> gcd(a,b * c) = abs b * gcd(a,c)`, ONCE_REWRITE_TAC[INT_GCD_SYM] THEN REWRITE_TAC[INT_GCD_COPRIME_DIVIDES_LMUL]);; let INT_GCD_COPRIME_EXISTS = prove (`!a b. ?a' b'. a = a' * gcd(a,b) /\ b = b' * gcd(a,b) /\ coprime(a',b')`, REPEAT GEN_TAC THEN ASM_CASES_TAC `gcd(a,b):int = &0` THENL [ALL_TAC; POP_ASSUM MP_TAC THEN CONV_TAC INTEGER_RULE] THEN RULE_ASSUM_TAC(REWRITE_RULE[INT_GCD_EQ_0]) THEN REPEAT(EXISTS_TAC `&1:int`) THEN ASM_REWRITE_TAC[INT_GCD_0] THEN CONV_TAC INT_REDUCE_CONV THEN CONV_TAC INTEGER_RULE);; Lemmas about lcms . let INT_ABS_LCM = prove (`!a b. abs(lcm(a,b)) = lcm(a,b)`, REWRITE_TAC[INT_ABS; INT_LCM_POS]);; let INT_LCM_EQ_0 = prove (`!m n. lcm(m,n) = &0 <=> m = &0 \/ n = &0`, REWRITE_TAC[INTEGER_RULE `n:int = &0 <=> &0 divides n`] THEN REWRITE_TAC[INT_DIVIDES_LCM_GCD] THEN INTEGER_TAC);; let INT_DIVIDES_LCM = prove (`!m n r. r divides m \/ r divides n ==> r divides lcm(m,n)`, REWRITE_TAC[INT_DIVIDES_LCM_GCD] THEN INTEGER_TAC);; let INT_LCM_0 = prove (`(!n. lcm(&0,n) = &0) /\ (!n. lcm(n,&0) = &0)`, REWRITE_TAC[INT_LCM_EQ_0]);; let INT_LCM_1 = prove (`(!n. lcm(&1,n) = abs n) /\ (!n. lcm(n,&1) = abs n)`, SIMP_TAC[int_lcm; INT_MUL_LID; INT_MUL_RID; INT_GCD_1] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_DIV_1; INT_ABS_NUM]);; let INT_LCM_UNIQUE_ABS = prove (`!a b m. lcm(a,b) = abs m <=> a divides m /\ b divides m /\ (!n. a divides n /\ b divides n ==> m divides n)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC[GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN REWRITE_TAC[INT_LCM_DIVIDES] THEN MESON_TAC[INT_DIVIDES_REFL; INT_DIVIDES_TRANS]);; let INT_LCM_UNIQUE = prove (`!a b m. lcm(a,b) = m <=> &0 <= m /\ a divides m /\ b divides m /\ (!n. a divides n /\ b divides n ==> m divides n)`, REPEAT GEN_TAC THEN REWRITE_TAC[GSYM INT_LCM_UNIQUE_ABS] THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_LCM_POS) THEN INT_ARITH_TAC);; let INT_LCM_EQ = prove (`!x y u v. (!m. x divides m /\ y divides m <=> u divides m /\ v divides m) ==> lcm(x,y) = lcm(u,v)`, REPEAT STRIP_TAC THEN ONCE_REWRITE_TAC [GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN ASM_REWRITE_TAC[INT_LCM_DIVIDES]);; let INT_LCM_REFL = prove (`!n. lcm(n,n) = abs n`, REWRITE_TAC[int_lcm; INT_GCD_REFL; INT_ENTIRE] THEN GEN_TAC THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_ABS_NUM; INT_ABS_MUL] THEN ASM_SIMP_TAC[INT_DIV_MUL; INT_ABS_ZERO]);; let INT_LCM_SYM = prove (`!m n. lcm(m,n) = lcm(n,m)`, REWRITE_TAC[int_lcm; INT_GCD_SYM; INT_MUL_SYM]);; let INT_LCM_ASSOC = prove (`!m n p. lcm(m,lcm(n,p)) = lcm(lcm(m,n),p)`, REPEAT GEN_TAC THEN ONCE_REWRITE_TAC [GSYM INT_ABS_LCM] THEN REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS; INT_DIVIDES_ANTISYM_MULTIPLES] THEN REWRITE_TAC[INT_LCM_DIVIDES] THEN REWRITE_TAC[CONJ_ASSOC]);; let INT_LCM_LNEG = prove (`!a b:int. lcm(--a,b) = lcm(a,b)`, SIMP_TAC[int_lcm; INT_MUL_LNEG; INT_ABS_NEG; INT_GCD_LNEG; INT_NEG_EQ_0]);; let INT_LCM_RNEG = prove (`!a b:int. lcm(a,--b) = lcm(a,b)`, SIMP_TAC[int_lcm; INT_MUL_RNEG; INT_ABS_NEG; INT_GCD_RNEG; INT_NEG_EQ_0]);; let INT_LCM_NEG = prove (`(!a b. lcm(--a,b) = lcm(a,b)) /\ (!a b. lcm(a,--b) = lcm(a,b))`, REWRITE_TAC[INT_LCM_LNEG; INT_LCM_RNEG]);; let INT_LCM_LABS = prove (`!a b. lcm(abs a,b) = lcm(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_LCM_LNEG]);; let INT_LCM_RABS = prove (`!a b. lcm(a,abs b) = lcm(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_LCM_RNEG]);; let INT_LCM_ABS = prove (`(!a b. lcm(abs a,b) = lcm(a,b)) /\ (!a b. lcm(a,abs b) = lcm(a,b))`, REWRITE_TAC[INT_LCM_LABS; INT_LCM_RABS]);; let INT_LCM_LMUL = prove (`!a b c:int. lcm(c * a,c * b) = abs c * lcm(a,b)`, REPEAT GEN_TAC THEN MAP_EVERY ASM_CASES_TAC [`a:int = &0`; `b:int = &0`; `c:int = &0`] THEN ASM_REWRITE_TAC[INT_MUL_LZERO; INT_MUL_RZERO; INT_ABS_NUM; INT_LCM_0] THEN MATCH_MP_TAC(INT_RING `!x:int. ~(x = &0) /\ a * x = b * x ==> a = b`) THEN EXISTS_TAC `gcd(c * a:int,c * b)` THEN ASM_REWRITE_TAC[INT_GCD_EQ_0; INT_ENTIRE; INT_MUL_LCM_GCD] THEN REWRITE_TAC[INT_GCD_LMUL; INT_MUL_LCM_GCD; INT_ARITH `(x * a) * x * b:int = x * x * a * b`] THEN REWRITE_TAC[INT_ABS_MUL; INT_MUL_AC]);; let INT_LCM_RMUL = prove (`!a b c:int. lcm(a * c,b * c) = lcm(a,b) * abs c`, ONCE_REWRITE_TAC[INT_MUL_SYM] THEN REWRITE_TAC[INT_LCM_LMUL]);; let INT_COPRIME = prove (`!a b. coprime(a,b) <=> !d. d divides a /\ d divides b ==> d divides &1`, REWRITE_TAC[INT_COPRIME_GCD; INT_GCD_UNIQUE; INT_POS; INT_DIVIDES_1]);; let INT_COPRIME_ALT = prove (`!a b. coprime(a,b) <=> !d. d divides a /\ d divides b <=> d divides &1`, MESON_TAC[INT_DIVIDES_1; INT_DIVIDES_TRANS; INT_COPRIME]);; let INT_COPRIME_SYM = prove (`!a b. coprime(a,b) <=> coprime(b,a)`, INTEGER_TAC);; let INT_COPRIME_DIVPROD = prove (`!d a b. d divides (a * b) /\ coprime(d,a) ==> d divides b`, INTEGER_TAC);; let INT_COPRIME_1 = prove (`!a. coprime(a,&1) /\ coprime(&1,a)`, INTEGER_TAC);; let INT_GCD_COPRIME = prove (`!a b a' b'. ~(gcd(a,b) = &0) /\ a = a' * gcd(a,b) /\ b = b' * gcd(a,b) ==> coprime(a',b')`, INTEGER_TAC);; let INT_COPRIME_0 = prove (`(!a. coprime(a,&0) <=> a divides &1) /\ (!a. coprime(&0,a) <=> a divides &1)`, INTEGER_TAC);; let INT_COPRIME_MUL = prove (`!d a b. coprime(d,a) /\ coprime(d,b) ==> coprime(d,a * b)`, INTEGER_TAC);; let INT_COPRIME_LMUL2 = prove (`!d a b. coprime(d,a * b) ==> coprime(d,b)`, INTEGER_TAC);; let INT_COPRIME_RMUL2 = prove (`!d a b. coprime(d,a * b) ==> coprime(d,a)`, INTEGER_TAC);; let INT_COPRIME_LMUL = prove (`!d a b. coprime(a * b,d) <=> coprime(a,d) /\ coprime(b,d)`, INTEGER_TAC);; let INT_COPRIME_RMUL = prove (`!d a b. coprime(d,a * b) <=> coprime(d,a) /\ coprime(d,b)`, INTEGER_TAC);; let INT_COPRIME_REFL = prove (`!n. coprime(n,n) <=> n divides &1`, INTEGER_TAC);; let INT_COPRIME_PLUS1 = prove (`!n. coprime(n + &1,n) /\ coprime(n,n + &1)`, INTEGER_TAC);; let INT_COPRIME_MINUS1 = prove (`!n. coprime(n - &1,n) /\ coprime(n,n - &1)`, INTEGER_TAC);; let INT_COPRIME_RPOW = prove (`!m n k. coprime(m,n pow k) <=> coprime(m,n) \/ k = 0`, GEN_TAC THEN GEN_TAC THEN INDUCT_TAC THEN ASM_SIMP_TAC[INT_POW; INT_COPRIME_1; INT_COPRIME_RMUL; NOT_SUC] THEN CONV_TAC TAUT);; let INT_COPRIME_LPOW = prove (`!m n k. coprime(m pow k,n) <=> coprime(m,n) \/ k = 0`, ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN REWRITE_TAC[INT_COPRIME_RPOW]);; let INT_COPRIME_POW2 = prove (`!m n k. coprime(m pow k,n pow k) <=> coprime(m,n) \/ k = 0`, REWRITE_TAC[INT_COPRIME_RPOW; INT_COPRIME_LPOW; DISJ_ACI]);; let INT_COPRIME_POW = prove (`!n a d. coprime(d,a) ==> coprime(d,a pow n)`, SIMP_TAC[INT_COPRIME_RPOW]);; let INT_COPRIME_POW_IMP = prove (`!n a b. coprime(a,b) ==> coprime(a pow n,b pow n)`, MESON_TAC[INT_COPRIME_POW; INT_COPRIME_SYM]);; let INT_GCD_POW = prove (`!(a:int) b n. gcd(a pow n,b pow n) = gcd(a,b) pow n`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_GCD_COPRIME_EXISTS) THEN REWRITE_TAC[LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`a':int`; `b':int`] THEN STRIP_TAC THEN ONCE_ASM_REWRITE_TAC[] THEN REWRITE_TAC[INT_POW_MUL; INT_GCD_RMUL; INT_ABS_POW] THEN ASM_SIMP_TAC[fst(EQ_IMP_RULE(SPEC_ALL INT_COPRIME_GCD)); INT_COPRIME_POW2; INT_POW_ONE]);; let INT_LCM_POW = prove (`!(a:int) b n. lcm(a pow n,b pow n) = lcm(a,b) pow n`, REPEAT GEN_TAC THEN ASM_CASES_TAC `n = 0` THEN ASM_REWRITE_TAC[INT_POW; INT_LCM_1; INT_POW_ONE; INT_ABS_NUM] THEN MAP_EVERY ASM_CASES_TAC [`a:int = &0`; `b:int = &0`] THEN ASM_REWRITE_TAC[INT_POW_ZERO; INT_LCM_0] THEN MATCH_MP_TAC(INT_RING `!x:int. ~(x = &0) /\ a * x = b * x ==> a = b`) THEN EXISTS_TAC `gcd((a:int) pow n,b pow n)` THEN ASM_REWRITE_TAC[INT_GCD_EQ_0; INT_POW_EQ_0; INT_MUL_LCM_GCD] THEN REWRITE_TAC[INT_GCD_POW; GSYM INT_POW_MUL] THEN REWRITE_TAC[INT_MUL_LCM_GCD; INT_ABS_POW]);; let INT_DIVISION_DECOMP = prove (`!a b c. a divides (b * c) ==> ?b' c'. (a = b' * c') /\ b' divides b /\ c' divides c`, REPEAT STRIP_TAC THEN EXISTS_TAC `gcd(a,b)` THEN ASM_CASES_TAC `gcd(a,b) = &0` THEN REPEAT(POP_ASSUM MP_TAC) THENL [SIMP_TAC[INT_GCD_EQ_0; INT_GCD_0; INT_ABS_NUM]; INTEGER_TAC] THEN REWRITE_TAC[INT_MUL_LZERO] THEN MESON_TAC[INT_DIVIDES_REFL]);; let INT_DIVIDES_MUL = prove (`!m n r. m divides r /\ n divides r /\ coprime(m,n) ==> (m * n) divides r`, INTEGER_TAC);; let INT_CHINESE_REMAINDER = prove (`!a b u v. coprime(a,b) /\ ~(a = &0) /\ ~(b = &0) ==> ?x q1 q2. (x = u + q1 * a) /\ (x = v + q2 * b)`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_USUAL = prove (`!a b u v. coprime(a,b) ==> ?x. (x == u) (mod a) /\ (x == v) (mod b)`, INTEGER_TAC);; let INT_COPRIME_DIVISORS = prove (`!a b d e. d divides a /\ e divides b /\ coprime(a,b) ==> coprime(d,e)`, INTEGER_TAC);; let INT_COPRIME_LNEG = prove (`!a b. coprime(--a,b) <=> coprime(a,b)`, INTEGER_TAC);; let INT_COPRIME_RNEG = prove (`!a b. coprime(a,--b) <=> coprime(a,b)`, INTEGER_TAC);; let INT_COPRIME_NEG = prove (`(!a b. coprime(--a,b) <=> coprime(a,b)) /\ (!a b. coprime(a,--b) <=> coprime(a,b))`, INTEGER_TAC);; let INT_COPRIME_LABS = prove (`!a b. coprime(abs a,b) <=> coprime(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_COPRIME_LNEG]);; let INT_COPRIME_RABS = prove (`!a b. coprime(a,abs b) <=> coprime(a,b)`, REWRITE_TAC[INT_ABS] THEN MESON_TAC[INT_COPRIME_RNEG]);; let INT_COPRIME_ABS = prove (`(!a b. coprime(abs a,b) <=> coprime(a,b)) /\ (!a b. coprime(a,abs b) <=> coprime(a,b))`, REWRITE_TAC[INT_COPRIME_LABS; INT_COPRIME_RABS]);; let INT_CONG_MOD_0 = prove (`!x y. (x == y) (mod &0) <=> (x = y)`, INTEGER_TAC);; let INT_CONG_MOD_1 = prove (`!x y. (x == y) (mod &1)`, INTEGER_TAC);; let INT_CONG = prove (`!x y n. (x == y) (mod n) <=> n divides (x - y)`, INTEGER_TAC);; let INT_CONG_MOD_ABS = prove (`!a b n:int. (a == b) (mod (abs n)) <=> (a == b) (mod n)`, REWRITE_TAC[INT_CONG; INT_DIVIDES_LABS]);; let INT_CONG_MUL_LCANCEL = prove (`!a n x y. coprime(a,n) /\ (a * x == a * y) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_MUL_RCANCEL = prove (`!a n x y. coprime(a,n) /\ (x * a == y * a) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_MULT_LCANCEL_ALL = INTEGER_RULE `!a x y n:int. (a * x == a * y) (mod (a * n)) <=> a = &0 \/ (x == y) (mod n)`;; let INT_CONG_LMUL = INTEGER_RULE `!a x y n:int. (x == y) (mod n) ==> (a * x == a * y) (mod n)`;; let INT_CONG_RMUL = INTEGER_RULE `!x y a n:int. (x == y) (mod n) ==> (x * a == y * a) (mod n)`;; let INT_CONG_REFL = prove (`!x n. (x == x) (mod n)`, INTEGER_TAC);; let INT_EQ_IMP_CONG = prove (`!a b n. a = b ==> (a == b) (mod n)`, INTEGER_TAC);; let INT_CONG_SYM = prove (`!x y n. (x == y) (mod n) <=> (y == x) (mod n)`, INTEGER_TAC);; let INT_CONG_TRANS = prove (`!x y z n. (x == y) (mod n) /\ (y == z) (mod n) ==> (x == z) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x + y == x' + y') (mod n)`, INTEGER_TAC);; let INT_CONG_SUB = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x - y == x' - y') (mod n)`, INTEGER_TAC);; let INT_CONG_MUL = prove (`!x x' y y'. (x == x') (mod n) /\ (y == y') (mod n) ==> (x * y == x' * y') (mod n)`, INTEGER_TAC);; let INT_CONG_POW = prove (`!n k x y. (x == y) (mod n) ==> (x pow k == y pow k) (mod n)`, GEN_TAC THEN INDUCT_TAC THEN ASM_SIMP_TAC[INT_CONG_MUL; INT_POW; INT_CONG_REFL]);; let INT_CONG_MUL_1 = prove (`!n x y:int. (x == &1) (mod n) /\ (y == &1) (mod n) ==> (x * y == &1) (mod n)`, MESON_TAC[INT_CONG_MUL; INT_MUL_LID]);; let INT_CONG_POW_1 = prove (`!a k n:int. (a == &1) (mod n) ==> (a pow k == &1) (mod n)`, MESON_TAC[INT_CONG_POW; INT_POW_ONE]);; let INT_CONG_MUL_LCANCEL_EQ = prove (`!a n x y. coprime(a,n) ==> ((a * x == a * y) (mod n) <=> (x == y) (mod n))`, INTEGER_TAC);; let INT_CONG_MUL_RCANCEL_EQ = prove (`!a n x y. coprime(a,n) ==> ((x * a == y * a) (mod n) <=> (x == y) (mod n))`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL_EQ = prove (`!a n x y. (a + x == a + y) (mod n) <=> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL_EQ = prove (`!a n x y. (x + a == y + a) (mod n) <=> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL = prove (`!a n x y. (x + a == y + a) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL = prove (`!a n x y. (a + x == a + y) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_LCANCEL_EQ_0 = prove (`!a n x y. (a + x == a) (mod n) <=> (x == &0) (mod n)`, INTEGER_TAC);; let INT_CONG_ADD_RCANCEL_EQ_0 = prove (`!a n x y. (x + a == a) (mod n) <=> (x == &0) (mod n)`, INTEGER_TAC);; let INT_CONG_INT_DIVIDES_MODULUS = prove (`!x y m n. (x == y) (mod m) /\ n divides m ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_0_DIVIDES = prove (`!n x. (x == &0) (mod n) <=> n divides x`, INTEGER_TAC);; let INT_CONG_1_DIVIDES = prove (`!n x. (x == &1) (mod n) ==> n divides (x - &1)`, INTEGER_TAC);; let INT_CONG_DIVIDES = prove (`!x y n. (x == y) (mod n) ==> (n divides x <=> n divides y)`, INTEGER_TAC);; let INT_CONG_COPRIME = prove (`!x y n. (x == y) (mod n) ==> (coprime(n,x) <=> coprime(n,y))`, INTEGER_TAC);; let INT_COPRIME_RREM = prove (`!m n. coprime(m,n rem m) <=> coprime(m,n)`, MESON_TAC[INT_CONG_COPRIME; INT_CONG_RREM; INT_CONG_REFL]);; let INT_COPRIME_LREM = prove (`!a b. coprime(a rem n,n) <=> coprime(a,n)`, MESON_TAC[INT_COPRIME_RREM; INT_COPRIME_SYM]);; let INT_CONG_MOD_MULT = prove (`!x y m n. (x == y) (mod n) /\ m divides n ==> (x == y) (mod m)`, INTEGER_TAC);; let INT_CONG_GCD_RIGHT = prove (`!x y n. (x == y) (mod n) ==> gcd(n,x) = gcd(n,y)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_CONG_GCD_LEFT = prove (`!x y n. (x == y) (mod n) ==> gcd(x,n) = gcd(y,n)`, REWRITE_TAC[INT_GCD_UNIQUE; INT_GCD_POS] THEN INTEGER_TAC);; let INT_CONG_TO_1 = prove (`!a n. (a == &1) (mod n) <=> ?m. a = &1 + m * n`, INTEGER_TAC);; let INT_CONG_SOLVE = prove (`!a b n. coprime(a,n) ==> ?x. (a * x == b) (mod n)`, INTEGER_TAC);; let INT_CONG_SOLVE_EQ = prove (`!n a b:int. (?x. (a * x == b) (mod n)) <=> gcd(a,n) divides b`, INTEGER_TAC);; let INT_CONG_SOLVE_UNIQUE = prove (`!a b n. coprime(a,n) ==> !x y. (a * x == b) (mod n) /\ (a * y == b) (mod n) ==> (x == y) (mod n)`, INTEGER_TAC);; let INT_CONG_CHINESE = prove (`coprime(a,b) /\ (x == y) (mod a) /\ (x == y) (mod b) ==> (x == y) (mod (a * b))`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_COPRIME = prove (`!a b m n. coprime(a,b) /\ ~(a = &0) /\ ~(b = &0) /\ coprime(m,a) /\ coprime(n,b) ==> ?x. coprime(x,a * b) /\ (x == m) (mod a) /\ (x == n) (mod b)`, INTEGER_TAC);; let INT_CHINESE_REMAINDER_COPRIME_UNIQUE = prove (`!a b m n x y. coprime(a,b) /\ (x == m) (mod a) /\ (x == n) (mod b) /\ (y == m) (mod a) /\ (y == n) (mod b) ==> (x == y) (mod (a * b))`, INTEGER_TAC);; let SOLVABLE_GCD = prove (`!a b n. gcd(a,n) divides b ==> ?x. (a * x == b) (mod n)`, INTEGER_TAC);; let INT_LINEAR_CONG_POS = prove (`!n a x:int. ~(n = &0) ==> ?y. &0 <= y /\ (a * x == a * y) (mod n)`, REPEAT STRIP_TAC THEN EXISTS_TAC `x + abs(x * n):int` THEN CONJ_TAC THENL [MATCH_MP_TAC(INT_ARITH `abs(x:int) * &1 <= y ==> &0 <= x + y`) THEN REWRITE_TAC[INT_ABS_MUL] THEN MATCH_MP_TAC INT_LE_LMUL THEN ASM_INT_ARITH_TAC; MATCH_MP_TAC(INTEGER_RULE `n divides y ==> (a * x:int == a * (x + y)) (mod n)`) THEN REWRITE_TAC[INT_DIVIDES_RABS] THEN INTEGER_TAC]);; let INT_CONG_SOLVE_POS = prove (`!a b n:int. coprime(a,n) /\ ~(n = &0 /\ abs a = &1) ==> ?x. &0 <= x /\ (a * x == b) (mod n)`, REPEAT GEN_TAC THEN ASM_CASES_TAC `n:int = &0` THEN ASM_REWRITE_TAC[INT_COPRIME_0; INT_DIVIDES_ONE] THENL [INT_ARITH_TAC; ASM_MESON_TAC[INT_LINEAR_CONG_POS; INT_CONG_SOLVE; INT_CONG_TRANS; INT_CONG_SYM]]);; let INT_CONG_IMP_EQ = prove (`!x y n:int. abs(x - y) < n /\ (x == y) (mod n) ==> x = y`, REPEAT GEN_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN ONCE_REWRITE_TAC[int_congruent; GSYM INT_SUB_0] THEN DISCH_THEN(X_CHOOSE_THEN `q:int` SUBST_ALL_TAC) THEN FIRST_X_ASSUM(MP_TAC o MATCH_MP (ARITH_RULE `abs(n * q) < n ==> abs(n * q) < abs n * &1`)) THEN REWRITE_TAC[INT_ABS_MUL; INT_ENTIRE] THEN REWRITE_TAC[INT_ARITH `abs n * (q:int) < abs n * &1 <=> ~(&0 <= abs n * (q - &1))`] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[DE_MORGAN_THM] THEN STRIP_TAC THEN MATCH_MP_TAC INT_LE_MUL THEN ASM_INT_ARITH_TAC);; let INT_CONG_DIV = prove (`!m n a b. ~(m = &0) /\ (a == m * b) (mod (m * n)) ==> (a div m == b) (mod n)`, METIS_TAC[INT_CONG_DIV2; INT_DIV_MUL; INT_LT_LE]);; let INT_CONG_DIV_COPRIME = prove (`!m n a b:int. coprime(m,n) /\ m divides a /\ (a == m * b) (mod n) ==> (a div m == b) (mod n)`, REPEAT GEN_TAC THEN ASM_CASES_TAC `m:int = &0` THEN ASM_SIMP_TAC[INT_COPRIME_0; INT_CONG_MOD_1] THENL [INTEGER_TAC; STRIP_TAC] THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC INT_CONG_DIV THEN REPEAT(POP_ASSUM MP_TAC) THEN CONV_TAC INTEGER_RULE);; let INT_CRT_STRONG = prove (`!a1 a2 n1 n2:int. (a1 == a2) (mod (gcd(n1,n2))) ==> ?x. (x == a1) (mod n1) /\ (x == a2) (mod n2)`, INTEGER_TAC);; let INT_CRT_STRONG_IFF = prove (`!a1 a2 n1 n2:int. (?x. (x == a1) (mod n1) /\ (x == a2) (mod n2)) <=> (a1 == a2) (mod (gcd(n1,n2)))`, INTEGER_TAC);; let EVEN_SQUARE_MOD4 = prove (`((&2 * n) pow 2 == &0) (mod &4)`, INTEGER_TAC);; let ODD_SQUARE_MOD4 = prove (`((&2 * n + &1) pow 2 == &1) (mod &4)`, INTEGER_TAC);; let INT_DIVIDES_LE = prove (`!x y. x divides y ==> abs(x) <= abs(y) \/ y = &0`, REWRITE_TAC[int_divides; LEFT_IMP_EXISTS_THM] THEN MAP_EVERY X_GEN_TAC [`x:int`; `y:int`; `z:int`] THEN DISCH_THEN SUBST1_TAC THEN REWRITE_TAC[INT_ABS_MUL; INT_ENTIRE] THEN REWRITE_TAC[INT_ARITH `x <= x * z <=> &0 <= x * (z - &1)`] THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `z = &0` THEN ASM_REWRITE_TAC[] THEN MATCH_MP_TAC INT_LE_MUL THEN ASM_INT_ARITH_TAC);; let INT_DIVIDES_POW_LE = prove (`!p m n. &2 <= abs p ==> ((p pow m) divides (p pow n) <=> m <= n)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_ARITH `&2 <= abs p ==> ~(p = &0)`] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[INT_NOT_LE; NOT_LE; INT_ABS_POW] THEN ASM_MESON_TAC[INT_POW_MONO_LT; ARITH_RULE `&2 <= x ==> &1 < x`]; SIMP_TAC[LE_EXISTS; LEFT_IMP_EXISTS_THM; INT_POW_ADD] THEN INTEGER_TAC]);; Integer primality / irreducibility . let int_prime = new_definition `int_prime p <=> abs(p) > &1 /\ !x. x divides p ==> abs(x) = &1 \/ abs(x) = abs(p)`;; let INT_PRIME_NEG = prove (`!p. int_prime(--p) <=> int_prime p`, REWRITE_TAC[int_prime; INT_DIVIDES_RNEG; INT_ABS_NEG]);; let INT_PRIME_ABS = prove (`!p. int_prime(abs p) <=> int_prime p`, GEN_TAC THEN REWRITE_TAC[INT_ABS] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[INT_PRIME_NEG]);; let INT_PRIME_GE_2 = prove (`!p. int_prime p ==> &2 <= abs(p)`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_0 = prove (`~(int_prime(&0))`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_1 = prove (`~(int_prime(&1))`, REWRITE_TAC[int_prime] THEN INT_ARITH_TAC);; let INT_PRIME_2 = prove (`int_prime(&2)`, REWRITE_TAC[int_prime] THEN CONV_TAC INT_REDUCE_CONV THEN X_GEN_TAC `x:int` THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[INT_DIVIDES_ZERO] THEN CONV_TAC INT_REDUCE_CONV THEN DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC);; let INT_PRIME_FACTOR = prove (`!x. ~(abs x = &1) ==> ?p. int_prime p /\ p divides x`, MATCH_MP_TAC WF_INT_MEASURE THEN EXISTS_TAC `abs` THEN REWRITE_TAC[INT_ABS_POS] THEN X_GEN_TAC `x:int` THEN REPEAT STRIP_TAC THEN ASM_CASES_TAC `int_prime x` THENL [EXISTS_TAC `x:int` THEN ASM_REWRITE_TAC[] THEN REPEAT(POP_ASSUM MP_TAC) THEN INTEGER_TAC; ALL_TAC] THEN ASM_CASES_TAC `x = &0` THEN ASM_REWRITE_TAC[] THENL [EXISTS_TAC `&2` THEN ASM_REWRITE_TAC[INT_PRIME_2; INT_DIVIDES_0]; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE RAND_CONV [int_prime]) THEN ASM_SIMP_TAC[INT_ARITH `~(x = &0) /\ ~(abs x = &1) ==> abs x > &1`] THEN REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; DE_MORGAN_THM] THEN DISCH_THEN(X_CHOOSE_THEN `y:int` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o SPEC `y:int`) THEN ASM_REWRITE_TAC[] THEN ANTS_TAC THENL [FIRST_X_ASSUM(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC; MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC THEN SIMP_TAC[] THEN UNDISCH_TAC `y divides x` THEN INTEGER_TAC]);; let INT_PRIME_FACTOR_LT = prove (`!n m p. int_prime(p) /\ ~(n = &0) /\ n = p * m ==> abs m < abs n`, REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[INT_ABS_MUL] THEN MATCH_MP_TAC(INT_ARITH `&0 < m * (p - &1) ==> m < p * m`) THEN MATCH_MP_TAC INT_LT_MUL THEN UNDISCH_TAC `~(n = &0)` THEN ASM_CASES_TAC `m = &0` THEN ASM_REWRITE_TAC[INT_MUL_RZERO] THEN DISCH_THEN(K ALL_TAC) THEN CONJ_TAC THENL [ASM_INT_ARITH_TAC; ALL_TAC] THEN FIRST_ASSUM(MP_TAC o MATCH_MP INT_PRIME_GE_2) THEN INT_ARITH_TAC);; let INT_PRIME_FACTOR_INDUCT = prove (`!P. P(&0) /\ P(&1) /\ P(-- &1) /\ (!p n. int_prime p /\ ~(n = &0) /\ P n ==> P(p * n)) ==> !n. P n`, GEN_TAC THEN STRIP_TAC THEN MATCH_MP_TAC WF_INT_MEASURE THEN EXISTS_TAC `abs` THEN REWRITE_TAC[INT_ABS_POS] THEN X_GEN_TAC `n:int` THEN DISCH_TAC THEN ASM_CASES_TAC `n = &0` THEN ASM_REWRITE_TAC[] THEN ASM_CASES_TAC `abs n = &1` THENL [ASM_MESON_TAC[INT_ARITH `abs x = &a <=> x = &a \/ x = -- &a`]; ALL_TAC] THEN FIRST_ASSUM(X_CHOOSE_THEN `p:int` STRIP_ASSUME_TAC o MATCH_MP INT_PRIME_FACTOR) THEN FIRST_X_ASSUM(X_CHOOSE_THEN `d:int` SUBST_ALL_TAC o GEN_REWRITE_RULE I [int_divides]) THEN FIRST_X_ASSUM(MP_TAC o SPECL [`p:int`; `d:int`]) THEN RULE_ASSUM_TAC(REWRITE_RULE[INT_ENTIRE; DE_MORGAN_THM]) THEN DISCH_THEN MATCH_MP_TAC THEN ASM_REWRITE_TAC[] THEN FIRST_X_ASSUM MATCH_MP_TAC THEN ASM_MESON_TAC[INT_PRIME_FACTOR_LT; INT_ENTIRE]);; Infinitude . let INT_DIVIDES_FACT = prove (`!n x. &1 <= abs(x) /\ abs(x) <= &n ==> x divides &(FACT n)`, INDUCT_TAC THENL [INT_ARITH_TAC; ALL_TAC] THEN REWRITE_TAC[FACT; INT_ARITH `x <= &n <=> x = &n \/ x < &n`] THEN REWRITE_TAC[GSYM INT_OF_NUM_SUC; INT_ARITH `x < &m + &1 <=> x <= &m`] THEN REWRITE_TAC[INT_OF_NUM_SUC; GSYM INT_OF_NUM_MUL] THEN REPEAT STRIP_TAC THEN ASM_SIMP_TAC[INT_DIVIDES_LMUL] THEN MATCH_MP_TAC INT_DIVIDES_RMUL THEN ASM_MESON_TAC[INT_DIVIDES_LABS; INT_DIVIDES_REFL]);; let INT_EUCLID_BOUND = prove (`!n. ?p. int_prime(p) /\ &n < p /\ p <= &(FACT n) + &1`, GEN_TAC THEN MP_TAC(SPEC `&(FACT n) + &1` INT_PRIME_FACTOR) THEN REWRITE_TAC[INT_OF_NUM_ADD; INT_ABS_NUM; INT_OF_NUM_EQ] THEN REWRITE_TAC[EQ_ADD_RCANCEL_0; FACT_NZ; GSYM INT_OF_NUM_ADD] THEN DISCH_THEN(X_CHOOSE_THEN `p:int` STRIP_ASSUME_TAC) THEN EXISTS_TAC `abs p` THEN ASM_REWRITE_TAC[INT_PRIME_ABS] THEN CONJ_TAC THENL [ALL_TAC; FIRST_ASSUM(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN REWRITE_TAC[GSYM INT_OF_NUM_ADD; GSYM INT_OF_NUM_SUC] THEN INT_ARITH_TAC] THEN REWRITE_TAC[GSYM INT_NOT_LE] THEN DISCH_TAC THEN MP_TAC(SPECL [`n:num`; `p:int`] INT_DIVIDES_FACT) THEN ASM_SIMP_TAC[INT_PRIME_GE_2; INT_ARITH `&2 <= p ==> &1 <= p`] THEN DISCH_TAC THEN SUBGOAL_THEN `p divides &1` MP_TAC THENL [REPEAT(POP_ASSUM MP_TAC) THEN INTEGER_TAC; REWRITE_TAC[INT_DIVIDES_ONE] THEN ASM_MESON_TAC[INT_PRIME_NEG; INT_PRIME_1]]);; let INT_EUCLID = prove (`!n. ?p. int_prime(p) /\ p > n`, MP_TAC INT_IMAGE THEN MATCH_MP_TAC MONO_FORALL THEN X_GEN_TAC `n:int` THEN REWRITE_TAC[INT_GT] THEN ASM_REWRITE_TAC[OR_EXISTS_THM; LEFT_IMP_EXISTS_THM] THEN MP_TAC INT_EUCLID_BOUND THEN MATCH_MP_TAC MONO_FORALL THEN X_GEN_TAC `m:num` THEN DISCH_THEN(fun th -> DISCH_TAC THEN MP_TAC th) THEN MATCH_MP_TAC MONO_EXISTS THEN SIMP_TAC[] THEN FIRST_X_ASSUM(DISJ_CASES_THEN SUBST1_TAC) THEN INT_ARITH_TAC);; let INT_PRIMES_INFINITE = prove (`INFINITE {p | int_prime p}`, SUBGOAL_THEN `INFINITE {n | int_prime(&n)}` MP_TAC THEN REWRITE_TAC[INFINITE; CONTRAPOS_THM] THENL [REWRITE_TAC[num_FINITE; IN_ELIM_THM] THEN REWRITE_TAC[NOT_EXISTS_THM; NOT_FORALL_THM; NOT_IMP; NOT_LE] THEN REWRITE_TAC[GSYM INT_OF_NUM_LT; INT_EXISTS_POS] THEN MP_TAC INT_EUCLID_BOUND THEN MATCH_MP_TAC MONO_FORALL THEN GEN_TAC THEN MATCH_MP_TAC MONO_EXISTS THEN GEN_TAC THEN SIMP_TAC[] THEN INT_ARITH_TAC; MP_TAC(ISPECL [`&`; `{p | int_prime p}`] FINITE_IMAGE_INJ) THEN REWRITE_TAC[INT_OF_NUM_EQ; IN_ELIM_THM]]);; let INT_COPRIME_PRIME = prove (`!p a b. coprime(a,b) ==> ~(int_prime(p) /\ p divides a /\ p divides b)`, REWRITE_TAC[INT_COPRIME] THEN MESON_TAC[INT_DIVIDES_ONE; INT_PRIME_NEG; INT_PRIME_1]);; let INT_COPRIME_PRIME_EQ = prove (`!a b. coprime(a,b) <=> !p. ~(int_prime(p) /\ p divides a /\ p divides b)`, REPEAT GEN_TAC THEN EQ_TAC THENL [MESON_TAC[INT_COPRIME_PRIME]; ALL_TAC] THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN REWRITE_TAC[INT_COPRIME; INT_DIVIDES_ONE_ABS] THEN ONCE_REWRITE_TAC[NOT_FORALL_THM] THEN REWRITE_TAC[NOT_IMP] THEN DISCH_THEN(X_CHOOSE_THEN `d:int` STRIP_ASSUME_TAC) THEN FIRST_ASSUM(X_CHOOSE_TAC `p:int` o MATCH_MP INT_PRIME_FACTOR) THEN EXISTS_TAC `p:int` THEN ASM_MESON_TAC[INT_DIVIDES_TRANS]);; let INT_PRIME_COPRIME = prove (`!x p. int_prime(p) ==> p divides x \/ coprime(p,x)`, REPEAT STRIP_TAC THEN REWRITE_TAC[INT_COPRIME] THEN MATCH_MP_TAC(TAUT `(~b ==> a) ==> a \/ b`) THEN REWRITE_TAC[NOT_FORALL_THM; NOT_IMP; INT_DIVIDES_ONE_ABS] THEN DISCH_THEN(X_CHOOSE_THEN `d:int` STRIP_ASSUME_TAC) THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [int_prime]) THEN DISCH_THEN(MP_TAC o SPEC `d:int` o CONJUNCT2) THEN ASM_REWRITE_TAC[] THEN ASM_MESON_TAC[INT_DIVIDES_TRANS; INT_DIVIDES_LABS; INT_DIVIDES_RABS]);; let INT_PRIME_COPRIME_EQ = prove (`!p n. int_prime p ==> (coprime(p,n) <=> ~(p divides n))`, REPEAT STRIP_TAC THEN MATCH_MP_TAC(TAUT `(b \/ a) /\ ~(a /\ b) ==> (a <=> ~b)`) THEN ASM_SIMP_TAC[INT_PRIME_COPRIME; INT_COPRIME; INT_DIVIDES_ONE_ABS] THEN ASM_MESON_TAC[INT_DIVIDES_REFL; INT_PRIME_1; INT_PRIME_ABS]);; let INT_COPRIME_PRIMEPOW = prove (`!p k m. int_prime p /\ ~(k = 0) ==> (coprime(m,p pow k) <=> ~(p divides m))`, SIMP_TAC[INT_COPRIME_RPOW] THEN ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN SIMP_TAC[INT_PRIME_COPRIME_EQ]);; let INT_COPRIME_BEZOUT = prove (`!a b. coprime(a,b) <=> ?x y. a * x + b * y = &1`, INTEGER_TAC);; let INT_COPRIME_BEZOUT_ALT = prove (`!a b. coprime(a,b) ==> ?x y. a * x = b * y + &1`, INTEGER_TAC);; let INT_BEZOUT_PRIME = prove (`!a p. int_prime p /\ ~(p divides a) ==> ?x y. a * x = p * y + &1`, MESON_TAC[INT_COPRIME_BEZOUT_ALT; INT_COPRIME_SYM; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_DIVPROD = prove (`!p a b. int_prime(p) /\ p divides (a * b) ==> p divides a \/ p divides b`, ONCE_REWRITE_TAC[TAUT `a /\ b ==> c \/ d <=> a ==> (~c /\ ~d ==> ~b)`] THEN SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ] THEN INTEGER_TAC);; let INT_PRIME_DIVPROD_EQ = prove (`!p a b. int_prime(p) ==> (p divides (a * b) <=> p divides a \/ p divides b)`, MESON_TAC[INT_PRIME_DIVPROD; INT_DIVIDES_LMUL; INT_DIVIDES_RMUL]);; let INT_PRIME_DIVPOW = prove (`!n p x. int_prime(p) /\ p divides (x pow n) ==> p divides x`, REPEAT GEN_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 ASSUME_TAC MP_TAC) THEN ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ; INT_COPRIME_POW]);; let INT_PRIME_DIVPOW_N = prove (`!n p x. int_prime p /\ p divides (x pow n) ==> (p pow n) divides (x pow n)`, MESON_TAC[INT_PRIME_DIVPOW; INT_DIVIDES_POW]);; let INT_COPRIME_SOS = prove (`!x y. coprime(x,y) ==> coprime(x * y,x pow 2 + y pow 2)`, INTEGER_TAC);; let INT_PRIME_IMP_NZ = prove (`!p. int_prime p ==> ~(p = &0)`, GEN_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP INT_PRIME_GE_2) THEN INT_ARITH_TAC);; let INT_DISTINCT_PRIME_COPRIME = prove (`!p q. int_prime p /\ int_prime q /\ ~(abs p = abs q) ==> coprime(p,q)`, REWRITE_TAC[GSYM INT_DIVIDES_ANTISYM_ABS] THEN MESON_TAC[INT_COPRIME_SYM; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_COPRIME_LT = prove (`!x p. int_prime p /\ &0 < abs x /\ abs x < abs p ==> coprime(x,p)`, ONCE_REWRITE_TAC[INT_COPRIME_SYM] THEN SIMP_TAC[INT_PRIME_COPRIME_EQ] THEN REPEAT GEN_TAC THEN STRIP_TAC THEN DISCH_THEN(MP_TAC o MATCH_MP INT_DIVIDES_LE) THEN ASM_INT_ARITH_TAC);; let INT_DIVIDES_PRIME_PRIME = prove (`!p q. int_prime p /\ int_prime q ==> (p divides q <=> abs p = abs q)`, REPEAT STRIP_TAC THEN EQ_TAC THENL [ONCE_REWRITE_TAC[GSYM CONTRAPOS_THM] THEN ASM_SIMP_TAC[GSYM INT_PRIME_COPRIME_EQ; INT_DISTINCT_PRIME_COPRIME]; SIMP_TAC[GSYM INT_DIVIDES_ANTISYM_ABS]]);; let INT_COPRIME_POW_DIVPROD = prove (`!d a b. (d pow n) divides (a * b) /\ coprime(d,a) ==> (d pow n) divides b`, MESON_TAC[INT_COPRIME_DIVPROD; INT_COPRIME_POW; INT_COPRIME_SYM]);; let INT_PRIME_COPRIME_CASES = prove (`!p a b. int_prime p /\ coprime(a,b) ==> coprime(p,a) \/ coprime(p,b)`, MESON_TAC[INT_COPRIME_PRIME; INT_PRIME_COPRIME_EQ]);; let INT_PRIME_DIVPROD_POW = prove (`!n p a b. int_prime(p) /\ coprime(a,b) /\ (p pow n) divides (a * b) ==> (p pow n) divides a \/ (p pow n) divides b`, MESON_TAC[INT_COPRIME_POW_DIVPROD; INT_PRIME_COPRIME_CASES; INT_MUL_SYM]);; let INT_DIVIDES_POW2_REV = prove (`!n a b. (a pow n) divides (b pow n) /\ ~(n = 0) ==> a divides b`, REPEAT GEN_TAC THEN ASM_CASES_TAC `gcd(a,b) = &0` THENL [ASM_MESON_TAC[INT_GCD_EQ_0; INT_DIVIDES_REFL]; ALL_TAC] THEN MP_TAC(SPECL [`a:int`; `b:int`] INT_GCD_COPRIME_EXISTS) THEN STRIP_TAC THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC ASSUME_TAC) THEN ONCE_ASM_REWRITE_TAC[] THEN REWRITE_TAC[INT_POW_MUL] THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_DIVIDES_RMUL2_EQ] THEN DISCH_THEN(MP_TAC o MATCH_MP (INTEGER_RULE `a divides b ==> coprime(a,b) ==> a divides &1`)) THEN ASM_SIMP_TAC[INT_COPRIME_POW2] THEN ASM_MESON_TAC[INT_DIVIDES_POW2; INT_DIVIDES_TRANS; INT_DIVIDES_1]);; let INT_DIVIDES_POW2_EQ = prove (`!n a b. ~(n = 0) ==> ((a pow n) divides (b pow n) <=> a divides b)`, MESON_TAC[INT_DIVIDES_POW2_REV; INT_DIVIDES_POW]);; let INT_POW_MUL_EXISTS = prove (`!m n p k. ~(m = &0) /\ m pow k * n = p pow k ==> ?q. n = q pow k`, REPEAT GEN_TAC THEN ASM_CASES_TAC `k = 0` THEN ASM_SIMP_TAC[INT_POW; INT_MUL_LID] THEN STRIP_TAC THEN MP_TAC(SPECL [`k:num`; `m:int`; `p:int`] INT_DIVIDES_POW2_REV) THEN ASM_REWRITE_TAC[] THEN ANTS_TAC THENL [ASM_MESON_TAC[int_divides; INT_MUL_SYM]; ALL_TAC] THEN REWRITE_TAC[int_divides] THEN DISCH_THEN(CHOOSE_THEN SUBST_ALL_TAC) THEN FIRST_X_ASSUM(MP_TAC o SYM) THEN ASM_SIMP_TAC[INT_POW_MUL; INT_EQ_MUL_LCANCEL; INT_POW_EQ_0] THEN MESON_TAC[]);; let INT_COPRIME_POW_ABS = prove (`!n a b c. coprime(a,b) /\ a * b = c pow n ==> ?r s. abs a = r pow n /\ abs b = s pow n`, GEN_TAC THEN GEN_REWRITE_TAC BINDER_CONV [SWAP_FORALL_THM] THEN GEN_REWRITE_TAC I [SWAP_FORALL_THM] THEN ASM_CASES_TAC `n = 0` THENL [ASM_REWRITE_TAC[INT_POW] THEN MESON_TAC[INT_ABS_MUL_1; INT_ABS_NUM]; ALL_TAC] THEN MATCH_MP_TAC INT_PRIME_FACTOR_INDUCT THEN REPEAT CONJ_TAC THENL [REPEAT GEN_TAC THEN ASM_REWRITE_TAC[INT_POW_ZERO; INT_ENTIRE] THEN DISCH_THEN(CONJUNCTS_THEN2 MP_TAC DISJ_CASES_TAC) THEN ASM_SIMP_TAC[INT_COPRIME_0; INT_DIVIDES_ONE_ABS; INT_ABS_NUM] THEN ASM_MESON_TAC[INT_POW_ONE; INT_POW_ZERO]; REPEAT STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o AP_TERM `abs:int->int`) THEN SIMP_TAC[INT_POW_ONE; INT_ABS_NUM; INT_ABS_MUL_1] THEN MESON_TAC[INT_POW_ONE]; REPEAT STRIP_TAC THEN FIRST_X_ASSUM(MP_TAC o AP_TERM `abs:int->int`) THEN SIMP_TAC[INT_POW_ONE; INT_ABS_POW; INT_ABS_NEG; INT_ABS_NUM; INT_ABS_MUL_1] THEN MESON_TAC[INT_POW_ONE]; REWRITE_TAC[INT_POW_MUL] THEN REPEAT STRIP_TAC THEN SUBGOAL_THEN `p pow n divides a \/ p pow n divides b` MP_TAC THENL [ASM_MESON_TAC[INT_PRIME_DIVPROD_POW; int_divides]; ALL_TAC] THEN REWRITE_TAC[int_divides] THEN DISCH_THEN(DISJ_CASES_THEN(X_CHOOSE_THEN `d:int` SUBST_ALL_TAC)) THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [INT_COPRIME_SYM]) THEN ASM_SIMP_TAC[INT_COPRIME_RMUL; INT_COPRIME_LMUL; INT_COPRIME_LPOW; INT_COPRIME_RPOW] THEN STRIP_TAC THENL [FIRST_X_ASSUM(MP_TAC o SPECL [`b:int`; `d:int`]); FIRST_X_ASSUM(MP_TAC o SPECL [`d:int`; `a:int`])] THEN ASM_REWRITE_TAC[] THEN (ANTS_TAC THENL [MATCH_MP_TAC(INT_RING `!p. ~(p = &0) /\ a * p = b * p ==> a = b`) THEN EXISTS_TAC `p pow n` THEN ASM_SIMP_TAC[INT_POW_EQ_0; INT_PRIME_IMP_NZ] THEN FIRST_X_ASSUM(MP_TAC o SYM) THEN CONV_TAC INT_RING; STRIP_TAC THEN ASM_REWRITE_TAC[INT_ABS_POW; GSYM INT_POW_MUL; INT_ABS_MUL] THEN MESON_TAC[]])]);; let INT_COPRIME_POW_ODD = prove (`!n a b c. ODD n /\ coprime(a,b) /\ a * b = c pow n ==> ?r s. a = r pow n /\ b = s pow n`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`n:num`; `a:int`; `b:int`; `c:int`] INT_COPRIME_POW_ABS) THEN ASM_REWRITE_TAC[INT_ABS] THEN REWRITE_TAC[RIGHT_EXISTS_AND_THM; LEFT_EXISTS_AND_THM] THEN MATCH_MP_TAC MONO_AND THEN REWRITE_TAC[INT_ABS] THEN ASM_MESON_TAC[INT_POW_NEG; INT_NEG_NEG; NOT_ODD]);; let INT_DIVIDES_PRIME_POW_LE = prove (`!p q m n. int_prime p /\ int_prime q ==> ((p pow m) divides (q pow n) <=> m = 0 \/ abs p = abs q /\ m <= n)`, REPEAT STRIP_TAC THEN ASM_CASES_TAC `m = 0` THEN ASM_REWRITE_TAC[INT_POW; INT_DIVIDES_1] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_LABS] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_RABS] THEN REWRITE_TAC[INT_ABS_POW] THEN EQ_TAC THENL [DISCH_TAC THEN MATCH_MP_TAC(TAUT `a /\ (a ==> b) ==> a /\ b`); ALL_TAC] THEN ASM_MESON_TAC[INT_DIVIDES_POW_LE; INT_PRIME_GE_2; INT_PRIME_DIVPOW; INT_ABS_ABS; INT_PRIME_ABS; INT_DIVIDES_POW2; INT_DIVIDES_PRIME_PRIME]);; let INT_EQ_PRIME_POW_ABS = prove (`!p q m n. int_prime p /\ int_prime q ==> (abs p pow m = abs q pow n <=> m = 0 /\ n = 0 \/ abs p = abs q /\ m = n)`, REPEAT STRIP_TAC THEN REWRITE_TAC[GSYM INT_ABS_POW] THEN GEN_REWRITE_TAC LAND_CONV [GSYM INT_DIVIDES_ANTISYM_ABS] THEN ASM_SIMP_TAC[INT_DIVIDES_PRIME_POW_LE; INT_PRIME_ABS] THEN ASM_CASES_TAC `abs p = abs q` THEN ASM_REWRITE_TAC[] THEN ARITH_TAC);; let INT_EQ_PRIME_POW_POS = prove (`!p q m n. int_prime p /\ int_prime q /\ &0 <= p /\ &0 <= q ==> (p pow m = q pow n <=> m = 0 /\ n = 0 \/ p = q /\ m = n)`, REPEAT STRIP_TAC THEN MP_TAC(SPECL [`p:int`; `q:int`; `m:num`; `n:num`] INT_EQ_PRIME_POW_ABS) THEN ASM_SIMP_TAC[INT_ABS]);; let INT_DIVIDES_FACT_PRIME = prove (`!p. int_prime p ==> !n. p divides &(FACT n) <=> abs p <= &n`, GEN_TAC THEN DISCH_TAC THEN INDUCT_TAC THEN REWRITE_TAC[FACT] THENL [REWRITE_TAC[INT_ARITH `abs x <= &0 <=> x = &0`] THEN ASM_MESON_TAC[INT_DIVIDES_ONE; INT_PRIME_NEG; INT_PRIME_0; INT_PRIME_1]; ASM_SIMP_TAC[INT_PRIME_DIVPROD_EQ; GSYM INT_OF_NUM_MUL] THEN REWRITE_TAC[GSYM INT_OF_NUM_SUC] THEN ASM_MESON_TAC[INT_DIVIDES_LE; INT_ARITH `x <= n ==> x <= n + &1`; INT_DIVIDES_REFL; INT_DIVIDES_LABS; INT_ARITH `p <= n + &1 ==> p <= n \/ p = n + &1`; INT_ARITH `~(&n + &1 = &0)`; INT_ARITH `abs(&n + &1) = &n + &1`]]);;
6aced61b508d2e946b8ad3a5144d9ae23f683cc257ebc9f61b066d13ae8c79a9
jchavarri/rebind
estree_translator.ml
* * Copyright ( c ) 2013 - present , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " flow " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "flow" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) module Ast = Spider_monkey_ast module type Translator = sig type t val string: string -> t val bool: bool -> t val obj: (string * t) array -> t val array: t array -> t val number: float -> t val null: t val regexp: Loc.t -> string -> string -> t end module Translate (Impl : Translator) : (sig type t val program: Loc.t * Ast.Statement.t list * (Loc.t * Ast.Comment.t') list -> t val expression: Ast.Expression.t -> t val errors: (Loc.t * Parse_error.t) list -> t end with type t = Impl.t) = struct type t = Impl.t open Ast open Impl let array_of_list fn list = array (Array.of_list (List.map fn list)) let int x = number (float x) let option f = function | Some v -> f v | None -> null let position p = obj [| "line", int p.Loc.line; "column", int p.Loc.column; |] let loc location = let source = match Loc.source location with | Some Loc.LibFile src | Some Loc.SourceFile src | Some Loc.JsonFile src | Some Loc.ResourceFile src -> string src | Some Loc.Builtins -> string "(global)" | None -> null in obj [| "source", source; "start", position location.Loc.start; "end", position location.Loc._end; |] let range location = Loc.( array [| int location.start.offset; int location._end.offset; |] ) let node _type location props = obj (Array.append [| "type", string _type; "loc", loc location; "range", range location; |] props) let errors l = let error (location, e) = obj [| "loc", loc location; "message", string (Parse_error.PP.error e); |] in array_of_list error l let rec program (loc, statements, comments) = node "Program" loc [| "body", statement_list statements; "comments", comment_list comments; |] and statement_list statements = array_of_list statement statements and statement = Statement.(function | loc, Empty -> node "EmptyStatement" loc [||] | loc, Block b -> block (loc, b) | loc, Expression expr -> node "ExpressionStatement" loc [| "expression", expression expr.Expression.expression; |] | loc, If _if -> If.( node "IfStatement" loc [| "test", expression _if.test; "consequent", statement _if.consequent; "alternate", option statement _if.alternate; |] ) | loc, Labeled labeled -> Labeled.( node "LabeledStatement" loc [| "label", identifier labeled.label; "body", statement labeled.body; |] ) | loc, Break break -> node "BreakStatement" loc [| "label", option identifier break.Break.label; |] | loc, Continue continue -> node "ContinueStatement" loc [| "label", option identifier continue.Continue.label; |] | loc, With _with -> With.( node "WithStatement" loc [| "object", expression _with._object; "body", statement _with.body; |] ) | loc, TypeAlias alias -> type_alias (loc, alias) | loc, Switch switch -> Switch.( node "SwitchStatement" loc [| "discriminant", expression switch.discriminant; "cases", array_of_list case switch.cases; |] ) | loc, Return return -> node "ReturnStatement" loc [| "argument", option expression return.Return.argument; |] | loc, Throw throw -> node "ThrowStatement" loc [| "argument", expression throw.Throw.argument; |] | loc, Try _try -> Try.( node "TryStatement" loc [| "block", block _try.block; "handler", option catch _try.handler; "finalizer", option block _try.finalizer; |] ) | loc, While _while -> While.( node "WhileStatement" loc [| "test", expression _while.test; "body", statement _while.body; |] ) | loc, DoWhile dowhile -> DoWhile.( node "DoWhileStatement" loc [| "body", statement dowhile.body; "test", expression dowhile.test; |] ) | loc, For _for -> For.( let init = function | InitDeclaration init -> variable_declaration init | InitExpression expr -> expression expr in node "ForStatement" loc [| "init", option init _for.init; "test", option expression _for.test; "update", option expression _for.update; "body", statement _for.body; |] ) | loc, ForIn forin -> ForIn.( let left = (match forin.left with | LeftDeclaration left -> variable_declaration left | LeftExpression left -> expression left) in node "ForInStatement" loc [| "left", left; "right", expression forin.right; "body", statement forin.body; "each", bool forin.each; |] ) | loc, ForOf forof -> ForOf.( let type_ = if forof.async then "ForAwaitStatement" else "ForOfStatement" in let left = (match forof.left with | LeftDeclaration left -> variable_declaration left | LeftExpression left -> expression left) in node type_ loc [| "left", left; "right", expression forof.right; "body", statement forof.body; |] ) | loc, Debugger -> node "DebuggerStatement" loc [||] | loc, ClassDeclaration c -> class_declaration (loc, c) | loc, InterfaceDeclaration i -> interface_declaration (loc, i) | loc, VariableDeclaration var -> variable_declaration (loc, var) | loc, FunctionDeclaration fn -> function_declaration (loc, fn) | loc, DeclareVariable d -> declare_variable (loc, d) | loc, DeclareFunction d -> declare_function (loc, d) | loc, DeclareClass d -> declare_class (loc, d) | loc, DeclareModule m -> DeclareModule.( let id = match m.id with | Literal lit -> literal lit | Identifier id -> identifier id in node "DeclareModule" loc [| "id", id; "body", block m.body; "kind", ( match m.kind with | DeclareModule.CommonJS _ -> string "CommonJS" | DeclareModule.ES _ -> string "ES" ) |] ) | loc, DeclareExportDeclaration export -> DeclareExportDeclaration.( match export.specifiers with | Some (ExportNamedDeclaration.ExportBatchSpecifier (_, None)) -> node "DeclareExportAllDeclaration" loc [| "source", option literal export.source; |] | _ -> let declaration = match export.declaration with | Some (Variable v) -> declare_variable v | Some (Function f) -> declare_function f | Some (Class c) -> declare_class c | Some (DefaultType t) -> _type t | Some (NamedType t) -> type_alias t | Some (Interface i) -> interface_declaration i | None -> null in node "DeclareExportDeclaration" loc [| "default", bool export.default; "declaration", declaration; "specifiers", export_specifiers export.specifiers; "source", option literal export.source; |] ) | loc, DeclareModuleExports annot -> node "DeclareModuleExports" loc [| "typeAnnotation", type_annotation annot |] | loc, ExportNamedDeclaration export -> ExportNamedDeclaration.( match export.specifiers with | Some (ExportBatchSpecifier (_, None)) -> node "ExportAllDeclaration" loc [| "source", option literal export.source; "exportKind", string (export_kind export.exportKind); |] | _ -> node "ExportNamedDeclaration" loc [| "declaration", option statement export.declaration; "specifiers", export_specifiers export.specifiers; "source", option literal export.source; "exportKind", string (export_kind export.exportKind); |] ) | loc, ExportDefaultDeclaration export -> ExportDefaultDeclaration.( let declaration = match export.declaration with | Declaration stmt -> statement stmt | ExportDefaultDeclaration.Expression expr -> expression expr in node "ExportDefaultDeclaration" loc [| "declaration", declaration; "exportKind", string (export_kind export.exportKind); |] ) | loc, ImportDeclaration import -> ImportDeclaration.( let specifiers = import.specifiers |> List.map (function | ImportDefaultSpecifier id -> import_default_specifier id | ImportNamedSpecifier {local; remote;} -> import_named_specifier local remote | ImportNamespaceSpecifier id -> import_namespace_specifier id ) in let import_kind = match import.importKind with | ImportType -> "type" | ImportTypeof -> "typeof" | ImportValue -> "value" in node "ImportDeclaration" loc [| "specifiers", array (Array.of_list specifiers); "source", literal import.source; "importKind", string (import_kind); |] ) ) and expression = Expression.(function | loc, This -> node "ThisExpression" loc [||] | loc, Super -> node "Super" loc [||] | loc, Array arr -> node "ArrayExpression" loc [| "elements", array_of_list (option expression_or_spread) arr.Array.elements; |] | loc, Object _object -> node "ObjectExpression" loc [| "properties", array_of_list object_property _object.Object.properties; |] | loc, Function _function -> function_expression (loc, _function) | loc, ArrowFunction arrow -> Function.( let body = (match arrow.body with | BodyBlock b -> block b | BodyExpression expr -> expression expr) in node "ArrowFunctionExpression" loc [| "id", option identifier arrow.id; "params", function_params arrow.params; "body", body; "async", bool arrow.async; "generator", bool arrow.generator; "predicate", option predicate arrow.predicate; "expression", bool arrow.expression; "returnType", option type_annotation arrow.returnType; "typeParameters", option type_parameter_declaration arrow.typeParameters; |] ) | loc, Sequence sequence -> node "SequenceExpression" loc [| "expressions", array_of_list expression sequence.Sequence.expressions; |] | loc, Unary unary -> Unary.( match unary.operator with | Await -> await is defined as a separate expression in ast - types * * TODO * 1 ) Send a PR to ast - types * ( -types/issues/113 ) * 2 ) Output a UnaryExpression * 3 ) Modify the esprima test runner to compare and * our UnaryExpression * * * TODO * 1) Send a PR to ast-types * (-types/issues/113) * 2) Output a UnaryExpression * 3) Modify the esprima test runner to compare AwaitExpression and * our UnaryExpression * *) node "AwaitExpression" loc [| "argument", expression unary.argument; |] | _ -> begin let operator = match unary.operator with | Minus -> "-" | Plus -> "+" | Not -> "!" | BitNot -> "~" | Typeof -> "typeof" | Void -> "void" | Delete -> "delete" | Await -> failwith "matched above" in node "UnaryExpression" loc [| "operator", string operator; "prefix", bool unary.prefix; "argument", expression unary.argument; |] end ) | loc, Binary binary -> Binary.( let operator = match binary.operator with | Equal -> "==" | NotEqual -> "!=" | StrictEqual -> "===" | StrictNotEqual -> "!==" | LessThan -> "<" | LessThanEqual -> "<=" | GreaterThan -> ">" | GreaterThanEqual -> ">=" | LShift -> "<<" | RShift -> ">>" | RShift3 -> ">>>" | Plus -> "+" | Minus -> "-" | Mult -> "*" | Exp -> "**" | Div -> "/" | Mod -> "%" | BitOr -> "|" | Xor -> "^" | BitAnd -> "&" | In -> "in" | Instanceof -> "instanceof" in node "BinaryExpression" loc [| "operator", string operator; "left", expression binary.left; "right", expression binary.right; |] ) | loc, TypeCast typecast -> TypeCast.( node "TypeCastExpression" loc [| "expression", expression typecast.expression; "typeAnnotation", type_annotation typecast.typeAnnotation; |] ) | loc, Assignment assignment -> Assignment.( let operator = match assignment.operator with | Assign -> "=" | PlusAssign -> "+=" | MinusAssign -> "-=" | MultAssign -> "*=" | ExpAssign -> "**=" | DivAssign -> "/=" | ModAssign -> "%=" | LShiftAssign -> "<<=" | RShiftAssign -> ">>=" | RShift3Assign -> ">>>=" | BitOrAssign -> "|=" | BitXorAssign -> "^=" | BitAndAssign -> "&=" in node "AssignmentExpression" loc [| "operator", string operator; "left", pattern assignment.left; "right", expression assignment.right; |] ) | loc, Update update -> Update.( let operator = match update.operator with | Increment -> "++" | Decrement -> "--" in node "UpdateExpression" loc [| "operator", string operator; "argument", expression update.argument; "prefix", bool update.prefix; |] ) | loc, Logical logical -> Logical.( let operator = match logical.operator with | Or -> "||" | And -> "&&" in node "LogicalExpression" loc [| "operator", string operator; "left", expression logical.left; "right", expression logical.right; |] ) | loc, Conditional conditional -> Conditional.( node "ConditionalExpression" loc [| "test", expression conditional.test; "consequent", expression conditional.consequent; "alternate", expression conditional.alternate; |] ) | loc, New _new -> New.( node "NewExpression" loc [| "callee", expression _new.callee; "arguments", array_of_list expression_or_spread _new.arguments; |] ) | loc, Call call -> Call.( node "CallExpression" loc [| "callee", expression call.callee; "arguments", array_of_list expression_or_spread call.arguments; |] ) | loc, Member member -> Member.( let property = match member.property with | PropertyIdentifier id -> identifier id | PropertyExpression expr -> expression expr in node "MemberExpression" loc [| "object", expression member._object; "property", property; "computed", bool member.computed; |] ) | loc, Yield yield -> Yield.( node "YieldExpression" loc [| "argument", option expression yield.argument; "delegate", bool yield.delegate; |] ) | loc, Comprehension comp -> Comprehension.( node "ComprehensionExpression" loc [| "blocks", array_of_list comprehension_block comp.blocks; "filter", option expression comp.filter; |] ) | loc, Generator gen -> Generator.( node "GeneratorExpression" loc [| "blocks", array_of_list comprehension_block gen.blocks; "filter", option expression gen.filter; |] ) | _loc, Identifier id -> identifier id | loc, Literal lit -> literal (loc, lit) | loc, TemplateLiteral lit -> template_literal (loc, lit) | loc, TaggedTemplate tagged -> tagged_template (loc, tagged) | loc, Class c -> class_expression (loc, c) | loc, JSXElement element -> jsx_element (loc, element) | loc, MetaProperty meta_prop -> MetaProperty.( node "MetaProperty" loc [| "meta", identifier meta_prop.meta; "property", identifier meta_prop.property; |] )) and function_declaration (loc, fn) = Function.( let body = match fn.body with | BodyBlock b -> block b | BodyExpression b -> expression b in node "FunctionDeclaration" loc [| estree has n't come around to the idea that function decls can have optional ids , but acorn , babel , espree and esprima all have , so let 's do it too . see optional ids, but acorn, babel, espree and esprima all have, so let's do it too. see *) "id", option identifier fn.id; "params", function_params fn.params; "body", body; "async", bool fn.async; "generator", bool fn.generator; "predicate", option predicate fn.predicate; "expression", bool fn.expression; "returnType", option type_annotation fn.returnType; "typeParameters", option type_parameter_declaration fn.typeParameters; |] ) and function_expression (loc, _function) = Function.( let body = match _function.body with | BodyBlock b -> block b | BodyExpression expr -> expression expr in node "FunctionExpression" loc [| "id", option identifier _function.id; "params", function_params _function.params; "body", body; "async", bool _function.async; "generator", bool _function.generator; "predicate", option predicate _function.predicate; "expression", bool _function.expression; "returnType", option type_annotation _function.returnType; "typeParameters", option type_parameter_declaration _function.typeParameters; |] ) and identifier (loc, name) = node "Identifier" loc [| "name", string name; "typeAnnotation", null; "optional", bool false; |] and pattern_identifier loc { Pattern.Identifier.name; typeAnnotation; optional; } = node "Identifier" loc [| "name", string (snd name); "typeAnnotation", option type_annotation typeAnnotation; "optional", bool optional; |] and case (loc, c) = Statement.Switch.Case.( node "SwitchCase" loc [| "test", option expression c.test; "consequent", array_of_list statement c.consequent; |] ) and catch (loc, c) = Statement.Try.CatchClause.( node "CatchClause" loc [| "param", pattern c.param; "body", block c.body; |] ) and block (loc, b) = node "BlockStatement" loc [| "body", statement_list b.Statement.Block.body; |] and declare_variable (loc, d) = Statement.DeclareVariable.( let id_loc = Loc.btwn (fst d.id) (match d.typeAnnotation with | Some typeAnnotation -> fst typeAnnotation | None -> fst d.id) in node "DeclareVariable" loc [| "id", pattern_identifier id_loc { Pattern.Identifier.name = d.id; typeAnnotation = d.typeAnnotation; optional = false; }; |] ) and declare_function (loc, d) = Statement.DeclareFunction.( let id_loc = Loc.btwn (fst d.id) (fst d.typeAnnotation) in node "DeclareFunction" loc [| "id", pattern_identifier id_loc { Pattern.Identifier.name = d.id; typeAnnotation = Some d.typeAnnotation; optional = false; }; "predicate", option predicate d.predicate |] ) and declare_class (loc, d) = Statement.Interface.( node "DeclareClass" loc [| "id", identifier d.id; "typeParameters", option type_parameter_declaration d.typeParameters; "body", object_type d.body; "extends", array_of_list interface_extends d.extends; |] ) and export_kind = function | Statement.ExportType -> "type" | Statement.ExportValue -> "value" and export_specifiers = Statement.ExportNamedDeclaration.(function | Some (ExportSpecifiers specifiers) -> array_of_list export_specifier specifiers | Some (ExportBatchSpecifier (loc, Some name)) -> array [| node "ExportNamespaceSpecifier" loc [| "exported", identifier name |] |] | Some (ExportBatchSpecifier (_, None)) -> (* this should've been handled by callers, since this represents an ExportAllDeclaration, not a specifier. *) array [||] | None -> array [||] ) and type_alias (loc, alias) = Statement.TypeAlias.( node "TypeAlias" loc [| "id", identifier alias.id; "typeParameters", option type_parameter_declaration alias.typeParameters; "right", _type alias.right; |] ) and class_declaration (loc, c) = Class.( node "ClassDeclaration" loc [| estree has n't come around to the idea that class decls can have optional ids , but acorn , babel , espree and esprima all have , so let 's do it too . see optional ids, but acorn, babel, espree and esprima all have, so let's do it too. see *) "id", option identifier c.id; "body", class_body c.body; "superClass", option expression c.superClass; "typeParameters", option type_parameter_declaration c.typeParameters; "superTypeParameters", option type_parameter_instantiation c.superTypeParameters; "implements", array_of_list class_implements c.implements; "decorators", array_of_list expression c.classDecorators; |] ) and class_expression (loc, c) = Class.( node "ClassExpression" loc [| "id", option identifier c.id; "body", class_body c.body; "superClass", option expression c.superClass; "typeParameters", option type_parameter_declaration c.typeParameters; "superTypeParameters", option type_parameter_instantiation c.superTypeParameters; "implements", array_of_list class_implements c.implements; "decorators", array_of_list expression c.classDecorators; |] ) and class_implements (loc, implements) = Class.Implements.( node "ClassImplements" loc [| "id", identifier implements.id; "typeParameters", option type_parameter_instantiation implements.typeParameters; |] ) and class_body (loc, body) = Class.Body.( node "ClassBody" loc [| "body", array_of_list class_element body.body; |] ) and class_element = Class.Body.(function | Method m -> class_method m | Property p -> class_property p) and class_method (loc, method_) = let { Class.Method.key; value; kind; static; decorators; } = method_ in let key, computed = Expression.Object.Property.(match key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in let kind = Class.Method.(match kind with | Constructor -> "constructor" | Method -> "method" | Get -> "get" | Set -> "set") in node "MethodDefinition" loc [| "key", key; "value", function_expression value; "kind", string kind; "static", bool static; "computed", bool computed; "decorators", array_of_list expression decorators; |] and class_property (loc, prop) = Class.Property.( let key, computed = (match prop.key with | Expression.Object.Property.Literal lit -> literal lit, false | Expression.Object.Property.Identifier id -> identifier id, false | Expression.Object.Property.Computed expr -> expression expr, true) in node "ClassProperty" loc [| "key", key; "value", option expression prop.value; "typeAnnotation", option type_annotation prop.typeAnnotation; "computed", bool computed; "static", bool prop.static; "variance", option variance prop.variance; |] ) and interface_declaration (loc, i) = Statement.Interface.( node "InterfaceDeclaration" loc [| "id", identifier i.id; "typeParameters", option type_parameter_declaration i.typeParameters; "body", object_type i.body; "extends", array_of_list interface_extends i.extends; |] ) and interface_extends (loc, g) = Type.Generic.( let id = match g.id with | Identifier.Unqualified id -> identifier id | Identifier.Qualified q -> generic_type_qualified_identifier q in node "InterfaceExtends" loc [| "id", id; "typeParameters", option type_parameter_instantiation g.typeParameters; |] ) and pattern = Pattern.(function | loc, Object obj -> node "ObjectPattern" loc [| "properties", array_of_list object_pattern_property obj.Object.properties; "typeAnnotation", option type_annotation obj.Object.typeAnnotation; |] | loc, Array arr -> node "ArrayPattern" loc [| "elements", array_of_list (option array_pattern_element) arr.Array.elements; "typeAnnotation", option type_annotation arr.Array.typeAnnotation; |] | loc, Assignment { Assignment.left; right } -> node "AssignmentPattern" loc [| "left", pattern left; "right", expression right |] | loc, Identifier pattern_id -> pattern_identifier loc pattern_id | _loc, Expression expr -> expression expr) and function_params = function | params, Some (rest_loc, { Function.RestElement.argument }) -> let rest = node "RestElement" rest_loc [| "argument", pattern argument; |] in let rev_params = params |> List.map pattern |> List.rev in let params = List.rev (rest::rev_params) in array (Array.of_list params) | params, None -> array_of_list pattern params and array_pattern_element = Pattern.Array.(function | Element p -> pattern p | RestElement (loc, { RestElement.argument; }) -> node "RestElement" loc [| "argument", pattern argument; |] ) and object_property = Expression.Object.(function | Property (loc, prop) -> Property.( This is a slight deviation from the Mozilla spec . In the spec , an object * property is not a proper node , and lacks a location and a " type " field . * Esprima promotes it to a proper node and that is useful , so I 'm * following their example * property is not a proper node, and lacks a location and a "type" field. * Esprima promotes it to a proper node and that is useful, so I'm * following their example *) let key, computed = (match prop.key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in let kind = match prop.kind with | Init -> "init" | Get -> "get" | Set -> "set" in node "Property" loc [| "key", key; "value", expression prop.value; "kind", string kind; "method", bool prop._method; "shorthand", bool prop.shorthand; "computed", bool computed; |] ) | SpreadProperty(loc, prop) -> SpreadProperty.( node "SpreadProperty" loc [| "argument", expression prop.argument; |] )) and object_pattern_property = Pattern.Object.(function | Property (loc, prop) -> Property.( let key, computed = (match prop.key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in node "Property" loc [| "key", key; "value", pattern prop.pattern; "kind", string "init"; "method", bool false; "shorthand", bool prop.shorthand; "computed", bool computed; |] ) | RestProperty (loc, prop) -> RestProperty.( node "RestProperty" loc [| "argument", pattern prop.argument; |] ) ) and expression_or_spread = Expression.(function | Expression expr -> expression expr | Spread (loc, { SpreadElement.argument; }) -> node "SpreadElement" loc [| "argument", expression argument; |] ) and comprehension_block (loc, b) = Expression.Comprehension.Block.( node "ComprehensionBlock" loc [| "left", pattern b.left; "right", expression b.right; "each", bool b.each; |] ) and literal (loc, lit) = Literal.( let { value; raw; } = lit in let value_ = match value with | String str -> string str | Boolean b -> bool b | Null -> null | Number f -> number f | RegExp { RegExp.pattern; flags; } -> regexp loc pattern flags in let props = match value with | RegExp { RegExp.pattern; flags; } -> let regex = obj [| "pattern", string pattern; "flags", string flags; |] in [| "value", value_; "raw", string raw; "regex", regex |] | _ -> [| "value", value_; "raw", string raw; |] in node "Literal" loc props ) and template_literal (loc, value) = Expression.TemplateLiteral.( node "TemplateLiteral" loc [| "quasis", array_of_list template_element value.quasis; "expressions", array_of_list expression value.expressions; |] ) and template_element (loc, element) = Expression.TemplateLiteral.Element.( let value = obj [| "raw", string element.value.raw; "cooked", string element.value.cooked; |] in node "TemplateElement" loc [| "value", value; "tail", bool element.tail; |] ) and tagged_template (loc, tagged) = Expression.TaggedTemplate.( node "TaggedTemplateExpression" loc [| "tag", expression tagged.tag; "quasi", template_literal tagged.quasi; |] ) and variable_declaration (loc, var) = Statement.VariableDeclaration.( let kind = match var.kind with | Var -> "var" | Let -> "let" | Const -> "const" in node "VariableDeclaration" loc [| "declarations", array_of_list variable_declarator var.declarations; "kind", string kind; |] ) and variable_declarator (loc, declarator) = Statement.VariableDeclaration.Declarator.( node "VariableDeclarator" loc [| "id", pattern declarator.id; "init", option expression declarator.init; |] ) and variance (_, sigil) = Variance.( match sigil with | Plus -> string "plus" | Minus -> string "minus" ) and _type (loc, t) = Type.( match t with | Any -> any_type loc | Mixed -> mixed_type loc | Empty -> empty_type loc | Void -> void_type loc | Null -> null_type loc | Number -> number_type loc | String -> string_type loc | Boolean -> boolean_type loc | Nullable t -> nullable_type loc t | Function fn -> function_type (loc, fn) | Object o -> object_type (loc, o) | Array t -> array_type loc t | Generic g -> generic_type (loc, g) | Union (t0, t1, ts) -> union_type (loc, t0::t1::ts) | Intersection (t0, t1, ts) -> intersection_type (loc, t0::t1::ts) | Typeof t -> typeof_type (loc, t) | Tuple t -> tuple_type (loc, t) | StringLiteral s -> string_literal_type (loc, s) | NumberLiteral n -> number_literal_type (loc, n) | BooleanLiteral b -> boolean_literal_type (loc, b) | Exists -> exists_type loc ) and any_type loc = node "AnyTypeAnnotation" loc [||] and mixed_type loc = node "MixedTypeAnnotation" loc [||] and empty_type loc = node "EmptyTypeAnnotation" loc [||] and void_type loc = node "VoidTypeAnnotation" loc [||] and null_type loc = node "NullLiteralTypeAnnotation" loc [||] and number_type loc = node "NumberTypeAnnotation" loc [||] and string_type loc = node "StringTypeAnnotation" loc [||] and boolean_type loc = node "BooleanTypeAnnotation" loc [||] and nullable_type loc t = node "NullableTypeAnnotation" loc [| "typeAnnotation", _type t; |] and function_type (loc, fn) = Type.Function.( let params, rest = fn.params in node "FunctionTypeAnnotation" loc [| "params", array_of_list function_type_param params; "returnType", _type fn.returnType; "rest", option function_type_rest rest; "typeParameters", option type_parameter_declaration fn.typeParameters; |] ) and function_type_param (loc, param) = Type.Function.Param.( node "FunctionTypeParam" loc [| "name", option identifier param.name; "typeAnnotation", _type param.typeAnnotation; "optional", bool param.optional; |] ) and function_type_rest (_loc, { Type.Function.RestParam.argument }) = TODO : add a node for the rest param itself , including the ` ... ` , like we do with on normal functions . This should be coordinated with Babel , ast - types , etc . so keeping the status quo for now . Here 's an example : like we do with RestElement on normal functions. This should be coordinated with Babel, ast-types, etc. so keeping the status quo for now. Here's an example: *) (* node "FunctionTypeRestParam" loc [| "argument", function_type_param argument; |] *) function_type_param argument and object_type (loc, o) = Type.Object.( node "ObjectTypeAnnotation" loc [| "exact", bool o.exact; "properties", array_of_list object_type_property o.properties; "indexers", array_of_list object_type_indexer o.indexers; "callProperties", array_of_list object_type_call_property o.callProperties; |] ) and object_type_property (loc, prop) = Type.Object.Property.( let key = match prop.key with | Expression.Object.Property.Literal lit -> literal lit | Expression.Object.Property.Identifier id -> identifier id | Expression.Object.Property.Computed _ -> failwith "There should not be computed object type property keys" in node "ObjectTypeProperty" loc [| "key", key; "value", _type prop.value; "optional", bool prop.optional; "static", bool prop.static; "variance", option variance prop.variance; |] ) and object_type_indexer (loc, indexer) = Type.Object.Indexer.( node "ObjectTypeIndexer" loc [| "id", option identifier indexer.id; "key", _type indexer.key; "value", _type indexer.value; "static", bool indexer.static; "variance", option variance indexer.variance; |] ) and object_type_call_property (loc, callProperty) = Type.Object.CallProperty.( node "ObjectTypeCallProperty" loc [| "value", function_type callProperty.value; "static", bool callProperty.static; |] ) and array_type loc t = node "ArrayTypeAnnotation" loc [| "elementType", (_type t); |] and generic_type_qualified_identifier (loc, q) = Type.Generic.Identifier.( let qualification = match q.qualification with | Unqualified id -> identifier id | Qualified q -> generic_type_qualified_identifier q in node "QualifiedTypeIdentifier" loc [| "qualification", qualification; "id", identifier q.id; |] ) and generic_type (loc, g) = Type.Generic.( let id = match g.id with | Identifier.Unqualified id -> identifier id | Identifier.Qualified q -> generic_type_qualified_identifier q in node "GenericTypeAnnotation" loc [| "id", id; "typeParameters", option type_parameter_instantiation g.typeParameters; |] ) and union_type (loc, ts) = node "UnionTypeAnnotation" loc [| "types", array_of_list _type ts; |] and intersection_type (loc, ts) = node "IntersectionTypeAnnotation" loc [| "types", array_of_list _type ts; |] and typeof_type (loc, t) = node "TypeofTypeAnnotation" loc [| "argument", _type t; |] and tuple_type (loc, tl) = node "TupleTypeAnnotation" loc [| "types", array_of_list _type tl; |] and string_literal_type (loc, s) = Type.StringLiteral.( node "StringLiteralTypeAnnotation" loc [| "value", string s.value; "raw", string s.raw; |] ) and number_literal_type (loc, s) = Type.NumberLiteral.( node "NumberLiteralTypeAnnotation" loc [| "value", number s.value; "raw", string s.raw; |] ) and boolean_literal_type (loc, s) = Type.BooleanLiteral.( node "BooleanLiteralTypeAnnotation" loc [| "value", bool s.value; "raw", string s.raw; |] ) and exists_type loc = node "ExistsTypeAnnotation" loc [||] and type_annotation (loc, ty) = node "TypeAnnotation" loc [| "typeAnnotation", _type ty; |] and type_parameter_declaration (loc, params) = Type.ParameterDeclaration.( node "TypeParameterDeclaration" loc [| "params", array_of_list type_param params.params; |] ) and type_param (loc, tp) = Type.ParameterDeclaration.TypeParam.( node "TypeParameter" loc [| "name", string tp.name; "bound", option type_annotation tp.bound; "variance", option variance tp.variance; "default", option _type tp.default; |] ) and type_parameter_instantiation (loc, params) = Type.ParameterInstantiation.( node "TypeParameterInstantiation" loc [| "params", array_of_list _type params.params; |] ) and jsx_element (loc, (element: JSX.element)) = JSX.( node "JSXElement" loc [| "openingElement", jsx_opening element.openingElement; "closingElement", option jsx_closing element.closingElement; "children", array_of_list jsx_child element.children; |] ) and jsx_opening (loc, opening) = JSX.Opening.( node "JSXOpeningElement" loc [| "name", jsx_name opening.name; "attributes", array_of_list jsx_opening_attribute opening.attributes; "selfClosing", bool opening.selfClosing; |] ) and jsx_opening_attribute = JSX.Opening.(function | Attribute attribute -> jsx_attribute attribute | SpreadAttribute attribute -> jsx_spread_attribute attribute ) and jsx_closing (loc, closing) = JSX.Closing.( node "JSXClosingElement" loc [| "name", jsx_name closing.name; |] ) and jsx_child = JSX.(function | loc, Element element -> jsx_element (loc, element) | loc, ExpressionContainer expr -> jsx_expression_container (loc, expr) | loc, Text str -> jsx_text (loc, str) ) and jsx_name = JSX.(function | Identifier id -> jsx_identifier id | NamespacedName namespaced_name -> jsx_namespaced_name namespaced_name | MemberExpression member -> jsx_member_expression member ) and jsx_attribute (loc, attribute) = JSX.Attribute.( let name = match attribute.name with | Identifier id -> jsx_identifier id | NamespacedName namespaced_name -> jsx_namespaced_name namespaced_name in node "JSXAttribute" loc [| "name", name; "value", option jsx_attribute_value attribute.value; |] ) and jsx_attribute_value = JSX.Attribute.(function | Literal (loc, value) -> literal (loc, value) | ExpressionContainer (loc, expr) -> jsx_expression_container (loc, expr) ) and jsx_spread_attribute (loc, attribute) = JSX.SpreadAttribute.( node "JSXSpreadAttribute" loc [| "argument", expression attribute.argument; |] ) and jsx_expression_container (loc, expr) = JSX.ExpressionContainer.( let expression = match expr.expression with | Expression expr -> expression expr | EmptyExpression empty_loc -> node "JSXEmptyExpression" empty_loc [||] in node "JSXExpressionContainer" loc [| "expression", expression; |] ) and jsx_text (loc, text) = JSX.Text.( let { value; raw; } = text in node "JSXText" loc [| "value", string value; "raw", string raw; |] ) and jsx_member_expression (loc, member_expression) = JSX.MemberExpression.( let _object = match member_expression._object with | Identifier id -> jsx_identifier id | MemberExpression member -> jsx_member_expression member in node "JSXMemberExpression" loc [| "object", _object; "property", jsx_identifier member_expression.property; |] ) and jsx_namespaced_name (loc, namespaced_name) = JSX.NamespacedName.( node "JSXNamespacedName" loc [| "namespace", jsx_identifier namespaced_name.namespace; "name", jsx_identifier namespaced_name.name; |] ) and jsx_identifier (loc, id) = JSX.Identifier.( node "JSXIdentifier" loc [| "name", string id.name; |] ) and export_specifier (loc, specifier) = let open Statement.ExportNamedDeclaration.ExportSpecifier in let exported = match specifier.exported with | Some exported -> identifier exported | None -> identifier specifier.local in node "ExportSpecifier" loc [| "local", identifier specifier.local; "exported", exported; |] and import_default_specifier id = node "ImportDefaultSpecifier" (fst id) [| "local", identifier id; |] and import_namespace_specifier (loc, id) = node "ImportNamespaceSpecifier" loc [| "local", identifier id; |] and import_named_specifier local_id remote_id = let span_loc = match local_id with | Some local_id -> Loc.btwn (fst remote_id) (fst local_id) | None -> fst remote_id in let local_id = match local_id with | Some id -> id | None -> remote_id in node "ImportSpecifier" span_loc [| "imported", identifier remote_id; "local", identifier local_id; |] and comment_list comments = array_of_list comment comments and comment (loc, c) = Comment.( let _type, value = match c with | Line s -> "Line", s | Block s -> "Block", s in node _type loc [| "value", string value; |] ) and predicate (loc, p) = Ast.Type.Predicate.( let _type, value = match p with | Declared e -> "DeclaredPredicate", [|"value", expression e|] | Inferred -> "InferredPredicate", [||] in node _type loc value ) end
null
https://raw.githubusercontent.com/jchavarri/rebind/ccfa1725ff5b16574daf4d0044c49dbf719aa105/vendor/flow/estree_translator.ml
ocaml
this should've been handled by callers, since this represents an ExportAllDeclaration, not a specifier. node "FunctionTypeRestParam" loc [| "argument", function_type_param argument; |]
* * Copyright ( c ) 2013 - present , Facebook , Inc. * All rights reserved . * * This source code is licensed under the BSD - style license found in the * LICENSE file in the " flow " directory of this source tree . An additional grant * of patent rights can be found in the PATENTS file in the same directory . * * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the "flow" directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * *) module Ast = Spider_monkey_ast module type Translator = sig type t val string: string -> t val bool: bool -> t val obj: (string * t) array -> t val array: t array -> t val number: float -> t val null: t val regexp: Loc.t -> string -> string -> t end module Translate (Impl : Translator) : (sig type t val program: Loc.t * Ast.Statement.t list * (Loc.t * Ast.Comment.t') list -> t val expression: Ast.Expression.t -> t val errors: (Loc.t * Parse_error.t) list -> t end with type t = Impl.t) = struct type t = Impl.t open Ast open Impl let array_of_list fn list = array (Array.of_list (List.map fn list)) let int x = number (float x) let option f = function | Some v -> f v | None -> null let position p = obj [| "line", int p.Loc.line; "column", int p.Loc.column; |] let loc location = let source = match Loc.source location with | Some Loc.LibFile src | Some Loc.SourceFile src | Some Loc.JsonFile src | Some Loc.ResourceFile src -> string src | Some Loc.Builtins -> string "(global)" | None -> null in obj [| "source", source; "start", position location.Loc.start; "end", position location.Loc._end; |] let range location = Loc.( array [| int location.start.offset; int location._end.offset; |] ) let node _type location props = obj (Array.append [| "type", string _type; "loc", loc location; "range", range location; |] props) let errors l = let error (location, e) = obj [| "loc", loc location; "message", string (Parse_error.PP.error e); |] in array_of_list error l let rec program (loc, statements, comments) = node "Program" loc [| "body", statement_list statements; "comments", comment_list comments; |] and statement_list statements = array_of_list statement statements and statement = Statement.(function | loc, Empty -> node "EmptyStatement" loc [||] | loc, Block b -> block (loc, b) | loc, Expression expr -> node "ExpressionStatement" loc [| "expression", expression expr.Expression.expression; |] | loc, If _if -> If.( node "IfStatement" loc [| "test", expression _if.test; "consequent", statement _if.consequent; "alternate", option statement _if.alternate; |] ) | loc, Labeled labeled -> Labeled.( node "LabeledStatement" loc [| "label", identifier labeled.label; "body", statement labeled.body; |] ) | loc, Break break -> node "BreakStatement" loc [| "label", option identifier break.Break.label; |] | loc, Continue continue -> node "ContinueStatement" loc [| "label", option identifier continue.Continue.label; |] | loc, With _with -> With.( node "WithStatement" loc [| "object", expression _with._object; "body", statement _with.body; |] ) | loc, TypeAlias alias -> type_alias (loc, alias) | loc, Switch switch -> Switch.( node "SwitchStatement" loc [| "discriminant", expression switch.discriminant; "cases", array_of_list case switch.cases; |] ) | loc, Return return -> node "ReturnStatement" loc [| "argument", option expression return.Return.argument; |] | loc, Throw throw -> node "ThrowStatement" loc [| "argument", expression throw.Throw.argument; |] | loc, Try _try -> Try.( node "TryStatement" loc [| "block", block _try.block; "handler", option catch _try.handler; "finalizer", option block _try.finalizer; |] ) | loc, While _while -> While.( node "WhileStatement" loc [| "test", expression _while.test; "body", statement _while.body; |] ) | loc, DoWhile dowhile -> DoWhile.( node "DoWhileStatement" loc [| "body", statement dowhile.body; "test", expression dowhile.test; |] ) | loc, For _for -> For.( let init = function | InitDeclaration init -> variable_declaration init | InitExpression expr -> expression expr in node "ForStatement" loc [| "init", option init _for.init; "test", option expression _for.test; "update", option expression _for.update; "body", statement _for.body; |] ) | loc, ForIn forin -> ForIn.( let left = (match forin.left with | LeftDeclaration left -> variable_declaration left | LeftExpression left -> expression left) in node "ForInStatement" loc [| "left", left; "right", expression forin.right; "body", statement forin.body; "each", bool forin.each; |] ) | loc, ForOf forof -> ForOf.( let type_ = if forof.async then "ForAwaitStatement" else "ForOfStatement" in let left = (match forof.left with | LeftDeclaration left -> variable_declaration left | LeftExpression left -> expression left) in node type_ loc [| "left", left; "right", expression forof.right; "body", statement forof.body; |] ) | loc, Debugger -> node "DebuggerStatement" loc [||] | loc, ClassDeclaration c -> class_declaration (loc, c) | loc, InterfaceDeclaration i -> interface_declaration (loc, i) | loc, VariableDeclaration var -> variable_declaration (loc, var) | loc, FunctionDeclaration fn -> function_declaration (loc, fn) | loc, DeclareVariable d -> declare_variable (loc, d) | loc, DeclareFunction d -> declare_function (loc, d) | loc, DeclareClass d -> declare_class (loc, d) | loc, DeclareModule m -> DeclareModule.( let id = match m.id with | Literal lit -> literal lit | Identifier id -> identifier id in node "DeclareModule" loc [| "id", id; "body", block m.body; "kind", ( match m.kind with | DeclareModule.CommonJS _ -> string "CommonJS" | DeclareModule.ES _ -> string "ES" ) |] ) | loc, DeclareExportDeclaration export -> DeclareExportDeclaration.( match export.specifiers with | Some (ExportNamedDeclaration.ExportBatchSpecifier (_, None)) -> node "DeclareExportAllDeclaration" loc [| "source", option literal export.source; |] | _ -> let declaration = match export.declaration with | Some (Variable v) -> declare_variable v | Some (Function f) -> declare_function f | Some (Class c) -> declare_class c | Some (DefaultType t) -> _type t | Some (NamedType t) -> type_alias t | Some (Interface i) -> interface_declaration i | None -> null in node "DeclareExportDeclaration" loc [| "default", bool export.default; "declaration", declaration; "specifiers", export_specifiers export.specifiers; "source", option literal export.source; |] ) | loc, DeclareModuleExports annot -> node "DeclareModuleExports" loc [| "typeAnnotation", type_annotation annot |] | loc, ExportNamedDeclaration export -> ExportNamedDeclaration.( match export.specifiers with | Some (ExportBatchSpecifier (_, None)) -> node "ExportAllDeclaration" loc [| "source", option literal export.source; "exportKind", string (export_kind export.exportKind); |] | _ -> node "ExportNamedDeclaration" loc [| "declaration", option statement export.declaration; "specifiers", export_specifiers export.specifiers; "source", option literal export.source; "exportKind", string (export_kind export.exportKind); |] ) | loc, ExportDefaultDeclaration export -> ExportDefaultDeclaration.( let declaration = match export.declaration with | Declaration stmt -> statement stmt | ExportDefaultDeclaration.Expression expr -> expression expr in node "ExportDefaultDeclaration" loc [| "declaration", declaration; "exportKind", string (export_kind export.exportKind); |] ) | loc, ImportDeclaration import -> ImportDeclaration.( let specifiers = import.specifiers |> List.map (function | ImportDefaultSpecifier id -> import_default_specifier id | ImportNamedSpecifier {local; remote;} -> import_named_specifier local remote | ImportNamespaceSpecifier id -> import_namespace_specifier id ) in let import_kind = match import.importKind with | ImportType -> "type" | ImportTypeof -> "typeof" | ImportValue -> "value" in node "ImportDeclaration" loc [| "specifiers", array (Array.of_list specifiers); "source", literal import.source; "importKind", string (import_kind); |] ) ) and expression = Expression.(function | loc, This -> node "ThisExpression" loc [||] | loc, Super -> node "Super" loc [||] | loc, Array arr -> node "ArrayExpression" loc [| "elements", array_of_list (option expression_or_spread) arr.Array.elements; |] | loc, Object _object -> node "ObjectExpression" loc [| "properties", array_of_list object_property _object.Object.properties; |] | loc, Function _function -> function_expression (loc, _function) | loc, ArrowFunction arrow -> Function.( let body = (match arrow.body with | BodyBlock b -> block b | BodyExpression expr -> expression expr) in node "ArrowFunctionExpression" loc [| "id", option identifier arrow.id; "params", function_params arrow.params; "body", body; "async", bool arrow.async; "generator", bool arrow.generator; "predicate", option predicate arrow.predicate; "expression", bool arrow.expression; "returnType", option type_annotation arrow.returnType; "typeParameters", option type_parameter_declaration arrow.typeParameters; |] ) | loc, Sequence sequence -> node "SequenceExpression" loc [| "expressions", array_of_list expression sequence.Sequence.expressions; |] | loc, Unary unary -> Unary.( match unary.operator with | Await -> await is defined as a separate expression in ast - types * * TODO * 1 ) Send a PR to ast - types * ( -types/issues/113 ) * 2 ) Output a UnaryExpression * 3 ) Modify the esprima test runner to compare and * our UnaryExpression * * * TODO * 1) Send a PR to ast-types * (-types/issues/113) * 2) Output a UnaryExpression * 3) Modify the esprima test runner to compare AwaitExpression and * our UnaryExpression * *) node "AwaitExpression" loc [| "argument", expression unary.argument; |] | _ -> begin let operator = match unary.operator with | Minus -> "-" | Plus -> "+" | Not -> "!" | BitNot -> "~" | Typeof -> "typeof" | Void -> "void" | Delete -> "delete" | Await -> failwith "matched above" in node "UnaryExpression" loc [| "operator", string operator; "prefix", bool unary.prefix; "argument", expression unary.argument; |] end ) | loc, Binary binary -> Binary.( let operator = match binary.operator with | Equal -> "==" | NotEqual -> "!=" | StrictEqual -> "===" | StrictNotEqual -> "!==" | LessThan -> "<" | LessThanEqual -> "<=" | GreaterThan -> ">" | GreaterThanEqual -> ">=" | LShift -> "<<" | RShift -> ">>" | RShift3 -> ">>>" | Plus -> "+" | Minus -> "-" | Mult -> "*" | Exp -> "**" | Div -> "/" | Mod -> "%" | BitOr -> "|" | Xor -> "^" | BitAnd -> "&" | In -> "in" | Instanceof -> "instanceof" in node "BinaryExpression" loc [| "operator", string operator; "left", expression binary.left; "right", expression binary.right; |] ) | loc, TypeCast typecast -> TypeCast.( node "TypeCastExpression" loc [| "expression", expression typecast.expression; "typeAnnotation", type_annotation typecast.typeAnnotation; |] ) | loc, Assignment assignment -> Assignment.( let operator = match assignment.operator with | Assign -> "=" | PlusAssign -> "+=" | MinusAssign -> "-=" | MultAssign -> "*=" | ExpAssign -> "**=" | DivAssign -> "/=" | ModAssign -> "%=" | LShiftAssign -> "<<=" | RShiftAssign -> ">>=" | RShift3Assign -> ">>>=" | BitOrAssign -> "|=" | BitXorAssign -> "^=" | BitAndAssign -> "&=" in node "AssignmentExpression" loc [| "operator", string operator; "left", pattern assignment.left; "right", expression assignment.right; |] ) | loc, Update update -> Update.( let operator = match update.operator with | Increment -> "++" | Decrement -> "--" in node "UpdateExpression" loc [| "operator", string operator; "argument", expression update.argument; "prefix", bool update.prefix; |] ) | loc, Logical logical -> Logical.( let operator = match logical.operator with | Or -> "||" | And -> "&&" in node "LogicalExpression" loc [| "operator", string operator; "left", expression logical.left; "right", expression logical.right; |] ) | loc, Conditional conditional -> Conditional.( node "ConditionalExpression" loc [| "test", expression conditional.test; "consequent", expression conditional.consequent; "alternate", expression conditional.alternate; |] ) | loc, New _new -> New.( node "NewExpression" loc [| "callee", expression _new.callee; "arguments", array_of_list expression_or_spread _new.arguments; |] ) | loc, Call call -> Call.( node "CallExpression" loc [| "callee", expression call.callee; "arguments", array_of_list expression_or_spread call.arguments; |] ) | loc, Member member -> Member.( let property = match member.property with | PropertyIdentifier id -> identifier id | PropertyExpression expr -> expression expr in node "MemberExpression" loc [| "object", expression member._object; "property", property; "computed", bool member.computed; |] ) | loc, Yield yield -> Yield.( node "YieldExpression" loc [| "argument", option expression yield.argument; "delegate", bool yield.delegate; |] ) | loc, Comprehension comp -> Comprehension.( node "ComprehensionExpression" loc [| "blocks", array_of_list comprehension_block comp.blocks; "filter", option expression comp.filter; |] ) | loc, Generator gen -> Generator.( node "GeneratorExpression" loc [| "blocks", array_of_list comprehension_block gen.blocks; "filter", option expression gen.filter; |] ) | _loc, Identifier id -> identifier id | loc, Literal lit -> literal (loc, lit) | loc, TemplateLiteral lit -> template_literal (loc, lit) | loc, TaggedTemplate tagged -> tagged_template (loc, tagged) | loc, Class c -> class_expression (loc, c) | loc, JSXElement element -> jsx_element (loc, element) | loc, MetaProperty meta_prop -> MetaProperty.( node "MetaProperty" loc [| "meta", identifier meta_prop.meta; "property", identifier meta_prop.property; |] )) and function_declaration (loc, fn) = Function.( let body = match fn.body with | BodyBlock b -> block b | BodyExpression b -> expression b in node "FunctionDeclaration" loc [| estree has n't come around to the idea that function decls can have optional ids , but acorn , babel , espree and esprima all have , so let 's do it too . see optional ids, but acorn, babel, espree and esprima all have, so let's do it too. see *) "id", option identifier fn.id; "params", function_params fn.params; "body", body; "async", bool fn.async; "generator", bool fn.generator; "predicate", option predicate fn.predicate; "expression", bool fn.expression; "returnType", option type_annotation fn.returnType; "typeParameters", option type_parameter_declaration fn.typeParameters; |] ) and function_expression (loc, _function) = Function.( let body = match _function.body with | BodyBlock b -> block b | BodyExpression expr -> expression expr in node "FunctionExpression" loc [| "id", option identifier _function.id; "params", function_params _function.params; "body", body; "async", bool _function.async; "generator", bool _function.generator; "predicate", option predicate _function.predicate; "expression", bool _function.expression; "returnType", option type_annotation _function.returnType; "typeParameters", option type_parameter_declaration _function.typeParameters; |] ) and identifier (loc, name) = node "Identifier" loc [| "name", string name; "typeAnnotation", null; "optional", bool false; |] and pattern_identifier loc { Pattern.Identifier.name; typeAnnotation; optional; } = node "Identifier" loc [| "name", string (snd name); "typeAnnotation", option type_annotation typeAnnotation; "optional", bool optional; |] and case (loc, c) = Statement.Switch.Case.( node "SwitchCase" loc [| "test", option expression c.test; "consequent", array_of_list statement c.consequent; |] ) and catch (loc, c) = Statement.Try.CatchClause.( node "CatchClause" loc [| "param", pattern c.param; "body", block c.body; |] ) and block (loc, b) = node "BlockStatement" loc [| "body", statement_list b.Statement.Block.body; |] and declare_variable (loc, d) = Statement.DeclareVariable.( let id_loc = Loc.btwn (fst d.id) (match d.typeAnnotation with | Some typeAnnotation -> fst typeAnnotation | None -> fst d.id) in node "DeclareVariable" loc [| "id", pattern_identifier id_loc { Pattern.Identifier.name = d.id; typeAnnotation = d.typeAnnotation; optional = false; }; |] ) and declare_function (loc, d) = Statement.DeclareFunction.( let id_loc = Loc.btwn (fst d.id) (fst d.typeAnnotation) in node "DeclareFunction" loc [| "id", pattern_identifier id_loc { Pattern.Identifier.name = d.id; typeAnnotation = Some d.typeAnnotation; optional = false; }; "predicate", option predicate d.predicate |] ) and declare_class (loc, d) = Statement.Interface.( node "DeclareClass" loc [| "id", identifier d.id; "typeParameters", option type_parameter_declaration d.typeParameters; "body", object_type d.body; "extends", array_of_list interface_extends d.extends; |] ) and export_kind = function | Statement.ExportType -> "type" | Statement.ExportValue -> "value" and export_specifiers = Statement.ExportNamedDeclaration.(function | Some (ExportSpecifiers specifiers) -> array_of_list export_specifier specifiers | Some (ExportBatchSpecifier (loc, Some name)) -> array [| node "ExportNamespaceSpecifier" loc [| "exported", identifier name |] |] | Some (ExportBatchSpecifier (_, None)) -> array [||] | None -> array [||] ) and type_alias (loc, alias) = Statement.TypeAlias.( node "TypeAlias" loc [| "id", identifier alias.id; "typeParameters", option type_parameter_declaration alias.typeParameters; "right", _type alias.right; |] ) and class_declaration (loc, c) = Class.( node "ClassDeclaration" loc [| estree has n't come around to the idea that class decls can have optional ids , but acorn , babel , espree and esprima all have , so let 's do it too . see optional ids, but acorn, babel, espree and esprima all have, so let's do it too. see *) "id", option identifier c.id; "body", class_body c.body; "superClass", option expression c.superClass; "typeParameters", option type_parameter_declaration c.typeParameters; "superTypeParameters", option type_parameter_instantiation c.superTypeParameters; "implements", array_of_list class_implements c.implements; "decorators", array_of_list expression c.classDecorators; |] ) and class_expression (loc, c) = Class.( node "ClassExpression" loc [| "id", option identifier c.id; "body", class_body c.body; "superClass", option expression c.superClass; "typeParameters", option type_parameter_declaration c.typeParameters; "superTypeParameters", option type_parameter_instantiation c.superTypeParameters; "implements", array_of_list class_implements c.implements; "decorators", array_of_list expression c.classDecorators; |] ) and class_implements (loc, implements) = Class.Implements.( node "ClassImplements" loc [| "id", identifier implements.id; "typeParameters", option type_parameter_instantiation implements.typeParameters; |] ) and class_body (loc, body) = Class.Body.( node "ClassBody" loc [| "body", array_of_list class_element body.body; |] ) and class_element = Class.Body.(function | Method m -> class_method m | Property p -> class_property p) and class_method (loc, method_) = let { Class.Method.key; value; kind; static; decorators; } = method_ in let key, computed = Expression.Object.Property.(match key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in let kind = Class.Method.(match kind with | Constructor -> "constructor" | Method -> "method" | Get -> "get" | Set -> "set") in node "MethodDefinition" loc [| "key", key; "value", function_expression value; "kind", string kind; "static", bool static; "computed", bool computed; "decorators", array_of_list expression decorators; |] and class_property (loc, prop) = Class.Property.( let key, computed = (match prop.key with | Expression.Object.Property.Literal lit -> literal lit, false | Expression.Object.Property.Identifier id -> identifier id, false | Expression.Object.Property.Computed expr -> expression expr, true) in node "ClassProperty" loc [| "key", key; "value", option expression prop.value; "typeAnnotation", option type_annotation prop.typeAnnotation; "computed", bool computed; "static", bool prop.static; "variance", option variance prop.variance; |] ) and interface_declaration (loc, i) = Statement.Interface.( node "InterfaceDeclaration" loc [| "id", identifier i.id; "typeParameters", option type_parameter_declaration i.typeParameters; "body", object_type i.body; "extends", array_of_list interface_extends i.extends; |] ) and interface_extends (loc, g) = Type.Generic.( let id = match g.id with | Identifier.Unqualified id -> identifier id | Identifier.Qualified q -> generic_type_qualified_identifier q in node "InterfaceExtends" loc [| "id", id; "typeParameters", option type_parameter_instantiation g.typeParameters; |] ) and pattern = Pattern.(function | loc, Object obj -> node "ObjectPattern" loc [| "properties", array_of_list object_pattern_property obj.Object.properties; "typeAnnotation", option type_annotation obj.Object.typeAnnotation; |] | loc, Array arr -> node "ArrayPattern" loc [| "elements", array_of_list (option array_pattern_element) arr.Array.elements; "typeAnnotation", option type_annotation arr.Array.typeAnnotation; |] | loc, Assignment { Assignment.left; right } -> node "AssignmentPattern" loc [| "left", pattern left; "right", expression right |] | loc, Identifier pattern_id -> pattern_identifier loc pattern_id | _loc, Expression expr -> expression expr) and function_params = function | params, Some (rest_loc, { Function.RestElement.argument }) -> let rest = node "RestElement" rest_loc [| "argument", pattern argument; |] in let rev_params = params |> List.map pattern |> List.rev in let params = List.rev (rest::rev_params) in array (Array.of_list params) | params, None -> array_of_list pattern params and array_pattern_element = Pattern.Array.(function | Element p -> pattern p | RestElement (loc, { RestElement.argument; }) -> node "RestElement" loc [| "argument", pattern argument; |] ) and object_property = Expression.Object.(function | Property (loc, prop) -> Property.( This is a slight deviation from the Mozilla spec . In the spec , an object * property is not a proper node , and lacks a location and a " type " field . * Esprima promotes it to a proper node and that is useful , so I 'm * following their example * property is not a proper node, and lacks a location and a "type" field. * Esprima promotes it to a proper node and that is useful, so I'm * following their example *) let key, computed = (match prop.key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in let kind = match prop.kind with | Init -> "init" | Get -> "get" | Set -> "set" in node "Property" loc [| "key", key; "value", expression prop.value; "kind", string kind; "method", bool prop._method; "shorthand", bool prop.shorthand; "computed", bool computed; |] ) | SpreadProperty(loc, prop) -> SpreadProperty.( node "SpreadProperty" loc [| "argument", expression prop.argument; |] )) and object_pattern_property = Pattern.Object.(function | Property (loc, prop) -> Property.( let key, computed = (match prop.key with | Literal lit -> literal lit, false | Identifier id -> identifier id, false | Computed expr -> expression expr, true) in node "Property" loc [| "key", key; "value", pattern prop.pattern; "kind", string "init"; "method", bool false; "shorthand", bool prop.shorthand; "computed", bool computed; |] ) | RestProperty (loc, prop) -> RestProperty.( node "RestProperty" loc [| "argument", pattern prop.argument; |] ) ) and expression_or_spread = Expression.(function | Expression expr -> expression expr | Spread (loc, { SpreadElement.argument; }) -> node "SpreadElement" loc [| "argument", expression argument; |] ) and comprehension_block (loc, b) = Expression.Comprehension.Block.( node "ComprehensionBlock" loc [| "left", pattern b.left; "right", expression b.right; "each", bool b.each; |] ) and literal (loc, lit) = Literal.( let { value; raw; } = lit in let value_ = match value with | String str -> string str | Boolean b -> bool b | Null -> null | Number f -> number f | RegExp { RegExp.pattern; flags; } -> regexp loc pattern flags in let props = match value with | RegExp { RegExp.pattern; flags; } -> let regex = obj [| "pattern", string pattern; "flags", string flags; |] in [| "value", value_; "raw", string raw; "regex", regex |] | _ -> [| "value", value_; "raw", string raw; |] in node "Literal" loc props ) and template_literal (loc, value) = Expression.TemplateLiteral.( node "TemplateLiteral" loc [| "quasis", array_of_list template_element value.quasis; "expressions", array_of_list expression value.expressions; |] ) and template_element (loc, element) = Expression.TemplateLiteral.Element.( let value = obj [| "raw", string element.value.raw; "cooked", string element.value.cooked; |] in node "TemplateElement" loc [| "value", value; "tail", bool element.tail; |] ) and tagged_template (loc, tagged) = Expression.TaggedTemplate.( node "TaggedTemplateExpression" loc [| "tag", expression tagged.tag; "quasi", template_literal tagged.quasi; |] ) and variable_declaration (loc, var) = Statement.VariableDeclaration.( let kind = match var.kind with | Var -> "var" | Let -> "let" | Const -> "const" in node "VariableDeclaration" loc [| "declarations", array_of_list variable_declarator var.declarations; "kind", string kind; |] ) and variable_declarator (loc, declarator) = Statement.VariableDeclaration.Declarator.( node "VariableDeclarator" loc [| "id", pattern declarator.id; "init", option expression declarator.init; |] ) and variance (_, sigil) = Variance.( match sigil with | Plus -> string "plus" | Minus -> string "minus" ) and _type (loc, t) = Type.( match t with | Any -> any_type loc | Mixed -> mixed_type loc | Empty -> empty_type loc | Void -> void_type loc | Null -> null_type loc | Number -> number_type loc | String -> string_type loc | Boolean -> boolean_type loc | Nullable t -> nullable_type loc t | Function fn -> function_type (loc, fn) | Object o -> object_type (loc, o) | Array t -> array_type loc t | Generic g -> generic_type (loc, g) | Union (t0, t1, ts) -> union_type (loc, t0::t1::ts) | Intersection (t0, t1, ts) -> intersection_type (loc, t0::t1::ts) | Typeof t -> typeof_type (loc, t) | Tuple t -> tuple_type (loc, t) | StringLiteral s -> string_literal_type (loc, s) | NumberLiteral n -> number_literal_type (loc, n) | BooleanLiteral b -> boolean_literal_type (loc, b) | Exists -> exists_type loc ) and any_type loc = node "AnyTypeAnnotation" loc [||] and mixed_type loc = node "MixedTypeAnnotation" loc [||] and empty_type loc = node "EmptyTypeAnnotation" loc [||] and void_type loc = node "VoidTypeAnnotation" loc [||] and null_type loc = node "NullLiteralTypeAnnotation" loc [||] and number_type loc = node "NumberTypeAnnotation" loc [||] and string_type loc = node "StringTypeAnnotation" loc [||] and boolean_type loc = node "BooleanTypeAnnotation" loc [||] and nullable_type loc t = node "NullableTypeAnnotation" loc [| "typeAnnotation", _type t; |] and function_type (loc, fn) = Type.Function.( let params, rest = fn.params in node "FunctionTypeAnnotation" loc [| "params", array_of_list function_type_param params; "returnType", _type fn.returnType; "rest", option function_type_rest rest; "typeParameters", option type_parameter_declaration fn.typeParameters; |] ) and function_type_param (loc, param) = Type.Function.Param.( node "FunctionTypeParam" loc [| "name", option identifier param.name; "typeAnnotation", _type param.typeAnnotation; "optional", bool param.optional; |] ) and function_type_rest (_loc, { Type.Function.RestParam.argument }) = TODO : add a node for the rest param itself , including the ` ... ` , like we do with on normal functions . This should be coordinated with Babel , ast - types , etc . so keeping the status quo for now . Here 's an example : like we do with RestElement on normal functions. This should be coordinated with Babel, ast-types, etc. so keeping the status quo for now. Here's an example: *) function_type_param argument and object_type (loc, o) = Type.Object.( node "ObjectTypeAnnotation" loc [| "exact", bool o.exact; "properties", array_of_list object_type_property o.properties; "indexers", array_of_list object_type_indexer o.indexers; "callProperties", array_of_list object_type_call_property o.callProperties; |] ) and object_type_property (loc, prop) = Type.Object.Property.( let key = match prop.key with | Expression.Object.Property.Literal lit -> literal lit | Expression.Object.Property.Identifier id -> identifier id | Expression.Object.Property.Computed _ -> failwith "There should not be computed object type property keys" in node "ObjectTypeProperty" loc [| "key", key; "value", _type prop.value; "optional", bool prop.optional; "static", bool prop.static; "variance", option variance prop.variance; |] ) and object_type_indexer (loc, indexer) = Type.Object.Indexer.( node "ObjectTypeIndexer" loc [| "id", option identifier indexer.id; "key", _type indexer.key; "value", _type indexer.value; "static", bool indexer.static; "variance", option variance indexer.variance; |] ) and object_type_call_property (loc, callProperty) = Type.Object.CallProperty.( node "ObjectTypeCallProperty" loc [| "value", function_type callProperty.value; "static", bool callProperty.static; |] ) and array_type loc t = node "ArrayTypeAnnotation" loc [| "elementType", (_type t); |] and generic_type_qualified_identifier (loc, q) = Type.Generic.Identifier.( let qualification = match q.qualification with | Unqualified id -> identifier id | Qualified q -> generic_type_qualified_identifier q in node "QualifiedTypeIdentifier" loc [| "qualification", qualification; "id", identifier q.id; |] ) and generic_type (loc, g) = Type.Generic.( let id = match g.id with | Identifier.Unqualified id -> identifier id | Identifier.Qualified q -> generic_type_qualified_identifier q in node "GenericTypeAnnotation" loc [| "id", id; "typeParameters", option type_parameter_instantiation g.typeParameters; |] ) and union_type (loc, ts) = node "UnionTypeAnnotation" loc [| "types", array_of_list _type ts; |] and intersection_type (loc, ts) = node "IntersectionTypeAnnotation" loc [| "types", array_of_list _type ts; |] and typeof_type (loc, t) = node "TypeofTypeAnnotation" loc [| "argument", _type t; |] and tuple_type (loc, tl) = node "TupleTypeAnnotation" loc [| "types", array_of_list _type tl; |] and string_literal_type (loc, s) = Type.StringLiteral.( node "StringLiteralTypeAnnotation" loc [| "value", string s.value; "raw", string s.raw; |] ) and number_literal_type (loc, s) = Type.NumberLiteral.( node "NumberLiteralTypeAnnotation" loc [| "value", number s.value; "raw", string s.raw; |] ) and boolean_literal_type (loc, s) = Type.BooleanLiteral.( node "BooleanLiteralTypeAnnotation" loc [| "value", bool s.value; "raw", string s.raw; |] ) and exists_type loc = node "ExistsTypeAnnotation" loc [||] and type_annotation (loc, ty) = node "TypeAnnotation" loc [| "typeAnnotation", _type ty; |] and type_parameter_declaration (loc, params) = Type.ParameterDeclaration.( node "TypeParameterDeclaration" loc [| "params", array_of_list type_param params.params; |] ) and type_param (loc, tp) = Type.ParameterDeclaration.TypeParam.( node "TypeParameter" loc [| "name", string tp.name; "bound", option type_annotation tp.bound; "variance", option variance tp.variance; "default", option _type tp.default; |] ) and type_parameter_instantiation (loc, params) = Type.ParameterInstantiation.( node "TypeParameterInstantiation" loc [| "params", array_of_list _type params.params; |] ) and jsx_element (loc, (element: JSX.element)) = JSX.( node "JSXElement" loc [| "openingElement", jsx_opening element.openingElement; "closingElement", option jsx_closing element.closingElement; "children", array_of_list jsx_child element.children; |] ) and jsx_opening (loc, opening) = JSX.Opening.( node "JSXOpeningElement" loc [| "name", jsx_name opening.name; "attributes", array_of_list jsx_opening_attribute opening.attributes; "selfClosing", bool opening.selfClosing; |] ) and jsx_opening_attribute = JSX.Opening.(function | Attribute attribute -> jsx_attribute attribute | SpreadAttribute attribute -> jsx_spread_attribute attribute ) and jsx_closing (loc, closing) = JSX.Closing.( node "JSXClosingElement" loc [| "name", jsx_name closing.name; |] ) and jsx_child = JSX.(function | loc, Element element -> jsx_element (loc, element) | loc, ExpressionContainer expr -> jsx_expression_container (loc, expr) | loc, Text str -> jsx_text (loc, str) ) and jsx_name = JSX.(function | Identifier id -> jsx_identifier id | NamespacedName namespaced_name -> jsx_namespaced_name namespaced_name | MemberExpression member -> jsx_member_expression member ) and jsx_attribute (loc, attribute) = JSX.Attribute.( let name = match attribute.name with | Identifier id -> jsx_identifier id | NamespacedName namespaced_name -> jsx_namespaced_name namespaced_name in node "JSXAttribute" loc [| "name", name; "value", option jsx_attribute_value attribute.value; |] ) and jsx_attribute_value = JSX.Attribute.(function | Literal (loc, value) -> literal (loc, value) | ExpressionContainer (loc, expr) -> jsx_expression_container (loc, expr) ) and jsx_spread_attribute (loc, attribute) = JSX.SpreadAttribute.( node "JSXSpreadAttribute" loc [| "argument", expression attribute.argument; |] ) and jsx_expression_container (loc, expr) = JSX.ExpressionContainer.( let expression = match expr.expression with | Expression expr -> expression expr | EmptyExpression empty_loc -> node "JSXEmptyExpression" empty_loc [||] in node "JSXExpressionContainer" loc [| "expression", expression; |] ) and jsx_text (loc, text) = JSX.Text.( let { value; raw; } = text in node "JSXText" loc [| "value", string value; "raw", string raw; |] ) and jsx_member_expression (loc, member_expression) = JSX.MemberExpression.( let _object = match member_expression._object with | Identifier id -> jsx_identifier id | MemberExpression member -> jsx_member_expression member in node "JSXMemberExpression" loc [| "object", _object; "property", jsx_identifier member_expression.property; |] ) and jsx_namespaced_name (loc, namespaced_name) = JSX.NamespacedName.( node "JSXNamespacedName" loc [| "namespace", jsx_identifier namespaced_name.namespace; "name", jsx_identifier namespaced_name.name; |] ) and jsx_identifier (loc, id) = JSX.Identifier.( node "JSXIdentifier" loc [| "name", string id.name; |] ) and export_specifier (loc, specifier) = let open Statement.ExportNamedDeclaration.ExportSpecifier in let exported = match specifier.exported with | Some exported -> identifier exported | None -> identifier specifier.local in node "ExportSpecifier" loc [| "local", identifier specifier.local; "exported", exported; |] and import_default_specifier id = node "ImportDefaultSpecifier" (fst id) [| "local", identifier id; |] and import_namespace_specifier (loc, id) = node "ImportNamespaceSpecifier" loc [| "local", identifier id; |] and import_named_specifier local_id remote_id = let span_loc = match local_id with | Some local_id -> Loc.btwn (fst remote_id) (fst local_id) | None -> fst remote_id in let local_id = match local_id with | Some id -> id | None -> remote_id in node "ImportSpecifier" span_loc [| "imported", identifier remote_id; "local", identifier local_id; |] and comment_list comments = array_of_list comment comments and comment (loc, c) = Comment.( let _type, value = match c with | Line s -> "Line", s | Block s -> "Block", s in node _type loc [| "value", string value; |] ) and predicate (loc, p) = Ast.Type.Predicate.( let _type, value = match p with | Declared e -> "DeclaredPredicate", [|"value", expression e|] | Inferred -> "InferredPredicate", [||] in node _type loc value ) end
95d030b503ea9528859f8141ecb33865c6890cfbf3b0445f75f279aa1c197cdf
jellea/muuuuu
musicplayer.cljs
(ns muuuuu.components.musicplayer (:require [goog.events :as events] [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [om.dom :as dom :include-macros true])) (defn toggle-play-pause [state] (om/transact! state #(assoc % :is-playing (not (:is-playing %))))) (defn next-track [state] (prn @state) ) (defn empty-playlist [state] (prn @state) ) (defn love-track [state] (prn @state) ) (defn init [{:keys [tracknumber tracktitle artist data-url playlist is-playing] :as state} owner] (reify om/IDidUpdate (did-update [_ _ _] (if is-playing (.play (. js/document (getElementById "audioplayer")) nil) (.pause (. js/document (getElementById "audioplayer")) nil)) ) om/IDidMount (did-mount [_] (.addEventListener (. js/document (getElementById "audioplayer")) "ended" #(next-track state)) ) om/IRender (render [_] (html [:div.musicplayer [:div.text.hide (str tracknumber ". " artist " - " tracktitle)] [:div.heart.hide "<3"] [:audio#audioplayer {:src data-url}] [:div.playbtn {:onClick #(toggle-play-pause state)} (if is-playing [:img {:src "resources/img/play2.svg"}] [:img {:src "resources/img/pause.svg"}])]]))))
null
https://raw.githubusercontent.com/jellea/muuuuu/d3536949c8dcec51dd4451243c1b8d42acfabac5/src/muuuuu/components/musicplayer.cljs
clojure
(ns muuuuu.components.musicplayer (:require [goog.events :as events] [om.core :as om :include-macros true] [sablono.core :as html :refer-macros [html]] [om.dom :as dom :include-macros true])) (defn toggle-play-pause [state] (om/transact! state #(assoc % :is-playing (not (:is-playing %))))) (defn next-track [state] (prn @state) ) (defn empty-playlist [state] (prn @state) ) (defn love-track [state] (prn @state) ) (defn init [{:keys [tracknumber tracktitle artist data-url playlist is-playing] :as state} owner] (reify om/IDidUpdate (did-update [_ _ _] (if is-playing (.play (. js/document (getElementById "audioplayer")) nil) (.pause (. js/document (getElementById "audioplayer")) nil)) ) om/IDidMount (did-mount [_] (.addEventListener (. js/document (getElementById "audioplayer")) "ended" #(next-track state)) ) om/IRender (render [_] (html [:div.musicplayer [:div.text.hide (str tracknumber ". " artist " - " tracktitle)] [:div.heart.hide "<3"] [:audio#audioplayer {:src data-url}] [:div.playbtn {:onClick #(toggle-play-pause state)} (if is-playing [:img {:src "resources/img/play2.svg"}] [:img {:src "resources/img/pause.svg"}])]]))))
6b32ecbb698cd157d6cd74938d20acfce318f663a856ff76e540026f5a463754
lispbuilder/lispbuilder
cffi-translate.lisp
SDL library using CFFI for foreign function interfacing ... ( C)2006 < > ;; see COPYING for license (in-package #:lispbuilder-sdl-cffi) (defctype sdl-surface :pointer) (defctype sdl-rectangle :pointer) (defctype sdl-string (:wrapper :string :to-c to-sdl-string)) ( defctype SDL - RWops : pointer ) ( defmethod translate - to - foreign ( value ( type ( eql ' sdl - surface ) ) ) ;; (unless (is-valid-ptr value) ;; (error "Error: sdl-surface must be a valid pointer")) ;; value) ( defmethod translate - from - foreign ( value ( type ( eql ' sdl - surface ) ) ) ;; (if (is-valid-ptr value) ;; value ;; nil)) ( defmethod translate - to - foreign ( value ( type ( eql ' SDL - RWops ) ) ) ;; (unless (is-valid-ptr value) ;; (error "Error: SDL-RWops must be a valid, non-NULL pointer")) ;; value) ( defmethod translate - to - foreign ( value ( type ( eql ' sdl - rectangle ) ) ) ;; (if value ;; (let ((rect (cffi:foreign-alloc 'SDL_Rect)) ( value ( vec - to - int value ) ) ) ( cffi : with - foreign - slots ( ( x y w h ) rect SDL_rect ) ( setf x ( rect - x value ) ;; y (rect-y value) ;; w (rect-w value) ;; h (rect-h value))) ;; (values rect t)) ;; (values (cffi:null-pointer) nil))) (defun to-sdl-string (value) (unless value (setf value "")) (values (cffi:foreign-string-alloc value) t)) ( defmethod free - translated - object ( ptr ( name ( eql ' sdl - rectangle ) ) free - p ) ;; (if free-p ;; (cffi:foreign-free ptr))) (defmethod free-translated-object (ptr (name (eql 'sdl-string)) free-p) (if free-p (cffi:foreign-string-free ptr))) (defctype return->=0-as-t (:wrapper :int :from-c return-val->=0-as-t)) ( defctype return->=0 - as - nil (: wrapper : int : from - c return - val->=0 - as - nil ) ) (defun return-val->=0-as-t (value) (if (>= value 0) t nil)) ;;(defun return-val->=0-as-nil (value) ( if (= value 0 ) nil t ) )
null
https://raw.githubusercontent.com/lispbuilder/lispbuilder/589b3c6d552bbec4b520f61388117d6c7b3de5ab/lispbuilder-sdl/cffi/cffi-translate.lisp
lisp
see COPYING for license (unless (is-valid-ptr value) (error "Error: sdl-surface must be a valid pointer")) value) (if (is-valid-ptr value) value nil)) (unless (is-valid-ptr value) (error "Error: SDL-RWops must be a valid, non-NULL pointer")) value) (if value (let ((rect (cffi:foreign-alloc 'SDL_Rect)) y (rect-y value) w (rect-w value) h (rect-h value))) (values rect t)) (values (cffi:null-pointer) nil))) (if free-p (cffi:foreign-free ptr))) (defun return-val->=0-as-nil (value)
SDL library using CFFI for foreign function interfacing ... ( C)2006 < > (in-package #:lispbuilder-sdl-cffi) (defctype sdl-surface :pointer) (defctype sdl-rectangle :pointer) (defctype sdl-string (:wrapper :string :to-c to-sdl-string)) ( defctype SDL - RWops : pointer ) ( defmethod translate - to - foreign ( value ( type ( eql ' sdl - surface ) ) ) ( defmethod translate - from - foreign ( value ( type ( eql ' sdl - surface ) ) ) ( defmethod translate - to - foreign ( value ( type ( eql ' SDL - RWops ) ) ) ( defmethod translate - to - foreign ( value ( type ( eql ' sdl - rectangle ) ) ) ( value ( vec - to - int value ) ) ) ( cffi : with - foreign - slots ( ( x y w h ) rect SDL_rect ) ( setf x ( rect - x value ) (defun to-sdl-string (value) (unless value (setf value "")) (values (cffi:foreign-string-alloc value) t)) ( defmethod free - translated - object ( ptr ( name ( eql ' sdl - rectangle ) ) free - p ) (defmethod free-translated-object (ptr (name (eql 'sdl-string)) free-p) (if free-p (cffi:foreign-string-free ptr))) (defctype return->=0-as-t (:wrapper :int :from-c return-val->=0-as-t)) ( defctype return->=0 - as - nil (: wrapper : int : from - c return - val->=0 - as - nil ) ) (defun return-val->=0-as-t (value) (if (>= value 0) t nil)) ( if (= value 0 ) nil t ) )
c2669b2f4e75e50856ec398ebdf6d781b0f42c577d423954f3393d8e1e0483ea
GracielaUSB/graciela
Assertion.hs
# LANGUAGE NamedFieldPuns # module Language.Graciela.Parser.Assertion ( assertion , bound , precond , postcond , invariant , repInv , coupInv ) where -------------------------------------------------------------------------------- import Language.Graciela.AST.Expression import Language.Graciela.AST.Type import Language.Graciela.Error as PE import Language.Graciela.Location import Language.Graciela.Parser.Declaration import Language.Graciela.Parser.Expression import Language.Graciela.Parser.Monad import Language.Graciela.Parser.State import Language.Graciela.Parser.Type import Language.Graciela.Token -------------------------------------------------------------------------------- import Control.Lens ((%=)) import Control.Monad (unless, void) import Data.Sequence ((|>)) import Text.Megaparsec (ParseError, between, lookAhead, manyTill, withRecovery) -------------------------------------------------------------------------------- bound :: Parser (Maybe Expression) bound = between (match TokLeftBound) (match' TokRightBound) (declarative bound') where bound' = do expr <- withRecovery recover expression case expr of Nothing -> pure Nothing Just Expression { loc = Location (from, _) , expType } | expType =:= GInt -> pure expr | otherwise -> do putError from $ BadBoundType expType pure Nothing recover :: ParseError TokenPos Error -> Parser (Maybe a) recover err = do errors %= (|> err) void . manyTill anyToken . lookAhead . match $ TokRightBound pure Nothing assert :: Token -> Token -> Parser (Maybe Expression) assert open close = between (match' open) (match' close) (declarative $ assert'' close) assert' :: Token -> Token -> Parser (Maybe Expression) assert' open close = between (match open) (match' close) (declarative $ assert'' close) ^^^^^ this match is not obligatory assert'' close = do expr <- withRecovery recover expression case expr of Nothing -> pure Nothing Just Expression { loc = Location (from, _), expType } | expType =:= GBool -> pure expr | otherwise -> do putError from $ BadAssertType expType pure Nothing where recover :: ParseError TokenPos Error -> Parser (Maybe a) recover err = do errors %= (|> err) void . manyTill anyToken . lookAhead . match $ close pure Nothing precond, postcond, assertion, invariant, repInv :: Parser (Maybe Expression) precond = assert TokLeftPre TokRightPre postcond = assert TokLeftPost TokRightPost assertion = assert' TokLeftBrace TokRightBrace invariant = assert TokLeftInv TokRightInv repInv = assert TokLeftRep TokRightRep coupInv = assert TokLeftAcopl TokRightAcopl
null
https://raw.githubusercontent.com/GracielaUSB/graciela/db69c8b225d6172aaa0ff90a67f4a997e4d8a0c6/src/Haskell/Language/Graciela/Parser/Assertion.hs
haskell
------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE NamedFieldPuns # module Language.Graciela.Parser.Assertion ( assertion , bound , precond , postcond , invariant , repInv , coupInv ) where import Language.Graciela.AST.Expression import Language.Graciela.AST.Type import Language.Graciela.Error as PE import Language.Graciela.Location import Language.Graciela.Parser.Declaration import Language.Graciela.Parser.Expression import Language.Graciela.Parser.Monad import Language.Graciela.Parser.State import Language.Graciela.Parser.Type import Language.Graciela.Token import Control.Lens ((%=)) import Control.Monad (unless, void) import Data.Sequence ((|>)) import Text.Megaparsec (ParseError, between, lookAhead, manyTill, withRecovery) bound :: Parser (Maybe Expression) bound = between (match TokLeftBound) (match' TokRightBound) (declarative bound') where bound' = do expr <- withRecovery recover expression case expr of Nothing -> pure Nothing Just Expression { loc = Location (from, _) , expType } | expType =:= GInt -> pure expr | otherwise -> do putError from $ BadBoundType expType pure Nothing recover :: ParseError TokenPos Error -> Parser (Maybe a) recover err = do errors %= (|> err) void . manyTill anyToken . lookAhead . match $ TokRightBound pure Nothing assert :: Token -> Token -> Parser (Maybe Expression) assert open close = between (match' open) (match' close) (declarative $ assert'' close) assert' :: Token -> Token -> Parser (Maybe Expression) assert' open close = between (match open) (match' close) (declarative $ assert'' close) ^^^^^ this match is not obligatory assert'' close = do expr <- withRecovery recover expression case expr of Nothing -> pure Nothing Just Expression { loc = Location (from, _), expType } | expType =:= GBool -> pure expr | otherwise -> do putError from $ BadAssertType expType pure Nothing where recover :: ParseError TokenPos Error -> Parser (Maybe a) recover err = do errors %= (|> err) void . manyTill anyToken . lookAhead . match $ close pure Nothing precond, postcond, assertion, invariant, repInv :: Parser (Maybe Expression) precond = assert TokLeftPre TokRightPre postcond = assert TokLeftPost TokRightPost assertion = assert' TokLeftBrace TokRightBrace invariant = assert TokLeftInv TokRightInv repInv = assert TokLeftRep TokRightRep coupInv = assert TokLeftAcopl TokRightAcopl
b2cfabcfde2ce287b945c0d97110390a2f554f7485afc0c39fc6f1a9ceadb086
dyzsr/ocaml-selectml
is_expansive.ml
(* TEST * expect *) match [] with x -> (fun x -> x);; [%%expect{| - : 'a -> 'a = <fun> |}];; match [] with x -> (fun x -> x) | _ -> .;; [%%expect{| - : 'a -> 'a = <fun> |}];;
null
https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/testsuite/tests/typing-misc/is_expansive.ml
ocaml
TEST * expect
match [] with x -> (fun x -> x);; [%%expect{| - : 'a -> 'a = <fun> |}];; match [] with x -> (fun x -> x) | _ -> .;; [%%expect{| - : 'a -> 'a = <fun> |}];;
82a560b23ef636b28763dff64f06badb292a68fdc365b2275cd0cc64373a8cd8
mfussenegger/mkjson
Cli.hs
# LANGUAGE TupleSections # {-# LANGUAGE OverloadedStrings #-} module Cli ( Args(..) , Amount(..) , parseArgs , Field ) where import Data.Bifunctor (bimap) import qualified Data.Text as T import qualified Expr as E import Options.Applicative hiding (Const) import Text.Read (readMaybe) type Field = (T.Text, E.Expr) data Args = Args { seed :: !(Maybe Int) , num :: !Amount , fields :: ![Field] } deriving (Show) data Amount = Const Int | Infinite deriving (Show) parseNum :: ReadM Amount parseNum = eitherReader parseNum' where parseNum' "Inf" = Right Infinite parseNum' s = case readMaybe s of (Just n) -> Right (Const n) Nothing -> Left "Expected a number or `Inf` for infinite records" parseExpr :: String -> Either String Field parseExpr s = case parts of [field, expr] -> bimap show (field ,) (E.parseExpr expr) [field] -> bimap show (field ,) (E.parseExpr "null()") _ -> Left "Field must be in <name>=<expr> format" where parts = T.splitOn "=" (T.pack s) args :: Parser Args args = Args <$> optional ( option auto ( long "seed" <> help "A seed for the random data generator" <> metavar "INT" )) <*> option parseNum ( long "num" <> value (Const 1) <> help "Number of records to generate. Use `Inf` for infinite records" ) <*> many (argument (eitherReader parseExpr) (metavar "FIELDS...")) parseArgs :: [String] -> IO Args parseArgs cliArgs = handleParseResult $ execParserPure defaultPrefs opts cliArgs where opts = info (args <**> helper) ( fullDesc <> progDesc "Generate random JSON records. Use <field>=<provider> pairs to specify the fields the records should have." )
null
https://raw.githubusercontent.com/mfussenegger/mkjson/312750647a71903a29f28948e314041e02bf3596/src/Cli.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE TupleSections # module Cli ( Args(..) , Amount(..) , parseArgs , Field ) where import Data.Bifunctor (bimap) import qualified Data.Text as T import qualified Expr as E import Options.Applicative hiding (Const) import Text.Read (readMaybe) type Field = (T.Text, E.Expr) data Args = Args { seed :: !(Maybe Int) , num :: !Amount , fields :: ![Field] } deriving (Show) data Amount = Const Int | Infinite deriving (Show) parseNum :: ReadM Amount parseNum = eitherReader parseNum' where parseNum' "Inf" = Right Infinite parseNum' s = case readMaybe s of (Just n) -> Right (Const n) Nothing -> Left "Expected a number or `Inf` for infinite records" parseExpr :: String -> Either String Field parseExpr s = case parts of [field, expr] -> bimap show (field ,) (E.parseExpr expr) [field] -> bimap show (field ,) (E.parseExpr "null()") _ -> Left "Field must be in <name>=<expr> format" where parts = T.splitOn "=" (T.pack s) args :: Parser Args args = Args <$> optional ( option auto ( long "seed" <> help "A seed for the random data generator" <> metavar "INT" )) <*> option parseNum ( long "num" <> value (Const 1) <> help "Number of records to generate. Use `Inf` for infinite records" ) <*> many (argument (eitherReader parseExpr) (metavar "FIELDS...")) parseArgs :: [String] -> IO Args parseArgs cliArgs = handleParseResult $ execParserPure defaultPrefs opts cliArgs where opts = info (args <**> helper) ( fullDesc <> progDesc "Generate random JSON records. Use <field>=<provider> pairs to specify the fields the records should have." )
f1ef3e5e1a2f3c788d417d87bc1800c7545e44b27e31222ec0581b2b90cc3e30
albertoruiz/easyVision
probability.hs
# LANGUAGE FlexibleContexts , UndecidableInstances # import Util.Probability import Control.Monad import Text.Printf import Control.Applicative((<$>),(<*>),pure) die = uniform [1..6] :: Prob Int coin = uniform ['-','+'] :: Prob Char --------------------------------------------- -- joint dist using explicit monadic/do style enfer :: Prob (String, String) enfer = do state <- bernoulli (1/1000) "infected" "sane" test <- case state of "infected" -> bernoulli (99/100) "+" "-" "sane" -> bernoulli (95/100) "-" "+" return (state,test) ------------------------------------------ -- using joint urn = bernoulli (10/11) "Good" "Bad" -- a conditioned distribution on urn ball "Good" = bernoulli (1/6) "fail" "ok" ball "Bad" = bernoulli (1/3) "fail" "ok" box :: Prob (String, String) box = joint ball urn ------------------------------------------- instance (Ord a, Eq (Prob a), Num a) => Num (Prob a) where fromInteger = return.fromInteger (+) a b = (+) <$> a <*> b (-) a b = (-) <$> a <*> b (*) a b = (*) <$> a <*> b abs = fmap abs signum = fmap signum multidice = do d0 <- die s <- replicateM d0 die return (sum s) ------------------------------------------- printev prob = printf "%s : %.1f db\n" (show m) evi where m = mode prob evi = evidence m prob sep msg x = putStrLn (msg ++ replicate 60 '-') >> print x >> printev x main = do sep "test" enfer sep "Jaynes (joint ball urn)" box sep "cond on fail" $ ((=="fail").fst) `pfilter` box sep "jointWith [] coin die" $ jointWith (\a b->[a, (head . show) b]) (const coin) die sep "using liftM2 (,)" $ liftM2 (,) coin die sep "sequence" $ sequence [coin, (head.show) <$> die] -- need same type in the list sep "jointWith (:) " $ jointWith (:) (const coin) $ jointWith (:) (const coin) (fmap return coin) sep "marg snd" $ box `marg` snd sep "cond fail" $ box `cond` ((=="fail").fst) `marg` snd sep "cond ok" $ pmap snd $ pfilter ((=="ok").fst) box sep "exper1" $ exper1 `cond` ((>=10).fst) `marg` (head.snd) sep "exper2" $ exper2 `cond` ((==6).fst) sep "joint" $ joint (return .length.filter (=='+')) (replicateM 5 coin) sep "marg" $ replicateM 5 coin `marg` (length.filter (=='+')) ---------------------------------------------------------------------- exper1 = joint (return.sum) (replicateM 3 die) exper2 = joint (\n-> sum <$> (replicateM n die)) die ----------------------------------------------------------------------- natural = bernoulli (1/2) "Boy" "Girl" name "Boy" = weighted [("B",1)] name "Girl" = weighted [("G",80),("Gx",20)] family = joint name natural `marg` fst families = replicateM 2 family -- <=> weighted [("G",40),("B",50),("Gx",10)] firstgirl = ((=='G').head.head) twogirls = (=="GG") . map head anyGx = any (=="Gx") anygirl = any ((=='G').head) sex = map head msg s x = putStrLn (replicate 30 '-' ++ ' ':s) >> print x florida = do msg "families" $ families msg "cond firstgirl" $ families `cond` firstgirl msg "sex | firstgirl" $ families `cond` firstgirl `marg` sex msg "twogirls | firstgirl" $ families `cond` firstgirl `marg` twogirls putStrLn "" msg "cond twogirls" $ families `cond` twogirls msg "sex | twogirls" $ families `cond` twogirls `marg` sex putStrLn "" msg "cond anygirl" $ families `cond` anygirl msg "sex | anygirl" $ families `cond` anygirl `marg` sex msg "twogirls | anygirl" $ families `cond` anygirl `marg` twogirls putStrLn "" msg "cond anyGx" $ families `cond` anyGx msg "sex | anyGx" $ families `cond` anyGx `marg` sex msg "twogirls | anyGx" $ families `cond` anyGx `marg` twogirls putStrLn "" msg "cond firstGx" $ families `cond` (("Gx"==).head) msg "sex | firstGx" $ families `cond` (("Gx"==).head) `marg` sex
null
https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/patrec/probability.hs
haskell
------------------------------------------- joint dist using explicit monadic/do style ---------------------------------------- using joint a conditioned distribution on urn ----------------------------------------- ----------------------------------------- need same type in the list -------------------------------------------------------------------- --------------------------------------------------------------------- <=> weighted [("G",40),("B",50),("Gx",10)]
# LANGUAGE FlexibleContexts , UndecidableInstances # import Util.Probability import Control.Monad import Text.Printf import Control.Applicative((<$>),(<*>),pure) die = uniform [1..6] :: Prob Int coin = uniform ['-','+'] :: Prob Char enfer :: Prob (String, String) enfer = do state <- bernoulli (1/1000) "infected" "sane" test <- case state of "infected" -> bernoulli (99/100) "+" "-" "sane" -> bernoulli (95/100) "-" "+" return (state,test) urn = bernoulli (10/11) "Good" "Bad" ball "Good" = bernoulli (1/6) "fail" "ok" ball "Bad" = bernoulli (1/3) "fail" "ok" box :: Prob (String, String) box = joint ball urn instance (Ord a, Eq (Prob a), Num a) => Num (Prob a) where fromInteger = return.fromInteger (+) a b = (+) <$> a <*> b (-) a b = (-) <$> a <*> b (*) a b = (*) <$> a <*> b abs = fmap abs signum = fmap signum multidice = do d0 <- die s <- replicateM d0 die return (sum s) printev prob = printf "%s : %.1f db\n" (show m) evi where m = mode prob evi = evidence m prob sep msg x = putStrLn (msg ++ replicate 60 '-') >> print x >> printev x main = do sep "test" enfer sep "Jaynes (joint ball urn)" box sep "cond on fail" $ ((=="fail").fst) `pfilter` box sep "jointWith [] coin die" $ jointWith (\a b->[a, (head . show) b]) (const coin) die sep "using liftM2 (,)" $ liftM2 (,) coin die sep "jointWith (:) " $ jointWith (:) (const coin) $ jointWith (:) (const coin) (fmap return coin) sep "marg snd" $ box `marg` snd sep "cond fail" $ box `cond` ((=="fail").fst) `marg` snd sep "cond ok" $ pmap snd $ pfilter ((=="ok").fst) box sep "exper1" $ exper1 `cond` ((>=10).fst) `marg` (head.snd) sep "exper2" $ exper2 `cond` ((==6).fst) sep "joint" $ joint (return .length.filter (=='+')) (replicateM 5 coin) sep "marg" $ replicateM 5 coin `marg` (length.filter (=='+')) exper1 = joint (return.sum) (replicateM 3 die) exper2 = joint (\n-> sum <$> (replicateM n die)) die natural = bernoulli (1/2) "Boy" "Girl" name "Boy" = weighted [("B",1)] name "Girl" = weighted [("G",80),("Gx",20)] family = joint name natural `marg` fst firstgirl = ((=='G').head.head) twogirls = (=="GG") . map head anyGx = any (=="Gx") anygirl = any ((=='G').head) sex = map head msg s x = putStrLn (replicate 30 '-' ++ ' ':s) >> print x florida = do msg "families" $ families msg "cond firstgirl" $ families `cond` firstgirl msg "sex | firstgirl" $ families `cond` firstgirl `marg` sex msg "twogirls | firstgirl" $ families `cond` firstgirl `marg` twogirls putStrLn "" msg "cond twogirls" $ families `cond` twogirls msg "sex | twogirls" $ families `cond` twogirls `marg` sex putStrLn "" msg "cond anygirl" $ families `cond` anygirl msg "sex | anygirl" $ families `cond` anygirl `marg` sex msg "twogirls | anygirl" $ families `cond` anygirl `marg` twogirls putStrLn "" msg "cond anyGx" $ families `cond` anyGx msg "sex | anyGx" $ families `cond` anyGx `marg` sex msg "twogirls | anyGx" $ families `cond` anyGx `marg` twogirls putStrLn "" msg "cond firstGx" $ families `cond` (("Gx"==).head) msg "sex | firstGx" $ families `cond` (("Gx"==).head) `marg` sex
e3df9d688e87546ecb4566458c35acb430ecd77b52665befdbd70b9e37facdc8
ThoughtWorksInc/stonecutter
handler.clj
(ns stonecutter.handler (:require [ring.middleware.defaults :as ring-mw] [ring.middleware.content-type :as ring-mct] [ring.util.response :as r] [ring.adapter.jetty :as ring-jetty] [ring.middleware.json :as ring-json] [ring.middleware.multipart-params :as ring-mw-mp] [scenic.routes :as scenic] [clojure.tools.logging :as log] [stonecutter.view.error :as error] [stonecutter.view.view-helpers :as vh] [stonecutter.helper :as sh] [stonecutter.routes :as routes] [stonecutter.controller.email-confirmations :as ec] [stonecutter.controller.user :as user] [stonecutter.controller.forgotten-password :as forgotten-password] [stonecutter.controller.oauth :as oauth] [stonecutter.controller.stylesheets :as stylesheets] [stonecutter.controller.admin :as admin] [stonecutter.translation :as t] [stonecutter.middleware :as m] [stonecutter.email :as email] [stonecutter.db.client-seed :as client-seed] [stonecutter.db.storage :as s] [stonecutter.db.user :as u] [stonecutter.db.migration :as migration] [stonecutter.db.mongo :as mongo] [stonecutter.config :as config] [stonecutter.admin :as ad] [stonecutter.db.storage :as storage] [stonecutter.jwt :as jwt] [taoensso.tower.ring :as tower-ring] [stonecutter.util.time :as time]) (:gen-class)) (defn not-found [request] (-> (error/not-found-error request) (sh/enlive-response request) (r/status 404))) (defn err-handler [request] (-> (error/internal-server-error request) (sh/enlive-response request) (r/status 500))) (defn csrf-err-handler [req] (-> (error/csrf-error req) (sh/enlive-response req) (r/status 403))) (defn forbidden-err-handler [req] (-> (error/forbidden-error req) (sh/enlive-response req) (r/status 403))) (defn ping [request] (log/debug "PING REQUEST: " request) (-> (r/response "pong") (r/content-type "text/plain"))) (defn site-handlers [clock stores-m email-sender] (let [profile-picture-store (storage/get-profile-picture-store stores-m) user-store (storage/get-user-store stores-m) client-store (storage/get-client-store stores-m) invitation-store (storage/get-invitation-store stores-m) token-store (storage/get-token-store stores-m) confirmation-store (storage/get-confirmation-store stores-m) auth-code-store (storage/get-auth-code-store stores-m) forgotten-password-store (storage/get-forgotten-password-store stores-m)] (-> {:index user/index :sign-in-or-register (partial user/sign-in-or-register user-store token-store confirmation-store email-sender) :ping ping :theme-css stylesheets/theme-css :sign-out user/sign-out :confirm-email-with-id (partial ec/confirm-email-with-id user-store confirmation-store) :confirmation-sign-in-form ec/show-confirm-sign-in-form :confirmation-sign-in (partial ec/confirmation-sign-in user-store token-store confirmation-store) :show-confirmation-delete (partial ec/show-confirmation-delete user-store confirmation-store) :confirmation-delete (partial ec/confirmation-delete user-store confirmation-store) :resend-confirmation-email (partial user/resend-confirmation-email user-store confirmation-store email-sender) :show-profile (partial user/show-profile client-store user-store profile-picture-store) :show-profile-created user/show-profile-created :show-profile-deleted user/show-profile-deleted :show-unshare-profile-card (partial user/show-unshare-profile-card client-store user-store) :unshare-profile-card (partial user/unshare-profile-card user-store) :show-delete-account-confirmation user/show-delete-account-confirmation :delete-account (partial user/delete-account user-store confirmation-store) :show-change-profile-form (partial user/show-change-profile-form user-store profile-picture-store) :change-profile (partial user/change-profile user-store profile-picture-store) :show-change-password-form user/show-change-password-form :change-password (partial user/change-password user-store email-sender) :change-email (partial user/update-user-email user-store confirmation-store email-sender) :update-profile-image (partial user/update-profile-image user-store profile-picture-store) :show-change-email-form user/show-change-email-form :show-forgotten-password-form forgotten-password/show-forgotten-password-form :send-forgotten-password-email (partial forgotten-password/forgotten-password-form-post email-sender user-store forgotten-password-store clock) :show-forgotten-password-confirmation forgotten-password/show-forgotten-password-confirmation :show-reset-password-form (partial forgotten-password/show-reset-password-form forgotten-password-store user-store clock) :reset-password (partial forgotten-password/reset-password-form-post forgotten-password-store user-store token-store clock) :show-authorise-form (partial oauth/show-authorise-form client-store user-store profile-picture-store) :authorise (partial oauth/authorise auth-code-store client-store user-store token-store profile-picture-store) :authorise-client (partial oauth/authorise-client auth-code-store client-store user-store token-store profile-picture-store) :show-authorise-failure (partial oauth/show-authorise-failure client-store) :show-user-list (partial admin/show-user-list user-store) :set-user-trustworthiness (partial admin/set-user-trustworthiness user-store) :show-apps-list (partial admin/show-apps-list client-store) :create-client (partial admin/create-client client-store) :delete-app (partial admin/delete-app client-store) :delete-app-confirmation admin/show-delete-app-form :show-invite admin/show-invite-user-form :send-invite (partial admin/send-user-invite email-sender user-store invitation-store clock) :accept-invite (partial user/accept-invite invitation-store) :register-using-invitation (partial user/register-using-invitation user-store token-store confirmation-store email-sender invitation-store) :download-vcard (partial user/download-vcard user-store profile-picture-store)} (m/wrap-handlers-except #(m/wrap-handle-403 % forbidden-err-handler) #{}) (m/wrap-handlers-except m/wrap-disable-caching #{:theme-css :index :sign-in-or-register}) (m/wrap-just-these-handlers #(m/wrap-authorised % (u/authorisation-checker user-store)) #{:show-user-list :set-user-trustworthiness :show-apps-list}) (m/wrap-handlers-except m/wrap-signed-in #{:index :sign-in-or-register :sign-out :accept-invite :register-using-invitation :show-profile-deleted :authorise :ping :theme-css :confirm-email-with-id :confirmation-sign-in-form :confirmation-sign-in :show-confirmation-delete :confirmation-delete :show-forgotten-password-form :send-forgotten-password-email :show-forgotten-password-confirmation :show-reset-password-form :reset-password})))) (defn api-handlers [config-m stores-m id-token-generator json-web-key-set] (let [auth-code-store (storage/get-auth-code-store stores-m) user-store (storage/get-user-store stores-m) client-store (storage/get-client-store stores-m) token-store (storage/get-token-store stores-m)] {:validate-token (partial oauth/validate-token config-m auth-code-store client-store user-store token-store id-token-generator) :jwk-set (partial oauth/jwk-set json-web-key-set)})) (defn splitter [site api] (fn [request] (let [uri (-> request :uri)] (if (.startsWith uri "/api") (api request) (site request))))) (defn handle-anti-forgery-error [req] (log/warn "ANTI_FORGERY_ERROR - headers: " (:headers req)) (csrf-err-handler req)) (defn wrap-defaults-config [session-store secure?] (-> (if secure? (assoc ring-mw/secure-site-defaults :proxy true) ring-mw/site-defaults) (assoc-in [:session :cookie-attrs :max-age] 3600) (assoc-in [:session :cookie-name] "stonecutter-session") (assoc-in [:session :store] session-store) (assoc-in [:security :anti-forgery] {:error-handler handle-anti-forgery-error}))) (defn create-site-app [clock config-m stores-m email-sender dev-mode?] (-> (scenic/scenic-handler routes/routes (site-handlers clock stores-m email-sender) not-found) (ring-mw/wrap-defaults (wrap-defaults-config (s/get-session-store stores-m) (config/secure? config-m))) (m/wrap-config config-m) (m/wrap-error-handling err-handler dev-mode?) (m/wrap-custom-static-resources config-m) (tower-ring/wrap-tower (t/config-translation)) ring-json/wrap-json-params ring-mw-mp/wrap-multipart-params ring-mct/wrap-content-type)) (defn create-api-app [config-m stores-m id-token-generator json-web-key-set dev-mode?] (-> (scenic/scenic-handler routes/routes (api-handlers config-m stores-m id-token-generator json-web-key-set) not-found) (ring-mw/wrap-defaults (if (config/secure? config-m) (assoc ring-mw/secure-api-defaults :proxy true) ring-mw/api-defaults)) TODO create json error handler (defn create-app ([config-m clock stores-m email-sender id-token-generator json-web-key-set] (create-app config-m clock stores-m email-sender id-token-generator json-web-key-set false)) ([config-m clock stores-m email-sender id-token-generator json-web-key-set prone-stacktraces?] (splitter (create-site-app clock config-m stores-m email-sender prone-stacktraces?) (create-api-app config-m stores-m id-token-generator json-web-key-set prone-stacktraces?)))) (defn -main [& args] (let [config-m (config/create-config)] (vh/enable-template-caching!) (let [db-and-conn-map (mongo/get-mongo-db (config/mongo-uri config-m)) db (:db db-and-conn-map) conn (:conn db-and-conn-map) stores-m (storage/create-mongo-stores db conn (config/mongo-db-name config-m)) clock (time/new-clock) email-sender (email/bash-sender-factory (config/email-script-path config-m)) json-web-key (jwt/load-key-pair (config/rsa-keypair-file-path config-m)) json-web-key-set (jwt/json-web-key->json-web-key-set json-web-key) id-token-generator (jwt/create-generator clock json-web-key (config/base-url config-m)) app (create-app config-m clock stores-m email-sender id-token-generator json-web-key-set)] (migration/run-migrations db) (ad/create-admin-user config-m (storage/get-user-store stores-m)) (client-seed/load-client-credentials-and-store-clients (storage/get-client-store stores-m) (config/client-credentials-file-path config-m)) (ring-jetty/run-jetty app {:port (config/port config-m) :host (config/host config-m)}))))
null
https://raw.githubusercontent.com/ThoughtWorksInc/stonecutter/37ed22dd276ac652176c4d880e0f1b0c1e27abfe/src/stonecutter/handler.clj
clojure
(ns stonecutter.handler (:require [ring.middleware.defaults :as ring-mw] [ring.middleware.content-type :as ring-mct] [ring.util.response :as r] [ring.adapter.jetty :as ring-jetty] [ring.middleware.json :as ring-json] [ring.middleware.multipart-params :as ring-mw-mp] [scenic.routes :as scenic] [clojure.tools.logging :as log] [stonecutter.view.error :as error] [stonecutter.view.view-helpers :as vh] [stonecutter.helper :as sh] [stonecutter.routes :as routes] [stonecutter.controller.email-confirmations :as ec] [stonecutter.controller.user :as user] [stonecutter.controller.forgotten-password :as forgotten-password] [stonecutter.controller.oauth :as oauth] [stonecutter.controller.stylesheets :as stylesheets] [stonecutter.controller.admin :as admin] [stonecutter.translation :as t] [stonecutter.middleware :as m] [stonecutter.email :as email] [stonecutter.db.client-seed :as client-seed] [stonecutter.db.storage :as s] [stonecutter.db.user :as u] [stonecutter.db.migration :as migration] [stonecutter.db.mongo :as mongo] [stonecutter.config :as config] [stonecutter.admin :as ad] [stonecutter.db.storage :as storage] [stonecutter.jwt :as jwt] [taoensso.tower.ring :as tower-ring] [stonecutter.util.time :as time]) (:gen-class)) (defn not-found [request] (-> (error/not-found-error request) (sh/enlive-response request) (r/status 404))) (defn err-handler [request] (-> (error/internal-server-error request) (sh/enlive-response request) (r/status 500))) (defn csrf-err-handler [req] (-> (error/csrf-error req) (sh/enlive-response req) (r/status 403))) (defn forbidden-err-handler [req] (-> (error/forbidden-error req) (sh/enlive-response req) (r/status 403))) (defn ping [request] (log/debug "PING REQUEST: " request) (-> (r/response "pong") (r/content-type "text/plain"))) (defn site-handlers [clock stores-m email-sender] (let [profile-picture-store (storage/get-profile-picture-store stores-m) user-store (storage/get-user-store stores-m) client-store (storage/get-client-store stores-m) invitation-store (storage/get-invitation-store stores-m) token-store (storage/get-token-store stores-m) confirmation-store (storage/get-confirmation-store stores-m) auth-code-store (storage/get-auth-code-store stores-m) forgotten-password-store (storage/get-forgotten-password-store stores-m)] (-> {:index user/index :sign-in-or-register (partial user/sign-in-or-register user-store token-store confirmation-store email-sender) :ping ping :theme-css stylesheets/theme-css :sign-out user/sign-out :confirm-email-with-id (partial ec/confirm-email-with-id user-store confirmation-store) :confirmation-sign-in-form ec/show-confirm-sign-in-form :confirmation-sign-in (partial ec/confirmation-sign-in user-store token-store confirmation-store) :show-confirmation-delete (partial ec/show-confirmation-delete user-store confirmation-store) :confirmation-delete (partial ec/confirmation-delete user-store confirmation-store) :resend-confirmation-email (partial user/resend-confirmation-email user-store confirmation-store email-sender) :show-profile (partial user/show-profile client-store user-store profile-picture-store) :show-profile-created user/show-profile-created :show-profile-deleted user/show-profile-deleted :show-unshare-profile-card (partial user/show-unshare-profile-card client-store user-store) :unshare-profile-card (partial user/unshare-profile-card user-store) :show-delete-account-confirmation user/show-delete-account-confirmation :delete-account (partial user/delete-account user-store confirmation-store) :show-change-profile-form (partial user/show-change-profile-form user-store profile-picture-store) :change-profile (partial user/change-profile user-store profile-picture-store) :show-change-password-form user/show-change-password-form :change-password (partial user/change-password user-store email-sender) :change-email (partial user/update-user-email user-store confirmation-store email-sender) :update-profile-image (partial user/update-profile-image user-store profile-picture-store) :show-change-email-form user/show-change-email-form :show-forgotten-password-form forgotten-password/show-forgotten-password-form :send-forgotten-password-email (partial forgotten-password/forgotten-password-form-post email-sender user-store forgotten-password-store clock) :show-forgotten-password-confirmation forgotten-password/show-forgotten-password-confirmation :show-reset-password-form (partial forgotten-password/show-reset-password-form forgotten-password-store user-store clock) :reset-password (partial forgotten-password/reset-password-form-post forgotten-password-store user-store token-store clock) :show-authorise-form (partial oauth/show-authorise-form client-store user-store profile-picture-store) :authorise (partial oauth/authorise auth-code-store client-store user-store token-store profile-picture-store) :authorise-client (partial oauth/authorise-client auth-code-store client-store user-store token-store profile-picture-store) :show-authorise-failure (partial oauth/show-authorise-failure client-store) :show-user-list (partial admin/show-user-list user-store) :set-user-trustworthiness (partial admin/set-user-trustworthiness user-store) :show-apps-list (partial admin/show-apps-list client-store) :create-client (partial admin/create-client client-store) :delete-app (partial admin/delete-app client-store) :delete-app-confirmation admin/show-delete-app-form :show-invite admin/show-invite-user-form :send-invite (partial admin/send-user-invite email-sender user-store invitation-store clock) :accept-invite (partial user/accept-invite invitation-store) :register-using-invitation (partial user/register-using-invitation user-store token-store confirmation-store email-sender invitation-store) :download-vcard (partial user/download-vcard user-store profile-picture-store)} (m/wrap-handlers-except #(m/wrap-handle-403 % forbidden-err-handler) #{}) (m/wrap-handlers-except m/wrap-disable-caching #{:theme-css :index :sign-in-or-register}) (m/wrap-just-these-handlers #(m/wrap-authorised % (u/authorisation-checker user-store)) #{:show-user-list :set-user-trustworthiness :show-apps-list}) (m/wrap-handlers-except m/wrap-signed-in #{:index :sign-in-or-register :sign-out :accept-invite :register-using-invitation :show-profile-deleted :authorise :ping :theme-css :confirm-email-with-id :confirmation-sign-in-form :confirmation-sign-in :show-confirmation-delete :confirmation-delete :show-forgotten-password-form :send-forgotten-password-email :show-forgotten-password-confirmation :show-reset-password-form :reset-password})))) (defn api-handlers [config-m stores-m id-token-generator json-web-key-set] (let [auth-code-store (storage/get-auth-code-store stores-m) user-store (storage/get-user-store stores-m) client-store (storage/get-client-store stores-m) token-store (storage/get-token-store stores-m)] {:validate-token (partial oauth/validate-token config-m auth-code-store client-store user-store token-store id-token-generator) :jwk-set (partial oauth/jwk-set json-web-key-set)})) (defn splitter [site api] (fn [request] (let [uri (-> request :uri)] (if (.startsWith uri "/api") (api request) (site request))))) (defn handle-anti-forgery-error [req] (log/warn "ANTI_FORGERY_ERROR - headers: " (:headers req)) (csrf-err-handler req)) (defn wrap-defaults-config [session-store secure?] (-> (if secure? (assoc ring-mw/secure-site-defaults :proxy true) ring-mw/site-defaults) (assoc-in [:session :cookie-attrs :max-age] 3600) (assoc-in [:session :cookie-name] "stonecutter-session") (assoc-in [:session :store] session-store) (assoc-in [:security :anti-forgery] {:error-handler handle-anti-forgery-error}))) (defn create-site-app [clock config-m stores-m email-sender dev-mode?] (-> (scenic/scenic-handler routes/routes (site-handlers clock stores-m email-sender) not-found) (ring-mw/wrap-defaults (wrap-defaults-config (s/get-session-store stores-m) (config/secure? config-m))) (m/wrap-config config-m) (m/wrap-error-handling err-handler dev-mode?) (m/wrap-custom-static-resources config-m) (tower-ring/wrap-tower (t/config-translation)) ring-json/wrap-json-params ring-mw-mp/wrap-multipart-params ring-mct/wrap-content-type)) (defn create-api-app [config-m stores-m id-token-generator json-web-key-set dev-mode?] (-> (scenic/scenic-handler routes/routes (api-handlers config-m stores-m id-token-generator json-web-key-set) not-found) (ring-mw/wrap-defaults (if (config/secure? config-m) (assoc ring-mw/secure-api-defaults :proxy true) ring-mw/api-defaults)) TODO create json error handler (defn create-app ([config-m clock stores-m email-sender id-token-generator json-web-key-set] (create-app config-m clock stores-m email-sender id-token-generator json-web-key-set false)) ([config-m clock stores-m email-sender id-token-generator json-web-key-set prone-stacktraces?] (splitter (create-site-app clock config-m stores-m email-sender prone-stacktraces?) (create-api-app config-m stores-m id-token-generator json-web-key-set prone-stacktraces?)))) (defn -main [& args] (let [config-m (config/create-config)] (vh/enable-template-caching!) (let [db-and-conn-map (mongo/get-mongo-db (config/mongo-uri config-m)) db (:db db-and-conn-map) conn (:conn db-and-conn-map) stores-m (storage/create-mongo-stores db conn (config/mongo-db-name config-m)) clock (time/new-clock) email-sender (email/bash-sender-factory (config/email-script-path config-m)) json-web-key (jwt/load-key-pair (config/rsa-keypair-file-path config-m)) json-web-key-set (jwt/json-web-key->json-web-key-set json-web-key) id-token-generator (jwt/create-generator clock json-web-key (config/base-url config-m)) app (create-app config-m clock stores-m email-sender id-token-generator json-web-key-set)] (migration/run-migrations db) (ad/create-admin-user config-m (storage/get-user-store stores-m)) (client-seed/load-client-credentials-and-store-clients (storage/get-client-store stores-m) (config/client-credentials-file-path config-m)) (ring-jetty/run-jetty app {:port (config/port config-m) :host (config/host config-m)}))))
87a602ac92356fc665a406fb9515c21f7085b6ef5000a279672abfb47f25bdaa
whostolebenfrog/rest-cljer
core.clj
(ns rest-cljer.test.core (:require [cheshire.core :as json] [clj-http.client :as http] [environ.core :refer [env]] [clojure.test :refer :all] [rest-cljer.core :refer [*rest-driver-port* json-capture rest-driven string-capture]]) (:import [com.github.restdriver.clientdriver ClientDriver ClientDriverRequest$Method] [com.github.restdriver.clientdriver.exception ClientDriverFailedExpectationException] [java.net SocketTimeoutException])) (defn local-path "Returns a URI to a resource on a free port, on localhost with the supplied postfix" [postfix] (str ":" *rest-driver-port* postfix)) (deftest rest-driven-call-succeeds-without-exceptions (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-returns-body-result (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-binary-body-succeeds-without-exceptions (let [resource-path "/some/resource/path" bytes (byte-array [(byte 10) (byte 20) (byte 30)])] (rest-driven [{:method :POST :url resource-path} {:status 200 :body bytes}] (is (= (seq bytes) (-> (http/post (local-path resource-path)) :body (.getBytes) seq)))))) (deftest unexpected-rest-driven-call-should-fail-with-exception (is (thrown? RuntimeException (rest-driven [] (http/post (local-path "/")))))) (deftest test-json-document-matching (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false}))))))) (deftest check-body-via-predicate (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body #(apply = (map sort [[3 2 1] %]))} {:status 204}] (is (= 204) (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string [1 3 2]) :throw-exceptions false})))))) (deftest check-body-via-predicate-with-type-as-string (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body [#(= "Hi" %) "application/text"]} {:status 204}] (is (= 204) (:status (http/post (local-path resource-path) {:content-type "application/text" :body "Hi" :throw-exceptions false})))))) (deftest check-body-via-predicate-order-independent (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body [#(= "Hi" %) "application/text"]} {:status 204} {:method :POST :url resource-path :body [#(= "not-hi" %) "application/text"]} {:status 204}] (http/post (local-path resource-path) {:content-type "application/text" :body "not-hi" :throw-exceptions false}) (is (= 204 (:status (http/post (local-path resource-path) {:content-type "application/text" :body "Hi" :throw-exceptions false}))))))) (deftest json-document-capture-as-a-string (let [resource-path "/some/resource/path" capturer (string-capture)] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"} :capture capturer} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false})))) (is (= "{\"ping\":\"pong\"}" (capturer)))))) (deftest json-document-captured-and-parsed-using-json-capture (let [resource-path "/some/resource/path" capturer (json-capture)] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"} :capture capturer} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false})))) (is (= {:ping "pong"} (capturer)))))) (deftest sweetening-of-response-definitions (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path} {:body {:inigo "montoya"}}] (let [{:keys [status body headers]} (http/get (local-path resource-path))] (is (= 200 status)) (is (= "application/json" (get headers "Content-Type"))) (is (= {:inigo "montoya"} (json/parse-string body true))))))) (deftest sweetening-of-response-does-not-override-explicit-http-status (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path} {:status 400 :body {:inigo "montoya"}}] (let [{:keys [status body headers]} (http/get (local-path resource-path) {:throw-exceptions false})] (is (= 400 status)) (is (= "application/json" (get headers "Content-Type"))) (is (= {:inigo "montoya"} (json/parse-string body true))))))) (deftest post-processing-of-request-and-response-replacing-initial-values-with-new-ones-using-the-:and-function (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :and #(.withMethod % ClientDriverRequest$Method/POST)} {:status 204 :and #(.withStatus % 205)}] (is (= 205 (:status (http/post (local-path resource-path)))))))) (deftest response-can-be-repeated-any-times (let [resource-path "/some/resource/path"] (rest-driven [{:method :PUT :url resource-path} {:status 204 :times :any}] (dotimes [n 3] (is (= 204 (:status (http/put (local-path resource-path))))))))) (deftest response-can-be-repeated-a-specific-number-of-times (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 200 :times 2}] (dotimes [n 2] (is (= 200 (:status (http/post (local-path resource-path))))))) (is (thrown? Exception (rest-driven [{:method :POST :url resource-path} {:status 200 :times 2}] (dotimes [n 2] (is (= 200 (:status (http/post (local-path resource-path)))))) (http/post (local-path resource-path))))))) (deftest rest-driven-call-with-expected-header-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :headers {"from" "mytest" "with" "value"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:headers {"from" "mytest" "with" "value"}}))))))) (deftest rest-driven-call-with-expected-header-succeeds-with-keyord-header-names (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :headers {:from "myfrom" :with "value"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:headers {"from" "myfrom" "with" "value"}}))))))) (deftest rest-driven-call-with-missing-header-throws-exception (let [resource-path "/some/resource/path"] (is (thrown? Exception (rest-driven [{:method :POST :url resource-path :headers {"From" "origin"}} {:status 204}] (http/post (local-path resource-path))))))) (deftest rest-driven-call-without-header-that-is-expected-to-be-absent-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :not {:headers {"myheader" "myvalue"}}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-header-that-is-expected-to-be-absent-throw-exception (let [resource-path "/some/resource/path"] (is (thrown? RuntimeException (rest-driven [{:method :POST :url resource-path :not {:headers {"myheader" "myvalue"}}} {:status 204}] (http/post (local-path resource-path) {:headers {"myheader" "myvalue"}})))))) (deftest rest-driven-call-with-vector-of-headers-that-are-expected-to-be-absent-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :not {:headers ["myheader"]}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-vector-of-headers-that-are-expected-to-be-absent-throw-exception (let [resource-path "/some/resource/path"] (is (thrown? RuntimeException (rest-driven [{:method :POST :url resource-path :not {:headers ["myheader"]}} {:status 204}] (http/post (local-path resource-path) {:headers {"myheader" "myvalue"}})))))) (deftest rest-driven-call-with-response-headers-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204 :headers {"from" "rest-cljer", "with" "value"}}] (let [{:keys [status headers]} (http/post (local-path resource-path))] (is (= 204 status)) (is (= "rest-cljer" (get headers "From"))) (is (= "value" (get headers "with"))))))) (deftest can-supply-params-using-keywords-as-well-as-strings (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :params {:a "a" "b" "b"}} {:status 200}] (is (= 200 (:status (http/get (local-path (str resource-path "?a=a&b=b"))))))))) (deftest can-specify-:any-params (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :params :any} {:status 200}] (is (= 200 (:status (http/get (local-path resource-path)))))))) (deftest request-method-is-:GET-by-default (let [resource-path "/some/resource/path"] (rest-driven [{:url resource-path} {:status 200}] (is (= 200 (:status (http/get (local-path resource-path)))))))) (deftest request-response-can-be-paired-as-a-vector (let [resource-path "/some/resource/path"] (rest-driven [[{:url resource-path} {:status 201}] [{:url resource-path} {:status 202}]] (is (= 201 (:status (http/get (local-path resource-path))))) (is (= 202 (:status (http/get (local-path resource-path)))))))) (deftest expected-rest-driven-call-with-an-unusual-http-method-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method "PATCH" :url resource-path} {:status 204}] (is (= 204 (:status (http/patch (local-path resource-path)))))))) (deftest expected-rest-driven-call-times-out-if-after-is-to-larger-than-socket-timeout (let [resource-path "/some/resource/path"] (rest-driven [{:url resource-path} {:status 200 :after 200}] (is (thrown? SocketTimeoutException (http/get (local-path resource-path) {:socket-timeout 100})))))) (deftest can-use-environ-to-provide-port (let [port (ClientDriver/getFreePort) original-env env] (try (alter-var-root (var env) assoc :restdriver-port port) (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (str ":" port resource-path))))))) (finally (alter-var-root (var env) (constantly original-env))))))
null
https://raw.githubusercontent.com/whostolebenfrog/rest-cljer/6f5f25a433d9177949e2c6c32eb428197fdf4eae/test/rest_cljer/test/core.clj
clojure
(ns rest-cljer.test.core (:require [cheshire.core :as json] [clj-http.client :as http] [environ.core :refer [env]] [clojure.test :refer :all] [rest-cljer.core :refer [*rest-driver-port* json-capture rest-driven string-capture]]) (:import [com.github.restdriver.clientdriver ClientDriver ClientDriverRequest$Method] [com.github.restdriver.clientdriver.exception ClientDriverFailedExpectationException] [java.net SocketTimeoutException])) (defn local-path "Returns a URI to a resource on a free port, on localhost with the supplied postfix" [postfix] (str ":" *rest-driver-port* postfix)) (deftest rest-driven-call-succeeds-without-exceptions (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-returns-body-result (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-binary-body-succeeds-without-exceptions (let [resource-path "/some/resource/path" bytes (byte-array [(byte 10) (byte 20) (byte 30)])] (rest-driven [{:method :POST :url resource-path} {:status 200 :body bytes}] (is (= (seq bytes) (-> (http/post (local-path resource-path)) :body (.getBytes) seq)))))) (deftest unexpected-rest-driven-call-should-fail-with-exception (is (thrown? RuntimeException (rest-driven [] (http/post (local-path "/")))))) (deftest test-json-document-matching (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false}))))))) (deftest check-body-via-predicate (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body #(apply = (map sort [[3 2 1] %]))} {:status 204}] (is (= 204) (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string [1 3 2]) :throw-exceptions false})))))) (deftest check-body-via-predicate-with-type-as-string (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body [#(= "Hi" %) "application/text"]} {:status 204}] (is (= 204) (:status (http/post (local-path resource-path) {:content-type "application/text" :body "Hi" :throw-exceptions false})))))) (deftest check-body-via-predicate-order-independent (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :body [#(= "Hi" %) "application/text"]} {:status 204} {:method :POST :url resource-path :body [#(= "not-hi" %) "application/text"]} {:status 204}] (http/post (local-path resource-path) {:content-type "application/text" :body "not-hi" :throw-exceptions false}) (is (= 204 (:status (http/post (local-path resource-path) {:content-type "application/text" :body "Hi" :throw-exceptions false}))))))) (deftest json-document-capture-as-a-string (let [resource-path "/some/resource/path" capturer (string-capture)] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"} :capture capturer} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false})))) (is (= "{\"ping\":\"pong\"}" (capturer)))))) (deftest json-document-captured-and-parsed-using-json-capture (let [resource-path "/some/resource/path" capturer (json-capture)] (rest-driven [{:method :POST :url resource-path :body {:ping "pong"} :capture capturer} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:content-type :json :body (json/generate-string {:ping "pong"}) :throw-exceptions false})))) (is (= {:ping "pong"} (capturer)))))) (deftest sweetening-of-response-definitions (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path} {:body {:inigo "montoya"}}] (let [{:keys [status body headers]} (http/get (local-path resource-path))] (is (= 200 status)) (is (= "application/json" (get headers "Content-Type"))) (is (= {:inigo "montoya"} (json/parse-string body true))))))) (deftest sweetening-of-response-does-not-override-explicit-http-status (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path} {:status 400 :body {:inigo "montoya"}}] (let [{:keys [status body headers]} (http/get (local-path resource-path) {:throw-exceptions false})] (is (= 400 status)) (is (= "application/json" (get headers "Content-Type"))) (is (= {:inigo "montoya"} (json/parse-string body true))))))) (deftest post-processing-of-request-and-response-replacing-initial-values-with-new-ones-using-the-:and-function (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :and #(.withMethod % ClientDriverRequest$Method/POST)} {:status 204 :and #(.withStatus % 205)}] (is (= 205 (:status (http/post (local-path resource-path)))))))) (deftest response-can-be-repeated-any-times (let [resource-path "/some/resource/path"] (rest-driven [{:method :PUT :url resource-path} {:status 204 :times :any}] (dotimes [n 3] (is (= 204 (:status (http/put (local-path resource-path))))))))) (deftest response-can-be-repeated-a-specific-number-of-times (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 200 :times 2}] (dotimes [n 2] (is (= 200 (:status (http/post (local-path resource-path))))))) (is (thrown? Exception (rest-driven [{:method :POST :url resource-path} {:status 200 :times 2}] (dotimes [n 2] (is (= 200 (:status (http/post (local-path resource-path)))))) (http/post (local-path resource-path))))))) (deftest rest-driven-call-with-expected-header-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :headers {"from" "mytest" "with" "value"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:headers {"from" "mytest" "with" "value"}}))))))) (deftest rest-driven-call-with-expected-header-succeeds-with-keyord-header-names (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :headers {:from "myfrom" :with "value"}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path) {:headers {"from" "myfrom" "with" "value"}}))))))) (deftest rest-driven-call-with-missing-header-throws-exception (let [resource-path "/some/resource/path"] (is (thrown? Exception (rest-driven [{:method :POST :url resource-path :headers {"From" "origin"}} {:status 204}] (http/post (local-path resource-path))))))) (deftest rest-driven-call-without-header-that-is-expected-to-be-absent-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :not {:headers {"myheader" "myvalue"}}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-header-that-is-expected-to-be-absent-throw-exception (let [resource-path "/some/resource/path"] (is (thrown? RuntimeException (rest-driven [{:method :POST :url resource-path :not {:headers {"myheader" "myvalue"}}} {:status 204}] (http/post (local-path resource-path) {:headers {"myheader" "myvalue"}})))))) (deftest rest-driven-call-with-vector-of-headers-that-are-expected-to-be-absent-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path :not {:headers ["myheader"]}} {:status 204}] (is (= 204 (:status (http/post (local-path resource-path)))))))) (deftest rest-driven-call-with-vector-of-headers-that-are-expected-to-be-absent-throw-exception (let [resource-path "/some/resource/path"] (is (thrown? RuntimeException (rest-driven [{:method :POST :url resource-path :not {:headers ["myheader"]}} {:status 204}] (http/post (local-path resource-path) {:headers {"myheader" "myvalue"}})))))) (deftest rest-driven-call-with-response-headers-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204 :headers {"from" "rest-cljer", "with" "value"}}] (let [{:keys [status headers]} (http/post (local-path resource-path))] (is (= 204 status)) (is (= "rest-cljer" (get headers "From"))) (is (= "value" (get headers "with"))))))) (deftest can-supply-params-using-keywords-as-well-as-strings (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :params {:a "a" "b" "b"}} {:status 200}] (is (= 200 (:status (http/get (local-path (str resource-path "?a=a&b=b"))))))))) (deftest can-specify-:any-params (let [resource-path "/some/resource/path"] (rest-driven [{:method :GET :url resource-path :params :any} {:status 200}] (is (= 200 (:status (http/get (local-path resource-path)))))))) (deftest request-method-is-:GET-by-default (let [resource-path "/some/resource/path"] (rest-driven [{:url resource-path} {:status 200}] (is (= 200 (:status (http/get (local-path resource-path)))))))) (deftest request-response-can-be-paired-as-a-vector (let [resource-path "/some/resource/path"] (rest-driven [[{:url resource-path} {:status 201}] [{:url resource-path} {:status 202}]] (is (= 201 (:status (http/get (local-path resource-path))))) (is (= 202 (:status (http/get (local-path resource-path)))))))) (deftest expected-rest-driven-call-with-an-unusual-http-method-succeeds (let [resource-path "/some/resource/path"] (rest-driven [{:method "PATCH" :url resource-path} {:status 204}] (is (= 204 (:status (http/patch (local-path resource-path)))))))) (deftest expected-rest-driven-call-times-out-if-after-is-to-larger-than-socket-timeout (let [resource-path "/some/resource/path"] (rest-driven [{:url resource-path} {:status 200 :after 200}] (is (thrown? SocketTimeoutException (http/get (local-path resource-path) {:socket-timeout 100})))))) (deftest can-use-environ-to-provide-port (let [port (ClientDriver/getFreePort) original-env env] (try (alter-var-root (var env) assoc :restdriver-port port) (let [resource-path "/some/resource/path"] (rest-driven [{:method :POST :url resource-path} {:status 204}] (is (= 204 (:status (http/post (str ":" port resource-path))))))) (finally (alter-var-root (var env) (constantly original-env))))))
88ceb009c13cdc26ca27efd91c9e6c622c076ea7d7d22eb63039e814a3ea496f
thlack/surfs
conversations_select.clj
(ns ^:no-doc thlack.surfs.elements.spec.conversations-select (:require [clojure.spec.alpha :as s] [thlack.surfs.strings.spec :as strings.spec])) (s/def ::type #{:conversations_select}) (s/def ::initial_conversation ::strings.spec/id) (s/def ::default_to_current_conversation boolean?)
null
https://raw.githubusercontent.com/thlack/surfs/e03d137d6d43c4b73a45a71984cf084d2904c4b0/src/thlack/surfs/elements/spec/conversations_select.clj
clojure
(ns ^:no-doc thlack.surfs.elements.spec.conversations-select (:require [clojure.spec.alpha :as s] [thlack.surfs.strings.spec :as strings.spec])) (s/def ::type #{:conversations_select}) (s/def ::initial_conversation ::strings.spec/id) (s/def ::default_to_current_conversation boolean?)
bf44c5d95fe5d92efc0b60df49e49e27dfe55201d1677ac887c8aa93e1100737
mzp/coq-ide-for-ios
prettyp.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 *) (************************************************************************) Changed by ( and thus parts copyright © ) by < > * on May - June 2006 for implementation of abstraction of pretty - printing of objects . * on May-June 2006 for implementation of abstraction of pretty-printing of objects. *) $ I d : prettyp.ml 13967 2011 - 04 - 08 14:08:43Z herbelin $ open Pp open Util open Names open Nameops open Term open Termops open Declarations open Inductive open Inductiveops open Sign open Reduction open Environ open Declare open Impargs open Libobject open Printer open Printmod open Libnames open Nametab open Recordops type object_pr = { print_inductive : mutual_inductive -> std_ppcmds; print_constant_with_infos : constant -> std_ppcmds; print_section_variable : variable -> std_ppcmds; print_syntactic_def : kernel_name -> std_ppcmds; print_module : bool -> Names.module_path -> std_ppcmds; print_modtype : module_path -> std_ppcmds; print_named_decl : identifier * constr option * types -> std_ppcmds; print_leaf_entry : bool -> Libnames.object_name * Libobject.obj -> Pp.std_ppcmds; print_library_entry : bool -> (object_name * Lib.node) -> std_ppcmds option; print_context : bool -> int option -> Lib.library_segment -> std_ppcmds; print_typed_value_in_env : Environ.env -> Term.constr * Term.types -> Pp.std_ppcmds; print_eval : Reductionops.reduction_function -> env -> Evd.evar_map -> Topconstr.constr_expr -> unsafe_judgment -> std_ppcmds; } let gallina_print_module = print_module let gallina_print_modtype = print_modtype (**************) (** Utilities *) let print_closed_sections = ref false let pr_infos_list l = v 0 (prlist_with_sep cut (fun x -> x) l) ++ fnl() let with_line_skip l = if l = [] then mt() else fnl() ++ pr_infos_list l let blankline = mt() (* add a blank sentence in the list of infos *) let add_colon prefix = if ismt prefix then mt () else prefix ++ str ": " let int_or_no n = if n=0 then str "no" else int n (*******************) (** Basic printing *) let print_basename sp = pr_global (ConstRef sp) let print_ref reduce ref = let typ = Global.type_of_global ref in let typ = if reduce then let ctx,ccl = Reductionops.splay_prod_assum (Global.env()) Evd.empty typ in it_mkProd_or_LetIn ccl ctx else typ in hov 0 (pr_global ref ++ str " :" ++ spc () ++ pr_ltype typ) (********************************) (** Printing implicit arguments *) let conjugate_verb_to_be = function [_] -> "is" | _ -> "are" let pr_impl_name imp = pr_id (name_of_implicit imp) let print_impargs_by_name max = function | [] -> [] | impls -> [hov 0 (str (plural (List.length impls) "Argument") ++ spc() ++ prlist_with_sep pr_comma pr_impl_name impls ++ spc() ++ str (conjugate_verb_to_be impls) ++ str" implicit" ++ (if max then strbrk " and maximally inserted" else mt()))] let print_one_impargs_list l = let imps = List.filter is_status_implicit l in let maximps = List.filter Impargs.maximal_insertion_of imps in let nonmaximps = list_subtract imps maximps in print_impargs_by_name false nonmaximps @ print_impargs_by_name true maximps let print_impargs_list prefix l = let l = extract_impargs_data l in List.flatten (List.map (fun (cond,imps) -> match cond with | None -> List.map (fun pp -> add_colon prefix ++ pp) (print_one_impargs_list imps) | Some (n1,n2) -> [v 2 (prlist_with_sep cut (fun x -> x) [(if ismt prefix then str "When" else prefix ++ str ", when") ++ str " applied to " ++ (if n1 = n2 then int_or_no n2 else if n1 = 0 then str "less than " ++ int n2 else int n1 ++ str " to " ++ int_or_no n2) ++ str (plural n2 " argument") ++ str ":"; v 0 (prlist_with_sep cut (fun x -> x) (if List.exists is_status_implicit imps then print_one_impargs_list imps else [str "No implicit arguments"]))])]) l) let need_expansion impl ref = let typ = Global.type_of_global ref in let ctx = (prod_assum typ) in let nprods = List.length (List.filter (fun (_,b,_) -> b=None) ctx) in impl <> [] & List.length impl >= nprods & let _,lastimpl = list_chop nprods impl in List.filter is_status_implicit lastimpl <> [] let print_impargs ref = let ref = Smartlocate.smart_global ref in let impl = implicits_of_global ref in let has_impl = impl <> [] in (* Need to reduce since implicits are computed with products flattened *) pr_infos_list ([ print_ref (need_expansion (select_impargs_size 0 impl) ref) ref; blankline ] @ (if has_impl then print_impargs_list (mt()) impl else [str "No implicit arguments"])) (*********************) (** Printing Scopes *) let print_argument_scopes prefix = function | [Some sc] -> [add_colon prefix ++ str"Argument scope is [" ++ str sc ++ str"]"] | l when not (List.for_all ((=) None) l) -> [add_colon prefix ++ hov 2 (str"Argument scopes are" ++ spc() ++ str "[" ++ prlist_with_sep spc (function Some sc -> str sc | None -> str "_") l ++ str "]")] | _ -> [] (*********************) (** Printing Opacity *) type opacity = | FullyOpaque | TransparentMaybeOpacified of Conv_oracle.level let opacity env = function | VarRef v when pi2 (Environ.lookup_named v env) <> None -> Some(TransparentMaybeOpacified (Conv_oracle.get_strategy(VarKey v))) | ConstRef cst -> let cb = Environ.lookup_constant cst env in if cb.const_body = None then None else if cb.const_opaque then Some FullyOpaque else Some (TransparentMaybeOpacified (Conv_oracle.get_strategy(ConstKey cst))) | _ -> None let print_opacity ref = match opacity (Global.env()) ref with | None -> [] | Some s -> [pr_global ref ++ str " is " ++ str (match s with | FullyOpaque -> "opaque" | TransparentMaybeOpacified Conv_oracle.Opaque -> "basically transparent but considered opaque for reduction" | TransparentMaybeOpacified lev when lev = Conv_oracle.transparent -> "transparent" | TransparentMaybeOpacified (Conv_oracle.Level n) -> "transparent (with expansion weight "^string_of_int n^")" | TransparentMaybeOpacified Conv_oracle.Expand -> "transparent (with minimal expansion weight)")] (*******************) (* *) let print_name_infos ref = let impls = implicits_of_global ref in let scopes = Notation.find_arguments_scope ref in let type_info_for_implicit = if need_expansion (select_impargs_size 0 impls) ref then (* Need to reduce since implicits are computed with products flattened *) [str "Expanded type for implicit arguments"; print_ref true ref; blankline] else [] in type_info_for_implicit @ print_impargs_list (mt()) impls @ print_argument_scopes (mt()) scopes let print_id_args_data test pr id l = if List.exists test l then pr (str "For " ++ pr_id id) l else [] let print_args_data_of_inductive_ids get test pr sp mipv = List.flatten (Array.to_list (Array.mapi (fun i mip -> print_id_args_data test pr mip.mind_typename (get (IndRef (sp,i))) @ List.flatten (Array.to_list (Array.mapi (fun j idc -> print_id_args_data test pr idc (get (ConstructRef ((sp,i),j+1)))) mip.mind_consnames))) mipv)) let print_inductive_implicit_args = print_args_data_of_inductive_ids implicits_of_global (fun l -> positions_of_implicits l <> []) print_impargs_list let print_inductive_argument_scopes = print_args_data_of_inductive_ids Notation.find_arguments_scope ((<>) None) print_argument_scopes (*********************) (* "Locate" commands *) type logical_name = | Term of global_reference | Dir of global_dir_reference | Syntactic of kernel_name | ModuleType of qualid * module_path | Undefined of qualid let locate_any_name ref = let module N = Nametab in let (loc,qid) = qualid_of_reference ref in try Term (N.locate qid) with Not_found -> try Syntactic (N.locate_syndef qid) with Not_found -> try Dir (N.locate_dir qid) with Not_found -> try ModuleType (qid, N.locate_modtype qid) with Not_found -> Undefined qid let pr_located_qualid = function | Term ref -> let ref_str = match ref with ConstRef _ -> "Constant" | IndRef _ -> "Inductive" | ConstructRef _ -> "Constructor" | VarRef _ -> "Variable" in str ref_str ++ spc () ++ pr_path (Nametab.path_of_global ref) | Syntactic kn -> str "Notation" ++ spc () ++ pr_path (Nametab.path_of_syndef kn) | Dir dir -> let s,dir = match dir with | DirOpenModule (dir,_) -> "Open Module", dir | DirOpenModtype (dir,_) -> "Open Module Type", dir | DirOpenSection (dir,_) -> "Open Section", dir | DirModule (dir,_) -> "Module", dir | DirClosedSection dir -> "Closed Section", dir in str s ++ spc () ++ pr_dirpath dir | ModuleType (qid,_) -> str "Module Type" ++ spc () ++ pr_path (Nametab.full_name_modtype qid) | Undefined qid -> pr_qualid qid ++ spc () ++ str "not a defined object." let print_located_qualid ref = let (loc,qid) = qualid_of_reference ref in let module N = Nametab in let expand = function | TrueGlobal ref -> Term ref, N.shortest_qualid_of_global Idset.empty ref | SynDef kn -> Syntactic kn, N.shortest_qualid_of_syndef Idset.empty kn in match List.map expand (N.locate_extended_all qid) with | [] -> let (dir,id) = repr_qualid qid in if dir = empty_dirpath then str "No object of basename " ++ pr_id id else str "No object of suffix " ++ pr_qualid qid | l -> prlist_with_sep fnl (fun (o,oqid) -> hov 2 (pr_located_qualid o ++ (if oqid <> qid then spc() ++ str "(shorter name to refer to it in current context is " ++ pr_qualid oqid ++ str")" else mt ()))) l (******************************************) (**** Printing declarations and judgments *) * * * layer * * * * let gallina_print_typed_value_in_env env (trm,typ) = (pr_lconstr_env env trm ++ fnl () ++ str " : " ++ pr_ltype_env env typ ++ fnl ()) (* To be improved; the type should be used to provide the types in the abstractions. This should be done recursively inside pr_lconstr, so that the pretty-print of a proposition (P:(nat->nat)->Prop)(P [u]u) synthesizes the type nat of the abstraction on u *) let print_named_def name body typ = let pbody = pr_lconstr body in let ptyp = pr_ltype typ in let pbody = if isCast body then surround pbody else pbody in (str "*** [" ++ str name ++ str " " ++ hov 0 (str ":=" ++ brk (1,2) ++ pbody ++ spc () ++ str ":" ++ brk (1,2) ++ ptyp) ++ str "]") let print_named_assum name typ = str "*** [" ++ str name ++ str " : " ++ pr_ltype typ ++ str "]" let gallina_print_named_decl (id,c,typ) = let s = string_of_id id in match c with | Some body -> print_named_def s body typ | None -> print_named_assum s typ let assumptions_for_print lna = List.fold_right (fun na env -> add_name na env) lna empty_names_context (*********************) (* *) let print_params env params = if params = [] then mt () else pr_rel_context env params ++ brk(1,2) let print_constructors envpar names types = let pc = prlist_with_sep (fun () -> brk(1,0) ++ str "| ") (fun (id,c) -> pr_id id ++ str " : " ++ pr_lconstr_env envpar c) (Array.to_list (array_map2 (fun n t -> (n,t)) names types)) in hv 0 (str " " ++ pc) let build_inductive sp tyi = let (mib,mip) = Global.lookup_inductive (sp,tyi) in let params = mib.mind_params_ctxt in let args = extended_rel_list 0 params in let env = Global.env() in let fullarity = match mip.mind_arity with | Monomorphic ar -> ar.mind_user_arity | Polymorphic ar -> it_mkProd_or_LetIn (mkSort (Type ar.poly_level)) mip.mind_arity_ctxt in let arity = hnf_prod_applist env fullarity args in let cstrtypes = type_of_constructors env (sp,tyi) in let cstrtypes = Array.map (fun c -> hnf_prod_applist env c args) cstrtypes in let cstrnames = mip.mind_consnames in (IndRef (sp,tyi), params, arity, cstrnames, cstrtypes) let print_one_inductive (sp,tyi) = let (ref, params, arity, cstrnames, cstrtypes) = build_inductive sp tyi in let env = Global.env () in let envpar = push_rel_context params env in hov 0 ( pr_global (IndRef (sp,tyi)) ++ brk(1,4) ++ print_params env params ++ str ": " ++ pr_lconstr_env envpar arity ++ str " :=") ++ brk(0,2) ++ print_constructors envpar cstrnames cstrtypes let pr_mutual_inductive finite indl = hov 0 ( str (if finite then "Inductive " else "CoInductive ") ++ prlist_with_sep (fun () -> fnl () ++ str" with ") print_one_inductive indl) let get_fields = let rec prodec_rec l subst c = match kind_of_term c with | Prod (na,t,c) -> let id = match na with Name id -> id | Anonymous -> id_of_string "_" in prodec_rec ((id,true,substl subst t)::l) (mkVar id::subst) c | LetIn (na,b,_,c) -> let id = match na with Name id -> id | Anonymous -> id_of_string "_" in prodec_rec ((id,false,substl subst b)::l) (mkVar id::subst) c | _ -> List.rev l in prodec_rec [] [] let pr_record (sp,tyi) = let (ref, params, arity, cstrnames, cstrtypes) = build_inductive sp tyi in let env = Global.env () in let envpar = push_rel_context params env in let fields = get_fields cstrtypes.(0) in hov 0 ( hov 0 ( str "Record " ++ pr_global (IndRef (sp,tyi)) ++ brk(1,4) ++ print_params env params ++ str ": " ++ pr_lconstr_env envpar arity ++ brk(1,2) ++ str ":= " ++ pr_id cstrnames.(0)) ++ brk(1,2) ++ hv 2 (str "{ " ++ prlist_with_sep (fun () -> str ";" ++ brk(2,0)) (fun (id,b,c) -> pr_id id ++ str (if b then " : " else " := ") ++ pr_lconstr_env envpar c) fields) ++ str" }") let gallina_print_inductive sp = let (mib,mip) = Global.lookup_inductive (sp,0) in let mipv = mib.mind_packets in let names = list_tabulate (fun x -> (sp,x)) (Array.length mipv) in (if mib.mind_record & not !Flags.raw_print then pr_record (List.hd names) else pr_mutual_inductive mib.mind_finite names) ++ fnl () ++ with_line_skip (print_inductive_implicit_args sp mipv @ print_inductive_argument_scopes sp mipv) let print_named_decl id = gallina_print_named_decl (Global.lookup_named id) ++ fnl () let gallina_print_section_variable id = print_named_decl id ++ with_line_skip (print_name_infos (VarRef id)) let print_body = function | Some lc -> pr_lconstr (Declarations.force lc) | None -> (str"<no body>") let print_typed_body (val_0,typ) = (print_body val_0 ++ fnl () ++ str " : " ++ pr_ltype typ) let ungeneralized_type_of_constant_type = function | PolymorphicArity (ctx,a) -> mkArity (ctx, Type a.poly_level) | NonPolymorphicType t -> t let print_constant with_values sep sp = let cb = Global.lookup_constant sp in let val_0 = cb.const_body in let typ = ungeneralized_type_of_constant_type cb.const_type in hov 0 ( match val_0 with | None -> str"*** [ " ++ print_basename sp ++ str " : " ++ cut () ++ pr_ltype typ ++ str" ]" | _ -> print_basename sp ++ str sep ++ cut () ++ (if with_values then print_typed_body (val_0,typ) else pr_ltype typ)) ++ fnl () let gallina_print_constant_with_infos sp = print_constant true " = " sp ++ with_line_skip (print_name_infos (ConstRef sp)) let gallina_print_syntactic_def kn = let qid = Nametab.shortest_qualid_of_syndef Idset.empty kn and (vars,a) = Syntax_def.search_syntactic_definition kn in let c = Topconstr.rawconstr_of_aconstr dummy_loc a in hov 2 (hov 4 (str "Notation " ++ pr_qualid qid ++ prlist (fun id -> spc () ++ pr_id id) (List.map fst vars) ++ spc () ++ str ":=") ++ spc () ++ Constrextern.without_symbols pr_rawconstr c) ++ fnl () let gallina_print_leaf_entry with_values ((sp,kn as oname),lobj) = let sep = if with_values then " = " else " : " and tag = object_tag lobj in match (oname,tag) with | (_,"VARIABLE") -> (* Outside sections, VARIABLES still exist but only with universes constraints *) (try Some(print_named_decl (basename sp)) with Not_found -> None) | (_,"CONSTANT") -> Some (print_constant with_values sep (constant_of_kn kn)) | (_,"INDUCTIVE") -> Some (gallina_print_inductive (mind_of_kn kn)) | (_,"MODULE") -> let (mp,_,l) = repr_kn kn in Some (print_module with_values (MPdot (mp,l))) | (_,"MODULE TYPE") -> let (mp,_,l) = repr_kn kn in Some (print_modtype (MPdot (mp,l))) | (_,("AUTOHINT"|"GRAMMAR"|"SYNTAXCONSTANT"|"PPSYNTAX"|"TOKEN"|"CLASS"| "COERCION"|"REQUIRE"|"END-SECTION"|"STRUCTURE")) -> None (* To deal with forgotten cases... *) | (_,s) -> None let gallina_print_library_entry with_values ent = let pr_name (sp,_) = pr_id (basename sp) in match ent with | (oname,Lib.Leaf lobj) -> gallina_print_leaf_entry with_values (oname,lobj) | (oname,Lib.OpenedSection (dir,_)) -> Some (str " >>>>>>> Section " ++ pr_name oname) | (oname,Lib.ClosedSection _) -> Some (str " >>>>>>> Closed Section " ++ pr_name oname) | (_,Lib.CompilingLibrary (dir,_)) -> Some (str " >>>>>>> Library " ++ pr_dirpath dir) | (oname,Lib.OpenedModule _) -> Some (str " >>>>>>> Module " ++ pr_name oname) | (oname,Lib.ClosedModule _) -> Some (str " >>>>>>> Closed Module " ++ pr_name oname) | (oname,Lib.OpenedModtype _) -> Some (str " >>>>>>> Module Type " ++ pr_name oname) | (oname,Lib.ClosedModtype _) -> Some (str " >>>>>>> Closed Module Type " ++ pr_name oname) | (_,Lib.FrozenState _) -> None let gallina_print_leaf_entry with_values c = match gallina_print_leaf_entry with_values c with | None -> mt () | Some pp -> pp ++ fnl() let gallina_print_context with_values = let rec prec n = function | h::rest when n = None or Option.get n > 0 -> (match gallina_print_library_entry with_values h with | None -> prec n rest | Some pp -> prec (Option.map ((+) (-1)) n) rest ++ pp ++ fnl ()) | _ -> mt () in prec let gallina_print_eval red_fun env evmap _ {uj_val=trm;uj_type=typ} = let ntrm = red_fun env evmap trm in (str " = " ++ gallina_print_typed_value_in_env env (ntrm,typ)) (******************************************) (**** Printing abstraction layer *) let default_object_pr = { print_inductive = gallina_print_inductive; print_constant_with_infos = gallina_print_constant_with_infos; print_section_variable = gallina_print_section_variable; print_syntactic_def = gallina_print_syntactic_def; print_module = gallina_print_module; print_modtype = gallina_print_modtype; print_named_decl = gallina_print_named_decl; print_leaf_entry = gallina_print_leaf_entry; print_library_entry = gallina_print_library_entry; print_context = gallina_print_context; print_typed_value_in_env = gallina_print_typed_value_in_env; print_eval = gallina_print_eval; } let object_pr = ref default_object_pr let set_object_pr = (:=) object_pr let print_inductive x = !object_pr.print_inductive x let print_constant_with_infos c = !object_pr.print_constant_with_infos c let print_section_variable c = !object_pr.print_section_variable c let print_syntactic_def x = !object_pr.print_syntactic_def x let print_module x = !object_pr.print_module x let print_modtype x = !object_pr.print_modtype x let print_named_decl x = !object_pr.print_named_decl x let print_leaf_entry x = !object_pr.print_leaf_entry x let print_library_entry x = !object_pr.print_library_entry x let print_context x = !object_pr.print_context x let print_typed_value_in_env x = !object_pr.print_typed_value_in_env x let print_eval x = !object_pr.print_eval x (******************************************) (**** Printing declarations and judgments *) (**** Abstract layer *****) let print_typed_value x = print_typed_value_in_env (Global.env ()) x let print_judgment env {uj_val=trm;uj_type=typ} = print_typed_value_in_env env (trm, typ) let print_safe_judgment env j = let trm = Safe_typing.j_val j in let typ = Safe_typing.j_type j in print_typed_value_in_env env (trm, typ) (*********************) (* *) let print_full_context () = print_context true None (Lib.contents_after None) let print_full_context_typ () = print_context false None (Lib.contents_after None) let print_full_pure_context () = let rec prec = function | ((_,kn),Lib.Leaf lobj)::rest -> let pp = match object_tag lobj with | "CONSTANT" -> let con = Global.constant_of_delta (constant_of_kn kn) in let cb = Global.lookup_constant con in let val_0 = cb.const_body in let typ = ungeneralized_type_of_constant_type cb.const_type in hov 0 ( match val_0 with | None -> str (if cb.const_opaque then "Axiom " else "Parameter ") ++ print_basename con ++ str " : " ++ cut () ++ pr_ltype typ | Some v -> if cb.const_opaque then str "Theorem " ++ print_basename con ++ cut () ++ str " : " ++ pr_ltype typ ++ str "." ++ fnl () ++ str "Proof " ++ print_body val_0 else str "Definition " ++ print_basename con ++ cut () ++ str " : " ++ pr_ltype typ ++ cut () ++ str " := " ++ print_body val_0) ++ str "." ++ fnl () ++ fnl () | "INDUCTIVE" -> let mind = Global.mind_of_delta (mind_of_kn kn) in let (mib,mip) = Global.lookup_inductive (mind,0) in let mipv = mib.mind_packets in let names = list_tabulate (fun x -> (mind,x)) (Array.length mipv) in pr_mutual_inductive mib.mind_finite names ++ str "." ++ fnl () ++ fnl () | "MODULE" -> (* TODO: make it reparsable *) let (mp,_,l) = repr_kn kn in print_module true (MPdot (mp,l)) ++ str "." ++ fnl () ++ fnl () | "MODULE TYPE" -> (* TODO: make it reparsable *) (* TODO: make it reparsable *) let (mp,_,l) = repr_kn kn in print_modtype (MPdot (mp,l)) ++ str "." ++ fnl () ++ fnl () | _ -> mt () in prec rest ++ pp | _::rest -> prec rest | _ -> mt () in prec (Lib.contents_after None) (* For printing an inductive definition with its constructors and elimination, assume that the declaration of constructors and eliminations follows the definition of the inductive type *) let list_filter_vec f vec = let rec frec n lf = if n < 0 then lf else if f vec.(n) then frec (n-1) (vec.(n)::lf) else frec (n-1) lf in frec (Array.length vec -1) [] (* This is designed to print the contents of an opened section *) let read_sec_context r = let loc,qid = qualid_of_reference r in let dir = try Nametab.locate_section qid with Not_found -> user_err_loc (loc,"read_sec_context", str "Unknown section.") in let rec get_cxt in_cxt = function | (_,Lib.OpenedSection ((dir',_),_) as hd)::rest -> if dir = dir' then (hd::in_cxt) else get_cxt (hd::in_cxt) rest | (_,Lib.ClosedSection _)::rest -> error "Cannot print the contents of a closed section." (* LEM: Actually, we could if we wanted to. *) | [] -> [] | hd::rest -> get_cxt (hd::in_cxt) rest in let cxt = (Lib.contents_after None) in List.rev (get_cxt [] cxt) let print_sec_context sec = print_context true None (read_sec_context sec) let print_sec_context_typ sec = print_context false None (read_sec_context sec) let print_any_name = function | Term (ConstRef sp) -> print_constant_with_infos sp | Term (IndRef (sp,_)) -> print_inductive sp | Term (ConstructRef ((sp,_),_)) -> print_inductive sp | Term (VarRef sp) -> print_section_variable sp | Syntactic kn -> print_syntactic_def kn | Dir (DirModule(dirpath,(mp,_))) -> print_module (printable_body dirpath) mp | Dir _ -> mt () | ModuleType (_,kn) -> print_modtype kn | Undefined qid -> Var locale de but , pas var de section ... pas d'implicits let dir,str = repr_qualid qid in if (repr_dirpath dir) <> [] then raise Not_found; let (_,c,typ) = Global.lookup_named str in (print_named_decl (str,c,typ)) with Not_found -> errorlabstrm "print_name" (pr_qualid qid ++ spc () ++ str "not a defined object.") let print_name = function | Genarg.ByNotation (loc,ntn,sc) -> print_any_name (Term (Notation.interp_notation_as_global_reference loc (fun _ -> true) ntn sc)) | Genarg.AN ref -> print_any_name (locate_any_name ref) let print_opaque_name qid = let env = Global.env () in match global qid with | ConstRef cst -> let cb = Global.lookup_constant cst in if cb.const_body <> None then print_constant_with_infos cst else error "Not a defined constant." | IndRef (sp,_) -> print_inductive sp | ConstructRef cstr -> let ty = Inductiveops.type_of_constructor env cstr in print_typed_value (mkConstruct cstr, ty) | VarRef id -> let (_,c,ty) = lookup_named id env in print_named_decl (id,c,ty) let print_about_any k = match k with | Term ref -> pr_infos_list ([print_ref false ref; blankline] @ print_name_infos ref @ print_opacity ref @ [hov 0 (str "Expands to: " ++ pr_located_qualid k)]) | Syntactic kn -> v 0 ( print_syntactic_def kn ++ hov 0 (str "Expands to: " ++ pr_located_qualid k)) ++ fnl() | Dir _ | ModuleType _ | Undefined _ -> hov 0 (pr_located_qualid k) ++ fnl() let print_about = function | Genarg.ByNotation (loc,ntn,sc) -> print_about_any (Term (Notation.interp_notation_as_global_reference loc (fun _ -> true) ntn sc)) | Genarg.AN ref -> print_about_any (locate_any_name ref) let unfold_head_fconst = let rec unfrec k = match kind_of_term k with | Const cst -> constant_value (Global.env ()) cst | Lambda (na,t,b) -> mkLambda (na,t,unfrec b) | App (f,v) -> appvect (unfrec f,v) | _ -> k in unfrec (* for debug *) let inspect depth = print_context false (Some depth) (Lib.contents_after None) (*************************************************************************) (* Pretty-printing functions coming from classops.ml *) open Classops let print_coercion_value v = pr_lconstr (get_coercion_value v) let print_class i = let cl,_ = class_info_from_index i in pr_class cl let print_path ((i,j),p) = hov 2 ( str"[" ++ hov 0 (prlist_with_sep pr_semicolon print_coercion_value p) ++ str"] : ") ++ print_class i ++ str" >-> " ++ print_class j let _ = Classops.install_path_printer print_path let print_graph () = prlist_with_sep pr_fnl print_path (inheritance_graph()) let print_classes () = prlist_with_sep pr_spc pr_class (classes()) let print_coercions () = prlist_with_sep pr_spc print_coercion_value (coercions()) let index_of_class cl = try fst (class_info cl) with _ -> errorlabstrm "index_of_class" (pr_class cl ++ spc() ++ str "not a defined class.") let print_path_between cls clt = let i = index_of_class cls in let j = index_of_class clt in let p = try lookup_path_between_class (i,j) with _ -> errorlabstrm "index_cl_of_id" (str"No path between " ++ pr_class cls ++ str" and " ++ pr_class clt ++ str ".") in print_path ((i,j),p) let print_canonical_projections () = prlist_with_sep pr_fnl (fun ((r1,r2),o) -> pr_cs_pattern r2 ++ str " <- " ++ pr_global r1 ++ str " ( " ++ pr_lconstr o.o_DEF ++ str " )") (canonical_projections ()) (*************************************************************************) (*************************************************************************) (* Pretty-printing functions for type classes *) open Typeclasses let pr_typeclass env t = print_ref false t.cl_impl ++ fnl () let print_typeclasses () = let env = Global.env () in prlist_with_sep fnl (pr_typeclass env) (typeclasses ()) let pr_instance env i = gallina_print_constant_with_infos i.is_impl (* lighter *) print_ref false (instance_impl i) ++ fnl () let print_all_instances () = let env = Global.env () in let inst = all_instances () in prlist_with_sep fnl (pr_instance env) inst let print_instances r = let env = Global.env () in let inst = instances r in prlist_with_sep fnl (pr_instance env) inst
null
https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/parsing/prettyp.ml
ocaml
********************************************************************** // * This file is distributed under the terms of the * GNU Lesser General Public License Version 2.1 ********************************************************************** ************ * Utilities add a blank sentence in the list of infos ***************** * Basic printing ****************************** * Printing implicit arguments Need to reduce since implicits are computed with products flattened ******************* * Printing Scopes ******************* * Printing Opacity ***************** Need to reduce since implicits are computed with products flattened ******************* "Locate" commands **************************************** *** Printing declarations and judgments To be improved; the type should be used to provide the types in the abstractions. This should be done recursively inside pr_lconstr, so that the pretty-print of a proposition (P:(nat->nat)->Prop)(P [u]u) synthesizes the type nat of the abstraction on u ******************* Outside sections, VARIABLES still exist but only with universes constraints To deal with forgotten cases... **************************************** *** Printing abstraction layer **************************************** *** Printing declarations and judgments *** Abstract layer **** ******************* TODO: make it reparsable TODO: make it reparsable TODO: make it reparsable For printing an inductive definition with its constructors and elimination, assume that the declaration of constructors and eliminations follows the definition of the inductive type This is designed to print the contents of an opened section LEM: Actually, we could if we wanted to. for debug *********************************************************************** Pretty-printing functions coming from classops.ml *********************************************************************** *********************************************************************** Pretty-printing functions for type classes lighter
v * The Coq Proof Assistant / The Coq Development Team < O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010 \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Changed by ( and thus parts copyright © ) by < > * on May - June 2006 for implementation of abstraction of pretty - printing of objects . * on May-June 2006 for implementation of abstraction of pretty-printing of objects. *) $ I d : prettyp.ml 13967 2011 - 04 - 08 14:08:43Z herbelin $ open Pp open Util open Names open Nameops open Term open Termops open Declarations open Inductive open Inductiveops open Sign open Reduction open Environ open Declare open Impargs open Libobject open Printer open Printmod open Libnames open Nametab open Recordops type object_pr = { print_inductive : mutual_inductive -> std_ppcmds; print_constant_with_infos : constant -> std_ppcmds; print_section_variable : variable -> std_ppcmds; print_syntactic_def : kernel_name -> std_ppcmds; print_module : bool -> Names.module_path -> std_ppcmds; print_modtype : module_path -> std_ppcmds; print_named_decl : identifier * constr option * types -> std_ppcmds; print_leaf_entry : bool -> Libnames.object_name * Libobject.obj -> Pp.std_ppcmds; print_library_entry : bool -> (object_name * Lib.node) -> std_ppcmds option; print_context : bool -> int option -> Lib.library_segment -> std_ppcmds; print_typed_value_in_env : Environ.env -> Term.constr * Term.types -> Pp.std_ppcmds; print_eval : Reductionops.reduction_function -> env -> Evd.evar_map -> Topconstr.constr_expr -> unsafe_judgment -> std_ppcmds; } let gallina_print_module = print_module let gallina_print_modtype = print_modtype let print_closed_sections = ref false let pr_infos_list l = v 0 (prlist_with_sep cut (fun x -> x) l) ++ fnl() let with_line_skip l = if l = [] then mt() else fnl() ++ pr_infos_list l let add_colon prefix = if ismt prefix then mt () else prefix ++ str ": " let int_or_no n = if n=0 then str "no" else int n let print_basename sp = pr_global (ConstRef sp) let print_ref reduce ref = let typ = Global.type_of_global ref in let typ = if reduce then let ctx,ccl = Reductionops.splay_prod_assum (Global.env()) Evd.empty typ in it_mkProd_or_LetIn ccl ctx else typ in hov 0 (pr_global ref ++ str " :" ++ spc () ++ pr_ltype typ) let conjugate_verb_to_be = function [_] -> "is" | _ -> "are" let pr_impl_name imp = pr_id (name_of_implicit imp) let print_impargs_by_name max = function | [] -> [] | impls -> [hov 0 (str (plural (List.length impls) "Argument") ++ spc() ++ prlist_with_sep pr_comma pr_impl_name impls ++ spc() ++ str (conjugate_verb_to_be impls) ++ str" implicit" ++ (if max then strbrk " and maximally inserted" else mt()))] let print_one_impargs_list l = let imps = List.filter is_status_implicit l in let maximps = List.filter Impargs.maximal_insertion_of imps in let nonmaximps = list_subtract imps maximps in print_impargs_by_name false nonmaximps @ print_impargs_by_name true maximps let print_impargs_list prefix l = let l = extract_impargs_data l in List.flatten (List.map (fun (cond,imps) -> match cond with | None -> List.map (fun pp -> add_colon prefix ++ pp) (print_one_impargs_list imps) | Some (n1,n2) -> [v 2 (prlist_with_sep cut (fun x -> x) [(if ismt prefix then str "When" else prefix ++ str ", when") ++ str " applied to " ++ (if n1 = n2 then int_or_no n2 else if n1 = 0 then str "less than " ++ int n2 else int n1 ++ str " to " ++ int_or_no n2) ++ str (plural n2 " argument") ++ str ":"; v 0 (prlist_with_sep cut (fun x -> x) (if List.exists is_status_implicit imps then print_one_impargs_list imps else [str "No implicit arguments"]))])]) l) let need_expansion impl ref = let typ = Global.type_of_global ref in let ctx = (prod_assum typ) in let nprods = List.length (List.filter (fun (_,b,_) -> b=None) ctx) in impl <> [] & List.length impl >= nprods & let _,lastimpl = list_chop nprods impl in List.filter is_status_implicit lastimpl <> [] let print_impargs ref = let ref = Smartlocate.smart_global ref in let impl = implicits_of_global ref in let has_impl = impl <> [] in pr_infos_list ([ print_ref (need_expansion (select_impargs_size 0 impl) ref) ref; blankline ] @ (if has_impl then print_impargs_list (mt()) impl else [str "No implicit arguments"])) let print_argument_scopes prefix = function | [Some sc] -> [add_colon prefix ++ str"Argument scope is [" ++ str sc ++ str"]"] | l when not (List.for_all ((=) None) l) -> [add_colon prefix ++ hov 2 (str"Argument scopes are" ++ spc() ++ str "[" ++ prlist_with_sep spc (function Some sc -> str sc | None -> str "_") l ++ str "]")] | _ -> [] type opacity = | FullyOpaque | TransparentMaybeOpacified of Conv_oracle.level let opacity env = function | VarRef v when pi2 (Environ.lookup_named v env) <> None -> Some(TransparentMaybeOpacified (Conv_oracle.get_strategy(VarKey v))) | ConstRef cst -> let cb = Environ.lookup_constant cst env in if cb.const_body = None then None else if cb.const_opaque then Some FullyOpaque else Some (TransparentMaybeOpacified (Conv_oracle.get_strategy(ConstKey cst))) | _ -> None let print_opacity ref = match opacity (Global.env()) ref with | None -> [] | Some s -> [pr_global ref ++ str " is " ++ str (match s with | FullyOpaque -> "opaque" | TransparentMaybeOpacified Conv_oracle.Opaque -> "basically transparent but considered opaque for reduction" | TransparentMaybeOpacified lev when lev = Conv_oracle.transparent -> "transparent" | TransparentMaybeOpacified (Conv_oracle.Level n) -> "transparent (with expansion weight "^string_of_int n^")" | TransparentMaybeOpacified Conv_oracle.Expand -> "transparent (with minimal expansion weight)")] let print_name_infos ref = let impls = implicits_of_global ref in let scopes = Notation.find_arguments_scope ref in let type_info_for_implicit = if need_expansion (select_impargs_size 0 impls) ref then [str "Expanded type for implicit arguments"; print_ref true ref; blankline] else [] in type_info_for_implicit @ print_impargs_list (mt()) impls @ print_argument_scopes (mt()) scopes let print_id_args_data test pr id l = if List.exists test l then pr (str "For " ++ pr_id id) l else [] let print_args_data_of_inductive_ids get test pr sp mipv = List.flatten (Array.to_list (Array.mapi (fun i mip -> print_id_args_data test pr mip.mind_typename (get (IndRef (sp,i))) @ List.flatten (Array.to_list (Array.mapi (fun j idc -> print_id_args_data test pr idc (get (ConstructRef ((sp,i),j+1)))) mip.mind_consnames))) mipv)) let print_inductive_implicit_args = print_args_data_of_inductive_ids implicits_of_global (fun l -> positions_of_implicits l <> []) print_impargs_list let print_inductive_argument_scopes = print_args_data_of_inductive_ids Notation.find_arguments_scope ((<>) None) print_argument_scopes type logical_name = | Term of global_reference | Dir of global_dir_reference | Syntactic of kernel_name | ModuleType of qualid * module_path | Undefined of qualid let locate_any_name ref = let module N = Nametab in let (loc,qid) = qualid_of_reference ref in try Term (N.locate qid) with Not_found -> try Syntactic (N.locate_syndef qid) with Not_found -> try Dir (N.locate_dir qid) with Not_found -> try ModuleType (qid, N.locate_modtype qid) with Not_found -> Undefined qid let pr_located_qualid = function | Term ref -> let ref_str = match ref with ConstRef _ -> "Constant" | IndRef _ -> "Inductive" | ConstructRef _ -> "Constructor" | VarRef _ -> "Variable" in str ref_str ++ spc () ++ pr_path (Nametab.path_of_global ref) | Syntactic kn -> str "Notation" ++ spc () ++ pr_path (Nametab.path_of_syndef kn) | Dir dir -> let s,dir = match dir with | DirOpenModule (dir,_) -> "Open Module", dir | DirOpenModtype (dir,_) -> "Open Module Type", dir | DirOpenSection (dir,_) -> "Open Section", dir | DirModule (dir,_) -> "Module", dir | DirClosedSection dir -> "Closed Section", dir in str s ++ spc () ++ pr_dirpath dir | ModuleType (qid,_) -> str "Module Type" ++ spc () ++ pr_path (Nametab.full_name_modtype qid) | Undefined qid -> pr_qualid qid ++ spc () ++ str "not a defined object." let print_located_qualid ref = let (loc,qid) = qualid_of_reference ref in let module N = Nametab in let expand = function | TrueGlobal ref -> Term ref, N.shortest_qualid_of_global Idset.empty ref | SynDef kn -> Syntactic kn, N.shortest_qualid_of_syndef Idset.empty kn in match List.map expand (N.locate_extended_all qid) with | [] -> let (dir,id) = repr_qualid qid in if dir = empty_dirpath then str "No object of basename " ++ pr_id id else str "No object of suffix " ++ pr_qualid qid | l -> prlist_with_sep fnl (fun (o,oqid) -> hov 2 (pr_located_qualid o ++ (if oqid <> qid then spc() ++ str "(shorter name to refer to it in current context is " ++ pr_qualid oqid ++ str")" else mt ()))) l * * * layer * * * * let gallina_print_typed_value_in_env env (trm,typ) = (pr_lconstr_env env trm ++ fnl () ++ str " : " ++ pr_ltype_env env typ ++ fnl ()) let print_named_def name body typ = let pbody = pr_lconstr body in let ptyp = pr_ltype typ in let pbody = if isCast body then surround pbody else pbody in (str "*** [" ++ str name ++ str " " ++ hov 0 (str ":=" ++ brk (1,2) ++ pbody ++ spc () ++ str ":" ++ brk (1,2) ++ ptyp) ++ str "]") let print_named_assum name typ = str "*** [" ++ str name ++ str " : " ++ pr_ltype typ ++ str "]" let gallina_print_named_decl (id,c,typ) = let s = string_of_id id in match c with | Some body -> print_named_def s body typ | None -> print_named_assum s typ let assumptions_for_print lna = List.fold_right (fun na env -> add_name na env) lna empty_names_context let print_params env params = if params = [] then mt () else pr_rel_context env params ++ brk(1,2) let print_constructors envpar names types = let pc = prlist_with_sep (fun () -> brk(1,0) ++ str "| ") (fun (id,c) -> pr_id id ++ str " : " ++ pr_lconstr_env envpar c) (Array.to_list (array_map2 (fun n t -> (n,t)) names types)) in hv 0 (str " " ++ pc) let build_inductive sp tyi = let (mib,mip) = Global.lookup_inductive (sp,tyi) in let params = mib.mind_params_ctxt in let args = extended_rel_list 0 params in let env = Global.env() in let fullarity = match mip.mind_arity with | Monomorphic ar -> ar.mind_user_arity | Polymorphic ar -> it_mkProd_or_LetIn (mkSort (Type ar.poly_level)) mip.mind_arity_ctxt in let arity = hnf_prod_applist env fullarity args in let cstrtypes = type_of_constructors env (sp,tyi) in let cstrtypes = Array.map (fun c -> hnf_prod_applist env c args) cstrtypes in let cstrnames = mip.mind_consnames in (IndRef (sp,tyi), params, arity, cstrnames, cstrtypes) let print_one_inductive (sp,tyi) = let (ref, params, arity, cstrnames, cstrtypes) = build_inductive sp tyi in let env = Global.env () in let envpar = push_rel_context params env in hov 0 ( pr_global (IndRef (sp,tyi)) ++ brk(1,4) ++ print_params env params ++ str ": " ++ pr_lconstr_env envpar arity ++ str " :=") ++ brk(0,2) ++ print_constructors envpar cstrnames cstrtypes let pr_mutual_inductive finite indl = hov 0 ( str (if finite then "Inductive " else "CoInductive ") ++ prlist_with_sep (fun () -> fnl () ++ str" with ") print_one_inductive indl) let get_fields = let rec prodec_rec l subst c = match kind_of_term c with | Prod (na,t,c) -> let id = match na with Name id -> id | Anonymous -> id_of_string "_" in prodec_rec ((id,true,substl subst t)::l) (mkVar id::subst) c | LetIn (na,b,_,c) -> let id = match na with Name id -> id | Anonymous -> id_of_string "_" in prodec_rec ((id,false,substl subst b)::l) (mkVar id::subst) c | _ -> List.rev l in prodec_rec [] [] let pr_record (sp,tyi) = let (ref, params, arity, cstrnames, cstrtypes) = build_inductive sp tyi in let env = Global.env () in let envpar = push_rel_context params env in let fields = get_fields cstrtypes.(0) in hov 0 ( hov 0 ( str "Record " ++ pr_global (IndRef (sp,tyi)) ++ brk(1,4) ++ print_params env params ++ str ": " ++ pr_lconstr_env envpar arity ++ brk(1,2) ++ str ":= " ++ pr_id cstrnames.(0)) ++ brk(1,2) ++ hv 2 (str "{ " ++ prlist_with_sep (fun () -> str ";" ++ brk(2,0)) (fun (id,b,c) -> pr_id id ++ str (if b then " : " else " := ") ++ pr_lconstr_env envpar c) fields) ++ str" }") let gallina_print_inductive sp = let (mib,mip) = Global.lookup_inductive (sp,0) in let mipv = mib.mind_packets in let names = list_tabulate (fun x -> (sp,x)) (Array.length mipv) in (if mib.mind_record & not !Flags.raw_print then pr_record (List.hd names) else pr_mutual_inductive mib.mind_finite names) ++ fnl () ++ with_line_skip (print_inductive_implicit_args sp mipv @ print_inductive_argument_scopes sp mipv) let print_named_decl id = gallina_print_named_decl (Global.lookup_named id) ++ fnl () let gallina_print_section_variable id = print_named_decl id ++ with_line_skip (print_name_infos (VarRef id)) let print_body = function | Some lc -> pr_lconstr (Declarations.force lc) | None -> (str"<no body>") let print_typed_body (val_0,typ) = (print_body val_0 ++ fnl () ++ str " : " ++ pr_ltype typ) let ungeneralized_type_of_constant_type = function | PolymorphicArity (ctx,a) -> mkArity (ctx, Type a.poly_level) | NonPolymorphicType t -> t let print_constant with_values sep sp = let cb = Global.lookup_constant sp in let val_0 = cb.const_body in let typ = ungeneralized_type_of_constant_type cb.const_type in hov 0 ( match val_0 with | None -> str"*** [ " ++ print_basename sp ++ str " : " ++ cut () ++ pr_ltype typ ++ str" ]" | _ -> print_basename sp ++ str sep ++ cut () ++ (if with_values then print_typed_body (val_0,typ) else pr_ltype typ)) ++ fnl () let gallina_print_constant_with_infos sp = print_constant true " = " sp ++ with_line_skip (print_name_infos (ConstRef sp)) let gallina_print_syntactic_def kn = let qid = Nametab.shortest_qualid_of_syndef Idset.empty kn and (vars,a) = Syntax_def.search_syntactic_definition kn in let c = Topconstr.rawconstr_of_aconstr dummy_loc a in hov 2 (hov 4 (str "Notation " ++ pr_qualid qid ++ prlist (fun id -> spc () ++ pr_id id) (List.map fst vars) ++ spc () ++ str ":=") ++ spc () ++ Constrextern.without_symbols pr_rawconstr c) ++ fnl () let gallina_print_leaf_entry with_values ((sp,kn as oname),lobj) = let sep = if with_values then " = " else " : " and tag = object_tag lobj in match (oname,tag) with | (_,"VARIABLE") -> (try Some(print_named_decl (basename sp)) with Not_found -> None) | (_,"CONSTANT") -> Some (print_constant with_values sep (constant_of_kn kn)) | (_,"INDUCTIVE") -> Some (gallina_print_inductive (mind_of_kn kn)) | (_,"MODULE") -> let (mp,_,l) = repr_kn kn in Some (print_module with_values (MPdot (mp,l))) | (_,"MODULE TYPE") -> let (mp,_,l) = repr_kn kn in Some (print_modtype (MPdot (mp,l))) | (_,("AUTOHINT"|"GRAMMAR"|"SYNTAXCONSTANT"|"PPSYNTAX"|"TOKEN"|"CLASS"| "COERCION"|"REQUIRE"|"END-SECTION"|"STRUCTURE")) -> None | (_,s) -> None let gallina_print_library_entry with_values ent = let pr_name (sp,_) = pr_id (basename sp) in match ent with | (oname,Lib.Leaf lobj) -> gallina_print_leaf_entry with_values (oname,lobj) | (oname,Lib.OpenedSection (dir,_)) -> Some (str " >>>>>>> Section " ++ pr_name oname) | (oname,Lib.ClosedSection _) -> Some (str " >>>>>>> Closed Section " ++ pr_name oname) | (_,Lib.CompilingLibrary (dir,_)) -> Some (str " >>>>>>> Library " ++ pr_dirpath dir) | (oname,Lib.OpenedModule _) -> Some (str " >>>>>>> Module " ++ pr_name oname) | (oname,Lib.ClosedModule _) -> Some (str " >>>>>>> Closed Module " ++ pr_name oname) | (oname,Lib.OpenedModtype _) -> Some (str " >>>>>>> Module Type " ++ pr_name oname) | (oname,Lib.ClosedModtype _) -> Some (str " >>>>>>> Closed Module Type " ++ pr_name oname) | (_,Lib.FrozenState _) -> None let gallina_print_leaf_entry with_values c = match gallina_print_leaf_entry with_values c with | None -> mt () | Some pp -> pp ++ fnl() let gallina_print_context with_values = let rec prec n = function | h::rest when n = None or Option.get n > 0 -> (match gallina_print_library_entry with_values h with | None -> prec n rest | Some pp -> prec (Option.map ((+) (-1)) n) rest ++ pp ++ fnl ()) | _ -> mt () in prec let gallina_print_eval red_fun env evmap _ {uj_val=trm;uj_type=typ} = let ntrm = red_fun env evmap trm in (str " = " ++ gallina_print_typed_value_in_env env (ntrm,typ)) let default_object_pr = { print_inductive = gallina_print_inductive; print_constant_with_infos = gallina_print_constant_with_infos; print_section_variable = gallina_print_section_variable; print_syntactic_def = gallina_print_syntactic_def; print_module = gallina_print_module; print_modtype = gallina_print_modtype; print_named_decl = gallina_print_named_decl; print_leaf_entry = gallina_print_leaf_entry; print_library_entry = gallina_print_library_entry; print_context = gallina_print_context; print_typed_value_in_env = gallina_print_typed_value_in_env; print_eval = gallina_print_eval; } let object_pr = ref default_object_pr let set_object_pr = (:=) object_pr let print_inductive x = !object_pr.print_inductive x let print_constant_with_infos c = !object_pr.print_constant_with_infos c let print_section_variable c = !object_pr.print_section_variable c let print_syntactic_def x = !object_pr.print_syntactic_def x let print_module x = !object_pr.print_module x let print_modtype x = !object_pr.print_modtype x let print_named_decl x = !object_pr.print_named_decl x let print_leaf_entry x = !object_pr.print_leaf_entry x let print_library_entry x = !object_pr.print_library_entry x let print_context x = !object_pr.print_context x let print_typed_value_in_env x = !object_pr.print_typed_value_in_env x let print_eval x = !object_pr.print_eval x let print_typed_value x = print_typed_value_in_env (Global.env ()) x let print_judgment env {uj_val=trm;uj_type=typ} = print_typed_value_in_env env (trm, typ) let print_safe_judgment env j = let trm = Safe_typing.j_val j in let typ = Safe_typing.j_type j in print_typed_value_in_env env (trm, typ) let print_full_context () = print_context true None (Lib.contents_after None) let print_full_context_typ () = print_context false None (Lib.contents_after None) let print_full_pure_context () = let rec prec = function | ((_,kn),Lib.Leaf lobj)::rest -> let pp = match object_tag lobj with | "CONSTANT" -> let con = Global.constant_of_delta (constant_of_kn kn) in let cb = Global.lookup_constant con in let val_0 = cb.const_body in let typ = ungeneralized_type_of_constant_type cb.const_type in hov 0 ( match val_0 with | None -> str (if cb.const_opaque then "Axiom " else "Parameter ") ++ print_basename con ++ str " : " ++ cut () ++ pr_ltype typ | Some v -> if cb.const_opaque then str "Theorem " ++ print_basename con ++ cut () ++ str " : " ++ pr_ltype typ ++ str "." ++ fnl () ++ str "Proof " ++ print_body val_0 else str "Definition " ++ print_basename con ++ cut () ++ str " : " ++ pr_ltype typ ++ cut () ++ str " := " ++ print_body val_0) ++ str "." ++ fnl () ++ fnl () | "INDUCTIVE" -> let mind = Global.mind_of_delta (mind_of_kn kn) in let (mib,mip) = Global.lookup_inductive (mind,0) in let mipv = mib.mind_packets in let names = list_tabulate (fun x -> (mind,x)) (Array.length mipv) in pr_mutual_inductive mib.mind_finite names ++ str "." ++ fnl () ++ fnl () | "MODULE" -> let (mp,_,l) = repr_kn kn in print_module true (MPdot (mp,l)) ++ str "." ++ fnl () ++ fnl () | "MODULE TYPE" -> let (mp,_,l) = repr_kn kn in print_modtype (MPdot (mp,l)) ++ str "." ++ fnl () ++ fnl () | _ -> mt () in prec rest ++ pp | _::rest -> prec rest | _ -> mt () in prec (Lib.contents_after None) let list_filter_vec f vec = let rec frec n lf = if n < 0 then lf else if f vec.(n) then frec (n-1) (vec.(n)::lf) else frec (n-1) lf in frec (Array.length vec -1) [] let read_sec_context r = let loc,qid = qualid_of_reference r in let dir = try Nametab.locate_section qid with Not_found -> user_err_loc (loc,"read_sec_context", str "Unknown section.") in let rec get_cxt in_cxt = function | (_,Lib.OpenedSection ((dir',_),_) as hd)::rest -> if dir = dir' then (hd::in_cxt) else get_cxt (hd::in_cxt) rest | (_,Lib.ClosedSection _)::rest -> error "Cannot print the contents of a closed section." | [] -> [] | hd::rest -> get_cxt (hd::in_cxt) rest in let cxt = (Lib.contents_after None) in List.rev (get_cxt [] cxt) let print_sec_context sec = print_context true None (read_sec_context sec) let print_sec_context_typ sec = print_context false None (read_sec_context sec) let print_any_name = function | Term (ConstRef sp) -> print_constant_with_infos sp | Term (IndRef (sp,_)) -> print_inductive sp | Term (ConstructRef ((sp,_),_)) -> print_inductive sp | Term (VarRef sp) -> print_section_variable sp | Syntactic kn -> print_syntactic_def kn | Dir (DirModule(dirpath,(mp,_))) -> print_module (printable_body dirpath) mp | Dir _ -> mt () | ModuleType (_,kn) -> print_modtype kn | Undefined qid -> Var locale de but , pas var de section ... pas d'implicits let dir,str = repr_qualid qid in if (repr_dirpath dir) <> [] then raise Not_found; let (_,c,typ) = Global.lookup_named str in (print_named_decl (str,c,typ)) with Not_found -> errorlabstrm "print_name" (pr_qualid qid ++ spc () ++ str "not a defined object.") let print_name = function | Genarg.ByNotation (loc,ntn,sc) -> print_any_name (Term (Notation.interp_notation_as_global_reference loc (fun _ -> true) ntn sc)) | Genarg.AN ref -> print_any_name (locate_any_name ref) let print_opaque_name qid = let env = Global.env () in match global qid with | ConstRef cst -> let cb = Global.lookup_constant cst in if cb.const_body <> None then print_constant_with_infos cst else error "Not a defined constant." | IndRef (sp,_) -> print_inductive sp | ConstructRef cstr -> let ty = Inductiveops.type_of_constructor env cstr in print_typed_value (mkConstruct cstr, ty) | VarRef id -> let (_,c,ty) = lookup_named id env in print_named_decl (id,c,ty) let print_about_any k = match k with | Term ref -> pr_infos_list ([print_ref false ref; blankline] @ print_name_infos ref @ print_opacity ref @ [hov 0 (str "Expands to: " ++ pr_located_qualid k)]) | Syntactic kn -> v 0 ( print_syntactic_def kn ++ hov 0 (str "Expands to: " ++ pr_located_qualid k)) ++ fnl() | Dir _ | ModuleType _ | Undefined _ -> hov 0 (pr_located_qualid k) ++ fnl() let print_about = function | Genarg.ByNotation (loc,ntn,sc) -> print_about_any (Term (Notation.interp_notation_as_global_reference loc (fun _ -> true) ntn sc)) | Genarg.AN ref -> print_about_any (locate_any_name ref) let unfold_head_fconst = let rec unfrec k = match kind_of_term k with | Const cst -> constant_value (Global.env ()) cst | Lambda (na,t,b) -> mkLambda (na,t,unfrec b) | App (f,v) -> appvect (unfrec f,v) | _ -> k in unfrec let inspect depth = print_context false (Some depth) (Lib.contents_after None) open Classops let print_coercion_value v = pr_lconstr (get_coercion_value v) let print_class i = let cl,_ = class_info_from_index i in pr_class cl let print_path ((i,j),p) = hov 2 ( str"[" ++ hov 0 (prlist_with_sep pr_semicolon print_coercion_value p) ++ str"] : ") ++ print_class i ++ str" >-> " ++ print_class j let _ = Classops.install_path_printer print_path let print_graph () = prlist_with_sep pr_fnl print_path (inheritance_graph()) let print_classes () = prlist_with_sep pr_spc pr_class (classes()) let print_coercions () = prlist_with_sep pr_spc print_coercion_value (coercions()) let index_of_class cl = try fst (class_info cl) with _ -> errorlabstrm "index_of_class" (pr_class cl ++ spc() ++ str "not a defined class.") let print_path_between cls clt = let i = index_of_class cls in let j = index_of_class clt in let p = try lookup_path_between_class (i,j) with _ -> errorlabstrm "index_cl_of_id" (str"No path between " ++ pr_class cls ++ str" and " ++ pr_class clt ++ str ".") in print_path ((i,j),p) let print_canonical_projections () = prlist_with_sep pr_fnl (fun ((r1,r2),o) -> pr_cs_pattern r2 ++ str " <- " ++ pr_global r1 ++ str " ( " ++ pr_lconstr o.o_DEF ++ str " )") (canonical_projections ()) open Typeclasses let pr_typeclass env t = print_ref false t.cl_impl ++ fnl () let print_typeclasses () = let env = Global.env () in prlist_with_sep fnl (pr_typeclass env) (typeclasses ()) let pr_instance env i = gallina_print_constant_with_infos i.is_impl print_ref false (instance_impl i) ++ fnl () let print_all_instances () = let env = Global.env () in let inst = all_instances () in prlist_with_sep fnl (pr_instance env) inst let print_instances r = let env = Global.env () in let inst = instances r in prlist_with_sep fnl (pr_instance env) inst
62a6bcedca03d31baf3ddd7d507522c9a617bbd70e8f9329aa03d044764d3f8d
timbertson/vdoml
test_diff.ml
open Test_util include Init open Vdoml open Vdom_ open Html open Sexplib open Diff open Log_ module Html_gen = struct let rand = lazy ( let seed = try let seed = int_of_string (Unix.getenv "RANDOM_SEED") in Printf.eprintf "Used existing RANDOM_SEED=%d\n" seed; seed with Not_found -> Initialize just to get a random seed :D Random.self_init (); let seed = Random.int (2 lsl 20) in Printf.eprintf "[ Generated new RANDOM_SEED=%d ]\n" seed; seed in Random.State.make [|seed|] ) let pick lst = let len = List.length lst in List.nth lst (Random.State.int (Lazy.force rand) len) type elem = [ `div | `input | `span | `p | `input | `text ] let digit () : int = pick [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9 ] let element () = let attr = "contents_" ^ (string_of_int (digit ())) in let id = pick [ Some (`Int (digit ())) ; None ] in let raw = match pick [`div;`input;`span;`p;`input;`text] with | `div -> div ~a:[a_title attr] [] | `input -> input ~a:[a_title attr] () | `span -> span ~a:[a_title attr] [] | `p -> p ~a:[a_title attr] [] | `text -> text attr in Vdom.Internal.root (match id with | Some id -> Ui.identify id raw | None -> raw ) let children () = let rec gen acc = function | 0 -> acc | n -> (element ()) :: (gen acc (n-1)) in gen [] (pick [ 0; 2; 3; 5; 7 ]) end module Diff_util = struct open Vdom open Sexp type raw_node = unit Vdom.raw_node type node = unit Vdom.node type node_mutation = unit Diff.node_mutation type node_mutations = node_mutation list let raw = raw_of_node let node : unit Vdom.Internal.pure_node -> unit Vdom.Internal.node = Vdom.Internal.root type mutation_mode = [ `id | `anon ] let sexp_of_raw_node node = Atom (string_of_raw node) let compare_raw_node = Stdlib.compare let sexp_of_identity = function | User_tag (`String s) -> Atom s | User_tag (`Int i) -> Atom (string_of_int i) | Internal_tag i -> Atom (string_of_int i) let sexp_of_node node = match node with | Anonymous node -> List [ Atom "Anonymous"; sexp_of_raw_node node ] | Identified (id, node) -> List [ Atom "Identified"; sexp_of_identity id; sexp_of_raw_node node ] let compare_node = Stdlib.compare let sexp_of_node_mutation = let s x = Atom x and l x = List x in function | Update ( a, b ) -> l [ s "Update"; s (string_of_raw a); s (string_of_raw b) ] | Insert a -> l [ s "Insert"; s (string_of_node a) ] | Append a -> l [ s "Append"; s (string_of_node a) ] | Remove a -> l [ s "Remove"; s (string_of_raw a) ] let string_of_node_list nodes = "["^( String.concat ", " (List.map string_of_node nodes) )^"]" let sexp_of_node_mutations m = Sexp.List (List.map sexp_of_node_mutation m) let compare_node_mutations = Stdlib.compare let assert_mutations ~existing ~replacements expected = let mutations = ref [] in let apply = (fun mutation state -> ignore state; mutations := mutation :: !mutations ) in Diff.update_children_pure ~apply existing replacements; let mutations = List.rev !mutations in [%test_result:node_mutations] ~expect:expected mutations let virtual_apply initial = let nodes = ref initial in let split_nodes state = Log.debug (fun m->m "splitting nodes on idx %d: %s" state.dom_idx (string_of_node_list !nodes) ); let rec loop = fun before after -> function | 0 -> Log.debug (fun m->m "split result: %s // %s" (string_of_node_list before) (string_of_node_list after) ); (before, after) | n -> (match after with | current::tail -> loop (before @ [current]) tail (n-1) | [] -> failwith "premature end of list" ) in loop [] !nodes state.dom_idx in let apply = fun mutation state -> let new_nodes = (match mutation with | Update (existing, replacement) -> ( match split_nodes state with | pre, current::remaining -> ( let current = match current with | Identified (id, _existing) -> [%test_result:raw_node] ~expect:_existing existing; Identified (id, replacement) | Anonymous _existing -> [%test_result:raw_node] ~expect:_existing existing; Anonymous replacement in pre @ [current] @ remaining ) | _ -> assert false ) | Insert addition -> let pre, remaining = split_nodes state in pre @ [addition] @ remaining | Append addition -> let pre, remaining = split_nodes state in [%test_result:node list] ~expect:[] remaining; pre @ remaining @ [addition] | Remove node -> ( match split_nodes state with | _, [] -> failwith "remove with no remaining nodes" | pre, current::remaining -> [%test_result:raw_node] ~expect:(raw current) node; pre @ remaining ) ) in Log.debug (fun m->m "after applying %s, nodes = %s" (string_of_node_mutation mutation) (string_of_node_list new_nodes) ); nodes := new_nodes in let extract () = !nodes in (apply, extract) end open Diff_util let first_div = node @@ div ~a:[a_class "first"] [] let first_span = node @@ span ~a:[a_class "first"] [] let first_p1 = node @@ p ~a:[a_class "first p1"] [] let first_p2 = node @@ p ~a:[a_class "first p2"] [] let first_p3 = node @@ p ~a:[a_class "first p3"] [] let second_div = node @@ div ~a:[a_class "second"] [] let second_span = node @@ span ~a:[a_class "second"] [] let second_p1 = node @@ p ~a:[a_class "second p1"] [] let second_p2 = node @@ p ~a:[a_class "second p2"] [] let second_p3 = node @@ p ~a:[a_class "second p3"] [] let first_id1 = node @@ Ui.identify (`Int 1) @@ div ~a:[a_class "first id1"] [] let first_id2 = node @@ Ui.identify (`Int 2) @@ div ~a:[a_class "first id2"] [] let first_id3 = node @@ Ui.identify (`Int 3) @@ div ~a:[a_class "first id3"] [] let second_id1 = node @@ Ui.identify (`Int 1) @@ div ~a:[a_class "second id1"] [] let second_id2 = node @@ Ui.identify (`Int 2) @@ div ~a:[a_class "second id2"] [] let second_id3 = node @@ Ui.identify (`Int 3) @@ div ~a:[a_class "second id3"] [] let%test_unit "removed element" = assert_mutations ~existing:[ first_div; first_span ] ~replacements: [ second_span ] [ Remove (raw first_div); Update (raw first_span, raw second_span); ] let%test_unit "inserted element" = assert_mutations ~existing:[ first_div ] ~replacements:[ second_span; second_div ] [ Insert (second_span); Update (raw first_div, raw second_div); ] let%test_unit "multiple inserted elements" = assert_mutations ~existing:[ first_div ] ~replacements:[ second_span; second_p1; second_p2; second_div ] [ Insert (second_span); Insert (second_p1); Insert (second_p2); Update (raw first_div, raw second_div); ] let%test_unit "reordered element" = assert_mutations ~existing:[ first_div; first_span ] ~replacements:[ second_span; second_div ] [ Remove (raw first_div); Update (raw first_span, raw second_span); Append (second_div); ] let%test_unit "identified elements reordered amongst anons" = assert_mutations ~existing:[ first_div; first_id1; first_span; first_id2 ] ~replacements:[ second_span; second_id2; second_div; second_id1 ] [ Insert (second_span); Remove (raw first_div); Remove (raw first_id1); Remove (raw first_span); Update (raw first_id2, raw second_id2); Append (second_div); Append (second_id1); ] let%test_unit "anon elements amongst identified" = assert_mutations ~existing:[ first_id1; first_id2; first_span; first_id3 ] ~replacements:[ second_id1; second_id2; second_id3; second_div ] [ Update (raw first_id1, raw second_id1); Update (raw first_id2, raw second_id2); Remove (raw first_span); Update (raw first_id3, raw second_id3); Append (second_div); ] let%test_unit "random update" = let iterations = ref 50 in while !iterations > 0; do decr iterations; let initial = Html_gen.children () in let apply, get_result = virtual_apply initial in let replacements = Html_gen.children () in Log.info (fun m->m "updating initial (%s) -> final (%s)" (string_of_node_list initial) (string_of_node_list replacements) ); Diff.update_children_pure ~apply initial replacements; [%test_result:node list] ~expect:replacements (get_result ()) done
null
https://raw.githubusercontent.com/timbertson/vdoml/fcbf81e89df989206bdad4a92327e593078525b2/test/test_diff.ml
ocaml
open Test_util include Init open Vdoml open Vdom_ open Html open Sexplib open Diff open Log_ module Html_gen = struct let rand = lazy ( let seed = try let seed = int_of_string (Unix.getenv "RANDOM_SEED") in Printf.eprintf "Used existing RANDOM_SEED=%d\n" seed; seed with Not_found -> Initialize just to get a random seed :D Random.self_init (); let seed = Random.int (2 lsl 20) in Printf.eprintf "[ Generated new RANDOM_SEED=%d ]\n" seed; seed in Random.State.make [|seed|] ) let pick lst = let len = List.length lst in List.nth lst (Random.State.int (Lazy.force rand) len) type elem = [ `div | `input | `span | `p | `input | `text ] let digit () : int = pick [ 0; 1; 2; 3; 4; 5; 6; 7; 8; 9 ] let element () = let attr = "contents_" ^ (string_of_int (digit ())) in let id = pick [ Some (`Int (digit ())) ; None ] in let raw = match pick [`div;`input;`span;`p;`input;`text] with | `div -> div ~a:[a_title attr] [] | `input -> input ~a:[a_title attr] () | `span -> span ~a:[a_title attr] [] | `p -> p ~a:[a_title attr] [] | `text -> text attr in Vdom.Internal.root (match id with | Some id -> Ui.identify id raw | None -> raw ) let children () = let rec gen acc = function | 0 -> acc | n -> (element ()) :: (gen acc (n-1)) in gen [] (pick [ 0; 2; 3; 5; 7 ]) end module Diff_util = struct open Vdom open Sexp type raw_node = unit Vdom.raw_node type node = unit Vdom.node type node_mutation = unit Diff.node_mutation type node_mutations = node_mutation list let raw = raw_of_node let node : unit Vdom.Internal.pure_node -> unit Vdom.Internal.node = Vdom.Internal.root type mutation_mode = [ `id | `anon ] let sexp_of_raw_node node = Atom (string_of_raw node) let compare_raw_node = Stdlib.compare let sexp_of_identity = function | User_tag (`String s) -> Atom s | User_tag (`Int i) -> Atom (string_of_int i) | Internal_tag i -> Atom (string_of_int i) let sexp_of_node node = match node with | Anonymous node -> List [ Atom "Anonymous"; sexp_of_raw_node node ] | Identified (id, node) -> List [ Atom "Identified"; sexp_of_identity id; sexp_of_raw_node node ] let compare_node = Stdlib.compare let sexp_of_node_mutation = let s x = Atom x and l x = List x in function | Update ( a, b ) -> l [ s "Update"; s (string_of_raw a); s (string_of_raw b) ] | Insert a -> l [ s "Insert"; s (string_of_node a) ] | Append a -> l [ s "Append"; s (string_of_node a) ] | Remove a -> l [ s "Remove"; s (string_of_raw a) ] let string_of_node_list nodes = "["^( String.concat ", " (List.map string_of_node nodes) )^"]" let sexp_of_node_mutations m = Sexp.List (List.map sexp_of_node_mutation m) let compare_node_mutations = Stdlib.compare let assert_mutations ~existing ~replacements expected = let mutations = ref [] in let apply = (fun mutation state -> ignore state; mutations := mutation :: !mutations ) in Diff.update_children_pure ~apply existing replacements; let mutations = List.rev !mutations in [%test_result:node_mutations] ~expect:expected mutations let virtual_apply initial = let nodes = ref initial in let split_nodes state = Log.debug (fun m->m "splitting nodes on idx %d: %s" state.dom_idx (string_of_node_list !nodes) ); let rec loop = fun before after -> function | 0 -> Log.debug (fun m->m "split result: %s // %s" (string_of_node_list before) (string_of_node_list after) ); (before, after) | n -> (match after with | current::tail -> loop (before @ [current]) tail (n-1) | [] -> failwith "premature end of list" ) in loop [] !nodes state.dom_idx in let apply = fun mutation state -> let new_nodes = (match mutation with | Update (existing, replacement) -> ( match split_nodes state with | pre, current::remaining -> ( let current = match current with | Identified (id, _existing) -> [%test_result:raw_node] ~expect:_existing existing; Identified (id, replacement) | Anonymous _existing -> [%test_result:raw_node] ~expect:_existing existing; Anonymous replacement in pre @ [current] @ remaining ) | _ -> assert false ) | Insert addition -> let pre, remaining = split_nodes state in pre @ [addition] @ remaining | Append addition -> let pre, remaining = split_nodes state in [%test_result:node list] ~expect:[] remaining; pre @ remaining @ [addition] | Remove node -> ( match split_nodes state with | _, [] -> failwith "remove with no remaining nodes" | pre, current::remaining -> [%test_result:raw_node] ~expect:(raw current) node; pre @ remaining ) ) in Log.debug (fun m->m "after applying %s, nodes = %s" (string_of_node_mutation mutation) (string_of_node_list new_nodes) ); nodes := new_nodes in let extract () = !nodes in (apply, extract) end open Diff_util let first_div = node @@ div ~a:[a_class "first"] [] let first_span = node @@ span ~a:[a_class "first"] [] let first_p1 = node @@ p ~a:[a_class "first p1"] [] let first_p2 = node @@ p ~a:[a_class "first p2"] [] let first_p3 = node @@ p ~a:[a_class "first p3"] [] let second_div = node @@ div ~a:[a_class "second"] [] let second_span = node @@ span ~a:[a_class "second"] [] let second_p1 = node @@ p ~a:[a_class "second p1"] [] let second_p2 = node @@ p ~a:[a_class "second p2"] [] let second_p3 = node @@ p ~a:[a_class "second p3"] [] let first_id1 = node @@ Ui.identify (`Int 1) @@ div ~a:[a_class "first id1"] [] let first_id2 = node @@ Ui.identify (`Int 2) @@ div ~a:[a_class "first id2"] [] let first_id3 = node @@ Ui.identify (`Int 3) @@ div ~a:[a_class "first id3"] [] let second_id1 = node @@ Ui.identify (`Int 1) @@ div ~a:[a_class "second id1"] [] let second_id2 = node @@ Ui.identify (`Int 2) @@ div ~a:[a_class "second id2"] [] let second_id3 = node @@ Ui.identify (`Int 3) @@ div ~a:[a_class "second id3"] [] let%test_unit "removed element" = assert_mutations ~existing:[ first_div; first_span ] ~replacements: [ second_span ] [ Remove (raw first_div); Update (raw first_span, raw second_span); ] let%test_unit "inserted element" = assert_mutations ~existing:[ first_div ] ~replacements:[ second_span; second_div ] [ Insert (second_span); Update (raw first_div, raw second_div); ] let%test_unit "multiple inserted elements" = assert_mutations ~existing:[ first_div ] ~replacements:[ second_span; second_p1; second_p2; second_div ] [ Insert (second_span); Insert (second_p1); Insert (second_p2); Update (raw first_div, raw second_div); ] let%test_unit "reordered element" = assert_mutations ~existing:[ first_div; first_span ] ~replacements:[ second_span; second_div ] [ Remove (raw first_div); Update (raw first_span, raw second_span); Append (second_div); ] let%test_unit "identified elements reordered amongst anons" = assert_mutations ~existing:[ first_div; first_id1; first_span; first_id2 ] ~replacements:[ second_span; second_id2; second_div; second_id1 ] [ Insert (second_span); Remove (raw first_div); Remove (raw first_id1); Remove (raw first_span); Update (raw first_id2, raw second_id2); Append (second_div); Append (second_id1); ] let%test_unit "anon elements amongst identified" = assert_mutations ~existing:[ first_id1; first_id2; first_span; first_id3 ] ~replacements:[ second_id1; second_id2; second_id3; second_div ] [ Update (raw first_id1, raw second_id1); Update (raw first_id2, raw second_id2); Remove (raw first_span); Update (raw first_id3, raw second_id3); Append (second_div); ] let%test_unit "random update" = let iterations = ref 50 in while !iterations > 0; do decr iterations; let initial = Html_gen.children () in let apply, get_result = virtual_apply initial in let replacements = Html_gen.children () in Log.info (fun m->m "updating initial (%s) -> final (%s)" (string_of_node_list initial) (string_of_node_list replacements) ); Diff.update_children_pure ~apply initial replacements; [%test_result:node list] ~expect:replacements (get_result ()) done
8644e68b4d9ef26b6c897733360b72900bb44da8dda6137c864d28c01b7b13fe
ghc/ghc
T4437.hs
| A test for ensuring that GHC 's supporting language extensions remains in sync with Cabal 's own extension list . -- -- If you have ended up here due to a test failure, please see Note [ Adding a language extension ] in compiler / GHC / Driver / Session.hs . module Main (main) where import Control.Monad import Data.List ( (\\) ) import GHC.Driver.Session import Language.Haskell.Extension main :: IO () main = do let ghcExtensions = map flagSpecName xFlags cabalExtensions = map show [ toEnum 0 :: KnownExtension .. ] ghcOnlyExtensions = ghcExtensions \\ cabalExtensions cabalOnlyExtensions = cabalExtensions \\ ghcExtensions check "GHC-only flags" expectedGhcOnlyExtensions ghcOnlyExtensions check "Cabal-only flags" expectedCabalOnlyExtensions cabalOnlyExtensions check :: String -> [String] -> [String] -> IO () check title expected got = do let unexpected = got \\ expected missing = expected \\ got showProblems problemType problems = unless (null problems) $ do putStrLn (title ++ ": " ++ problemType) putStrLn "-----" mapM_ putStrLn problems putStrLn "-----" putStrLn "" showProblems "Unexpected flags" unexpected showProblems "Missing flags" missing See Note [ Adding a language extension ] in compiler / GHC / Driver / Session.hs . expectedGhcOnlyExtensions :: [String] expectedGhcOnlyExtensions = [ "TypeAbstractions" ] expectedCabalOnlyExtensions :: [String] expectedCabalOnlyExtensions = ["Generics", "ExtensibleRecords", "RestrictedTypeSynonyms", "HereDocuments", "NewQualifiedOperators", "XmlSyntax", "RegularPatterns", "SafeImports", "Safe", "Unsafe", "Trustworthy", "MonadFailDesugaring", "MonoPatBinds", -- "RequiredTypeArguments" ]
null
https://raw.githubusercontent.com/ghc/ghc/083f701553852c4460159cd6deb2515d3373714d/testsuite/tests/driver/T4437.hs
haskell
If you have ended up here due to a test failure, please see
| A test for ensuring that GHC 's supporting language extensions remains in sync with Cabal 's own extension list . Note [ Adding a language extension ] in compiler / GHC / Driver / Session.hs . module Main (main) where import Control.Monad import Data.List ( (\\) ) import GHC.Driver.Session import Language.Haskell.Extension main :: IO () main = do let ghcExtensions = map flagSpecName xFlags cabalExtensions = map show [ toEnum 0 :: KnownExtension .. ] ghcOnlyExtensions = ghcExtensions \\ cabalExtensions cabalOnlyExtensions = cabalExtensions \\ ghcExtensions check "GHC-only flags" expectedGhcOnlyExtensions ghcOnlyExtensions check "Cabal-only flags" expectedCabalOnlyExtensions cabalOnlyExtensions check :: String -> [String] -> [String] -> IO () check title expected got = do let unexpected = got \\ expected missing = expected \\ got showProblems problemType problems = unless (null problems) $ do putStrLn (title ++ ": " ++ problemType) putStrLn "-----" mapM_ putStrLn problems putStrLn "-----" putStrLn "" showProblems "Unexpected flags" unexpected showProblems "Missing flags" missing See Note [ Adding a language extension ] in compiler / GHC / Driver / Session.hs . expectedGhcOnlyExtensions :: [String] expectedGhcOnlyExtensions = [ "TypeAbstractions" ] expectedCabalOnlyExtensions :: [String] expectedCabalOnlyExtensions = ["Generics", "ExtensibleRecords", "RestrictedTypeSynonyms", "HereDocuments", "NewQualifiedOperators", "XmlSyntax", "RegularPatterns", "SafeImports", "Safe", "Unsafe", "Trustworthy", "MonadFailDesugaring", "MonoPatBinds", "RequiredTypeArguments" ]
583c209055ba29a8e46c6d694b8183bb612a778fb4096cb1b6e851d6d0a47495
kiranlak/austin-sbst
options.ml
Copyright : , University College London , 2011 open Cil open ConfigFile let hashtblInitSize = 10000 let maxSymbolicStatements = 100000 let austinOutDir = ref "" let austinLibDir = ref "" let mkFileName (name:string) = let exists = try Sys.is_directory !austinOutDir with | _ -> false in if not(exists) && !austinOutDir <> "" then ( 0o640 ); Filename.concat !austinOutDir name let keyAustinLibDir = "austinLibDir" let keyAustinOutDir = "austinOutDir" let keyBranchTraceName = "branchTrace" let keySUTpreamble = "sutPreamble" let keyRenamedMain = "renamedMain" let keyDrvFundec = "drvFundec" let keyFutFundec = "futFundec" let keyBinSolName = "binSolutionDat" let keyTestCaseFile = "txtTestCases" let keyInstrumentedSource = "instrumentedSource" let keyBinInstrumentedSrouce = "binInstrumentedSource" let keyCfgInfo = "cfgInfo" let keySymState = "symState" let keySymPath = "symPath" let keyBranchIds = "txtBranchIds" let keyInstrumentLog = "instrLog" let keyExecLog = "execLog" let keySUTLog = "sutLog" let keyLogConfig = "logConfig" let keyLogToScreen = "logToScreen" let keyLogToFile = "logToFile" let keyLogLevel = "logLevel" let keyLogCsv = "logCsvResults" let keyLogTestCases = "logTestCases" let keySeeds = "rndSeeds" let keyPreconditionFile = "preconFile" let keyArrayFile = "arrayFile" let keyBaseLvalsFile = "baseLvals" let machineDependentPreamble = match Sys.word_size with | 32 -> "extra/x86.c" | _ -> "extra/x86_64.c" let keyTDGMethod = "tdgSearchMethod" let keyTDGCriterion = "tdgCriterion" let keyCompiler = "cc" let keyCompilerIncl = "compilerIncludes" let keyCompilerOpts = "compilerOpts" let keyHillClimberDecimalPlaces = "hillClimberDecimalPlaces" let addOptionKeysToConfig () = add keySUTpreamble (Filename.concat !austinLibDir machineDependentPreamble); add keyRenamedMain "orig_main"; add keyDrvFundec (mkFileName "drv.dat"); add keyFutFundec (mkFileName "fut.dat"); add keyBinSolName (mkFileName "camlSolution.dat"); add keyTestCaseFile (mkFileName "testCases.c"); add keyInstrumentedSource (mkFileName "austin_instrumented.c"); add keyBinInstrumentedSrouce (mkFileName "austin_instrumented.dat"); add keyCfgInfo (mkFileName "cfginfo.dat"); add keySymState (mkFileName "symstate.dat"); add keySymPath (mkFileName "pathCondition.dat"); add keyBranchIds (mkFileName "branchids.txt"); add keyInstrumentLog (mkFileName "instrumentation.log"); add keyExecLog (mkFileName "execution.log"); add keySUTLog (mkFileName "sut.log"); add keyLogConfig (mkFileName "log.config"); add keySeeds (mkFileName "randomNumberSeeds.txt"); add keyBranchTraceName (mkFileName "traceInfo.dat"); add keyPreconditionFile (mkFileName "precon.dat"); add keyArrayFile (mkFileName "arrayFile.dat"); add keyBaseLvalsFile (mkFileName "baseLvals.dat"); add keyCompiler "gcc"; add keyCompilerIncl "-I ."; add keyCompilerOpts "-P -E" ;;
null
https://raw.githubusercontent.com/kiranlak/austin-sbst/9c8aac72692dca952302e0e4fdb9ff381bba58ae/AustinOcaml/options.ml
ocaml
Copyright : , University College London , 2011 open Cil open ConfigFile let hashtblInitSize = 10000 let maxSymbolicStatements = 100000 let austinOutDir = ref "" let austinLibDir = ref "" let mkFileName (name:string) = let exists = try Sys.is_directory !austinOutDir with | _ -> false in if not(exists) && !austinOutDir <> "" then ( 0o640 ); Filename.concat !austinOutDir name let keyAustinLibDir = "austinLibDir" let keyAustinOutDir = "austinOutDir" let keyBranchTraceName = "branchTrace" let keySUTpreamble = "sutPreamble" let keyRenamedMain = "renamedMain" let keyDrvFundec = "drvFundec" let keyFutFundec = "futFundec" let keyBinSolName = "binSolutionDat" let keyTestCaseFile = "txtTestCases" let keyInstrumentedSource = "instrumentedSource" let keyBinInstrumentedSrouce = "binInstrumentedSource" let keyCfgInfo = "cfgInfo" let keySymState = "symState" let keySymPath = "symPath" let keyBranchIds = "txtBranchIds" let keyInstrumentLog = "instrLog" let keyExecLog = "execLog" let keySUTLog = "sutLog" let keyLogConfig = "logConfig" let keyLogToScreen = "logToScreen" let keyLogToFile = "logToFile" let keyLogLevel = "logLevel" let keyLogCsv = "logCsvResults" let keyLogTestCases = "logTestCases" let keySeeds = "rndSeeds" let keyPreconditionFile = "preconFile" let keyArrayFile = "arrayFile" let keyBaseLvalsFile = "baseLvals" let machineDependentPreamble = match Sys.word_size with | 32 -> "extra/x86.c" | _ -> "extra/x86_64.c" let keyTDGMethod = "tdgSearchMethod" let keyTDGCriterion = "tdgCriterion" let keyCompiler = "cc" let keyCompilerIncl = "compilerIncludes" let keyCompilerOpts = "compilerOpts" let keyHillClimberDecimalPlaces = "hillClimberDecimalPlaces" let addOptionKeysToConfig () = add keySUTpreamble (Filename.concat !austinLibDir machineDependentPreamble); add keyRenamedMain "orig_main"; add keyDrvFundec (mkFileName "drv.dat"); add keyFutFundec (mkFileName "fut.dat"); add keyBinSolName (mkFileName "camlSolution.dat"); add keyTestCaseFile (mkFileName "testCases.c"); add keyInstrumentedSource (mkFileName "austin_instrumented.c"); add keyBinInstrumentedSrouce (mkFileName "austin_instrumented.dat"); add keyCfgInfo (mkFileName "cfginfo.dat"); add keySymState (mkFileName "symstate.dat"); add keySymPath (mkFileName "pathCondition.dat"); add keyBranchIds (mkFileName "branchids.txt"); add keyInstrumentLog (mkFileName "instrumentation.log"); add keyExecLog (mkFileName "execution.log"); add keySUTLog (mkFileName "sut.log"); add keyLogConfig (mkFileName "log.config"); add keySeeds (mkFileName "randomNumberSeeds.txt"); add keyBranchTraceName (mkFileName "traceInfo.dat"); add keyPreconditionFile (mkFileName "precon.dat"); add keyArrayFile (mkFileName "arrayFile.dat"); add keyBaseLvalsFile (mkFileName "baseLvals.dat"); add keyCompiler "gcc"; add keyCompilerIncl "-I ."; add keyCompilerOpts "-P -E" ;;
c6a2bb8cc4f88e22d642ab1da6ba891d1d929af84ce548caaf4eb9ef4351dd8c
ankushdas/Nomos
ErrorMsg.ml
module F = RastFlags (* Initial values of compiler state variables *) let anyErrors = ref false;; let reset () = ( anyErrors := false );; type error_cat = Lex | Parse | Type | Pragma | Runtime;; let err_string cat = match cat with Lex -> "lex" | Parse -> "parse" | Type -> "type" | Pragma -> "pragma" | Runtime -> "runtime";; We turn tabs into spaces because they are counted as a single character in the extents , so in order for the emphasis to be correct we need each character to be one column wide . the extents, so in order for the emphasis to be correct we need each character to be one column wide. *) let tabToSpace = String.map (fun c -> match c with | '\t' -> ' ' | c -> c);; let omap f opt = match opt with None -> None | Some x -> Some (f x);; let pmsg str ext note = ( ignore (omap (fun x -> print_string (Mark.show x)) ext) ; List.iter print_string [":"; str; ":"; note; "\n"] ; ignore (omap (fun x -> print_string (tabToSpace (Mark.show_source x))) ext) );; let error_msg cat ext note = ( anyErrors := true ; if !F.verbosity >= 0 (* verbosity < 0: don't print error messages! *) then pmsg (err_string cat ^ " error") ext note else () );; let warn cat ext note = pmsg (err_string cat ^ " warning") ext note;; (* Print the given error message and then abort compilation *) exception Error let error cat ext msg = ( error_msg cat ext msg ; raise Error );;
null
https://raw.githubusercontent.com/ankushdas/Nomos/db678f3981e75a1b3310bb55f66009bb23430cb1/rast/ErrorMsg.ml
ocaml
Initial values of compiler state variables verbosity < 0: don't print error messages! Print the given error message and then abort compilation
module F = RastFlags let anyErrors = ref false;; let reset () = ( anyErrors := false );; type error_cat = Lex | Parse | Type | Pragma | Runtime;; let err_string cat = match cat with Lex -> "lex" | Parse -> "parse" | Type -> "type" | Pragma -> "pragma" | Runtime -> "runtime";; We turn tabs into spaces because they are counted as a single character in the extents , so in order for the emphasis to be correct we need each character to be one column wide . the extents, so in order for the emphasis to be correct we need each character to be one column wide. *) let tabToSpace = String.map (fun c -> match c with | '\t' -> ' ' | c -> c);; let omap f opt = match opt with None -> None | Some x -> Some (f x);; let pmsg str ext note = ( ignore (omap (fun x -> print_string (Mark.show x)) ext) ; List.iter print_string [":"; str; ":"; note; "\n"] ; ignore (omap (fun x -> print_string (tabToSpace (Mark.show_source x))) ext) );; let error_msg cat ext note = ( anyErrors := true then pmsg (err_string cat ^ " error") ext note else () );; let warn cat ext note = pmsg (err_string cat ^ " warning") ext note;; exception Error let error cat ext msg = ( error_msg cat ext msg ; raise Error );;
01734705922867b3e033dd662a8cf0a52d9473e85088ef46c27309172ebf40a9
Zert/amqp-erlang-sample
client_iface.erl
-module(client_iface). -author('Maxim Treskin'). -behaviour(gen_server). -include("client.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(conn, { channel :: pid(), exchange :: binary(), queue :: binary(), croute :: binary(), sroute :: binary(), broker :: binary(), tag :: binary() }). -record(state, { conn, info, uniq }). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init(_) -> process_flag(trap_exit, true), User = client_app:get_app_env(iface_mq_user, ?DEF_IFACE_MQ_USER), Password = client_app:get_app_env(iface_mq_pass, ?DEF_IFACE_MQ_PASS), Host = client_app:get_app_env(iface_mq_host, ?DEF_IFACE_MQ_HOST), Realm = list_to_binary(client_app:get_app_env(iface_mq_realm, ?DEF_IFACE_MQ_REALM)), ?DBG("Start Interface: ~p~n~p~n~p~n~p", [User, Password, Host, Realm]), Exch = <<"dispatcher.adapter">>, BrokerRoutKey = <<"dispatcher.main">>, AP = #amqp_params{username = User, password = Password, virtual_host = Realm, host = Host}, Connection = amqp_connection:start_network(AP), Channel = amqp_connection:open_channel(Connection), amqp_channel:call( Channel, #'exchange.declare'{exchange = Exch, auto_delete = true}), Uniq = base64:encode(erlang:md5(term_to_binary(make_ref()))), ?DBG("Uniq: ~p", [Uniq]), CRoutKey = Queue = <<"client.main.", Uniq/binary>>, SRoutKey = <<"client.serv.", Uniq/binary>>, ?DBG("Queue: ~p", [Queue]), amqp_channel:call( Channel, #'queue.declare'{queue = Queue, auto_delete = true}), amqp_channel:call( Channel, #'queue.bind'{queue = Queue, routing_key = CRoutKey, exchange = Exch}), Tag = amqp_channel:subscribe( Channel, #'basic.consume'{queue = Queue}, self()), ?DBG("Tag: ~p", [Tag]), %% Fanout FExch = <<"dispatcher.ctl">>, FQueue = <<"client.fanout.", Uniq/binary>>, amqp_channel:call( Channel, #'queue.declare'{queue = FQueue, auto_delete = true}), amqp_channel:call( Channel, #'queue.bind'{queue = FQueue, exchange = FExch}), amqp_channel:subscribe( Channel, #'basic.consume'{queue = FQueue}, self()), ?DBG("Client iface started", []), self() ! {register}, {ok, #state{conn = #conn{channel = Channel, exchange = Exch, queue = Queue, croute = CRoutKey, sroute = SRoutKey, broker = BrokerRoutKey}, uniq = Uniq}}. handle_call(Request, _From, State) -> {reply, Request, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(#'basic.consume_ok'{consumer_tag = CTag}, #state{} = State) -> ?DBG("Consumer Tag: ~p", [CTag]), {noreply, State}; handle_info({#'basic.deliver'{consumer_tag = CTag, delivery_tag = DeliveryTag, exchange = Exch, routing_key = RK}, #amqp_msg{payload = Data} = Content}, #state{conn = _Conn} = State) -> ?DBG("ConsumerTag: ~p" "~nDeliveryTag: ~p" "~nExchange: ~p" "~nRoutingKey: ~p" "~nContent: ~p" "~n", [CTag, DeliveryTag, Exch, RK, Content]), D = binary_to_term(Data), ?INFO("Data: ~p", [D]), {noreply, State}; handle_info({register}, #state{conn = #conn{channel = Channel, exchange = Exch, broker = BrokerRoutKey}, uniq = Uniq} = State) -> ?DBG("Registration on: ~p", [BrokerRoutKey]), Payload = term_to_binary({register, Uniq}), amqp_channel:call(Channel, #'basic.publish'{exchange = Exch, routing_key = BrokerRoutKey}, #amqp_msg{props = #'P_basic'{}, payload = Payload}), {noreply, State}; handle_info({msg, Msg}, #state{conn = #conn{channel = Channel, exchange = Exch, sroute = SRoutKey}} = State) -> ?DBG("Message: ~p", [Msg]), Payload = term_to_binary(Msg), amqp_channel:call(Channel, #'basic.publish'{exchange = Exch, routing_key = SRoutKey}, #amqp_msg{props = #'P_basic'{}, payload = Payload}), {noreply, State}; handle_info(Info, State) -> ?DBG("Handle Info noreply: ~p, ~p", [Info, State]), {noreply, State}. terminate(Reason, State) -> ?DBG("Terminate: ~p, ~p", [Reason, State]), ok. code_change(OldVsn, State, Extra) -> ?DBG("Code Change: ~p, ~p, ~p", [OldVsn, State, Extra]), {ok, State}.
null
https://raw.githubusercontent.com/Zert/amqp-erlang-sample/db6619a78a5eb1c3fe6b241b96b147f56de65f41/client/src/client_iface.erl
erlang
Fanout
-module(client_iface). -author('Maxim Treskin'). -behaviour(gen_server). -include("client.hrl"). -include_lib("amqp_client/include/amqp_client.hrl"). -export([start_link/0]). -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -record(conn, { channel :: pid(), exchange :: binary(), queue :: binary(), croute :: binary(), sroute :: binary(), broker :: binary(), tag :: binary() }). -record(state, { conn, info, uniq }). start_link() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []). init(_) -> process_flag(trap_exit, true), User = client_app:get_app_env(iface_mq_user, ?DEF_IFACE_MQ_USER), Password = client_app:get_app_env(iface_mq_pass, ?DEF_IFACE_MQ_PASS), Host = client_app:get_app_env(iface_mq_host, ?DEF_IFACE_MQ_HOST), Realm = list_to_binary(client_app:get_app_env(iface_mq_realm, ?DEF_IFACE_MQ_REALM)), ?DBG("Start Interface: ~p~n~p~n~p~n~p", [User, Password, Host, Realm]), Exch = <<"dispatcher.adapter">>, BrokerRoutKey = <<"dispatcher.main">>, AP = #amqp_params{username = User, password = Password, virtual_host = Realm, host = Host}, Connection = amqp_connection:start_network(AP), Channel = amqp_connection:open_channel(Connection), amqp_channel:call( Channel, #'exchange.declare'{exchange = Exch, auto_delete = true}), Uniq = base64:encode(erlang:md5(term_to_binary(make_ref()))), ?DBG("Uniq: ~p", [Uniq]), CRoutKey = Queue = <<"client.main.", Uniq/binary>>, SRoutKey = <<"client.serv.", Uniq/binary>>, ?DBG("Queue: ~p", [Queue]), amqp_channel:call( Channel, #'queue.declare'{queue = Queue, auto_delete = true}), amqp_channel:call( Channel, #'queue.bind'{queue = Queue, routing_key = CRoutKey, exchange = Exch}), Tag = amqp_channel:subscribe( Channel, #'basic.consume'{queue = Queue}, self()), ?DBG("Tag: ~p", [Tag]), FExch = <<"dispatcher.ctl">>, FQueue = <<"client.fanout.", Uniq/binary>>, amqp_channel:call( Channel, #'queue.declare'{queue = FQueue, auto_delete = true}), amqp_channel:call( Channel, #'queue.bind'{queue = FQueue, exchange = FExch}), amqp_channel:subscribe( Channel, #'basic.consume'{queue = FQueue}, self()), ?DBG("Client iface started", []), self() ! {register}, {ok, #state{conn = #conn{channel = Channel, exchange = Exch, queue = Queue, croute = CRoutKey, sroute = SRoutKey, broker = BrokerRoutKey}, uniq = Uniq}}. handle_call(Request, _From, State) -> {reply, Request, State}. handle_cast(_Msg, State) -> {noreply, State}. handle_info(#'basic.consume_ok'{consumer_tag = CTag}, #state{} = State) -> ?DBG("Consumer Tag: ~p", [CTag]), {noreply, State}; handle_info({#'basic.deliver'{consumer_tag = CTag, delivery_tag = DeliveryTag, exchange = Exch, routing_key = RK}, #amqp_msg{payload = Data} = Content}, #state{conn = _Conn} = State) -> ?DBG("ConsumerTag: ~p" "~nDeliveryTag: ~p" "~nExchange: ~p" "~nRoutingKey: ~p" "~nContent: ~p" "~n", [CTag, DeliveryTag, Exch, RK, Content]), D = binary_to_term(Data), ?INFO("Data: ~p", [D]), {noreply, State}; handle_info({register}, #state{conn = #conn{channel = Channel, exchange = Exch, broker = BrokerRoutKey}, uniq = Uniq} = State) -> ?DBG("Registration on: ~p", [BrokerRoutKey]), Payload = term_to_binary({register, Uniq}), amqp_channel:call(Channel, #'basic.publish'{exchange = Exch, routing_key = BrokerRoutKey}, #amqp_msg{props = #'P_basic'{}, payload = Payload}), {noreply, State}; handle_info({msg, Msg}, #state{conn = #conn{channel = Channel, exchange = Exch, sroute = SRoutKey}} = State) -> ?DBG("Message: ~p", [Msg]), Payload = term_to_binary(Msg), amqp_channel:call(Channel, #'basic.publish'{exchange = Exch, routing_key = SRoutKey}, #amqp_msg{props = #'P_basic'{}, payload = Payload}), {noreply, State}; handle_info(Info, State) -> ?DBG("Handle Info noreply: ~p, ~p", [Info, State]), {noreply, State}. terminate(Reason, State) -> ?DBG("Terminate: ~p, ~p", [Reason, State]), ok. code_change(OldVsn, State, Extra) -> ?DBG("Code Change: ~p, ~p, ~p", [OldVsn, State, Extra]), {ok, State}.
f1eb65117a4a1f938db3a41b302973c899b578520c2514293045474509c56b37
15Galan/asignatura-204
StackOnList.hs
------------------------------------------------------------------------------- -- Stacks implemented using lists -- Data Structures . en Informática . UMA . , 2011 ------------------------------------------------------------------------------- module DataStructures.Stack.StackOnList ( Stack , empty , isEmpty , push , pop , top ) where import Data.List(intercalate) import Test.QuickCheck data Stack a = SonL [a] empty :: Stack a empty = SonL [] isEmpty :: Stack a -> Bool isEmpty (SonL []) = True isEmpty _ = False push :: a -> Stack a -> Stack a push x (SonL xs) = SonL (x:xs) top :: Stack a -> a top (SonL []) = error "top on empty Stack" top (SonL (x:xs)) = x pop :: Stack a -> Stack a pop (SonL []) = error "pop on empty Stack" pop (SonL (x:xs)) = SonL xs -- Showing a stack instance (Show a) => Show (Stack a) where show (SonL xs) = "StackOnList(" ++ intercalate "," (map show xs) ++ ")" -- Stack equality instance (Eq a) => Eq (Stack a) where (SonL xs) == (SonL xs') = xs==xs' -- uses list predefined equality This instance is used by QuickCheck to generate random stacks instance (Arbitrary a) => Arbitrary (Stack a) where arbitrary = do xs <- listOf arbitrary return (foldr push empty xs)
null
https://raw.githubusercontent.com/15Galan/asignatura-204/894f33ff8e0f52a75d8f9ff15155c656f1a8f771/Recursos/data.structures/haskell/DataStructures/Stack/StackOnList.hs
haskell
----------------------------------------------------------------------------- Stacks implemented using lists ----------------------------------------------------------------------------- Showing a stack Stack equality uses list predefined equality
Data Structures . en Informática . UMA . , 2011 module DataStructures.Stack.StackOnList ( Stack , empty , isEmpty , push , pop , top ) where import Data.List(intercalate) import Test.QuickCheck data Stack a = SonL [a] empty :: Stack a empty = SonL [] isEmpty :: Stack a -> Bool isEmpty (SonL []) = True isEmpty _ = False push :: a -> Stack a -> Stack a push x (SonL xs) = SonL (x:xs) top :: Stack a -> a top (SonL []) = error "top on empty Stack" top (SonL (x:xs)) = x pop :: Stack a -> Stack a pop (SonL []) = error "pop on empty Stack" pop (SonL (x:xs)) = SonL xs instance (Show a) => Show (Stack a) where show (SonL xs) = "StackOnList(" ++ intercalate "," (map show xs) ++ ")" instance (Eq a) => Eq (Stack a) where This instance is used by QuickCheck to generate random stacks instance (Arbitrary a) => Arbitrary (Stack a) where arbitrary = do xs <- listOf arbitrary return (foldr push empty xs)
8a0a07dc1572f9249ff2b74f3da8863c0fb3a84733397b4d96e60abffdeaa241
bufferswap/ViralityEngine
line2d.lisp
(in-package #:cl-user) ;;; NOTE: Line2d represents a 2D line segment, not an infinite line in the mathematical sense. Since ;;; line segments are so common in physics, we have chosen to use this convention (as many other ;;; game physics libraries do). (defpackage #:vorigin.geometry.line2d (:local-nicknames (#:point2d #:vorigin.geometry.point2d) (#:u #:vutils) (#:v2 #:vorigin.vec2)) (:use #:cl) (:shadow #:length) (:export #:direction #:end #:length #:length-squared #:line #:midpoint #:start)) (in-package #:vorigin.geometry.line2d) (declaim (inline %line)) (defstruct (line (:predicate nil) (:copier nil) (:constructor %line (start end)) (:conc-name nil)) (start (point2d:point) :type point2d:point) (end (point2d:point) :type point2d:point)) (u:fn-> line (&key (:start point2d:point) (:end point2d:point)) line) (declaim (inline line)) (defun line (&key (start (point2d:point)) (end (point2d:point))) (declare (optimize speed)) (%line start end)) (u:fn-> length (line) u:f32) (declaim (inline length)) (defun length (line) (declare (optimize speed)) (v2:length (v2:- (end line) (start line)))) (u:fn-> length-squared (line) u:f32) (declaim (inline length-squared)) (defun length-squared (line) (declare (optimize speed)) (v2:length-squared (v2:- (end line) (start line)))) (u:fn-> midpoint (line) point2d:point) (declaim (inline midpoint)) (defun midpoint (line) (declare (optimize speed)) (v2:lerp (start line) (end line) 0.5f0)) (u:fn-> direction (line) v2:vec) (declaim (inline direction)) (defun direction (line) (declare (optimize speed)) (v2:normalize (v2:- (end line) (start line))))
null
https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/support/vorigin/src/geometry/shapes/line2d.lisp
lisp
NOTE: Line2d represents a 2D line segment, not an infinite line in the mathematical sense. Since line segments are so common in physics, we have chosen to use this convention (as many other game physics libraries do).
(in-package #:cl-user) (defpackage #:vorigin.geometry.line2d (:local-nicknames (#:point2d #:vorigin.geometry.point2d) (#:u #:vutils) (#:v2 #:vorigin.vec2)) (:use #:cl) (:shadow #:length) (:export #:direction #:end #:length #:length-squared #:line #:midpoint #:start)) (in-package #:vorigin.geometry.line2d) (declaim (inline %line)) (defstruct (line (:predicate nil) (:copier nil) (:constructor %line (start end)) (:conc-name nil)) (start (point2d:point) :type point2d:point) (end (point2d:point) :type point2d:point)) (u:fn-> line (&key (:start point2d:point) (:end point2d:point)) line) (declaim (inline line)) (defun line (&key (start (point2d:point)) (end (point2d:point))) (declare (optimize speed)) (%line start end)) (u:fn-> length (line) u:f32) (declaim (inline length)) (defun length (line) (declare (optimize speed)) (v2:length (v2:- (end line) (start line)))) (u:fn-> length-squared (line) u:f32) (declaim (inline length-squared)) (defun length-squared (line) (declare (optimize speed)) (v2:length-squared (v2:- (end line) (start line)))) (u:fn-> midpoint (line) point2d:point) (declaim (inline midpoint)) (defun midpoint (line) (declare (optimize speed)) (v2:lerp (start line) (end line) 0.5f0)) (u:fn-> direction (line) v2:vec) (declaim (inline direction)) (defun direction (line) (declare (optimize speed)) (v2:normalize (v2:- (end line) (start line))))
5334b63ebfd94d6a26a61a424158ed27965de0ef05894f98dd9d513de57c5181
kevsmith/giza
giza_t_005.erl
-module(giza_t_005). -export([start/0]). start() -> etap:plan(9), Update = giza_update:new("foo"), etap:is("localhost", giza_update:host(Update), "Can get host"), etap:is(3312, giza_update:port(Update), "Can get port"), etap:is([], giza_update:attributes(Update), "Update fields default to empty list"), U1 = giza_update:add_attribute(Update, "wibble"), etap:is([<<"wibble">>], giza_update:attributes(U1), "Can add fields to a pending update"), U2 = giza_update:remove_attribute(Update, "wibble"), etap:is([], giza_update:attributes(U2), "Can remove fields to a pending update"), U3 = giza_update:add_attribute(U2, "wibble"), U4 = giza_update:add_doc(U3, 123, [777]), etap:is([{123, [777]}], giza_update:docs(U4), "Can get set of pending doc updates"), U5 = giza_update:remove_attribute(U4, "wibble"), etap:is([], giza_update:docs(U5), "Removing a field removes pending updates for that field"), U6 = giza_update:add_attributes(U5, ["foo", "bar", "baz"]), U7 = giza_update:add_doc(U6, 123, [1,1,1]), U8 = giza_update:add_doc(U7, 456, [2,2,2]), U9 = giza_update:add_doc(U8, 789, [3,3,3]), U10 = giza_update:remove_attribute(U9, "bar"), etap:is([{123, [1,1]}, {456, [2,2]}, {789, [3,3]}], giza_update:docs(U10), "Removing one field leaves the rest in place"), U11 = giza_update:new("foo"), U12 = giza_update:add_attributes(U11, ["foo", "bar", "baz"]), U13 = giza_update:add_doc(U12, 123, [1, 11, 111]), U14 = giza_update:add_doc(U13, 456, [2, 22, 222]), U15 = giza_update:remove_attribute(U14, "baz"), etap:is([{123, [1, 11]}, {456, [2, 22]}], giza_update:docs(U15), "Checking field removal with unique update values"), etap:end_tests().
null
https://raw.githubusercontent.com/kevsmith/giza/576eada45ccff8d7fb688b8abe3a33c25d34028d/t/giza_t_005.erl
erlang
-module(giza_t_005). -export([start/0]). start() -> etap:plan(9), Update = giza_update:new("foo"), etap:is("localhost", giza_update:host(Update), "Can get host"), etap:is(3312, giza_update:port(Update), "Can get port"), etap:is([], giza_update:attributes(Update), "Update fields default to empty list"), U1 = giza_update:add_attribute(Update, "wibble"), etap:is([<<"wibble">>], giza_update:attributes(U1), "Can add fields to a pending update"), U2 = giza_update:remove_attribute(Update, "wibble"), etap:is([], giza_update:attributes(U2), "Can remove fields to a pending update"), U3 = giza_update:add_attribute(U2, "wibble"), U4 = giza_update:add_doc(U3, 123, [777]), etap:is([{123, [777]}], giza_update:docs(U4), "Can get set of pending doc updates"), U5 = giza_update:remove_attribute(U4, "wibble"), etap:is([], giza_update:docs(U5), "Removing a field removes pending updates for that field"), U6 = giza_update:add_attributes(U5, ["foo", "bar", "baz"]), U7 = giza_update:add_doc(U6, 123, [1,1,1]), U8 = giza_update:add_doc(U7, 456, [2,2,2]), U9 = giza_update:add_doc(U8, 789, [3,3,3]), U10 = giza_update:remove_attribute(U9, "bar"), etap:is([{123, [1,1]}, {456, [2,2]}, {789, [3,3]}], giza_update:docs(U10), "Removing one field leaves the rest in place"), U11 = giza_update:new("foo"), U12 = giza_update:add_attributes(U11, ["foo", "bar", "baz"]), U13 = giza_update:add_doc(U12, 123, [1, 11, 111]), U14 = giza_update:add_doc(U13, 456, [2, 22, 222]), U15 = giza_update:remove_attribute(U14, "baz"), etap:is([{123, [1, 11]}, {456, [2, 22]}], giza_update:docs(U15), "Checking field removal with unique update values"), etap:end_tests().
8a13de677c761e8b6eb94c5ff2184025b2c87c3e3ec7a41c62850eb1526d2a9f
jubnzv/iec-checker
unused_variable.mli
(** Detect unused variables in the source code. *) open IECCheckerCore module S = Syntax val run : S.iec_library_element list -> Warn.t list
null
https://raw.githubusercontent.com/jubnzv/iec-checker/666cd8a28cb1211465a900862df84d70460c2742/src/analysis/unused_variable.mli
ocaml
* Detect unused variables in the source code.
open IECCheckerCore module S = Syntax val run : S.iec_library_element list -> Warn.t list
61ffa04850bded88d472c3e943c2fe7412a6ffca309f7e61ff0e6b8dbc3116c0
ku-fpg/hermit
AST.hs
# LANGUAGE CPP # # LANGUAGE LambdaCase # | Output the raw constructors . Helpful for writing pattern matching rewrites . module HERMIT.PrettyPrinter.AST * HERMIT 's AST Pretty - Printer for GHC Core externals , pretty , ppCoreTC , ppModGuts , ppCoreProg , ppCoreBind , ppCoreExpr , ppCoreAlt , ppKindOrType , ppCoercion , ppForallQuantification ) where import Control.Arrow hiding ((<+>)) import Data.Char (isSpace) import Data.Default.Class import HERMIT.Core import HERMIT.External import HERMIT.GHC hiding (($$), (<+>), (<>), ($+$), cat, nest, parens, text, empty, hsep) import HERMIT.Kure import HERMIT.PrettyPrinter.Common import Text.PrettyPrint.MarkedHughesPJ as PP --------------------------------------------------------------------------- coText :: String -> DocH coText = coercionColor . text tyText :: String -> DocH tyText = typeColor . text --------------------------------------------------------------------------- externals :: [External] externals = [ external "ast" pretty ["AST pretty printer."] ] pretty :: PrettyPrinter TODO , pOptions = def , pTag = "ast" } | Pretty print a fragment of GHC Core using 's \"AST\ " pretty printer . -- This displays the tree of constructors using nested indentation. ppCoreTC :: PrettyH CoreTC ppCoreTC = promoteExprT ppCoreExpr <+ promoteProgT ppCoreProg <+ promoteBindT ppCoreBind <+ promoteDefT ppCoreDef <+ promoteModGutsT ppModGuts <+ promoteAltT ppCoreAlt <+ promoteTypeT ppKindOrType <+ promoteCoercionT ppCoercion Use for any GHC structure , the ' showSDoc ' prefix is to remind us -- that we are eliding infomation here. ppSDoc :: Outputable a => PrettyH a ppSDoc = do dynFlags <- constT getDynFlags hideNotes <- (po_notes . prettyC_options) ^<< contextT arr (toDoc . (if hideNotes then id else ("showSDoc: " ++)) . showPpr dynFlags) where toDoc s | any isSpace s = parens (text s) | otherwise = text s ppModGuts :: PrettyH ModGuts ppModGuts = mg_module ^>> ppSDoc ppCoreProg :: PrettyH CoreProg ppCoreProg = progConsT ppCoreBind ppCoreProg ($+$) <+ progNilT empty ppCoreExpr :: PrettyH CoreExpr ppCoreExpr = varT (ppVar >>^ \ i -> text "Var" <+> i) <+ litT (ppSDoc >>^ \ x -> text "Lit" <+> x) <+ appT ppCoreExpr ppCoreExpr (\ a b -> text "App" $$ nest 2 (cat [parens a, parens b])) <+ lamT ppVar ppCoreExpr (\ v e -> text "Lam" <+> v $$ nest 2 (parens e)) <+ letT ppCoreBind ppCoreExpr (\ b e -> text "Let" $$ nest 2 (cat [parens b, parens e])) <+ caseT ppCoreExpr ppVar ppKindOrType (const ppCoreAlt) (\s w ty alts -> text "Case" $$ nest 2 (parens s) $$ nest 2 w $$ nest 2 (parens ty) $$ nest 2 (vlist alts)) <+ castT ppCoreExpr ppCoercion (\ e co -> text "Cast" $$ nest 2 (cat [parens e, parens co])) <+ tickT ppSDoc ppCoreExpr (\ tk e -> text "Tick" $$ nest 2 (tk <+> parens e)) <+ typeT (ppKindOrType >>^ \ ty -> text "Type" $$ nest 2 (parens ty)) <+ coercionT (ppCoercion >>^ \ co -> text "Coercion" $$ nest 2 (parens co)) ppCoreBind :: PrettyH CoreBind ppCoreBind = nonRecT ppVar ppCoreExpr (\ v e -> text "NonRec" <+> v $$ nest 2 (parens e)) <+ recT (const ppCoreDef) (\ bnds -> text "Rec" $$ nest 2 (vlist bnds)) ppCoreAlt :: PrettyH CoreAlt ppCoreAlt = altT ppSDoc (\ _ -> ppVar) ppCoreExpr $ \ con vs e -> text "Alt" <+> con <+> hlist vs $$ nest 2 (parens e) ppCoreDef :: PrettyH CoreDef ppCoreDef = defT ppVar ppCoreExpr (\ i e -> text "Def" <+> i $$ nest 2 (parens e)) ppKindOrType :: PrettyH Type ppKindOrType = readerT $ \case TyVarTy{} -> tyVarT (ppVar >>^ \ v -> tyText "TyVarTy" <+> v) AppTy{} -> appTyT ppKindOrType ppKindOrType (\ ty1 ty2 -> tyText "AppTy" $$ nest 2 (cat [parens ty1, parens ty2])) TyConApp{} -> tyConAppT ppSDoc (const ppKindOrType) $ \ con tys -> tyText "TyConApp" <+> con $$ nest 2 (vlist $ map parens tys) #if __GLASGOW_HASKELL__ > 710 CastTy{} -> castTyT ppKindOrType ppCoercion (\ ty co -> tyText "CastTy" $$ nest 2 (cat [parens ty, parens co])) CoercionTy{} -> coercionTyT ppCoercion >>= \ co -> return (tyText "CoercionTy" $$ nest 2 (parens co)) ForAllTy{} -> forAllTyT ppTyBinder ppKindOrType (\ tb ty -> tyText "ForAllTy" <+> tb $$ nest 2 (parens ty)) #else FunTy{} -> funTyT ppKindOrType ppKindOrType (\ ty1 ty2 -> tyText "FunTy" $$ nest 2 (cat [parens ty1, parens ty2])) ForAllTy{} -> forAllTyT ppVar ppKindOrType (\ v ty -> tyText "ForAllTy" <+> v $$ nest 2 (parens ty)) #endif LitTy{} -> litTyT (ppSDoc >>^ \ l -> tyText "LitTy" <+> l) #if __GLASGOW_HASKELL__ > 710 ppTyBinder :: PrettyH TyBinder ppTyBinder = readerT $ \case Named tv v -> do d <- return tv >>> ppVar return $ tyText "Named" <+> d <+> tyText (showVis v) Anon ty -> do d <- return ty >>> ppKindOrType return $ tyText "Anon" <+> d ppUnivCoProvenance :: PrettyH UnivCoProvenance ppUnivCoProvenance = readerT $ \case UnsafeCoerceProv -> return $ coText "UnsafeCoerceProv" PhantomProv co -> do d <- return co >>> ppCoercion return $ coText "PhantomProv" <+> parens d ProofIrrelProv co -> do d <- return co >>> ppCoercion return $ coText "ProofIrrelProv" <+> parens d PluginProv s -> return $ coText "PluginProv" <+> coText s HoleProv _ -> return $ coText "HoleProv - IMPOSSIBLE!" #endif ppCoercion :: PrettyH Coercion ppCoercion = readerT $ \case Refl{} -> reflT ppKindOrType (\ r ty -> coText "Refl" <+> coText (showRole r) $$ nest 2 (parens ty)) TyConAppCo{} -> tyConAppCoT ppSDoc (const ppCoercion) $ \ r con coes -> coText "TyConAppCo" <+> coText (showRole r) <+> con $$ nest 2 (vlist $ map parens coes) AppCo{} -> appCoT ppCoercion ppCoercion (\ co1 co2 -> coText "AppCo" $$ nest 2 (cat [parens co1, parens co2])) #if __GLASGOW_HASKELL__ > 710 ForAllCo{} -> forAllCoT ppVar ppCoercion ppCoercion $ \ v c1 c2 -> coText "ForAllCo" <+> v $$ nest 2 (cat [parens c1, parens c2]) #else ForAllCo{} -> forAllCoT ppVar ppCoercion (\ v co -> coText "ForAllCo" <+> v $$ nest 2 (parens co)) #endif CoVarCo{} -> coVarCoT (ppVar >>^ \ v -> coText "CoVarCo" <+> v) AxiomInstCo{} -> axiomInstCoT ppSDoc ppSDoc (const ppCoercion) $ \ ax idx coes -> coText "AxiomInstCo" <+> ax <+> idx $$ nest 2 (vlist $ map parens coes) #if __GLASGOW_HASKELL__ > 710 UnivCo p _ _ _ -> do pd <- return p >>> ppUnivCoProvenance univCoT ppKindOrType ppKindOrType $ \ _ r dom ran -> coText "UnivCo" <+> pd <+> coText (showRole r) $$ nest 2 (cat [parens dom, parens ran]) #else UnivCo{} -> univCoT ppKindOrType ppKindOrType $ \ s r dom ran -> coText "UnivCo" <+> coText (show s) <+> coText (showRole r) $$ nest 2 (cat [parens dom, parens ran]) #endif SymCo{} -> symCoT (ppCoercion >>^ \ co -> coText "SymCo" $$ nest 2 (parens co)) TransCo{} -> transCoT ppCoercion ppCoercion (\ co1 co2 -> coText "TransCo" $$ nest 2 (cat [parens co1, parens co2])) NthCo{} -> nthCoT (arr $ coText . show) ppCoercion (\ n co -> coText "NthCo" <+> n $$ parens co) LRCo{} -> lrCoT ppSDoc ppCoercion (\ lr co -> coText "LRCo" <+> lr $$ nest 2 (parens co)) #if __GLASGOW_HASKELL__ > 710 InstCo{} -> instCoT ppCoercion ppCoercion (\ c1 c2 -> coText "InstCo" $$ nest 2 (cat [parens c1, parens c2])) #else InstCo{} -> instCoT ppCoercion ppKindOrType (\ co ty -> coText "InstCo" $$ nest 2 (cat [parens co, parens ty])) #endif SubCo{} -> subCoT (ppCoercion >>^ \ co -> coText "SubCo" $$ nest 2 (parens co)) ppVar :: PrettyH Var ppVar = readerT $ \ v -> ppSDoc >>^ modCol v where modCol v | isTyVar v = typeColor | isCoVar v = coercionColor | otherwise = idColor A bit hacky , currently only used to pretty - print Lemmas . ppForallQuantification :: PrettyH [Var] ppForallQuantification = do vs <- mapT ppVar if null vs then return empty else return $ keywordText "forall" <+> hsep vs <> keywordText "." keywordText :: String -> DocH keywordText = keywordColor . text ---------------------------------------------------------------------------
null
https://raw.githubusercontent.com/ku-fpg/hermit/3e7be430fae74a9e3860b8b574f36efbf9648dec/src/HERMIT/PrettyPrinter/AST.hs
haskell
------------------------------------------------------------------------- ------------------------------------------------------------------------- This displays the tree of constructors using nested indentation. that we are eliding infomation here. -------------------------------------------------------------------------
# LANGUAGE CPP # # LANGUAGE LambdaCase # | Output the raw constructors . Helpful for writing pattern matching rewrites . module HERMIT.PrettyPrinter.AST * HERMIT 's AST Pretty - Printer for GHC Core externals , pretty , ppCoreTC , ppModGuts , ppCoreProg , ppCoreBind , ppCoreExpr , ppCoreAlt , ppKindOrType , ppCoercion , ppForallQuantification ) where import Control.Arrow hiding ((<+>)) import Data.Char (isSpace) import Data.Default.Class import HERMIT.Core import HERMIT.External import HERMIT.GHC hiding (($$), (<+>), (<>), ($+$), cat, nest, parens, text, empty, hsep) import HERMIT.Kure import HERMIT.PrettyPrinter.Common import Text.PrettyPrint.MarkedHughesPJ as PP coText :: String -> DocH coText = coercionColor . text tyText :: String -> DocH tyText = typeColor . text externals :: [External] externals = [ external "ast" pretty ["AST pretty printer."] ] pretty :: PrettyPrinter TODO , pOptions = def , pTag = "ast" } | Pretty print a fragment of GHC Core using 's \"AST\ " pretty printer . ppCoreTC :: PrettyH CoreTC ppCoreTC = promoteExprT ppCoreExpr <+ promoteProgT ppCoreProg <+ promoteBindT ppCoreBind <+ promoteDefT ppCoreDef <+ promoteModGutsT ppModGuts <+ promoteAltT ppCoreAlt <+ promoteTypeT ppKindOrType <+ promoteCoercionT ppCoercion Use for any GHC structure , the ' showSDoc ' prefix is to remind us ppSDoc :: Outputable a => PrettyH a ppSDoc = do dynFlags <- constT getDynFlags hideNotes <- (po_notes . prettyC_options) ^<< contextT arr (toDoc . (if hideNotes then id else ("showSDoc: " ++)) . showPpr dynFlags) where toDoc s | any isSpace s = parens (text s) | otherwise = text s ppModGuts :: PrettyH ModGuts ppModGuts = mg_module ^>> ppSDoc ppCoreProg :: PrettyH CoreProg ppCoreProg = progConsT ppCoreBind ppCoreProg ($+$) <+ progNilT empty ppCoreExpr :: PrettyH CoreExpr ppCoreExpr = varT (ppVar >>^ \ i -> text "Var" <+> i) <+ litT (ppSDoc >>^ \ x -> text "Lit" <+> x) <+ appT ppCoreExpr ppCoreExpr (\ a b -> text "App" $$ nest 2 (cat [parens a, parens b])) <+ lamT ppVar ppCoreExpr (\ v e -> text "Lam" <+> v $$ nest 2 (parens e)) <+ letT ppCoreBind ppCoreExpr (\ b e -> text "Let" $$ nest 2 (cat [parens b, parens e])) <+ caseT ppCoreExpr ppVar ppKindOrType (const ppCoreAlt) (\s w ty alts -> text "Case" $$ nest 2 (parens s) $$ nest 2 w $$ nest 2 (parens ty) $$ nest 2 (vlist alts)) <+ castT ppCoreExpr ppCoercion (\ e co -> text "Cast" $$ nest 2 (cat [parens e, parens co])) <+ tickT ppSDoc ppCoreExpr (\ tk e -> text "Tick" $$ nest 2 (tk <+> parens e)) <+ typeT (ppKindOrType >>^ \ ty -> text "Type" $$ nest 2 (parens ty)) <+ coercionT (ppCoercion >>^ \ co -> text "Coercion" $$ nest 2 (parens co)) ppCoreBind :: PrettyH CoreBind ppCoreBind = nonRecT ppVar ppCoreExpr (\ v e -> text "NonRec" <+> v $$ nest 2 (parens e)) <+ recT (const ppCoreDef) (\ bnds -> text "Rec" $$ nest 2 (vlist bnds)) ppCoreAlt :: PrettyH CoreAlt ppCoreAlt = altT ppSDoc (\ _ -> ppVar) ppCoreExpr $ \ con vs e -> text "Alt" <+> con <+> hlist vs $$ nest 2 (parens e) ppCoreDef :: PrettyH CoreDef ppCoreDef = defT ppVar ppCoreExpr (\ i e -> text "Def" <+> i $$ nest 2 (parens e)) ppKindOrType :: PrettyH Type ppKindOrType = readerT $ \case TyVarTy{} -> tyVarT (ppVar >>^ \ v -> tyText "TyVarTy" <+> v) AppTy{} -> appTyT ppKindOrType ppKindOrType (\ ty1 ty2 -> tyText "AppTy" $$ nest 2 (cat [parens ty1, parens ty2])) TyConApp{} -> tyConAppT ppSDoc (const ppKindOrType) $ \ con tys -> tyText "TyConApp" <+> con $$ nest 2 (vlist $ map parens tys) #if __GLASGOW_HASKELL__ > 710 CastTy{} -> castTyT ppKindOrType ppCoercion (\ ty co -> tyText "CastTy" $$ nest 2 (cat [parens ty, parens co])) CoercionTy{} -> coercionTyT ppCoercion >>= \ co -> return (tyText "CoercionTy" $$ nest 2 (parens co)) ForAllTy{} -> forAllTyT ppTyBinder ppKindOrType (\ tb ty -> tyText "ForAllTy" <+> tb $$ nest 2 (parens ty)) #else FunTy{} -> funTyT ppKindOrType ppKindOrType (\ ty1 ty2 -> tyText "FunTy" $$ nest 2 (cat [parens ty1, parens ty2])) ForAllTy{} -> forAllTyT ppVar ppKindOrType (\ v ty -> tyText "ForAllTy" <+> v $$ nest 2 (parens ty)) #endif LitTy{} -> litTyT (ppSDoc >>^ \ l -> tyText "LitTy" <+> l) #if __GLASGOW_HASKELL__ > 710 ppTyBinder :: PrettyH TyBinder ppTyBinder = readerT $ \case Named tv v -> do d <- return tv >>> ppVar return $ tyText "Named" <+> d <+> tyText (showVis v) Anon ty -> do d <- return ty >>> ppKindOrType return $ tyText "Anon" <+> d ppUnivCoProvenance :: PrettyH UnivCoProvenance ppUnivCoProvenance = readerT $ \case UnsafeCoerceProv -> return $ coText "UnsafeCoerceProv" PhantomProv co -> do d <- return co >>> ppCoercion return $ coText "PhantomProv" <+> parens d ProofIrrelProv co -> do d <- return co >>> ppCoercion return $ coText "ProofIrrelProv" <+> parens d PluginProv s -> return $ coText "PluginProv" <+> coText s HoleProv _ -> return $ coText "HoleProv - IMPOSSIBLE!" #endif ppCoercion :: PrettyH Coercion ppCoercion = readerT $ \case Refl{} -> reflT ppKindOrType (\ r ty -> coText "Refl" <+> coText (showRole r) $$ nest 2 (parens ty)) TyConAppCo{} -> tyConAppCoT ppSDoc (const ppCoercion) $ \ r con coes -> coText "TyConAppCo" <+> coText (showRole r) <+> con $$ nest 2 (vlist $ map parens coes) AppCo{} -> appCoT ppCoercion ppCoercion (\ co1 co2 -> coText "AppCo" $$ nest 2 (cat [parens co1, parens co2])) #if __GLASGOW_HASKELL__ > 710 ForAllCo{} -> forAllCoT ppVar ppCoercion ppCoercion $ \ v c1 c2 -> coText "ForAllCo" <+> v $$ nest 2 (cat [parens c1, parens c2]) #else ForAllCo{} -> forAllCoT ppVar ppCoercion (\ v co -> coText "ForAllCo" <+> v $$ nest 2 (parens co)) #endif CoVarCo{} -> coVarCoT (ppVar >>^ \ v -> coText "CoVarCo" <+> v) AxiomInstCo{} -> axiomInstCoT ppSDoc ppSDoc (const ppCoercion) $ \ ax idx coes -> coText "AxiomInstCo" <+> ax <+> idx $$ nest 2 (vlist $ map parens coes) #if __GLASGOW_HASKELL__ > 710 UnivCo p _ _ _ -> do pd <- return p >>> ppUnivCoProvenance univCoT ppKindOrType ppKindOrType $ \ _ r dom ran -> coText "UnivCo" <+> pd <+> coText (showRole r) $$ nest 2 (cat [parens dom, parens ran]) #else UnivCo{} -> univCoT ppKindOrType ppKindOrType $ \ s r dom ran -> coText "UnivCo" <+> coText (show s) <+> coText (showRole r) $$ nest 2 (cat [parens dom, parens ran]) #endif SymCo{} -> symCoT (ppCoercion >>^ \ co -> coText "SymCo" $$ nest 2 (parens co)) TransCo{} -> transCoT ppCoercion ppCoercion (\ co1 co2 -> coText "TransCo" $$ nest 2 (cat [parens co1, parens co2])) NthCo{} -> nthCoT (arr $ coText . show) ppCoercion (\ n co -> coText "NthCo" <+> n $$ parens co) LRCo{} -> lrCoT ppSDoc ppCoercion (\ lr co -> coText "LRCo" <+> lr $$ nest 2 (parens co)) #if __GLASGOW_HASKELL__ > 710 InstCo{} -> instCoT ppCoercion ppCoercion (\ c1 c2 -> coText "InstCo" $$ nest 2 (cat [parens c1, parens c2])) #else InstCo{} -> instCoT ppCoercion ppKindOrType (\ co ty -> coText "InstCo" $$ nest 2 (cat [parens co, parens ty])) #endif SubCo{} -> subCoT (ppCoercion >>^ \ co -> coText "SubCo" $$ nest 2 (parens co)) ppVar :: PrettyH Var ppVar = readerT $ \ v -> ppSDoc >>^ modCol v where modCol v | isTyVar v = typeColor | isCoVar v = coercionColor | otherwise = idColor A bit hacky , currently only used to pretty - print Lemmas . ppForallQuantification :: PrettyH [Var] ppForallQuantification = do vs <- mapT ppVar if null vs then return empty else return $ keywordText "forall" <+> hsep vs <> keywordText "." keywordText :: String -> DocH keywordText = keywordColor . text
5ab5031a034a946c37271286e8bc6083d9ae9c34a1dcdbd32e2b734b5bd5f2d9
abhinav/language-thrift
Main.hs
module Main (main) where import Test.Hspec.Runner import qualified Spec main :: IO () main = hspecWith defaultConfig { configQuickCheckMaxSize = Just 30 } Spec.spec
null
https://raw.githubusercontent.com/abhinav/language-thrift/48e98348cdd49aec2898b9e399d52ac5a5f17fe3/test/Main.hs
haskell
module Main (main) where import Test.Hspec.Runner import qualified Spec main :: IO () main = hspecWith defaultConfig { configQuickCheckMaxSize = Just 30 } Spec.spec
4922d41cd7d9e47a50c034938101fe43eefd1069279b348a9ec465018d3a11c4
erlang/otp
f_include_3.erl
-module(f_include_3). -feature(experimental_ftr_1, enable). -ifdef(end_prefix). -record(constant, {value = 42}). -endif. %% Enable feature inside include file -include("enable.hrl"). %% At this point the prefix will definitely end, if it has not already -export([foo/1]). -if(?FEATURE_ENABLED(experimental_ftr_2)). foo(1) -> exp2_enabled. -else. foo(1) -> exp2_disabled. -endif.
null
https://raw.githubusercontent.com/erlang/otp/018277451bc9d6fa249cd1d62b416b8721ce43ee/erts/test/erlc_SUITE_data/src/f_include_3.erl
erlang
Enable feature inside include file At this point the prefix will definitely end, if it has not already
-module(f_include_3). -feature(experimental_ftr_1, enable). -ifdef(end_prefix). -record(constant, {value = 42}). -endif. -include("enable.hrl"). -export([foo/1]). -if(?FEATURE_ENABLED(experimental_ftr_2)). foo(1) -> exp2_enabled. -else. foo(1) -> exp2_disabled. -endif.
aac71aaeb7edcad3315f900d5c95f068256a5808ebb9138cd479ff8a1e5be948
aeternity/aeternity
aesc_close_solo_tx.erl
%%%============================================================================= 2018 , Aeternity Anstalt %%% @doc Module defining the State Channel close solo transaction %%% @end %%%============================================================================= -module(aesc_close_solo_tx). -behavior(aetx). %% Behavior API -export([new/1, type/0, fee/1, gas/1, ttl/1, nonce/1, origin/1, check/3, payload/1, process/3, signers/2, version/1, serialization_template/1, serialize/1, deserialize/2, for_client/1, valid_at_protocol/2 ]). % aesc_signable_transaction callbacks -export([channel_id/1, channel_pubkey/1]). -ifdef(TEST). -export([ set_payload/2 , set_nonce/2 ]). -endif. %%%=================================================================== %%% Types %%%=================================================================== -define(CHANNEL_CLOSE_SOLO_TX_VSN, 1). -define(CHANNEL_CLOSE_SOLO_TX_TYPE, channel_close_solo_tx). -type vsn() :: non_neg_integer(). -record(channel_close_solo_tx, { channel_id :: aeser_id:id(), from_id :: aeser_id:id(), payload :: binary(), poi :: aec_trees:poi(), ttl :: aetx:tx_ttl(), fee :: non_neg_integer(), nonce :: non_neg_integer() }). -opaque tx() :: #channel_close_solo_tx{}. -export_type([tx/0]). %%%=================================================================== %%% Behaviour API %%%=================================================================== -spec new(map()) -> {ok, aetx:tx()}. new(#{channel_id := ChannelId, from_id := FromId, payload := Payload, poi := PoI, fee := Fee, nonce := Nonce} = Args) -> channel = aeser_id:specialize_type(ChannelId), account = aeser_id:specialize_type(FromId), Tx = #channel_close_solo_tx{ channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = maps:get(ttl, Args, 0), fee = Fee, nonce = Nonce}, {ok, aetx:new(?MODULE, Tx)}. type() -> ?CHANNEL_CLOSE_SOLO_TX_TYPE. -spec fee(tx()) -> non_neg_integer(). fee(#channel_close_solo_tx{fee = Fee}) -> Fee. -spec gas(tx()) -> non_neg_integer(). gas(#channel_close_solo_tx{}) -> 0. -spec ttl(tx()) -> aetx:tx_ttl(). ttl(#channel_close_solo_tx{ttl = TTL}) -> TTL. -spec nonce(tx()) -> non_neg_integer(). nonce(#channel_close_solo_tx{nonce = Nonce}) -> Nonce. -spec origin(tx()) -> aec_keys:pubkey(). origin(#channel_close_solo_tx{} = Tx) -> from_pubkey(Tx). -spec channel_pubkey(tx()) -> aesc_channels:pubkey(). channel_pubkey(#channel_close_solo_tx{channel_id = ChannelId}) -> aeser_id:specialize(ChannelId, channel). channel_id(#channel_close_solo_tx{channel_id = ChannelId}) -> ChannelId. -spec payload(tx()) -> binary(). payload(#channel_close_solo_tx{payload = Payload}) -> Payload. from_pubkey(#channel_close_solo_tx{from_id = FromPubKey}) -> aeser_id:specialize(FromPubKey, account). -spec check(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees()} | {error, term()}. check(#channel_close_solo_tx{payload = Payload, poi = PoI, fee = Fee, nonce = Nonce} = Tx, Trees, Env) -> ChannelPubKey = channel_pubkey(Tx), FromPubKey = from_pubkey(Tx), case aesc_utils:check_solo_close_payload(ChannelPubKey, FromPubKey, Nonce, Fee, Payload, PoI, Trees, Env) of ok -> {ok, Trees}; Err -> Err end. -spec process(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees(), aetx_env:env()}. process(#channel_close_solo_tx{payload = Payload, poi = PoI, fee = Fee, nonce = Nonce} = Tx, Trees, Env) -> Height = aetx_env:height(Env), ChannelPubKey = channel_pubkey(Tx), FromPubKey = from_pubkey(Tx), aesc_utils:process_solo_close(ChannelPubKey, FromPubKey, Nonce, Fee, Payload, PoI, Height, Trees, Env). -spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}. signers(#channel_close_solo_tx{} = Tx, _) -> {ok, [from_pubkey(Tx)]}. -spec serialize(tx()) -> {vsn(), list()}. serialize(#channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = TTL, fee = Fee, nonce = Nonce} = Tx) -> {version(Tx), [ {channel_id, ChannelId} , {from_id , FromId} , {payload , Payload} , {poi , aec_trees:serialize_poi(PoI)} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce} ]}. -spec deserialize(vsn(), list()) -> tx(). deserialize(?CHANNEL_CLOSE_SOLO_TX_VSN, [ {channel_id, ChannelId} , {from_id , FromId} , {payload , Payload} , {poi , PoI} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce}]) -> channel = aeser_id:specialize_type(ChannelId), account = aeser_id:specialize_type(FromId), #channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = aec_trees:deserialize_poi(PoI), ttl = TTL, fee = Fee, nonce = Nonce}. -spec for_client(tx()) -> map(). for_client(#channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = TTL, fee = Fee, nonce = Nonce}) -> #{<<"channel_id">> => aeser_api_encoder:encode(id_hash, ChannelId), <<"from_id">> => aeser_api_encoder:encode(id_hash, FromId), <<"payload">> => aeser_api_encoder:encode(transaction, Payload), <<"poi">> => aeser_api_encoder:encode(poi, aec_trees:serialize_poi(PoI)), <<"ttl">> => TTL, <<"fee">> => Fee, <<"nonce">> => Nonce}. serialization_template(?CHANNEL_CLOSE_SOLO_TX_VSN) -> [ {channel_id, id} , {from_id , id} , {payload , binary} , {poi , binary} , {ttl , int} , {fee , int} , {nonce , int} ]. -spec version(tx()) -> non_neg_integer(). version(_) -> ?CHANNEL_CLOSE_SOLO_TX_VSN. -spec valid_at_protocol(aec_hard_forks:protocol_vsn(), tx()) -> boolean(). valid_at_protocol(Protocol, #channel_close_solo_tx{payload = Payload}) -> aesc_utils:is_payload_valid_at_protocol(Protocol, Payload). -ifdef(TEST). set_payload(#channel_close_solo_tx{} = Tx, Payload) when is_binary(Payload) -> Tx#channel_close_solo_tx{payload = Payload}. set_nonce(#channel_close_solo_tx{} = Tx, Nonce) when is_integer(Nonce) -> Tx#channel_close_solo_tx{nonce = Nonce}. -endif.
null
https://raw.githubusercontent.com/aeternity/aeternity/a3df5ba31e089c292a662a49b1ffffdef003707c/apps/aechannel/src/aesc_close_solo_tx.erl
erlang
============================================================================= @doc @end ============================================================================= Behavior API aesc_signable_transaction callbacks =================================================================== Types =================================================================== =================================================================== Behaviour API ===================================================================
2018 , Aeternity Anstalt Module defining the State Channel close solo transaction -module(aesc_close_solo_tx). -behavior(aetx). -export([new/1, type/0, fee/1, gas/1, ttl/1, nonce/1, origin/1, check/3, payload/1, process/3, signers/2, version/1, serialization_template/1, serialize/1, deserialize/2, for_client/1, valid_at_protocol/2 ]). -export([channel_id/1, channel_pubkey/1]). -ifdef(TEST). -export([ set_payload/2 , set_nonce/2 ]). -endif. -define(CHANNEL_CLOSE_SOLO_TX_VSN, 1). -define(CHANNEL_CLOSE_SOLO_TX_TYPE, channel_close_solo_tx). -type vsn() :: non_neg_integer(). -record(channel_close_solo_tx, { channel_id :: aeser_id:id(), from_id :: aeser_id:id(), payload :: binary(), poi :: aec_trees:poi(), ttl :: aetx:tx_ttl(), fee :: non_neg_integer(), nonce :: non_neg_integer() }). -opaque tx() :: #channel_close_solo_tx{}. -export_type([tx/0]). -spec new(map()) -> {ok, aetx:tx()}. new(#{channel_id := ChannelId, from_id := FromId, payload := Payload, poi := PoI, fee := Fee, nonce := Nonce} = Args) -> channel = aeser_id:specialize_type(ChannelId), account = aeser_id:specialize_type(FromId), Tx = #channel_close_solo_tx{ channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = maps:get(ttl, Args, 0), fee = Fee, nonce = Nonce}, {ok, aetx:new(?MODULE, Tx)}. type() -> ?CHANNEL_CLOSE_SOLO_TX_TYPE. -spec fee(tx()) -> non_neg_integer(). fee(#channel_close_solo_tx{fee = Fee}) -> Fee. -spec gas(tx()) -> non_neg_integer(). gas(#channel_close_solo_tx{}) -> 0. -spec ttl(tx()) -> aetx:tx_ttl(). ttl(#channel_close_solo_tx{ttl = TTL}) -> TTL. -spec nonce(tx()) -> non_neg_integer(). nonce(#channel_close_solo_tx{nonce = Nonce}) -> Nonce. -spec origin(tx()) -> aec_keys:pubkey(). origin(#channel_close_solo_tx{} = Tx) -> from_pubkey(Tx). -spec channel_pubkey(tx()) -> aesc_channels:pubkey(). channel_pubkey(#channel_close_solo_tx{channel_id = ChannelId}) -> aeser_id:specialize(ChannelId, channel). channel_id(#channel_close_solo_tx{channel_id = ChannelId}) -> ChannelId. -spec payload(tx()) -> binary(). payload(#channel_close_solo_tx{payload = Payload}) -> Payload. from_pubkey(#channel_close_solo_tx{from_id = FromPubKey}) -> aeser_id:specialize(FromPubKey, account). -spec check(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees()} | {error, term()}. check(#channel_close_solo_tx{payload = Payload, poi = PoI, fee = Fee, nonce = Nonce} = Tx, Trees, Env) -> ChannelPubKey = channel_pubkey(Tx), FromPubKey = from_pubkey(Tx), case aesc_utils:check_solo_close_payload(ChannelPubKey, FromPubKey, Nonce, Fee, Payload, PoI, Trees, Env) of ok -> {ok, Trees}; Err -> Err end. -spec process(tx(), aec_trees:trees(), aetx_env:env()) -> {ok, aec_trees:trees(), aetx_env:env()}. process(#channel_close_solo_tx{payload = Payload, poi = PoI, fee = Fee, nonce = Nonce} = Tx, Trees, Env) -> Height = aetx_env:height(Env), ChannelPubKey = channel_pubkey(Tx), FromPubKey = from_pubkey(Tx), aesc_utils:process_solo_close(ChannelPubKey, FromPubKey, Nonce, Fee, Payload, PoI, Height, Trees, Env). -spec signers(tx(), aec_trees:trees()) -> {ok, list(aec_keys:pubkey())}. signers(#channel_close_solo_tx{} = Tx, _) -> {ok, [from_pubkey(Tx)]}. -spec serialize(tx()) -> {vsn(), list()}. serialize(#channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = TTL, fee = Fee, nonce = Nonce} = Tx) -> {version(Tx), [ {channel_id, ChannelId} , {from_id , FromId} , {payload , Payload} , {poi , aec_trees:serialize_poi(PoI)} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce} ]}. -spec deserialize(vsn(), list()) -> tx(). deserialize(?CHANNEL_CLOSE_SOLO_TX_VSN, [ {channel_id, ChannelId} , {from_id , FromId} , {payload , Payload} , {poi , PoI} , {ttl , TTL} , {fee , Fee} , {nonce , Nonce}]) -> channel = aeser_id:specialize_type(ChannelId), account = aeser_id:specialize_type(FromId), #channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = aec_trees:deserialize_poi(PoI), ttl = TTL, fee = Fee, nonce = Nonce}. -spec for_client(tx()) -> map(). for_client(#channel_close_solo_tx{channel_id = ChannelId, from_id = FromId, payload = Payload, poi = PoI, ttl = TTL, fee = Fee, nonce = Nonce}) -> #{<<"channel_id">> => aeser_api_encoder:encode(id_hash, ChannelId), <<"from_id">> => aeser_api_encoder:encode(id_hash, FromId), <<"payload">> => aeser_api_encoder:encode(transaction, Payload), <<"poi">> => aeser_api_encoder:encode(poi, aec_trees:serialize_poi(PoI)), <<"ttl">> => TTL, <<"fee">> => Fee, <<"nonce">> => Nonce}. serialization_template(?CHANNEL_CLOSE_SOLO_TX_VSN) -> [ {channel_id, id} , {from_id , id} , {payload , binary} , {poi , binary} , {ttl , int} , {fee , int} , {nonce , int} ]. -spec version(tx()) -> non_neg_integer(). version(_) -> ?CHANNEL_CLOSE_SOLO_TX_VSN. -spec valid_at_protocol(aec_hard_forks:protocol_vsn(), tx()) -> boolean(). valid_at_protocol(Protocol, #channel_close_solo_tx{payload = Payload}) -> aesc_utils:is_payload_valid_at_protocol(Protocol, Payload). -ifdef(TEST). set_payload(#channel_close_solo_tx{} = Tx, Payload) when is_binary(Payload) -> Tx#channel_close_solo_tx{payload = Payload}. set_nonce(#channel_close_solo_tx{} = Tx, Nonce) when is_integer(Nonce) -> Tx#channel_close_solo_tx{nonce = Nonce}. -endif.
aa09016adbbb6a204a45eb2f7a26449300b18e3291cee0b6b31f4af029278b88
technomancy/leiningen
main.clj
(ns leiningen.core.test.main (:use [clojure.test] [leiningen.core.main])) ;; Shamelessly stolen from #L28 (defmacro with-err-str "Evaluates exprs in a context in which *err* is bound to a fresh StringWriter. Returns the string created by any nested printing calls." [& body] `(let [s# (new java.io.StringWriter) p# (new java.io.PrintWriter s#)] (binding [*err* p#] ~@body (str s#)))) (deftest test-logs-sent-to-*err* (testing "main/warn sent to *err*" (is (= "Warning message\n" (with-err-str (warn "Warning message")))))) (deftest test-lookup-alias (testing "meta merging" (let [project {:aliases {"a" ^:foo ["root"] "b" ^:bar ["a"] "c" ^{:pass-through-help false :doc "Yo"} ["b"] "d" ^:pass-through-help ["c"]}}] (are [task m] (= (meta (lookup-alias task project)) m) "a" {:foo true} "b" {:bar true} "c" {:doc "Yo" :pass-through-help false} "d" {:pass-through-help true})))) (deftest test-task-args-help-pass-through (let [project {:aliases {"sirius-p" ["sirius" "partial"] "s" "sirius" "s-p" ["s" "partial"] "sirius-pp" ["sirius-p" "foo"] "sp" "s-p" "test" "test" "ohai" ^:pass-through-help ["run" "-m" "o.hai"] "aliaso" ["ohai"] "aliaso2" ["ohai"]}}] (testing "with :pass-through-help meta" (testing "on a var" (are [res arg] (= res (task-args arg project)) ["help" ["sirius"]] ["help" "sirius"] ["sirius" ["-h"]] ["sirius" "-h"] ["sirius" ["-?"]] ["sirius" "-?"] ["sirius" ["--help"]] ["sirius" "--help"] ["sirius" []] ["sirius"])) (testing "on an alias" (are [res arg] (= res (task-args arg project)) ["help" ["sirius-p"]] ["help" "sirius-p"] ["help" ["s"]] ["help" "s"] ["sirius" ["-h"]] ["s" "-h"] [["sirius" "partial"] ["-?"]] ["sirius-p" "-?"] ["sirius" ["--help"]] ["s" "--help"] [["sirius" "partial"] []] ["sirius-p"] [["sirius" "partial"] []] ["s-p"] [["sirius" "partial"] []] ["sp"] [["sirius" "partial" "foo"] ["bar"]] ["sirius-pp" "bar"] ["test" []] ["test"] ["sirius" []] ["s"] [["run" "-m" "o.hai"] ["-h"]] ["ohai" "-h"] [["run" "-m" "o.hai"] ["-h"]] ["aliaso" "-h"] [["run" "-m" "o.hai"] ["-h"]] ["aliaso2" "-h"] [["run" "-m" "o.hai"] ["--help"]] ["ohai" "--help"] [["run" "-m" "o.hai"] ["help"]] ["ohai" "help"]))))) (deftest test-matching-arity (is (not (matching-arity? (resolve-task "bluuugh") ["bogus" "arg" "s"]))) (is (matching-arity? (resolve-task "bluuugh") [])) (is (matching-arity? (resolve-task "var-args") [])) (is (matching-arity? (resolve-task "var-args") ["test-core" "hey"])) (is (not (matching-arity? (resolve-task "one-or-two") []))) (is (matching-arity? (resolve-task "one-or-two") ["clojure"])) (is (matching-arity? (resolve-task "one-or-two") ["clojure" "2"])) (is (not (matching-arity? (resolve-task "one-or-two") ["clojure" "2" "3"])))) (deftest partial-tasks (are [task args] (matching-arity? (resolve-task task) args) ["one-or-two" "clojure"] ["2"] ["one-or-two" "clojure" "2"] [] ["fixed-and-var-args" "one"] ["two"] ["fixed-and-var-args" "one" "two"] [] ["fixed-and-var-args" "one" "two"] ["more"]) (are [task args] (not (matching-arity? (resolve-task task) args)) ["one-or-two" "clojure"] ["2" "3"] ["one-or-two" "clojure" "2"] ["3"] ["fixed-and-var-args" "one"] [])) (deftest test-versions-match (is (versions-match? "1.2.12" "1.2.12")) (is (versions-match? "3.0" "3.0")) (is (versions-match? " 12.1.2" "12.1.2 ")) (is (not (versions-match? "1.2" "1.3"))) (is (not (versions-match? "1.2.0" "1.2"))) (is (not (versions-match? "1.2" "1.2.0"))) (is (versions-match? "2.1.3-SNAPSHOT" "2.1.3")) (is (versions-match? " 2.1.3-SNAPSHOT" "2.1.3")) (is (versions-match? "2.1.3" "2.1.3-FOO")) (is (not (versions-match? "3.0.0" "3.0.1-BAR")))) (deftest test-version-satisfies (is (version-satisfies? "1.5.0" "1.4.2")) (is (not (version-satisfies? "1.4.2" "1.5.0"))) (is (version-satisfies? "1.2.3" "1.1.1")) (is (version-satisfies? "1.2.0" "1.2")) (is (version-satisfies? "1.2" "1")) (is (not (version-satisfies? "1.67" "16.7")))) (deftest one-or-two-args (try (binding [*err* (java.io.StringWriter.)] (resolve-and-apply {:root true} ["one-or-two"])) (catch clojure.lang.ExceptionInfo e (re-find #"(?s)Wrong number of arguments to one-or-two task.*Expected \[one\] or \[one two\]" (.getMessage e))))) (deftest zero-args-msg (try (binding [*err* (java.io.StringWriter.)] (resolve-and-apply {:root true} ["zero" "too" "many" "args"])) (catch clojure.lang.ExceptionInfo e (re-find #"(?s)Wrong number of arguments to zero task.*Expected \[\]" (.getMessage e))))) (def ^:private distance @#'leiningen.core.main/distance) (deftest test-damerau-levensthein (is (zero? (distance "run" "run"))) (is (zero? (distance "uberjar" "uberjar"))) (is (zero? (distance "classpath" "classpath"))) (is (zero? (distance "with-profile" "with-profile"))) (is (= 1 (distance "rep" "repl"))) (is (= 1 (distance "est" "test"))) (is (= 1 (distance "java" "javac"))) (is (= 1 (distance "halp" "help"))) (is (= 1 (distance "lien" "lein"))) (is (= 4 (distance "" "repl"))) (is (= 6 (distance "foobar" ""))) (is (= 2 (distance "erlp" "repl"))) (is (= 2 (distance "deploy" "epdloy"))) (is (= 3 (distance "pugared" "upgrade")))) (deftest test-parse-options (is (= (parse-options ["--chicken"]) [{:--chicken true} '()])) (is (= (parse-options ["--beef" "rare"]) [{:--beef "rare"} []])) (is (= (parse-options [":fish" "salmon"]) [{:fish "salmon"} []])) (is (= (parse-options ["salmon" "trout"]) [{} ["salmon" "trout"]])) (is (= (parse-options ["--to-dir" "test2" "--ham"]) [{:--ham true, :--to-dir "test2"} []])) (is (= (parse-options ["--to-dir" "test2" "--ham" "--" "pate"]) [{:--ham true, :--to-dir "test2"} ["pate"]])) (is (= (parse-options ["--ham" "--to-dir" "test2" "pate"]) [{:--ham true, :--to-dir "test2"} ["pate"]])) (is (= (parse-options ["--to-dir" "test2" "--ham" "--"]) [{:--ham true, :--to-dir "test2"} []]))) (deftest test-spliced-project-values (let [p {:aliases {"go" ["echo" "write" :project/version]} :version "seventeen" :eval-in :leiningen} out (with-out-str (resolve-and-apply p ["go"]))] (is (= "write seventeen\n" out))))
null
https://raw.githubusercontent.com/technomancy/leiningen/24fb93936133bd7fc30c393c127e9e69bb5f2392/leiningen-core/test/leiningen/core/test/main.clj
clojure
Shamelessly stolen from
(ns leiningen.core.test.main (:use [clojure.test] [leiningen.core.main])) #L28 (defmacro with-err-str "Evaluates exprs in a context in which *err* is bound to a fresh StringWriter. Returns the string created by any nested printing calls." [& body] `(let [s# (new java.io.StringWriter) p# (new java.io.PrintWriter s#)] (binding [*err* p#] ~@body (str s#)))) (deftest test-logs-sent-to-*err* (testing "main/warn sent to *err*" (is (= "Warning message\n" (with-err-str (warn "Warning message")))))) (deftest test-lookup-alias (testing "meta merging" (let [project {:aliases {"a" ^:foo ["root"] "b" ^:bar ["a"] "c" ^{:pass-through-help false :doc "Yo"} ["b"] "d" ^:pass-through-help ["c"]}}] (are [task m] (= (meta (lookup-alias task project)) m) "a" {:foo true} "b" {:bar true} "c" {:doc "Yo" :pass-through-help false} "d" {:pass-through-help true})))) (deftest test-task-args-help-pass-through (let [project {:aliases {"sirius-p" ["sirius" "partial"] "s" "sirius" "s-p" ["s" "partial"] "sirius-pp" ["sirius-p" "foo"] "sp" "s-p" "test" "test" "ohai" ^:pass-through-help ["run" "-m" "o.hai"] "aliaso" ["ohai"] "aliaso2" ["ohai"]}}] (testing "with :pass-through-help meta" (testing "on a var" (are [res arg] (= res (task-args arg project)) ["help" ["sirius"]] ["help" "sirius"] ["sirius" ["-h"]] ["sirius" "-h"] ["sirius" ["-?"]] ["sirius" "-?"] ["sirius" ["--help"]] ["sirius" "--help"] ["sirius" []] ["sirius"])) (testing "on an alias" (are [res arg] (= res (task-args arg project)) ["help" ["sirius-p"]] ["help" "sirius-p"] ["help" ["s"]] ["help" "s"] ["sirius" ["-h"]] ["s" "-h"] [["sirius" "partial"] ["-?"]] ["sirius-p" "-?"] ["sirius" ["--help"]] ["s" "--help"] [["sirius" "partial"] []] ["sirius-p"] [["sirius" "partial"] []] ["s-p"] [["sirius" "partial"] []] ["sp"] [["sirius" "partial" "foo"] ["bar"]] ["sirius-pp" "bar"] ["test" []] ["test"] ["sirius" []] ["s"] [["run" "-m" "o.hai"] ["-h"]] ["ohai" "-h"] [["run" "-m" "o.hai"] ["-h"]] ["aliaso" "-h"] [["run" "-m" "o.hai"] ["-h"]] ["aliaso2" "-h"] [["run" "-m" "o.hai"] ["--help"]] ["ohai" "--help"] [["run" "-m" "o.hai"] ["help"]] ["ohai" "help"]))))) (deftest test-matching-arity (is (not (matching-arity? (resolve-task "bluuugh") ["bogus" "arg" "s"]))) (is (matching-arity? (resolve-task "bluuugh") [])) (is (matching-arity? (resolve-task "var-args") [])) (is (matching-arity? (resolve-task "var-args") ["test-core" "hey"])) (is (not (matching-arity? (resolve-task "one-or-two") []))) (is (matching-arity? (resolve-task "one-or-two") ["clojure"])) (is (matching-arity? (resolve-task "one-or-two") ["clojure" "2"])) (is (not (matching-arity? (resolve-task "one-or-two") ["clojure" "2" "3"])))) (deftest partial-tasks (are [task args] (matching-arity? (resolve-task task) args) ["one-or-two" "clojure"] ["2"] ["one-or-two" "clojure" "2"] [] ["fixed-and-var-args" "one"] ["two"] ["fixed-and-var-args" "one" "two"] [] ["fixed-and-var-args" "one" "two"] ["more"]) (are [task args] (not (matching-arity? (resolve-task task) args)) ["one-or-two" "clojure"] ["2" "3"] ["one-or-two" "clojure" "2"] ["3"] ["fixed-and-var-args" "one"] [])) (deftest test-versions-match (is (versions-match? "1.2.12" "1.2.12")) (is (versions-match? "3.0" "3.0")) (is (versions-match? " 12.1.2" "12.1.2 ")) (is (not (versions-match? "1.2" "1.3"))) (is (not (versions-match? "1.2.0" "1.2"))) (is (not (versions-match? "1.2" "1.2.0"))) (is (versions-match? "2.1.3-SNAPSHOT" "2.1.3")) (is (versions-match? " 2.1.3-SNAPSHOT" "2.1.3")) (is (versions-match? "2.1.3" "2.1.3-FOO")) (is (not (versions-match? "3.0.0" "3.0.1-BAR")))) (deftest test-version-satisfies (is (version-satisfies? "1.5.0" "1.4.2")) (is (not (version-satisfies? "1.4.2" "1.5.0"))) (is (version-satisfies? "1.2.3" "1.1.1")) (is (version-satisfies? "1.2.0" "1.2")) (is (version-satisfies? "1.2" "1")) (is (not (version-satisfies? "1.67" "16.7")))) (deftest one-or-two-args (try (binding [*err* (java.io.StringWriter.)] (resolve-and-apply {:root true} ["one-or-two"])) (catch clojure.lang.ExceptionInfo e (re-find #"(?s)Wrong number of arguments to one-or-two task.*Expected \[one\] or \[one two\]" (.getMessage e))))) (deftest zero-args-msg (try (binding [*err* (java.io.StringWriter.)] (resolve-and-apply {:root true} ["zero" "too" "many" "args"])) (catch clojure.lang.ExceptionInfo e (re-find #"(?s)Wrong number of arguments to zero task.*Expected \[\]" (.getMessage e))))) (def ^:private distance @#'leiningen.core.main/distance) (deftest test-damerau-levensthein (is (zero? (distance "run" "run"))) (is (zero? (distance "uberjar" "uberjar"))) (is (zero? (distance "classpath" "classpath"))) (is (zero? (distance "with-profile" "with-profile"))) (is (= 1 (distance "rep" "repl"))) (is (= 1 (distance "est" "test"))) (is (= 1 (distance "java" "javac"))) (is (= 1 (distance "halp" "help"))) (is (= 1 (distance "lien" "lein"))) (is (= 4 (distance "" "repl"))) (is (= 6 (distance "foobar" ""))) (is (= 2 (distance "erlp" "repl"))) (is (= 2 (distance "deploy" "epdloy"))) (is (= 3 (distance "pugared" "upgrade")))) (deftest test-parse-options (is (= (parse-options ["--chicken"]) [{:--chicken true} '()])) (is (= (parse-options ["--beef" "rare"]) [{:--beef "rare"} []])) (is (= (parse-options [":fish" "salmon"]) [{:fish "salmon"} []])) (is (= (parse-options ["salmon" "trout"]) [{} ["salmon" "trout"]])) (is (= (parse-options ["--to-dir" "test2" "--ham"]) [{:--ham true, :--to-dir "test2"} []])) (is (= (parse-options ["--to-dir" "test2" "--ham" "--" "pate"]) [{:--ham true, :--to-dir "test2"} ["pate"]])) (is (= (parse-options ["--ham" "--to-dir" "test2" "pate"]) [{:--ham true, :--to-dir "test2"} ["pate"]])) (is (= (parse-options ["--to-dir" "test2" "--ham" "--"]) [{:--ham true, :--to-dir "test2"} []]))) (deftest test-spliced-project-values (let [p {:aliases {"go" ["echo" "write" :project/version]} :version "seventeen" :eval-in :leiningen} out (with-out-str (resolve-and-apply p ["go"]))] (is (= "write seventeen\n" out))))
36248f068215876fa7aa5bded310f244ee18fb1e8de2726939b5e23fbd38891d
komadori/HsQML
Objects.hs
{-# LANGUAGE ScopedTypeVariables, TypeFamilies, FlexibleContexts, FlexibleInstances, LiberalTypeSynonyms #-} -- | Facilities for defining new object types which can be marshalled between and . module Graphics.QML.Objects ( -- * Object References ObjRef, newObject, newObjectDC, fromObjRef, -- * Dynamic Object References AnyObjRef, anyObjRef, fromAnyObjRef, -- * Class Definition Class, newClass, DefaultClass ( classMembers), Member, -- * Methods defMethod, defMethod', MethodSuffix, -- * Signals defSignal, defSignalNamedParams, fireSignal, SignalKey, newSignalKey, SignalKeyClass ( type SignalParams), SignalSuffix, -- * Properties defPropertyConst, defPropertyRO, defPropertySigRO, defPropertyRW, defPropertySigRW, defPropertyConst', defPropertyRO', defPropertySigRO', defPropertyRW', defPropertySigRW' ) where import Graphics.QML.Internal.BindCore import Graphics.QML.Internal.BindObj import Graphics.QML.Internal.JobQueue import Graphics.QML.Internal.Marshal import Graphics.QML.Internal.MetaObj import Graphics.QML.Internal.Objects import Graphics.QML.Internal.Types import Graphics.QML.Objects.ParamNames import Control.Concurrent.MVar import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe import Data.Proxy import Data.Tagged import Data.Typeable import Data.IORef import Data.Unique import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Array import System.IO.Unsafe import Numeric -- ObjRef -- | Creates a object given a ' Class ' and a value of type @tt@. newObject :: forall tt. Class tt -> tt -> IO (ObjRef tt) newObject (Class cHndl) obj = fmap ObjRef $ hsqmlCreateObject obj cHndl | Creates a object given a value of type @tt@ which has a ' DefaultClass ' instance . newObjectDC :: forall tt. (DefaultClass tt) => tt -> IO (ObjRef tt) newObjectDC obj = do clazz <- getDefaultClass :: IO (Class tt) newObject clazz obj | Returns the associated value of the underlying type @tt@ from an instance of the class which wraps it . fromObjRef :: ObjRef tt -> tt fromObjRef = unsafeDupablePerformIO . fromObjRefIO | Upcasts an ' ObjRef ' into an ' AnyObjRef ' . anyObjRef :: ObjRef tt -> AnyObjRef anyObjRef (ObjRef hndl) = AnyObjRef hndl | Attempts to downcast an ' AnyObjRef ' into an ' ObjRef ' with the specific underlying type @tt@. fromAnyObjRef :: (Typeable tt) => AnyObjRef -> Maybe (ObjRef tt) fromAnyObjRef = unsafeDupablePerformIO . fromAnyObjRefIO -- -- Class -- | Represents a class which wraps the type @tt@. newtype Class tt = Class HsQMLClassHandle | Creates a new class for the type @tt@. newClass :: forall tt. (Typeable tt) => [Member tt] -> IO (Class tt) newClass = fmap Class . createClass (typeOf (undefined :: tt)) createClass :: forall tt. TypeRep -> [Member tt] -> IO HsQMLClassHandle createClass typRep ms = do hsqmlInit classId <- hsqmlGetNextClassId let constrs t = typeRepTyCon t : (concatMap constrs $ typeRepArgs t) name = foldr (\c s -> showString (tyConName c) . showChar '_' . s) id (constrs typRep) $ showInt classId "" ms' = ms ++ implicitSignals ms moc = compileClass name ms' sigs = filterMembers SignalMember ms' sigMap = Map.fromList $ flip zip [0..] $ map (fromJust . memberKey) sigs info = ClassInfo typRep sigMap maybeMarshalFunc = maybe (return nullFunPtr) marshalFunc metaDataPtr <- crlToNewArray return (mData moc) metaStrInfoPtr <- crlToNewArray return (mStrInfo moc) metaStrCharPtr <- crlToNewArray return (mStrChar moc) methodsPtr <- crlToNewArray maybeMarshalFunc (mFuncMethods moc) propsPtr <- crlToNewArray maybeMarshalFunc (mFuncProperties moc) maybeHndl <- hsqmlCreateClass metaDataPtr metaStrInfoPtr metaStrCharPtr info methodsPtr propsPtr case maybeHndl of Just hndl -> return hndl Nothing -> error ("Failed to create QML class '"++name++"'.") implicitSignals :: [Member tt] -> [Member tt] implicitSignals ms = let sigKeys = Set.fromList $ mapMaybe memberKey $ filterMembers SignalMember ms impKeys = filter (flip Set.notMember sigKeys) $ mapMaybe memberKey $ filterMembers PropertyMember ms impMember i k = Member SignalMember ("__implicitSignal" ++ show i) tyVoid [] (\_ _ -> return ()) Nothing (Just k) in map (uncurry impMember) $ zip [(0::Int)..] impKeys -- -- Default Class -- data MemoStore k v = MemoStore (MVar (Map k v)) (IORef (Map k v)) newMemoStore :: IO (MemoStore k v) newMemoStore = do let m = Map.empty mr <- newMVar m ir <- newIORef m return $ MemoStore mr ir getFromMemoStore :: (Ord k) => MemoStore k v -> k -> IO v -> IO (Bool, v) getFromMemoStore (MemoStore mr ir) key fn = do fstMap <- readIORef ir case Map.lookup key fstMap of Just val -> return (False, val) Nothing -> modifyMVar mr $ \sndMap -> do case Map.lookup key sndMap of Just val -> return (sndMap, (False, val)) Nothing -> do val <- fn let newMap = Map.insert key val sndMap writeIORef ir newMap return (newMap, (True, val)) | The class ' DefaultClass ' specifies a standard class definition for the type @tt@. class (Typeable tt) => DefaultClass tt where -- | List of default class members. classMembers :: [Member tt] # NOINLINE defaultClassDb # defaultClassDb :: MemoStore TypeRep HsQMLClassHandle defaultClassDb = unsafePerformIO $ newMemoStore getDefaultClass :: forall tt. (DefaultClass tt) => IO (Class tt) getDefaultClass = do let typ = typeOf (undefined :: tt) (_, val) <- getFromMemoStore defaultClassDb typ $ createClass typ (classMembers :: [Member tt]) return (Class val) -- -- Method -- data MethodTypeInfo = MethodTypeInfo { methodParamTypes :: [TypeId], methodReturnType :: TypeId } | Supports marshalling functions with an arbitrary number of -- arguments. class MethodSuffix a where mkMethodFunc :: Int -> a -> Ptr (Ptr ()) -> ErrIO () mkMethodTypes :: Tagged a MethodTypeInfo instance (Marshal a, CanGetFrom a ~ Yes, MethodSuffix b) => MethodSuffix (a -> b) where mkMethodFunc n f pv = do ptr <- errIO $ peekElemOff pv n val <- mFromCVal ptr mkMethodFunc (n+1) (f val) pv return () mkMethodTypes = let (MethodTypeInfo p r) = untag (mkMethodTypes :: Tagged b MethodTypeInfo) typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ MethodTypeInfo (typ:p) r instance (Marshal a, CanReturnTo a ~ Yes) => MethodSuffix (IO a) where mkMethodFunc _ f pv = errIO $ do ptr <- peekElemOff pv 0 val <- f if nullPtr == ptr then return () else mToCVal val ptr mkMethodTypes = let typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ MethodTypeInfo [] typ mkUniformFunc :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms) => (tt -> ms) -> UniformFunc mkUniformFunc f = \pt pv -> do hndl <- hsqmlGetObjectFromPointer pt this <- mFromHndl hndl runErrIO $ mkMethodFunc 1 (f this) pv newtype VoidIO = VoidIO {runVoidIO :: (IO ())} instance MethodSuffix VoidIO where mkMethodFunc _ f _ = errIO $ runVoidIO f mkMethodTypes = Tagged $ MethodTypeInfo [] tyVoid class IsVoidIO a instance (IsVoidIO b) => IsVoidIO (a -> b) instance IsVoidIO VoidIO mkSpecialFunc :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms, IsVoidIO ms) => (tt -> ms) -> UniformFunc mkSpecialFunc f = \pt pv -> do hndl <- hsqmlGetObjectFromPointer pt this <- mFromHndl hndl runErrIO $ mkMethodFunc 0 (f this) pv | Defines a named method using a function @f@ in the IO monad . -- The first argument to receives the \"this\ " object and hence must match -- the type of the class on which the method is being defined. Subsequently, there may be zero or more parameter arguments followed by an optional return argument in the IO monad . defMethod :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms) => String -> (tt -> ms) -> Member (GetObjType tt) defMethod name f = let crude = untag (mkMethodTypes :: Tagged ms MethodTypeInfo) in Member MethodMember name (methodReturnType crude) (map (\t->("",t)) $ methodParamTypes crude) (mkUniformFunc f) Nothing Nothing | of ' defMethod ' which is less polymorphic to reduce the need for type -- signatures. defMethod' :: forall obj ms. (Typeable obj, MethodSuffix ms) => String -> (ObjRef obj -> ms) -> Member obj defMethod' = defMethod -- Signal -- data SignalTypeInfo = SignalTypeInfo { signalParamTypes :: [TypeId] } -- | Defines a named signal. The signal is identified in subsequent calls to ' fireSignal ' using a ' SignalKeyValue ' . This can be either i ) type - based -- using 'Proxy' @sk@ where @sk@ is an instance of the 'SignalKeyClass' class or ii ) value - based using a ' SignalKey ' value creating using ' newSignalKey ' . defSignal :: forall obj skv. (SignalKeyValue skv) => String -> skv -> Member obj defSignal name key = defSignalNamedParams name key anonParams -- | Defines a named signal with named parameters. This is otherwise identical to ' defSignal ' , but allows code to reference signal parameters by - name -- in addition to by-position. defSignalNamedParams :: forall obj skv. (SignalKeyValue skv) => String -> skv -> ParamNames (SignalParamNames (SignalValueParams skv)) -> Member obj defSignalNamedParams name key pnames = let crude = untag (mkSignalTypes :: Tagged (SignalValueParams skv) SignalTypeInfo) in Member SignalMember name tyVoid (paramNames pnames `zip` signalParamTypes crude) (\_ _ -> return ()) Nothing (Just $ signalKey key) -- | Fires a signal defined on an object instance. The signal is identified -- using either a type- or value-based signal key, as described in the documentation for ' defSignal ' . The first argument is the signal key , the second is the object , and the remaining arguments , if any , are the arguments -- to the signal as specified by the signal key. -- -- If this function is called using a signal key which doesn't match a signal -- defined on the supplied object, it will silently do nothing. -- -- This function is safe to call from any thread. Any attached signal handlers -- will be executed asynchronously on the event loop thread. fireSignal :: forall tt skv. (Marshal tt, CanPassTo tt ~ Yes, IsObjType tt ~ Yes, SignalKeyValue skv) => skv -> tt -> SignalValueParams skv fireSignal key this = let start cnt = postJob $ do hndl <- mToHndl this info <- hsqmlObjectGetHsTyperep hndl let slotMay = Map.lookup (signalKey key) $ cinfoSignals info case slotMay of Just slotIdx -> withActiveObject hndl $ cnt $ SignalData hndl slotIdx Nothing -> return () -- Should warn? cont ps (SignalData hndl slotIdx) = withArray (nullPtr:ps) (\pptr -> hsqmlFireSignal hndl slotIdx pptr) in mkSignalArgs start cont data SignalData = SignalData HsQMLObjectHandle Int | Values of the type ' SignalKey ' identify distinct signals by value . The -- type parameter @p@ specifies the signal's signature. newtype SignalKey p = SignalKey Unique | Creates a new ' SignalKey ' . newSignalKey :: (SignalSuffix p) => IO (SignalKey p) newSignalKey = fmap SignalKey $ newUnique -- | Instances of the 'SignalKeyClass' class identify distinct signals by type. The associated ' SignalParams ' type specifies the signal 's signature . class (SignalSuffix (SignalParams sk)) => SignalKeyClass sk where type SignalParams sk class (SignalSuffix (SignalValueParams skv)) => SignalKeyValue skv where type SignalValueParams skv signalKey :: skv -> MemberKey instance (SignalKeyClass sk, Typeable sk) => SignalKeyValue (Proxy sk) where type SignalValueParams (Proxy sk) = SignalParams sk signalKey _ = TypeKey $ typeOf (undefined :: sk) instance (SignalSuffix p) => SignalKeyValue (SignalKey p) where type SignalValueParams (SignalKey p) = p signalKey (SignalKey u) = DataKey u | Supports marshalling an arbitrary number of arguments into a signal . class (AnonParams (SignalParamNames ss)) => SignalSuffix ss where type SignalParamNames ss mkSignalArgs :: forall usr. ((usr -> IO ()) -> IO ()) -> ([Ptr ()] -> usr -> IO ()) -> ss mkSignalTypes :: Tagged ss SignalTypeInfo instance (Marshal a, CanPassTo a ~ Yes, SignalSuffix b) => SignalSuffix (a -> b) where type SignalParamNames (a -> b) = String -> SignalParamNames b mkSignalArgs start cont param = mkSignalArgs start (\ps usr -> mWithCVal param (\ptr -> cont (ptr:ps) usr)) mkSignalTypes = let (SignalTypeInfo p) = untag (mkSignalTypes :: Tagged b SignalTypeInfo) typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ SignalTypeInfo (typ:p) instance SignalSuffix (IO ()) where type SignalParamNames (IO ()) = () mkSignalArgs start cont = start $ cont [] mkSignalTypes = Tagged $ SignalTypeInfo [] -- -- Property -- -- | Defines a named constant property using an accessor function in the IO -- monad. defPropertyConst :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes) => String -> (tt -> IO tr) -> Member (GetObjType tt) defPropertyConst name g = Member ConstPropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing Nothing -- | Defines a named read-only property using an accessor function in the IO -- monad. defPropertyRO :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes) => String -> (tt -> IO tr) -> Member (GetObjType tt) defPropertyRO name g = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing Nothing -- | Defines a named read-only property with an associated signal. defPropertySigRO :: forall tt tr skv. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, SignalKeyValue skv) => String -> skv -> (tt -> IO tr) -> Member (GetObjType tt) defPropertySigRO name key g = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing (Just $ signalKey key) -- | Defines a named read-write property using a pair of accessor and mutator functions in the IO monad . defPropertyRW :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) => String -> (tt -> IO tr) -> (tt -> tr -> IO ()) -> Member (GetObjType tt) defPropertyRW name g s = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) (Just $ mkSpecialFunc (\a b -> VoidIO $ s a b)) Nothing -- | Defines a named read-write property with an associated signal. defPropertySigRW :: forall tt tr skv. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes, SignalKeyValue skv) => String -> skv -> (tt -> IO tr) -> (tt -> tr -> IO ()) -> Member (GetObjType tt) defPropertySigRW name key g s = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) (Just $ mkSpecialFunc (\a b -> VoidIO $ s a b)) (Just $ signalKey key) | of ' defPropertyConst ' which is less polymorphic to reduce the need -- for type signatures. defPropertyConst' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> Member obj defPropertyConst' = defPropertyConst | of ' defPropertyRO ' which is less polymorphic to reduce the need for -- type signatures. defPropertyRO' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> Member obj defPropertyRO' = defPropertyRO | of ' defPropertySigRO ' which is less polymorphic to reduce the need -- for type signatures. defPropertySigRO' :: forall obj tr skv. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, SignalKeyValue skv) => String -> skv -> (ObjRef obj -> IO tr) -> Member obj defPropertySigRO' = defPropertySigRO | of ' defPropertyRW ' which is less polymorphic to reduce the need for -- type signatures. defPropertyRW' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj defPropertyRW' = defPropertyRW | of ' defPropertySigRW ' which is less polymorphic to reduce the need -- for type signatures. defPropertySigRW' :: forall obj tr skv. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes, SignalKeyValue skv) => String -> skv -> (ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj defPropertySigRW' = defPropertySigRW
null
https://raw.githubusercontent.com/komadori/HsQML/f57cffe4e3595bdf743bdbe6f44bf45a4001d35f/src/Graphics/QML/Objects.hs
haskell
# LANGUAGE ScopedTypeVariables, TypeFamilies, FlexibleContexts, FlexibleInstances, LiberalTypeSynonyms # | Facilities for defining new object types which can be marshalled between * Object References * Dynamic Object References * Class Definition * Methods * Signals * Properties Class Default Class | List of default class members. Method arguments. the type of the class on which the method is being defined. Subsequently, signatures. | Defines a named signal. The signal is identified in subsequent calls to using 'Proxy' @sk@ where @sk@ is an instance of the 'SignalKeyClass' class | Defines a named signal with named parameters. This is otherwise identical in addition to by-position. | Fires a signal defined on an object instance. The signal is identified using either a type- or value-based signal key, as described in the to the signal as specified by the signal key. If this function is called using a signal key which doesn't match a signal defined on the supplied object, it will silently do nothing. This function is safe to call from any thread. Any attached signal handlers will be executed asynchronously on the event loop thread. Should warn? type parameter @p@ specifies the signal's signature. | Instances of the 'SignalKeyClass' class identify distinct signals by type. Property | Defines a named constant property using an accessor function in the IO monad. | Defines a named read-only property using an accessor function in the IO monad. | Defines a named read-only property with an associated signal. | Defines a named read-write property using a pair of accessor and mutator | Defines a named read-write property with an associated signal. for type signatures. type signatures. for type signatures. type signatures. for type signatures.
and . module Graphics.QML.Objects ( ObjRef, newObject, newObjectDC, fromObjRef, AnyObjRef, anyObjRef, fromAnyObjRef, Class, newClass, DefaultClass ( classMembers), Member, defMethod, defMethod', MethodSuffix, defSignal, defSignalNamedParams, fireSignal, SignalKey, newSignalKey, SignalKeyClass ( type SignalParams), SignalSuffix, defPropertyConst, defPropertyRO, defPropertySigRO, defPropertyRW, defPropertySigRW, defPropertyConst', defPropertyRO', defPropertySigRO', defPropertyRW', defPropertySigRW' ) where import Graphics.QML.Internal.BindCore import Graphics.QML.Internal.BindObj import Graphics.QML.Internal.JobQueue import Graphics.QML.Internal.Marshal import Graphics.QML.Internal.MetaObj import Graphics.QML.Internal.Objects import Graphics.QML.Internal.Types import Graphics.QML.Objects.ParamNames import Control.Concurrent.MVar import Data.Map (Map) import qualified Data.Map as Map import qualified Data.Set as Set import Data.Maybe import Data.Proxy import Data.Tagged import Data.Typeable import Data.IORef import Data.Unique import Foreign.Ptr import Foreign.Storable import Foreign.Marshal.Array import System.IO.Unsafe import Numeric ObjRef | Creates a object given a ' Class ' and a value of type @tt@. newObject :: forall tt. Class tt -> tt -> IO (ObjRef tt) newObject (Class cHndl) obj = fmap ObjRef $ hsqmlCreateObject obj cHndl | Creates a object given a value of type @tt@ which has a ' DefaultClass ' instance . newObjectDC :: forall tt. (DefaultClass tt) => tt -> IO (ObjRef tt) newObjectDC obj = do clazz <- getDefaultClass :: IO (Class tt) newObject clazz obj | Returns the associated value of the underlying type @tt@ from an instance of the class which wraps it . fromObjRef :: ObjRef tt -> tt fromObjRef = unsafeDupablePerformIO . fromObjRefIO | Upcasts an ' ObjRef ' into an ' AnyObjRef ' . anyObjRef :: ObjRef tt -> AnyObjRef anyObjRef (ObjRef hndl) = AnyObjRef hndl | Attempts to downcast an ' AnyObjRef ' into an ' ObjRef ' with the specific underlying type @tt@. fromAnyObjRef :: (Typeable tt) => AnyObjRef -> Maybe (ObjRef tt) fromAnyObjRef = unsafeDupablePerformIO . fromAnyObjRefIO | Represents a class which wraps the type @tt@. newtype Class tt = Class HsQMLClassHandle | Creates a new class for the type @tt@. newClass :: forall tt. (Typeable tt) => [Member tt] -> IO (Class tt) newClass = fmap Class . createClass (typeOf (undefined :: tt)) createClass :: forall tt. TypeRep -> [Member tt] -> IO HsQMLClassHandle createClass typRep ms = do hsqmlInit classId <- hsqmlGetNextClassId let constrs t = typeRepTyCon t : (concatMap constrs $ typeRepArgs t) name = foldr (\c s -> showString (tyConName c) . showChar '_' . s) id (constrs typRep) $ showInt classId "" ms' = ms ++ implicitSignals ms moc = compileClass name ms' sigs = filterMembers SignalMember ms' sigMap = Map.fromList $ flip zip [0..] $ map (fromJust . memberKey) sigs info = ClassInfo typRep sigMap maybeMarshalFunc = maybe (return nullFunPtr) marshalFunc metaDataPtr <- crlToNewArray return (mData moc) metaStrInfoPtr <- crlToNewArray return (mStrInfo moc) metaStrCharPtr <- crlToNewArray return (mStrChar moc) methodsPtr <- crlToNewArray maybeMarshalFunc (mFuncMethods moc) propsPtr <- crlToNewArray maybeMarshalFunc (mFuncProperties moc) maybeHndl <- hsqmlCreateClass metaDataPtr metaStrInfoPtr metaStrCharPtr info methodsPtr propsPtr case maybeHndl of Just hndl -> return hndl Nothing -> error ("Failed to create QML class '"++name++"'.") implicitSignals :: [Member tt] -> [Member tt] implicitSignals ms = let sigKeys = Set.fromList $ mapMaybe memberKey $ filterMembers SignalMember ms impKeys = filter (flip Set.notMember sigKeys) $ mapMaybe memberKey $ filterMembers PropertyMember ms impMember i k = Member SignalMember ("__implicitSignal" ++ show i) tyVoid [] (\_ _ -> return ()) Nothing (Just k) in map (uncurry impMember) $ zip [(0::Int)..] impKeys data MemoStore k v = MemoStore (MVar (Map k v)) (IORef (Map k v)) newMemoStore :: IO (MemoStore k v) newMemoStore = do let m = Map.empty mr <- newMVar m ir <- newIORef m return $ MemoStore mr ir getFromMemoStore :: (Ord k) => MemoStore k v -> k -> IO v -> IO (Bool, v) getFromMemoStore (MemoStore mr ir) key fn = do fstMap <- readIORef ir case Map.lookup key fstMap of Just val -> return (False, val) Nothing -> modifyMVar mr $ \sndMap -> do case Map.lookup key sndMap of Just val -> return (sndMap, (False, val)) Nothing -> do val <- fn let newMap = Map.insert key val sndMap writeIORef ir newMap return (newMap, (True, val)) | The class ' DefaultClass ' specifies a standard class definition for the type @tt@. class (Typeable tt) => DefaultClass tt where classMembers :: [Member tt] # NOINLINE defaultClassDb # defaultClassDb :: MemoStore TypeRep HsQMLClassHandle defaultClassDb = unsafePerformIO $ newMemoStore getDefaultClass :: forall tt. (DefaultClass tt) => IO (Class tt) getDefaultClass = do let typ = typeOf (undefined :: tt) (_, val) <- getFromMemoStore defaultClassDb typ $ createClass typ (classMembers :: [Member tt]) return (Class val) data MethodTypeInfo = MethodTypeInfo { methodParamTypes :: [TypeId], methodReturnType :: TypeId } | Supports marshalling functions with an arbitrary number of class MethodSuffix a where mkMethodFunc :: Int -> a -> Ptr (Ptr ()) -> ErrIO () mkMethodTypes :: Tagged a MethodTypeInfo instance (Marshal a, CanGetFrom a ~ Yes, MethodSuffix b) => MethodSuffix (a -> b) where mkMethodFunc n f pv = do ptr <- errIO $ peekElemOff pv n val <- mFromCVal ptr mkMethodFunc (n+1) (f val) pv return () mkMethodTypes = let (MethodTypeInfo p r) = untag (mkMethodTypes :: Tagged b MethodTypeInfo) typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ MethodTypeInfo (typ:p) r instance (Marshal a, CanReturnTo a ~ Yes) => MethodSuffix (IO a) where mkMethodFunc _ f pv = errIO $ do ptr <- peekElemOff pv 0 val <- f if nullPtr == ptr then return () else mToCVal val ptr mkMethodTypes = let typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ MethodTypeInfo [] typ mkUniformFunc :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms) => (tt -> ms) -> UniformFunc mkUniformFunc f = \pt pv -> do hndl <- hsqmlGetObjectFromPointer pt this <- mFromHndl hndl runErrIO $ mkMethodFunc 1 (f this) pv newtype VoidIO = VoidIO {runVoidIO :: (IO ())} instance MethodSuffix VoidIO where mkMethodFunc _ f _ = errIO $ runVoidIO f mkMethodTypes = Tagged $ MethodTypeInfo [] tyVoid class IsVoidIO a instance (IsVoidIO b) => IsVoidIO (a -> b) instance IsVoidIO VoidIO mkSpecialFunc :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms, IsVoidIO ms) => (tt -> ms) -> UniformFunc mkSpecialFunc f = \pt pv -> do hndl <- hsqmlGetObjectFromPointer pt this <- mFromHndl hndl runErrIO $ mkMethodFunc 0 (f this) pv | Defines a named method using a function @f@ in the IO monad . The first argument to receives the \"this\ " object and hence must match there may be zero or more parameter arguments followed by an optional return argument in the IO monad . defMethod :: forall tt ms. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, MethodSuffix ms) => String -> (tt -> ms) -> Member (GetObjType tt) defMethod name f = let crude = untag (mkMethodTypes :: Tagged ms MethodTypeInfo) in Member MethodMember name (methodReturnType crude) (map (\t->("",t)) $ methodParamTypes crude) (mkUniformFunc f) Nothing Nothing | of ' defMethod ' which is less polymorphic to reduce the need for type defMethod' :: forall obj ms. (Typeable obj, MethodSuffix ms) => String -> (ObjRef obj -> ms) -> Member obj defMethod' = defMethod Signal data SignalTypeInfo = SignalTypeInfo { signalParamTypes :: [TypeId] } ' fireSignal ' using a ' SignalKeyValue ' . This can be either i ) type - based or ii ) value - based using a ' SignalKey ' value creating using ' newSignalKey ' . defSignal :: forall obj skv. (SignalKeyValue skv) => String -> skv -> Member obj defSignal name key = defSignalNamedParams name key anonParams to ' defSignal ' , but allows code to reference signal parameters by - name defSignalNamedParams :: forall obj skv. (SignalKeyValue skv) => String -> skv -> ParamNames (SignalParamNames (SignalValueParams skv)) -> Member obj defSignalNamedParams name key pnames = let crude = untag (mkSignalTypes :: Tagged (SignalValueParams skv) SignalTypeInfo) in Member SignalMember name tyVoid (paramNames pnames `zip` signalParamTypes crude) (\_ _ -> return ()) Nothing (Just $ signalKey key) documentation for ' defSignal ' . The first argument is the signal key , the second is the object , and the remaining arguments , if any , are the arguments fireSignal :: forall tt skv. (Marshal tt, CanPassTo tt ~ Yes, IsObjType tt ~ Yes, SignalKeyValue skv) => skv -> tt -> SignalValueParams skv fireSignal key this = let start cnt = postJob $ do hndl <- mToHndl this info <- hsqmlObjectGetHsTyperep hndl let slotMay = Map.lookup (signalKey key) $ cinfoSignals info case slotMay of Just slotIdx -> withActiveObject hndl $ cnt $ SignalData hndl slotIdx Nothing -> cont ps (SignalData hndl slotIdx) = withArray (nullPtr:ps) (\pptr -> hsqmlFireSignal hndl slotIdx pptr) in mkSignalArgs start cont data SignalData = SignalData HsQMLObjectHandle Int | Values of the type ' SignalKey ' identify distinct signals by value . The newtype SignalKey p = SignalKey Unique | Creates a new ' SignalKey ' . newSignalKey :: (SignalSuffix p) => IO (SignalKey p) newSignalKey = fmap SignalKey $ newUnique The associated ' SignalParams ' type specifies the signal 's signature . class (SignalSuffix (SignalParams sk)) => SignalKeyClass sk where type SignalParams sk class (SignalSuffix (SignalValueParams skv)) => SignalKeyValue skv where type SignalValueParams skv signalKey :: skv -> MemberKey instance (SignalKeyClass sk, Typeable sk) => SignalKeyValue (Proxy sk) where type SignalValueParams (Proxy sk) = SignalParams sk signalKey _ = TypeKey $ typeOf (undefined :: sk) instance (SignalSuffix p) => SignalKeyValue (SignalKey p) where type SignalValueParams (SignalKey p) = p signalKey (SignalKey u) = DataKey u | Supports marshalling an arbitrary number of arguments into a signal . class (AnonParams (SignalParamNames ss)) => SignalSuffix ss where type SignalParamNames ss mkSignalArgs :: forall usr. ((usr -> IO ()) -> IO ()) -> ([Ptr ()] -> usr -> IO ()) -> ss mkSignalTypes :: Tagged ss SignalTypeInfo instance (Marshal a, CanPassTo a ~ Yes, SignalSuffix b) => SignalSuffix (a -> b) where type SignalParamNames (a -> b) = String -> SignalParamNames b mkSignalArgs start cont param = mkSignalArgs start (\ps usr -> mWithCVal param (\ptr -> cont (ptr:ps) usr)) mkSignalTypes = let (SignalTypeInfo p) = untag (mkSignalTypes :: Tagged b SignalTypeInfo) typ = untag (mTypeCVal :: Tagged a TypeId) in Tagged $ SignalTypeInfo (typ:p) instance SignalSuffix (IO ()) where type SignalParamNames (IO ()) = () mkSignalArgs start cont = start $ cont [] mkSignalTypes = Tagged $ SignalTypeInfo [] defPropertyConst :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes) => String -> (tt -> IO tr) -> Member (GetObjType tt) defPropertyConst name g = Member ConstPropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing Nothing defPropertyRO :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes) => String -> (tt -> IO tr) -> Member (GetObjType tt) defPropertyRO name g = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing Nothing defPropertySigRO :: forall tt tr skv. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, SignalKeyValue skv) => String -> skv -> (tt -> IO tr) -> Member (GetObjType tt) defPropertySigRO name key g = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) Nothing (Just $ signalKey key) functions in the IO monad . defPropertyRW :: forall tt tr. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) => String -> (tt -> IO tr) -> (tt -> tr -> IO ()) -> Member (GetObjType tt) defPropertyRW name g s = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) (Just $ mkSpecialFunc (\a b -> VoidIO $ s a b)) Nothing defPropertySigRW :: forall tt tr skv. (Marshal tt, CanGetFrom tt ~ Yes, IsObjType tt ~ Yes, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes, SignalKeyValue skv) => String -> skv -> (tt -> IO tr) -> (tt -> tr -> IO ()) -> Member (GetObjType tt) defPropertySigRW name key g s = Member PropertyMember name (untag (mTypeCVal :: Tagged tr TypeId)) [] (mkUniformFunc g) (Just $ mkSpecialFunc (\a b -> VoidIO $ s a b)) (Just $ signalKey key) | of ' defPropertyConst ' which is less polymorphic to reduce the need defPropertyConst' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> Member obj defPropertyConst' = defPropertyConst | of ' defPropertyRO ' which is less polymorphic to reduce the need for defPropertyRO' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> Member obj defPropertyRO' = defPropertyRO | of ' defPropertySigRO ' which is less polymorphic to reduce the need defPropertySigRO' :: forall obj tr skv. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, SignalKeyValue skv) => String -> skv -> (ObjRef obj -> IO tr) -> Member obj defPropertySigRO' = defPropertySigRO | of ' defPropertyRW ' which is less polymorphic to reduce the need for defPropertyRW' :: forall obj tr. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes) => String -> (ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj defPropertyRW' = defPropertyRW | of ' defPropertySigRW ' which is less polymorphic to reduce the need defPropertySigRW' :: forall obj tr skv. (Typeable obj, Marshal tr, CanReturnTo tr ~ Yes, CanGetFrom tr ~ Yes, SignalKeyValue skv) => String -> skv -> (ObjRef obj -> IO tr) -> (ObjRef obj -> tr -> IO ()) -> Member obj defPropertySigRW' = defPropertySigRW
8a3b4dad198ba4a7dac92e53049357efb01a1cf953389448d33e8faecf067abe
coq-tactician/coq-tactician
dijkstra_iterative_search.ml
open Tactician_util open Search_strategy open Proofview open Notations exception DepthEnd of float let tclFoldPredictions max_reached tacs = let rec aux tacs depth = let open Proofview in match IStream.peek tacs with | IStream.Nil -> tclZERO ( match depth with | None -> PredictionsEnd | Some depth -> DepthEnd depth) | IStream.Cons (tac, tacs) -> tclOR tac (fun e -> if max_reached () then tclZERO PredictionsEnd else let depth = Option.append depth (match e with | (DepthEnd depth', _) -> Some depth' | _ -> None) in aux tacs depth) in aux tacs None (* TODO: max_reached is a hack, remove *) let tclSearchDijkstraDFS max_reached predict max_dfs = let rec aux (max_dfs : float) : float tactic = if max_reached () then tclZERO PredictionsEnd else Goal.goals >>= function | [] -> tclUNIT max_dfs | _ -> let independent = tclFOCUS 1 1 (predict >>= fun predictions -> tclFoldPredictions max_reached (mapi (fun _i {focus=_; tactic; confidence} -> (* TODO: At some point we should start using the focus *) if confidence <= 0. then tclZERO PredictionsEnd else let lconfidence = Float.log confidence /. Float.log 2. in let max_dfs = max_dfs +. lconfidence in if max_dfs <= 0. then tclZERO (DepthEnd max_dfs) else (tactic >>= fun _ -> aux max_dfs)) predictions) >>= aux) in tclONCE independent >>= aux in aux max_dfs >>= fun _ -> tclUNIT () let rec tclSearchDijkstraIterative d max_reached predict : unit tactic = ( tclLIFT ( ( Pp.str ( " Iterative depth : " ^ string_of_float d ) ) ) ) < * > if max_reached () then Tacticals.New.tclZEROMSG (Pp.str "No more executions") else tclOR (tclSearchDijkstraDFS max_reached predict d) (function | (PredictionsEnd, _) -> Tacticals.New.tclZEROMSG (Pp.str "Tactician failed: there are no more tactics left") | (DepthEnd delta, _) -> let d = d -. delta +. 1. in Feedback.msg_notice Pp.(str " ----------- new iteration : " + + real d + + str " previous reached " + + real delta ) ; tclSearchDijkstraIterative d max_reached predict | (e, info) -> tclZERO ~info e ) (* let () = register_search_strategy "dijkstra iterative search" (tclSearchDijkstraIterative 0.) *)
null
https://raw.githubusercontent.com/coq-tactician/coq-tactician/9608491ed6294f50929bad1c2aaa29d1ae053965/src/dijkstra_iterative_search.ml
ocaml
TODO: max_reached is a hack, remove TODO: At some point we should start using the focus let () = register_search_strategy "dijkstra iterative search" (tclSearchDijkstraIterative 0.)
open Tactician_util open Search_strategy open Proofview open Notations exception DepthEnd of float let tclFoldPredictions max_reached tacs = let rec aux tacs depth = let open Proofview in match IStream.peek tacs with | IStream.Nil -> tclZERO ( match depth with | None -> PredictionsEnd | Some depth -> DepthEnd depth) | IStream.Cons (tac, tacs) -> tclOR tac (fun e -> if max_reached () then tclZERO PredictionsEnd else let depth = Option.append depth (match e with | (DepthEnd depth', _) -> Some depth' | _ -> None) in aux tacs depth) in aux tacs None let tclSearchDijkstraDFS max_reached predict max_dfs = let rec aux (max_dfs : float) : float tactic = if max_reached () then tclZERO PredictionsEnd else Goal.goals >>= function | [] -> tclUNIT max_dfs | _ -> let independent = tclFOCUS 1 1 (predict >>= fun predictions -> tclFoldPredictions max_reached (mapi if confidence <= 0. then tclZERO PredictionsEnd else let lconfidence = Float.log confidence /. Float.log 2. in let max_dfs = max_dfs +. lconfidence in if max_dfs <= 0. then tclZERO (DepthEnd max_dfs) else (tactic >>= fun _ -> aux max_dfs)) predictions) >>= aux) in tclONCE independent >>= aux in aux max_dfs >>= fun _ -> tclUNIT () let rec tclSearchDijkstraIterative d max_reached predict : unit tactic = ( tclLIFT ( ( Pp.str ( " Iterative depth : " ^ string_of_float d ) ) ) ) < * > if max_reached () then Tacticals.New.tclZEROMSG (Pp.str "No more executions") else tclOR (tclSearchDijkstraDFS max_reached predict d) (function | (PredictionsEnd, _) -> Tacticals.New.tclZEROMSG (Pp.str "Tactician failed: there are no more tactics left") | (DepthEnd delta, _) -> let d = d -. delta +. 1. in Feedback.msg_notice Pp.(str " ----------- new iteration : " + + real d + + str " previous reached " + + real delta ) ; tclSearchDijkstraIterative d max_reached predict | (e, info) -> tclZERO ~info e )
45c54e59da59606f9f96a3c1f307e51f9527713667737ef8aa6904d948f753cf
kirasystems/views
hash.clj
(ns views.hash (:require [hasch.benc :refer [-coerce magics PHashCoercion]] [hasch.core :refer [edn-hash]] [hasch.platform :refer [encode md5-message-digest]])) (extend-protocol PHashCoercion java.math.BigDecimal (-coerce [this md-create-fn write-handlers] (encode (:number magics) (.getBytes (.toString this) "UTF-8"))) clojure.lang.BigInt (-coerce [this md-create-fn write-handlers] (encode (:number magics) (.getBytes (.toString this) "UTF-8")))) (defn md5-hash "This hashing function is a drop-in replacement of Clojure's hash function. Unfortunately, Clojure's hash function has the same result for 0 and nil values. Therefore, passing from nil or 0 to the other won't trigger a view refresh." [value] (edn-hash value md5-message-digest {}))
null
https://raw.githubusercontent.com/kirasystems/views/16746454cf32041b70ed269b7836290dabbc0bb1/src/views/hash.clj
clojure
(ns views.hash (:require [hasch.benc :refer [-coerce magics PHashCoercion]] [hasch.core :refer [edn-hash]] [hasch.platform :refer [encode md5-message-digest]])) (extend-protocol PHashCoercion java.math.BigDecimal (-coerce [this md-create-fn write-handlers] (encode (:number magics) (.getBytes (.toString this) "UTF-8"))) clojure.lang.BigInt (-coerce [this md-create-fn write-handlers] (encode (:number magics) (.getBytes (.toString this) "UTF-8")))) (defn md5-hash "This hashing function is a drop-in replacement of Clojure's hash function. Unfortunately, Clojure's hash function has the same result for 0 and nil values. Therefore, passing from nil or 0 to the other won't trigger a view refresh." [value] (edn-hash value md5-message-digest {}))
33bfcc73676f24a26048f5fd4fad2ab54112930ce7908761dd6a23f5c5ed8087
jfischoff/twitch
Rule.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE BangPatterns # module Tests.Twitch.Rule where import Test.Hspec import Twitch.Rule import Data.IORef import Data.Default testSetter sel setter = do ref <- newIORef "" let rule = def `setter` writeIORef ref expected = "yo" sel rule expected actual <- readIORef ref actual `shouldBe` expected testAddModify f = do ref <- newIORef "" let rule = def `f` writeIORef ref expected = "yo" add rule expected actual <- readIORef ref actual `shouldBe` expected modify rule expected actual <- readIORef ref actual `shouldBe` expected testName :: (Rule -> String -> Rule) -> Expectation testName f = name (f def "name") `shouldBe` "name" tests :: Spec tests = do describe "|+" $ it " sets the add member" $ testSetter add (|+) describe "|-" $ it " sets the delete member" $ testSetter delete (|-) describe "|%" $ it " sets the modify member" $ testSetter modify (|%) describe "|>" $ it " sets the add and modify member" $ testAddModify (|>) describe "|#" $ it " sets the name member" $ testName (|#) describe "addF" $ it " sets the add member" $ testSetter add $ flip addF describe "modifyF" $ it " sets the modify member" $ testSetter modify $ flip modifyF describe "deleteF" $ it " sets the delete member" $ testSetter delete $ flip deleteF describe "addModifyF" $ it " sets the add and modify member" $ testAddModify (flip addModifyF) describe "nameF" $ it " sets the name member" $ testName $ flip nameF describe "makeAbsolutePath" $ do it "doesn't change an absolute path" $ makeAbsolutePath "/usr" "/home" `shouldBe` "/home" it "adds the current directory if it is relative" $ do makeAbsolutePath "/usr" "./home" `shouldBe` "/usr/./home" makeAbsolutePath "/usr" "home" `shouldBe` "/usr/home" describe "compilePattern" $ do it "'s happy path works" $ do let Right test = compilePattern "/home/*.js" test "/home/help.js" `shouldBe` True test "/usr/help.js" `shouldBe` False it "with an invalid pattern fails" $ do let Left (PatternCompliationFailed !_ !_) = compilePattern "/home/****.js" return () :: IO ()
null
https://raw.githubusercontent.com/jfischoff/twitch/9ed10b0aaff8aace3b8b2eb47d605d9107194b95/tests/Tests/Twitch/Rule.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE BangPatterns # module Tests.Twitch.Rule where import Test.Hspec import Twitch.Rule import Data.IORef import Data.Default testSetter sel setter = do ref <- newIORef "" let rule = def `setter` writeIORef ref expected = "yo" sel rule expected actual <- readIORef ref actual `shouldBe` expected testAddModify f = do ref <- newIORef "" let rule = def `f` writeIORef ref expected = "yo" add rule expected actual <- readIORef ref actual `shouldBe` expected modify rule expected actual <- readIORef ref actual `shouldBe` expected testName :: (Rule -> String -> Rule) -> Expectation testName f = name (f def "name") `shouldBe` "name" tests :: Spec tests = do describe "|+" $ it " sets the add member" $ testSetter add (|+) describe "|-" $ it " sets the delete member" $ testSetter delete (|-) describe "|%" $ it " sets the modify member" $ testSetter modify (|%) describe "|>" $ it " sets the add and modify member" $ testAddModify (|>) describe "|#" $ it " sets the name member" $ testName (|#) describe "addF" $ it " sets the add member" $ testSetter add $ flip addF describe "modifyF" $ it " sets the modify member" $ testSetter modify $ flip modifyF describe "deleteF" $ it " sets the delete member" $ testSetter delete $ flip deleteF describe "addModifyF" $ it " sets the add and modify member" $ testAddModify (flip addModifyF) describe "nameF" $ it " sets the name member" $ testName $ flip nameF describe "makeAbsolutePath" $ do it "doesn't change an absolute path" $ makeAbsolutePath "/usr" "/home" `shouldBe` "/home" it "adds the current directory if it is relative" $ do makeAbsolutePath "/usr" "./home" `shouldBe` "/usr/./home" makeAbsolutePath "/usr" "home" `shouldBe` "/usr/home" describe "compilePattern" $ do it "'s happy path works" $ do let Right test = compilePattern "/home/*.js" test "/home/help.js" `shouldBe` True test "/usr/help.js" `shouldBe` False it "with an invalid pattern fails" $ do let Left (PatternCompliationFailed !_ !_) = compilePattern "/home/****.js" return () :: IO ()
51a4201561453ce0ff8d76b9d9f81ac2c10026660d51019f61d35f2811cab070
madvas/emojillionaire
db.cljs
(ns emojillionaire.db (:require [cljs-web3.core :as web3] [cljs.spec :as s] [cljsjs.bignumber] [emojillionaire.emojis :refer [emojis]])) (def default-db {:web3 (or (aget js/window "web3") (if goog.DEBUG (web3/create-web3 ":8545/") Let 's borrow this ;) Thanks MetaMask guys ! :provides-web3? (or (aget js/window "web3") goog.DEBUG) :drawer-open? false :chat-open? false :snackbar {:open? false :message "" :auto-hide-duration 10000} :network :testnet ;:network :privnet :conversion-rates {} :contract {:state :active :stats {} :config {:oraclize-fee (js/BigNumber. 7029368029739770)} :name "Emojillionaire" :code nil :code-loading? false :abi nil :bin nil :instance nil :address "0x01e29a1db0f4a7b522a93458e002392a7c49e8ce" ; testnet } :dev-accounts {:privnet [["0x6fce64667819c82a8bcbb78e294d7b444d2e1a29" "m"] ["0xe206f52728e2c1e23de7d42d233f39ac2e748977" "m"] ["0x522f9c6b122f4ca8067eb5459c10d03a35798ed9" "m"] ["0xc5aa141d3822c3368df69bfd93ef2b13d1c59aec" "m"]]} :blockchain {} :gas-limits {:bet 650000 :sponsor 500000 :withdraw 50000} :new-bet {:guesses [] :rolls [] :address nil :rolling? false :transaction-hash nil :bet-processed? false} :emoji-select-form {:selected-emoji {:index 1 :emoji-key ":100:"}} :selectable-emojis emojis :accounts {} :my-addresses [] :jackpot {} :bets {} :sponsors {} :sponsorships {} :top-sponsors-addresses [] :new-sponsor {:amount 1 :name "" :sending? false :transaction-hash nil} :withdraw {:sending? false :transaction-hash nil} :winning-guess nil :winnings {} })
null
https://raw.githubusercontent.com/madvas/emojillionaire/ee47e874db0c88b91985b6f9e72221f12d3010ff/src/cljs/emojillionaire/db.cljs
clojure
) Thanks MetaMask guys ! :network :privnet testnet
(ns emojillionaire.db (:require [cljs-web3.core :as web3] [cljs.spec :as s] [cljsjs.bignumber] [emojillionaire.emojis :refer [emojis]])) (def default-db {:web3 (or (aget js/window "web3") (if goog.DEBUG (web3/create-web3 ":8545/") :provides-web3? (or (aget js/window "web3") goog.DEBUG) :drawer-open? false :chat-open? false :snackbar {:open? false :message "" :auto-hide-duration 10000} :network :testnet :conversion-rates {} :contract {:state :active :stats {} :config {:oraclize-fee (js/BigNumber. 7029368029739770)} :name "Emojillionaire" :code nil :code-loading? false :abi nil :bin nil :instance nil } :dev-accounts {:privnet [["0x6fce64667819c82a8bcbb78e294d7b444d2e1a29" "m"] ["0xe206f52728e2c1e23de7d42d233f39ac2e748977" "m"] ["0x522f9c6b122f4ca8067eb5459c10d03a35798ed9" "m"] ["0xc5aa141d3822c3368df69bfd93ef2b13d1c59aec" "m"]]} :blockchain {} :gas-limits {:bet 650000 :sponsor 500000 :withdraw 50000} :new-bet {:guesses [] :rolls [] :address nil :rolling? false :transaction-hash nil :bet-processed? false} :emoji-select-form {:selected-emoji {:index 1 :emoji-key ":100:"}} :selectable-emojis emojis :accounts {} :my-addresses [] :jackpot {} :bets {} :sponsors {} :sponsorships {} :top-sponsors-addresses [] :new-sponsor {:amount 1 :name "" :sending? false :transaction-hash nil} :withdraw {:sending? false :transaction-hash nil} :winning-guess nil :winnings {} })
b67677f396165e2e24cfd57140c9eccecf3389ef52e8790c813cded4c72631e2
clojurians-org/haskell-example
MinIO.hs
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # LANGUAGE RecursiveDo # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # module Frontend.Page.DataSource.SQLCursor (dataSource_sqlCursor_handle, dataSource_sqlCursor) where import Common.WebSocketMessage import Prelude import Control.Monad (forM) import Control.Monad.Fix (MonadFix) import Control.Monad.IO.Class (MonadIO, liftIO) import Reflex.Dom.Core import Control.Concurrent (MVar) import Data.String.Conversions (cs) dataSource_sqlCursor_handle :: forall t m r. ( MonadHold t m, MonadFix m , MonadIO m, MonadIO (Performable m), PerformEvent t m) => MVar r -> Event t WSResponseMessage -> m (Event t WSResponseMessage) dataSource_sqlCursor_handle wsST wsResponseEvt = do let wsEvt = ffilter (isWSInitResponse ||| isSQLCursorCreateResponse ||| isSQLCursorUpdateResponse ||| isSQLCursorDeleteResponse ||| isSQLCursorDatabaseReadResponse ||| isSQLCursorTableReadResponse) wsResponseEvt return wsEvt theadUI :: forall t m . (DomBuilder t m, PostBuild t m) => m () theadUI = do el "thead" $ el "tr" $ do elClass "th" "" $ checkbox False def elClass "th" "" $ text "数据源名称" elClass "th" "" $ text "数据源类型" elClass "th" "" $ text "主机" elClass "th" "" $ text "数据库" elClass "th" "" $ text "数据表" tbodyUI :: forall t m . (DomBuilder t m, PostBuild t m, MonadFix m, MonadHold t m) => m () tbodyUI = do el "tbody" $ do elClass "tr" "warning" $ do el "td" $ elClass "i" "notched circle loading icon" blank -- name el "td" $ divClass "ui mini input" $ inputElement def -- type el "td" $ divClass "ui mini input" $ dropdown "PostgreSQL" (constDyn ( "PostgreSQL" =: "PostgreSQL" <> "Oracle" =: "Oracle" <> "MySQL" =: "MySQL" )) def -- host el "td" $ divClass "ui mini input" $ inputElement def -- database el "td" $ divClass "ui mini input" $ inputElement def -- table el "td" $ divClass "ui mini input" $ inputElement (def & inputElementConfig_initialValue .~ "aaa" & initialAttributes .~ ("readonly" =: "") <> ("style" =: "background-color:pink;")) return () tfootUI :: forall t m . (DomBuilder t m, PostBuild t m) => m () tfootUI = do el "tfoot" $ do blank dataSource_sqlCursor :: forall t m. ( DomBuilder t m, PostBuild t m, MonadFix m, MonadHold t m) => (Event t WSResponseMessage) -> m (Event t [WSRequestMessage]) dataSource_sqlCursor wsEvt = do divClass "ui segment basic" $ do elClass "table" "ui table collapsing" $ do theadUI tbodyUI tfootUI divClass "ui segment basic" $ do divClass "ui grid" $ divClass "twelve wide column" $ do elClass "h4" "ui horizontal divider header" $ do text "数据源详情" divClass "ui form compact" $ do divClass "fields" $ do divClass "field" $ do el "label" $ text "用户名" inputElement def divClass "field" $ do el "label" $ text "密码" inputElement def divClass "field" $ do el "label" $ elClass "i" "angle double down icon" blank elClass' "button" "ui button teal" (text "连接") divClass "ui segment basic" $ do divClass "ui grid" $ do divClass "four wide column" $ do divClass "ui segment" $ do divClass "ui mini icon input" $ do inputElement def elClass "i" "circular search link icon" blank divClass "ui list" $ do divClass "item" $ do elClass "i" "database icon" blank divClass "content" $ elClass "h4" "ui header" $ text "information_schema" divClass "list" $ do divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "to_be_fill" elClass "i" "database icon" blank divClass "content" $ elClass "h4" "ui header" $ text "public" divClass "list" $ do divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "hello" divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "world" divClass "eight wide column" $ do elClass "table" "ui table" $ do el "thead" $ el "tr" $ do elClass "th" "" $ checkbox False def elClass "th" "" $ text "名称" elClass "th" "" $ text "类型" elClass "th" "" $ text "描述" el "tbody" $ do el "tr" $ do el "td" $ checkbox False def el "td" $ text "name" el "td" $ text "text" el "td" $ text "NULL" el "tr" $ do el "td" $ checkbox False def el "td" $ text "expr" el "td" $ text "text" el "td" $ text "NULL" el "tr" $ do el "td" $ checkbox False def el "td" $ text "type" el "td" $ text "text" el "td" $ text "NULL" return never
null
https://raw.githubusercontent.com/clojurians-org/haskell-example/c96b021bdef52a121e04ea203c8c3e458770a25a/conduit-ui/frontend/src/Frontend/Page/DataSandbox/DataService/FileService/MinIO.hs
haskell
name type host database table
# LANGUAGE NoImplicitPrelude # # LANGUAGE ScopedTypeVariables # # LANGUAGE LambdaCase # # LANGUAGE RecursiveDo # # LANGUAGE DataKinds # # LANGUAGE FlexibleContexts # module Frontend.Page.DataSource.SQLCursor (dataSource_sqlCursor_handle, dataSource_sqlCursor) where import Common.WebSocketMessage import Prelude import Control.Monad (forM) import Control.Monad.Fix (MonadFix) import Control.Monad.IO.Class (MonadIO, liftIO) import Reflex.Dom.Core import Control.Concurrent (MVar) import Data.String.Conversions (cs) dataSource_sqlCursor_handle :: forall t m r. ( MonadHold t m, MonadFix m , MonadIO m, MonadIO (Performable m), PerformEvent t m) => MVar r -> Event t WSResponseMessage -> m (Event t WSResponseMessage) dataSource_sqlCursor_handle wsST wsResponseEvt = do let wsEvt = ffilter (isWSInitResponse ||| isSQLCursorCreateResponse ||| isSQLCursorUpdateResponse ||| isSQLCursorDeleteResponse ||| isSQLCursorDatabaseReadResponse ||| isSQLCursorTableReadResponse) wsResponseEvt return wsEvt theadUI :: forall t m . (DomBuilder t m, PostBuild t m) => m () theadUI = do el "thead" $ el "tr" $ do elClass "th" "" $ checkbox False def elClass "th" "" $ text "数据源名称" elClass "th" "" $ text "数据源类型" elClass "th" "" $ text "主机" elClass "th" "" $ text "数据库" elClass "th" "" $ text "数据表" tbodyUI :: forall t m . (DomBuilder t m, PostBuild t m, MonadFix m, MonadHold t m) => m () tbodyUI = do el "tbody" $ do elClass "tr" "warning" $ do el "td" $ elClass "i" "notched circle loading icon" blank el "td" $ divClass "ui mini input" $ inputElement def el "td" $ divClass "ui mini input" $ dropdown "PostgreSQL" (constDyn ( "PostgreSQL" =: "PostgreSQL" <> "Oracle" =: "Oracle" <> "MySQL" =: "MySQL" )) def el "td" $ divClass "ui mini input" $ inputElement def el "td" $ divClass "ui mini input" $ inputElement def el "td" $ divClass "ui mini input" $ inputElement (def & inputElementConfig_initialValue .~ "aaa" & initialAttributes .~ ("readonly" =: "") <> ("style" =: "background-color:pink;")) return () tfootUI :: forall t m . (DomBuilder t m, PostBuild t m) => m () tfootUI = do el "tfoot" $ do blank dataSource_sqlCursor :: forall t m. ( DomBuilder t m, PostBuild t m, MonadFix m, MonadHold t m) => (Event t WSResponseMessage) -> m (Event t [WSRequestMessage]) dataSource_sqlCursor wsEvt = do divClass "ui segment basic" $ do elClass "table" "ui table collapsing" $ do theadUI tbodyUI tfootUI divClass "ui segment basic" $ do divClass "ui grid" $ divClass "twelve wide column" $ do elClass "h4" "ui horizontal divider header" $ do text "数据源详情" divClass "ui form compact" $ do divClass "fields" $ do divClass "field" $ do el "label" $ text "用户名" inputElement def divClass "field" $ do el "label" $ text "密码" inputElement def divClass "field" $ do el "label" $ elClass "i" "angle double down icon" blank elClass' "button" "ui button teal" (text "连接") divClass "ui segment basic" $ do divClass "ui grid" $ do divClass "four wide column" $ do divClass "ui segment" $ do divClass "ui mini icon input" $ do inputElement def elClass "i" "circular search link icon" blank divClass "ui list" $ do divClass "item" $ do elClass "i" "database icon" blank divClass "content" $ elClass "h4" "ui header" $ text "information_schema" divClass "list" $ do divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "to_be_fill" elClass "i" "database icon" blank divClass "content" $ elClass "h4" "ui header" $ text "public" divClass "list" $ do divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "hello" divClass "item" $ do elClass "i" "expand icon" blank divClass "content" $ el "a" $ text "world" divClass "eight wide column" $ do elClass "table" "ui table" $ do el "thead" $ el "tr" $ do elClass "th" "" $ checkbox False def elClass "th" "" $ text "名称" elClass "th" "" $ text "类型" elClass "th" "" $ text "描述" el "tbody" $ do el "tr" $ do el "td" $ checkbox False def el "td" $ text "name" el "td" $ text "text" el "td" $ text "NULL" el "tr" $ do el "td" $ checkbox False def el "td" $ text "expr" el "td" $ text "text" el "td" $ text "NULL" el "tr" $ do el "td" $ checkbox False def el "td" $ text "type" el "td" $ text "text" el "td" $ text "NULL" return never
5575e8a7b1cb0179eac8b1918d2745257b7c3b8212e3bbf54b13534613c4e3f1
ucsd-progsys/mist
SimpleTypes.hs
# LANGUAGE PatternSynonyms # module Tests.SimpleTypes ( T.Prim (..) , T.Id , T.Type (..), T.TVar (..), T.Ctor (..) , T.RType (..) -- * Abstract syntax of Mist , T.Expr , pattern Number , pattern AnnNumber , pattern Boolean , pattern AnnBoolean , pattern Unit , pattern AnnUnit , pattern Id , pattern AnnId , pattern Prim , pattern AnnPrim , pattern If , pattern AnnIf , pattern Let , pattern AnnLet , pattern App , pattern AnnApp , pattern Lam , pattern AnnLam , pattern TApp , pattern AnnTApp , pattern TAbs , pattern AnnTAbs , T.ParsedAnnotation (..) , T.ParsedExpr, T.ParsedBind , T.ElaboratedAnnotation , pattern T.ElabUnrefined, pattern T.ElabRefined , T.ElaboratedExpr, T.ElaboratedBind , T.Bind , pattern Bind , pattern AnnBind ) where import qualified Language.Mist.Types as T import qualified Language.Mist.UX as UX import Text.Megaparsec.Pos (initialPos) pattern Number i = T.Number i () pattern Boolean b = T.Boolean b () pattern Unit = T.Unit () pattern Id x = T.Id x () pattern Prim p = T.Prim p () pattern If e1 e2 e3 = T.If e1 e2 e3 () pattern Let b e1 e2 = T.Let b e1 e2 () pattern App e1 e2 = T.App e1 e2 () pattern Lam b e = T.Lam b e () pattern TApp e t = T.TApp e t () pattern TAbs alpha e = T.TAbs alpha e () pattern Bind x = T.Bind x () pattern AnnNumber i tag = T.AnnNumber i tag () pattern AnnBoolean b tag = T.AnnBoolean b tag () pattern AnnUnit tag = T.AnnUnit tag () pattern AnnId x tag = T.AnnId x tag () pattern AnnPrim p tag = T.AnnPrim p tag () pattern AnnIf e1 e2 e3 tag = T.AnnIf e1 e2 e3 tag () pattern AnnLet b e1 e2 tag = T.AnnLet b e1 e2 tag () pattern AnnApp e1 e2 tag = T.AnnApp e1 e2 tag () pattern AnnLam b e tag = T.AnnLam b e tag () pattern AnnTApp e t tag = T.AnnTApp e t tag () pattern AnnTAbs alpha e tag = T.AnnTAbs alpha e tag () pattern AnnBind {bindId, bindAnn} = T.AnnBind{ T.bindId = bindId , T.bindAnn = bindAnn , T.bindTag = ()} instance UX.Located () where sourceSpan () = UX.SS { UX.ssBegin = initialPos "test" , UX.ssEnd = initialPos "test" }
null
https://raw.githubusercontent.com/ucsd-progsys/mist/0a9345e73dc53ff8e8adb8bed78d0e3e0cdc6af0/tests/Tests/SimpleTypes.hs
haskell
* Abstract syntax of Mist
# LANGUAGE PatternSynonyms # module Tests.SimpleTypes ( T.Prim (..) , T.Id , T.Type (..), T.TVar (..), T.Ctor (..) , T.RType (..) , T.Expr , pattern Number , pattern AnnNumber , pattern Boolean , pattern AnnBoolean , pattern Unit , pattern AnnUnit , pattern Id , pattern AnnId , pattern Prim , pattern AnnPrim , pattern If , pattern AnnIf , pattern Let , pattern AnnLet , pattern App , pattern AnnApp , pattern Lam , pattern AnnLam , pattern TApp , pattern AnnTApp , pattern TAbs , pattern AnnTAbs , T.ParsedAnnotation (..) , T.ParsedExpr, T.ParsedBind , T.ElaboratedAnnotation , pattern T.ElabUnrefined, pattern T.ElabRefined , T.ElaboratedExpr, T.ElaboratedBind , T.Bind , pattern Bind , pattern AnnBind ) where import qualified Language.Mist.Types as T import qualified Language.Mist.UX as UX import Text.Megaparsec.Pos (initialPos) pattern Number i = T.Number i () pattern Boolean b = T.Boolean b () pattern Unit = T.Unit () pattern Id x = T.Id x () pattern Prim p = T.Prim p () pattern If e1 e2 e3 = T.If e1 e2 e3 () pattern Let b e1 e2 = T.Let b e1 e2 () pattern App e1 e2 = T.App e1 e2 () pattern Lam b e = T.Lam b e () pattern TApp e t = T.TApp e t () pattern TAbs alpha e = T.TAbs alpha e () pattern Bind x = T.Bind x () pattern AnnNumber i tag = T.AnnNumber i tag () pattern AnnBoolean b tag = T.AnnBoolean b tag () pattern AnnUnit tag = T.AnnUnit tag () pattern AnnId x tag = T.AnnId x tag () pattern AnnPrim p tag = T.AnnPrim p tag () pattern AnnIf e1 e2 e3 tag = T.AnnIf e1 e2 e3 tag () pattern AnnLet b e1 e2 tag = T.AnnLet b e1 e2 tag () pattern AnnApp e1 e2 tag = T.AnnApp e1 e2 tag () pattern AnnLam b e tag = T.AnnLam b e tag () pattern AnnTApp e t tag = T.AnnTApp e t tag () pattern AnnTAbs alpha e tag = T.AnnTAbs alpha e tag () pattern AnnBind {bindId, bindAnn} = T.AnnBind{ T.bindId = bindId , T.bindAnn = bindAnn , T.bindTag = ()} instance UX.Located () where sourceSpan () = UX.SS { UX.ssBegin = initialPos "test" , UX.ssEnd = initialPos "test" }
1985ad0ac3ea765e56f12dcec55ee33766c582595ebca98186213c7747c0f8f9
zcaudate/hara
wagon_test.clj
(ns hara.lib.aether.wagon-test (:use hara.test) (:require [hara.lib.aether.wagon :refer :all])) ^{:refer hara.lib.aether.wagon/add-factory :added "3.0"} (fact "registers a wagon factory for creating transports") ^{:refer hara.lib.aether.wagon/remove-factory :added "3.0"} (fact "removes the registered wagon factory") ^{:refer hara.lib.aether.wagon/all-factories :added "3.0"} (fact "list all registered factories" (all-factories) => {:https org.apache.maven.wagon.providers.webdav.WebDavWagon}) ^{:refer hara.lib.aether.wagon/create :added "3.0"} (fact "create a wagon given a scheme" (create :https) => org.apache.maven.wagon.providers.webdav.WebDavWagon)
null
https://raw.githubusercontent.com/zcaudate/hara/481316c1f5c2aeba5be6e01ae673dffc46a63ec9/test/hara/lib/aether/wagon_test.clj
clojure
(ns hara.lib.aether.wagon-test (:use hara.test) (:require [hara.lib.aether.wagon :refer :all])) ^{:refer hara.lib.aether.wagon/add-factory :added "3.0"} (fact "registers a wagon factory for creating transports") ^{:refer hara.lib.aether.wagon/remove-factory :added "3.0"} (fact "removes the registered wagon factory") ^{:refer hara.lib.aether.wagon/all-factories :added "3.0"} (fact "list all registered factories" (all-factories) => {:https org.apache.maven.wagon.providers.webdav.WebDavWagon}) ^{:refer hara.lib.aether.wagon/create :added "3.0"} (fact "create a wagon given a scheme" (create :https) => org.apache.maven.wagon.providers.webdav.WebDavWagon)
efc475c4bc69b970c48ccfca312159766ac97dd8bc167f10decbaa56edb70774
threatgrid/ctim
campaign_test.clj
(ns ctim.generators.campaign-test (:require [clj-momo.test-helpers.core :as mth] [clojure.test :refer [use-fixtures]] [clojure.test.check.clojure-test :refer [defspec]] [ctim.schemas.campaign :as campaign] [ctim.test-helpers [core :as th] [properties :as property]] [flanders.utils :as fu])) (use-fixtures :once th/fixture-spec-validation mth/fixture-schema-validation (th/fixture-spec campaign/Campaign "test.campaign") (th/fixture-spec campaign/NewCampaign "test.new-campaign") (th/fixture-spec (fu/require-all campaign/Campaign) "test.max.campaign") (th/fixture-spec (fu/require-all campaign/NewCampaign) "test.max.new-campaign")) ;; Campaign (defspec ^:gen spec-generated-campaign-is-valid (property/generated-entity-is-valid :test.campaign/map)) (defspec ^:gen spec-generated-max-campaign-is-valid (property/generated-entity-is-valid :test.max.campaign/map)) (defspec ^:gen spec-generated-campaign-id-is-valid (property/generated-entity-id-is-valid :test.campaign/map "campaign")) ;; New Campaign (defspec ^:gen spec-generated-new-campaign-is-valid (property/generated-entity-is-valid :test.new-campaign/map)) (defspec ^:gen spec-generated-max-new-campaign-is-valid (property/generated-entity-is-valid :test.max.new-campaign/map)) (defspec ^:gen spec-generated-new-campaign-id-is-valid (property/generated-entity-id-is-valid :test.new-campaign/map "campaign" :optional))
null
https://raw.githubusercontent.com/threatgrid/ctim/2ecae70682e69495cc3a12fd58a474d4ea57ae9c/test/ctim/generators/campaign_test.clj
clojure
Campaign New Campaign
(ns ctim.generators.campaign-test (:require [clj-momo.test-helpers.core :as mth] [clojure.test :refer [use-fixtures]] [clojure.test.check.clojure-test :refer [defspec]] [ctim.schemas.campaign :as campaign] [ctim.test-helpers [core :as th] [properties :as property]] [flanders.utils :as fu])) (use-fixtures :once th/fixture-spec-validation mth/fixture-schema-validation (th/fixture-spec campaign/Campaign "test.campaign") (th/fixture-spec campaign/NewCampaign "test.new-campaign") (th/fixture-spec (fu/require-all campaign/Campaign) "test.max.campaign") (th/fixture-spec (fu/require-all campaign/NewCampaign) "test.max.new-campaign")) (defspec ^:gen spec-generated-campaign-is-valid (property/generated-entity-is-valid :test.campaign/map)) (defspec ^:gen spec-generated-max-campaign-is-valid (property/generated-entity-is-valid :test.max.campaign/map)) (defspec ^:gen spec-generated-campaign-id-is-valid (property/generated-entity-id-is-valid :test.campaign/map "campaign")) (defspec ^:gen spec-generated-new-campaign-is-valid (property/generated-entity-is-valid :test.new-campaign/map)) (defspec ^:gen spec-generated-max-new-campaign-is-valid (property/generated-entity-is-valid :test.max.new-campaign/map)) (defspec ^:gen spec-generated-new-campaign-id-is-valid (property/generated-entity-id-is-valid :test.new-campaign/map "campaign" :optional))
75f8cc854bf891d6c9e981bbe751345a355a23fff7f1801f823f76b364ae6499
facebook/infer
Pulse.ml
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module F = Format module L = Logging module IRAttributes = Attributes open PulseBasicInterface open PulseDomainInterface open PulseOperationResult.Import (** raised when we detect that pulse is using too much memory to stop the analysis of the current procedure *) exception AboutToOOM let report_topl_errors proc_desc err_log summary = let f = function | ContinueProgram astate -> PulseTopl.report_errors proc_desc err_log (AbductiveDomain.Topl.get astate) | _ -> () in List.iter ~f summary let is_not_implicit_or_copy_ctor_assignment pname = not (Option.exists (IRAttributes.load pname) ~f:(fun attrs -> attrs.ProcAttributes.is_cpp_implicit || attrs.ProcAttributes.is_cpp_copy_ctor || attrs.ProcAttributes.is_cpp_copy_assignment ) ) let is_non_deleted_copy pname = (* TODO: Default is set to true for now because we can't get the attributes of library calls right now. *) Option.value_map ~default:true (IRAttributes.load pname) ~f:(fun attrs -> attrs.ProcAttributes.is_cpp_copy_ctor && not attrs.ProcAttributes.is_cpp_deleted ) let is_type_copiable tenv typ = match typ with | {Typ.desc= Tstruct name} | {Typ.desc= Tptr ({desc= Tstruct name}, _)} -> ( match Tenv.lookup tenv name with | None | Some {dummy= true} -> true | Some {methods} -> List.exists ~f:is_non_deleted_copy methods ) | _ -> true let get_loc_instantiated pname = IRAttributes.load pname |> Option.bind ~f:ProcAttributes.get_loc_instantiated let report_unnecessary_copies proc_desc err_log non_disj_astate = let pname = Procdesc.get_proc_name proc_desc in if is_not_implicit_or_copy_ctor_assignment pname then PulseNonDisjunctiveDomain.get_copied non_disj_astate |> List.iter ~f:(fun (copied_into, source_typ, location, copied_location, from) -> let copy_name = Format.asprintf "%a" Attribute.CopiedInto.pp copied_into in let is_suppressed = PulseNonDisjunctiveOperations.has_copy_in copy_name in let location_instantiated = get_loc_instantiated pname in let diagnostic = Diagnostic.UnnecessaryCopy {copied_into; source_typ; location; copied_location; location_instantiated; from} in PulseReport.report ~is_suppressed ~latent:false proc_desc err_log diagnostic ) let report_unnecessary_parameter_copies tenv proc_desc err_log non_disj_astate = let pname = Procdesc.get_proc_name proc_desc in if is_not_implicit_or_copy_ctor_assignment pname then PulseNonDisjunctiveDomain.get_const_refable_parameters non_disj_astate |> List.iter ~f:(fun (param, typ, location) -> if is_type_copiable tenv typ then let diagnostic = if Typ.is_shared_pointer typ then if NonDisjDomain.is_lifetime_extended param non_disj_astate then None else let used_locations = NonDisjDomain.get_loaded_locations param non_disj_astate in Some (Diagnostic.ReadonlySharedPtrParameter {param; typ; location; used_locations}) else Some (Diagnostic.ConstRefableParameter {param; typ; location}) in Option.iter diagnostic ~f:(fun diagnostic -> PulseReport.report ~is_suppressed:false ~latent:false proc_desc err_log diagnostic ) ) let heap_size () = (Gc.quick_stat ()).heap_words module PulseTransferFunctions = struct module CFG = ProcCfg.ExceptionalNoSinkToExitEdge module DisjDomain = AbstractDomain.PairDisjunct (ExecutionDomain) (PathContext) module NonDisjDomain = NonDisjDomain type analysis_data = PulseSummary.t InterproceduralAnalysis.t let get_pvar_formals pname = IRAttributes.load pname |> Option.map ~f:ProcAttributes.get_pvar_formals let need_specialization astates = List.exists astates ~f:(fun res -> match PulseResult.ok res with | Some ( ContinueProgram {AbductiveDomain.need_specialization} | ExceptionRaised {AbductiveDomain.need_specialization} ) -> need_specialization | Some ( ExitProgram astate | AbortProgram astate | LatentAbortProgram {astate} | LatentInvalidAccess {astate} ) -> AbductiveDomain.Summary.need_specialization astate | None -> false ) let reset_need_specialization needed_specialization astates = if needed_specialization then List.map astates ~f:(fun res -> PulseResult.map res ~f:(function | ExceptionRaised astate -> let astate = AbductiveDomain.set_need_specialization astate in ExceptionRaised astate | ContinueProgram astate -> let astate = AbductiveDomain.set_need_specialization astate in ContinueProgram astate | ExitProgram astate -> let astate = AbductiveDomain.Summary.with_need_specialization astate in ExitProgram astate | AbortProgram astate -> let astate = AbductiveDomain.Summary.with_need_specialization astate in AbortProgram astate | LatentAbortProgram latent_abort_program -> let astate = AbductiveDomain.Summary.with_need_specialization latent_abort_program.astate in LatentAbortProgram {latent_abort_program with astate} | LatentInvalidAccess latent_invalid_access -> let astate = AbductiveDomain.Summary.with_need_specialization latent_invalid_access.astate in LatentInvalidAccess {latent_invalid_access with astate} ) ) else astates let interprocedural_call ({InterproceduralAnalysis.analyze_dependency; tenv; proc_desc} as analysis_data) path ret callee_pname call_exp func_args call_loc (flags : CallFlags.t) astate = let actuals = List.map func_args ~f:(fun ProcnameDispatcher.Call.FuncArg.{arg_payload; typ} -> (arg_payload, typ) ) in match callee_pname with | Some callee_pname when not Config.pulse_intraprocedural_only -> let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in let call_kind_of call_exp = match call_exp with | Exp.Closure {captured_vars} -> `Closure captured_vars | Exp.Var id -> `Var id | _ -> `ResolvedProcname in (* [needed_specialization] = current function already needs specialization before the upcoming call (i.e. we did not have enough information to sufficiently specialize a callee). *) let needed_specialization = astate.AbductiveDomain.need_specialization in (* [astate.need_specialization] is false when entering the call. This is to detect calls that need specialization. The value will be set back to true (if it was) in the end by [reset_need_specialization] *) let astate = AbductiveDomain.unset_need_specialization astate in let call_kind = call_kind_of call_exp in let maybe_call_with_alias callee_pname call_exp ((res, contradiction) as call_res) = if List.is_empty res then match contradiction with | Some (PulseInterproc.Aliasing _) -> ( L.d_printfln "Trying to alias-specialize %a" Exp.pp call_exp ; match PulseAliasSpecialization.make_specialized_call_exp callee_pname func_args (call_kind_of call_exp) path call_loc astate with | Some (callee_pname, call_exp, astate) -> L.d_printfln "Succesfully alias-specialized %a@\n" Exp.pp call_exp ; let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in let call_res = PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind:(call_kind_of call_exp) astate in (callee_pname, call_exp, call_res) | None -> L.d_printfln "Failed to alias-specialize %a@\n" Exp.pp call_exp ; (callee_pname, call_exp, call_res) ) | _ -> (callee_pname, call_exp, call_res) else (callee_pname, call_exp, call_res) in let maybe_call_specialization callee_pname call_exp ((res, _) as call_res) = if (not needed_specialization) && need_specialization res then ( L.d_printfln "Trying to closure-specialize %a" Exp.pp call_exp ; match PulseClosureSpecialization.make_specialized_call_exp analysis_data func_args callee_pname (call_kind_of call_exp) path call_loc astate with | Some (callee_pname, call_exp, astate) -> L.d_printfln "Succesfully closure-specialized %a@\n" Exp.pp call_exp ; let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind:(call_kind_of call_exp) astate |> maybe_call_with_alias callee_pname call_exp | None -> L.d_printfln "Failed to closure-specialize %a@\n" Exp.pp call_exp ; (callee_pname, call_exp, call_res) ) else (callee_pname, call_exp, call_res) in let res, _contradiction = let callee_pname, call_exp, call_res = PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind astate |> maybe_call_with_alias callee_pname call_exp in let _, _, call_res = maybe_call_specialization callee_pname call_exp call_res in call_res in ( reset_need_specialization needed_specialization res , if Option.is_none callee_data then `UnknownCall else `KnownCall ) | _ -> (* dereference call expression to catch nil issues *) ( (let<**> astate, _ = if flags.cf_is_objc_block then (* We are on an unknown block call, meaning that the block was defined outside the current function and was either passed by the caller as an argument or retrieved from an object. We do not handle blocks inside objects yet so we assume we are in the former case. In this case, we tell the caller that we are missing some information by setting [need_specialization] in the resulting state and the caller will then try to specialize the current function with its available information. *) let astate = AbductiveDomain.set_need_specialization astate in PulseOperations.eval_deref path ~must_be_valid_reason:BlockCall call_loc call_exp astate else let astate = if (* this condition may need refining to check that the function comes from the function's parameters or captured variables. The function_pointer_specialization option is there to compensate this / control the specialization's agressivity *) Config.function_pointer_specialization && Language.equal Language.Clang (Procname.get_language (Procdesc.get_proc_name proc_desc)) then AbductiveDomain.set_need_specialization astate else astate in PulseOperations.eval_deref path call_loc call_exp astate in L.d_printfln "Skipping indirect call %a@\n" Exp.pp call_exp ; let astate = let arg_values = List.map actuals ~f:(fun ((value, _), _) -> value) in PulseOperations.conservatively_initialize_args arg_values astate in let<++> astate = PulseCallOperations.unknown_call path call_loc (SkippedUnknownCall call_exp) callee_pname ~ret ~actuals ~formals_opt:None astate in astate ) , `UnknownCall ) (** has an object just gone out of scope? *) let get_out_of_scope_object callee_pname actuals (flags : CallFlags.t) = (* injected destructors are precisely inserted where an object goes out of scope *) if flags.cf_injected_destructor then match (callee_pname, actuals) with | Some (Procname.ObjC_Cpp pname), [(Exp.Lvar pvar, typ)] when Pvar.is_local pvar && not (Procname.ObjC_Cpp.is_inner_destructor pname) -> (* ignore inner destructors, only trigger out of scope on the final destructor call *) Some (pvar, typ) | _ -> None else None (** [out_of_scope_access_expr] has just gone out of scope and in now invalid *) let exec_object_out_of_scope path call_loc (pvar, typ) exec_state = match (exec_state : ExecutionDomain.t) with | ContinueProgram astate | ExceptionRaised astate -> let gone_out_of_scope = Invalidation.GoneOutOfScope (pvar, typ) in let+* astate, out_of_scope_base = PulseOperations.eval path NoAccess call_loc (Exp.Lvar pvar) astate in (* invalidate [&x] *) PulseOperations.invalidate path (StackAddress (Var.of_pvar pvar, ValueHistory.epoch)) call_loc gone_out_of_scope out_of_scope_base astate >>| ExecutionDomain.continue | AbortProgram _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> Sat (Ok exec_state) let topl_small_step loc procname arguments (return, _typ) exec_state_res = let arguments = List.map arguments ~f:(fun {ProcnameDispatcher.Call.FuncArg.arg_payload} -> fst arg_payload) in let return = Var.of_id return in let do_astate astate = let return = Option.map ~f:fst (Stack.find_opt return astate) in let topl_event = PulseTopl.Call {return; arguments; procname} in AbductiveDomain.Topl.small_step loc topl_event astate in let do_one_exec_state (exec_state : ExecutionDomain.t) : ExecutionDomain.t = match exec_state with | ContinueProgram astate -> ContinueProgram (do_astate astate) | AbortProgram _ | LatentAbortProgram _ | ExitProgram _ | ExceptionRaised _ | LatentInvalidAccess _ -> exec_state in List.map ~f:(PulseResult.map ~f:do_one_exec_state) exec_state_res let topl_store_step path loc ~lhs ~rhs:_ astate = match (lhs : Exp.t) with | Lindex (arr, index) -> (let** _astate, (aw_array, _history) = PulseOperations.eval path Read loc arr astate in let++ _astate, (aw_index, _history) = PulseOperations.eval path Read loc index astate in let topl_event = PulseTopl.ArrayWrite {aw_array; aw_index} in AbductiveDomain.Topl.small_step loc topl_event astate ) |> PulseOperationResult.sat_ok |> (* don't emit Topl event if evals fail *) Option.value ~default:astate | _ -> astate assume that virtual calls are only made on instance methods where it makes sense , in which case the receiver is always the first argument if present the receiver is always the first argument if present *) let get_receiver _proc_name actuals = match actuals with receiver :: _ -> Some receiver | _ -> None let get_dynamic_type_name astate v = match AbductiveDomain.AddressAttributes.get_dynamic_type_source_file v astate with | Some ({desc= Tstruct name}, source_file_opt) -> Some (name, source_file_opt) | Some (t, _) -> L.d_printfln "dynamic type %a of %a is not a Tstruct" (Typ.pp_full Pp.text) t AbstractValue.pp v ; None | None -> L.d_printfln "no dynamic type found for %a" AbstractValue.pp v ; None let find_override tenv astate actuals proc_name proc_name_opt = let open IOption.Let_syntax in let* {ProcnameDispatcher.Call.FuncArg.arg_payload= receiver, _} = get_receiver proc_name actuals in let* dynamic_type_name, source_file_opt = get_dynamic_type_name astate receiver in let* type_name = Procname.get_class_type_name proc_name in if Typ.Name.equal type_name dynamic_type_name then proc_name_opt else let method_exists proc_name methods = List.mem ~equal:Procname.equal methods proc_name in (* if we have a source file then do the look up in the (local) tenv for that source file instead of in the tenv for the current file *) let tenv = Option.bind source_file_opt ~f:Tenv.load |> Option.value ~default:tenv in Tenv.resolve_method ~method_exists tenv dynamic_type_name proc_name let resolve_virtual_call tenv astate actuals proc_name_opt = Option.map proc_name_opt ~f:(fun proc_name -> match find_override tenv astate actuals proc_name proc_name_opt with | Some proc_name' -> L.d_printfln "Dynamic dispatch: %a resolved to %a" Procname.pp proc_name Procname.pp proc_name' ; proc_name' | None -> proc_name ) type model_search_result = | DoliModel of Procname.t | OcamlModel of (PulseModelsImport.model * Procname.t) | NoModel let rec dispatch_call_eval_args ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) path ret call_exp actuals func_args call_loc flags astate callee_pname = let callee_pname = if flags.CallFlags.cf_virtual then resolve_virtual_call tenv astate func_args callee_pname else callee_pname in let astate = match (callee_pname, func_args) with | Some callee_pname, [{ProcnameDispatcher.Call.FuncArg.arg_payload= arg, _}] when Procname.is_std_move callee_pname -> AddressAttributes.add_one arg StdMoved astate | _, _ -> astate in let astate = List.fold func_args ~init:astate ~f:(fun acc {ProcnameDispatcher.Call.FuncArg.arg_payload= arg, _; exp} -> match exp with | Cast (typ, _) when Typ.is_rvalue_reference typ -> AddressAttributes.add_one arg StdMoved acc | _ -> acc ) in let model = match callee_pname with | Some callee_pname -> ( match DoliToTextual.matcher callee_pname with | Some procname -> DoliModel procname | None -> PulseModels.dispatch tenv callee_pname func_args |> Option.value_map ~default:NoModel ~f:(fun model -> OcamlModel (model, callee_pname)) ) | None -> (* unresolved function pointer, etc.: skip *) NoModel in (* do interprocedural call then destroy objects going out of scope *) let exec_states_res, call_was_unknown = match model with | OcamlModel (model, callee_procname) -> L.d_printfln "Found ocaml model for call@\n" ; let astate = let arg_values = List.map func_args ~f:(fun {ProcnameDispatcher.Call.FuncArg.arg_payload= value, _} -> value ) in PulseOperations.conservatively_initialize_args arg_values astate in ( model { analysis_data ; dispatch_call_eval_args ; path ; callee_procname ; location= call_loc ; ret } astate , `KnownCall ) | DoliModel callee_pname -> L.d_printfln "Found doli model %a for call@\n" Procname.pp callee_pname ; PerfEvent.(log (fun logger -> log_begin_event logger ~name:"pulse interproc call" ())) ; let r = interprocedural_call analysis_data path ret (Some callee_pname) call_exp func_args call_loc flags astate in PerfEvent.(log (fun logger -> log_end_event logger ())) ; r | NoModel -> PerfEvent.(log (fun logger -> log_begin_event logger ~name:"pulse interproc call" ())) ; let r = interprocedural_call analysis_data path ret callee_pname call_exp func_args call_loc flags astate in PerfEvent.(log (fun logger -> log_end_event logger ())) ; r in let exec_states_res = let one_state exec_state_res = let* exec_state = exec_state_res in match exec_state with | ContinueProgram astate -> let call_event = match callee_pname with | None -> Either.First call_exp | Some proc_name -> Either.Second proc_name in let call_was_unknown = match call_was_unknown with `UnknownCall -> true | `KnownCall -> false in let+ astate = PulseTaintOperations.call tenv path call_loc ret ~call_was_unknown call_event func_args astate in ContinueProgram astate | ( ExceptionRaised _ | ExitProgram _ | AbortProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ ) as exec_state -> Ok exec_state in List.map exec_states_res ~f:one_state in let exec_states_res = if Topl.is_active () then match callee_pname with | Some callee_pname -> topl_small_step call_loc callee_pname func_args ret exec_states_res | None -> (* skip, as above for non-topl *) exec_states_res else exec_states_res in let exec_states_res = match get_out_of_scope_object callee_pname actuals flags with | Some pvar_typ -> L.d_printfln "%a is going out of scope" Pvar.pp_value (fst pvar_typ) ; List.filter_map exec_states_res ~f:(fun exec_state -> exec_state >>>= exec_object_out_of_scope path call_loc pvar_typ |> SatUnsat.sat ) | None -> exec_states_res in if Option.exists callee_pname ~f:IRAttributes.is_no_return then List.filter_map exec_states_res ~f:(fun exec_state_res -> (let+ exec_state = exec_state_res in PulseSummary.force_exit_program tenv proc_desc err_log call_loc exec_state |> SatUnsat.sat ) |> PulseResult.of_some ) else exec_states_res let dispatch_call analysis_data path ret call_exp actuals call_loc flags astate = let<**> astate, callee_pname = PulseOperations.eval_proc_name path call_loc call_exp astate in (* special case for objc dispatch models *) let callee_pname, call_exp, actuals = match callee_pname with | Some callee_pname when ObjCDispatchModels.is_model callee_pname -> ( match ObjCDispatchModels.get_dispatch_closure_opt actuals with | Some (block_name, closure_exp, args) -> (Some block_name, closure_exp, args) | None -> (Some callee_pname, call_exp, actuals) ) | _ -> (callee_pname, call_exp, actuals) in (* evaluate all actuals *) let<**> astate, rev_func_args = PulseOperationResult.list_fold actuals ~init:(astate, []) ~f:(fun (astate, rev_func_args) (actual_exp, actual_typ) -> let++ astate, actual_evaled = PulseOperations.eval path Read call_loc actual_exp astate in ( astate , ProcnameDispatcher.Call.FuncArg. {exp= actual_exp; arg_payload= actual_evaled; typ= actual_typ} :: rev_func_args ) ) in let func_args = List.rev rev_func_args in dispatch_call_eval_args analysis_data path ret call_exp actuals func_args call_loc flags astate callee_pname [ get_dealloc_from_dynamic_types vars_types ] returns a dealloc procname and vars and type needed to execute a call to dealloc for the given variables for which the dynamic type is an Objective - C class . type needed to execute a call to dealloc for the given variables for which the dynamic type is an Objective-C class. *) let get_dealloc_from_dynamic_types dynamic_types_unreachable = let get_dealloc (var, typ) = Typ.name typ |> Option.bind ~f:(fun name -> let cls_typ = Typ.mk (Typ.Tstruct name) in match Var.get_ident var with | Some id when Typ.is_objc_class cls_typ -> let ret_id = Ident.create_fresh Ident.knormal in let dealloc = Procname.make_objc_dealloc name in let typ = Typ.mk_ptr cls_typ in Some (ret_id, id, typ, dealloc) | _ -> None ) in List.filter_map ~f:get_dealloc dynamic_types_unreachable Count strong references reachable from the stack for each RefCounted object in memory and set that count to their respective _ _ infer_mode_reference_count field by calling the _ _ objc_set_ref_count builtin object in memory and set that count to their respective __infer_mode_reference_count field by calling the __objc_set_ref_count builtin *) let set_ref_counts astate location path ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) = let find_var_opt astate addr = Stack.fold (fun var (var_addr, _) var_opt -> if AbstractValue.equal addr var_addr then Some var else var_opt ) astate None in let ref_counts = PulseRefCounting.count_references tenv astate in AbstractValue.Map.fold (fun addr count (astates, ret_vars) -> let ret_vars = ref ret_vars in let astates = List.concat_map astates ~f:(fun astate -> match astate with | AbortProgram _ | ExceptionRaised _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> [astate] | ContinueProgram astate as default_astate -> let astates : ExecutionDomain.t list option = let open IOption.Let_syntax in let* self_var = find_var_opt astate addr in let+ self_typ, _ = let* attrs = AbductiveDomain.AddressAttributes.find_opt addr astate in Attributes.get_dynamic_type_source_file attrs in let ret_id = Ident.create_fresh Ident.knormal in ret_vars := Var.of_id ret_id :: !ret_vars ; let ret = (ret_id, StdTyp.void) in let call_flags = CallFlags.default in let call_exp = Exp.Const (Cfun BuiltinDecl.__objc_set_ref_count) in let actuals = [ (Var.to_exp self_var, self_typ) ; (Exp.Const (Cint (IntLit.of_int count)), StdTyp.uint) ] in let call_instr = Sil.Call (ret, call_exp, actuals, location, call_flags) in L.d_printfln ~color:Pp.Orange "@\nExecuting injected instr:%a@\n@." (Sil.pp_instr Pp.text ~print_types:true) call_instr ; dispatch_call analysis_data path ret call_exp actuals location call_flags astate |> PulseReport.report_exec_results tenv proc_desc err_log location in Option.value ~default:[default_astate] astates ) in (astates, !ret_vars) ) ref_counts ([ContinueProgram astate], []) In the case of variables that point to Objective - C classes for which we have a dynamic type , we add and execute calls to dealloc . The main advantage of adding this calls is that some memory could be freed in dealloc , and we would be reporting a leak on it if we did n't call it . add and execute calls to dealloc. The main advantage of adding this calls is that some memory could be freed in dealloc, and we would be reporting a leak on it if we didn't call it. *) let execute_injected_dealloc_calls ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) path vars astate location = let used_ids = Stack.keys astate |> List.filter_map ~f:(fun var -> Var.get_ident var) in Ident.update_name_generator used_ids ; let call_dealloc (astate_list : ExecutionDomain.t list) (ret_id, id, typ, dealloc) = let ret = (ret_id, StdTyp.void) in let call_flags = CallFlags.default in let call_exp = Exp.Const (Cfun dealloc) in let actuals = [(Exp.Var id, typ)] in let call_instr = Sil.Call (ret, call_exp, actuals, location, call_flags) in L.d_printfln ~color:Pp.Orange "@\nExecuting injected instr:%a@\n@." (Sil.pp_instr Pp.text ~print_types:true) call_instr ; List.concat_map astate_list ~f:(fun (astate : ExecutionDomain.t) -> match astate with | AbortProgram _ | ExceptionRaised _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> [astate] | ContinueProgram astate -> dispatch_call analysis_data path ret call_exp actuals location call_flags astate |> PulseReport.report_exec_results tenv proc_desc err_log location ) in let dynamic_types_unreachable = PulseOperations.get_dynamic_type_unreachable_values vars astate in let dealloc_data = get_dealloc_from_dynamic_types dynamic_types_unreachable in let ret_vars = List.map ~f:(fun (ret_id, _, _, _) -> Var.of_id ret_id) dealloc_data in L.d_printfln ~color:Pp.Orange "Executing injected call to dealloc for vars (%a) that are exiting the scope@." (Pp.seq ~sep:"," Var.pp) vars ; let astates = List.fold ~f:call_dealloc dealloc_data ~init:[ContinueProgram astate] in (astates, ret_vars) let remove_vars vars location astates = List.map astates ~f:(fun (exec_state : ExecutionDomain.t) -> match exec_state with | AbortProgram _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> exec_state | ContinueProgram astate -> ContinueProgram (PulseOperations.remove_vars vars location astate) | ExceptionRaised astate -> ExceptionRaised (PulseOperations.remove_vars vars location astate) ) let exit_scope vars location path astate astate_n ({InterproceduralAnalysis.proc_desc; tenv} as analysis_data) = if Procname.is_java (Procdesc.get_proc_name proc_desc) then (remove_vars vars location [ContinueProgram astate], path, astate_n) else Some RefCounted variables must not be removed at their ExitScope because they may still be referenced by someone and that reference may be destroyed in the future . In that case , we would miss the opportunity to properly dealloc the object if it were removed from the stack , leading to potential FP memory leaks because they may still be referenced by someone and that reference may be destroyed in the future. In that case, we would miss the opportunity to properly dealloc the object if it were removed from the stack, leading to potential FP memory leaks *) let vars = PulseRefCounting.removable_vars tenv astate vars in Prepare objects in memory before calling any dealloc : - set the number of unique strong references accessible from the stack to each object 's respective _ _ infer_mode_reference_count field by calling the _ _ objc_set_ref_count modelled function This needs to be done before any call to dealloc because dealloc 's behavior depends on this ref count and one 's dealloc may call another 's . Consequently , they each need to be up to date beforehand . The return variables of the calls to _ _ objc_set_ref_count must be removed - set the number of unique strong references accessible from the stack to each object's respective __infer_mode_reference_count field by calling the __objc_set_ref_count modelled function This needs to be done before any call to dealloc because dealloc's behavior depends on this ref count and one's dealloc may call another's. Consequently, they each need to be up to date beforehand. The return variables of the calls to __objc_set_ref_count must be removed *) let astates, ret_vars = set_ref_counts astate location path analysis_data in (* Here we add and execute calls to dealloc for Objective-C objects before removing the variables. The return variables of those calls must be removed as welll *) let astates, ret_vars = List.fold_left astates ~init:([], ret_vars) ~f:(fun ((acc_astates, acc_ret_vars) as acc) astate -> match astate with | ContinueProgram astate -> let astates, ret_vars = execute_injected_dealloc_calls analysis_data path vars astate location in (astates @ acc_astates, ret_vars @ acc_ret_vars) | _ -> acc ) in : avoid re - allocating [ vars ] when [ ret_vars ] is empty ( in particular if no ObjC objects are involved ) , but otherwise assume [ ret_vars ] is potentially larger than [ vars ] and so append [ vars ] to [ ret_vars ] . (in particular if no ObjC objects are involved), but otherwise assume [ret_vars] is potentially larger than [vars] and so append [vars] to [ret_vars]. *) let vars_to_remove = if List.is_empty ret_vars then vars else List.rev_append vars ret_vars in ( remove_vars vars_to_remove location astates , path , PulseNonDisjunctiveOperations.mark_modified_copies_and_parameters vars astates astate_n ) let and_is_int_if_integer_type typ v astate = if Typ.is_int typ then PulseArithmetic.and_is_int v astate else Sat (Ok astate) let check_modified_before_dtor args call_exp astate astate_n = match ((call_exp : Exp.t), args) with | (Const (Cfun proc_name) | Closure {name= proc_name}), (Exp.Lvar pvar, _) :: _ when Procname.is_destructor proc_name -> let var = Var.of_pvar pvar in PulseNonDisjunctiveOperations.mark_modified_copies_and_parameters_on_abductive [var] astate astate_n |> NonDisjDomain.checked_via_dtor var | _ -> astate_n let check_config_usage {InterproceduralAnalysis.proc_desc} loc exp astate = let pname = Procdesc.get_proc_name proc_desc in let trace = Trace.Immediate {location= loc; history= ValueHistory.epoch} in Sequence.fold (Exp.free_vars exp) ~init:(Ok astate) ~f:(fun acc var -> Option.value_map (PulseOperations.read_id var astate) ~default:acc ~f:(fun addr_hist -> let* acc in PulseOperations.check_used_as_branch_cond addr_hist ~pname_using_config:pname ~branch_location:loc ~location:loc trace acc ) ) let set_global_astates path ({InterproceduralAnalysis.proc_desc} as analysis_data) exp typ loc astate = let is_global_constant pvar = Pvar.(is_global pvar && (is_const pvar || is_compile_constant pvar)) in let is_global_func_pointer pvar = Pvar.is_global pvar && Typ.is_pointer_to_function typ && Config.pulse_inline_global_init_func_pointer in match (exp : Exp.t) with | Lvar pvar when is_global_constant pvar || is_global_func_pointer pvar -> ( Inline initializers of global constants or globals function pointers when they are being used . This addresses nullptr false positives by pruning infeasable paths global_var ! = global_constant_value , where global_constant_value is the value of global_var This addresses nullptr false positives by pruning infeasable paths global_var != global_constant_value, where global_constant_value is the value of global_var *) (* TODO: Initial global constants only once *) match Pvar.get_initializer_pname pvar with | Some init_pname when not (Procname.equal (Procdesc.get_proc_name proc_desc) init_pname) -> L.d_printfln_escaped "Found initializer for %a" (Pvar.pp Pp.text) pvar ; let call_flags = CallFlags.default in let ret_id_void = (Ident.create_fresh Ident.knormal, StdTyp.void) in let no_error_states = dispatch_call analysis_data path ret_id_void (Const (Cfun init_pname)) [] loc call_flags astate |> List.filter_map ~f:(function | Ok (ContinueProgram astate) -> Some astate | _ -> (* ignore errors in global initializers *) None ) in if List.is_empty no_error_states then [astate] else no_error_states | _ -> [astate] ) | _ -> [astate] let exec_instr_aux ({PathContext.timestamp} as path) (astate : ExecutionDomain.t) (astate_n : NonDisjDomain.t) ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) _cfg_node (instr : Sil.instr) : ExecutionDomain.t list * PathContext.t * NonDisjDomain.t = match astate with | AbortProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> ([astate], path, astate_n) (* an exception has been raised, we skip the other instructions until we enter in exception edge *) | ExceptionRaised _ (* program already exited, simply propagate the exited state upwards *) | ExitProgram _ -> ([astate], path, astate_n) | ContinueProgram astate -> ( match instr with | Load {id= lhs_id; e= rhs_exp; loc; typ} -> (* [lhs_id := *rhs_exp] *) let deref_rhs astate = (let** astate, rhs_addr_hist = PulseOperations.eval_deref path loc rhs_exp astate in and_is_int_if_integer_type typ (fst rhs_addr_hist) astate >>|| PulseOperations.write_id lhs_id rhs_addr_hist ) |> SatUnsat.to_list |> PulseReport.report_results tenv proc_desc err_log loc in let astates = set_global_astates path analysis_data rhs_exp typ loc astate in let astate_n = match rhs_exp with | Lvar pvar -> NonDisjDomain.set_load loc timestamp lhs_id (Var.of_pvar pvar) astate_n | _ -> astate_n in (List.concat_map astates ~f:deref_rhs, path, astate_n) | Store {e1= lhs_exp; e2= rhs_exp; loc; typ} -> (* [*lhs_exp := rhs_exp] *) let event = match lhs_exp with | Lvar v when Pvar.is_return v -> ValueHistory.Returned (loc, timestamp) | _ -> ValueHistory.Assignment (loc, timestamp) in let astate_n = Exp.program_vars lhs_exp |> Sequence.fold ~init:astate_n ~f:(fun astate_n pvar -> NonDisjDomain.set_store loc timestamp pvar astate_n ) in let result = let<**> astate, (rhs_addr, rhs_history) = PulseOperations.eval path NoAccess loc rhs_exp astate in let<**> ls_astate_lhs_addr_hist = let++ astate, lhs_addr_hist = PulseOperations.eval path Write loc lhs_exp astate in [Ok (astate, lhs_addr_hist)] in let hist = ValueHistory.sequence ~context:path.conditions event rhs_history in let astates = List.concat_map ls_astate_lhs_addr_hist ~f:(fun result -> let<*> astate, lhs_addr_hist = result in let<**> astate = and_is_int_if_integer_type typ rhs_addr astate in [ PulseOperations.write_deref path loc ~ref:lhs_addr_hist ~obj:(rhs_addr, hist) astate ] ) in let astates = if Topl.is_active () then List.map astates ~f:(fun result -> let+ astate = result in topl_store_step path loc ~lhs:lhs_exp ~rhs:rhs_exp astate ) else astates in match lhs_exp with | Lvar pvar when Pvar.is_return pvar -> List.map astates ~f:(fun result -> let* astate = result in PulseOperations.check_address_escape loc proc_desc rhs_addr rhs_history astate ) | _ -> astates in let astate_n = NonDisjDomain.set_captured_variables rhs_exp astate_n in (PulseReport.report_results tenv proc_desc err_log loc result, path, astate_n) | Call (ret, call_exp, actuals, loc, call_flags) -> let astate_n = check_modified_before_dtor actuals call_exp astate astate_n in let astates = List.fold actuals ~init:[astate] ~f:(fun astates (exp, typ) -> List.concat_map astates ~f:(fun astate -> set_global_astates path analysis_data exp typ loc astate ) ) in let astates = List.concat_map astates ~f:(fun astate -> dispatch_call analysis_data path ret call_exp actuals loc call_flags astate ) |> PulseReport.report_exec_results tenv proc_desc err_log loc in let astate_n, astates = PulseNonDisjunctiveOperations.call tenv proc_desc path loc ~call_exp ~actuals astates astate_n in let astate_n = NonDisjDomain.set_passed_to loc timestamp call_exp actuals astate_n in (astates, path, astate_n) | Prune (condition, loc, is_then_branch, if_kind) -> let prune_result = let=* astate = check_config_usage analysis_data loc condition astate in PulseOperations.prune path loc ~condition astate in let path = match PulseOperationResult.sat_ok prune_result with | None -> path | Some (_, hist) -> if Sil.is_terminated_if_kind if_kind then let hist = ValueHistory.sequence (ConditionPassed {if_kind; is_then_branch; location= loc; timestamp}) hist in {path with conditions= hist :: path.conditions} else path in let results = let<++> astate, _ = prune_result in astate in (PulseReport.report_exec_results tenv proc_desc err_log loc results, path, astate_n) | Metadata EndBranches -> (* We assume that terminated conditions are well-parenthesised, hence an [EndBranches] instruction terminates the most recently seen terminated conditional. The empty case shouldn't happen but let's not crash by the fault of possible errors in frontends. *) let path = {path with conditions= List.tl path.conditions |> Option.value ~default:[]} in ([ContinueProgram astate], path, astate_n) | Metadata (ExitScope (vars, location)) -> exit_scope vars location path astate astate_n analysis_data | Metadata (VariableLifetimeBegins (pvar, typ, location)) when not (Pvar.is_global pvar) -> ( [ PulseOperations.realloc_pvar tenv path pvar typ location astate |> ExecutionDomain.continue ] , path , astate_n ) | Metadata ( Abstract _ | CatchEntry _ | Nullify _ | Skip | TryEntry _ | TryExit _ | VariableLifetimeBegins _ ) -> ([ContinueProgram astate], path, astate_n) ) let exec_instr ((astate, path), astate_n) analysis_data cfg_node instr : DisjDomain.t list * NonDisjDomain.t = let heap_size = heap_size () in ( match Config.pulse_max_heap with | Some max_heap_size when heap_size > max_heap_size -> let pname = Procdesc.get_proc_name analysis_data.InterproceduralAnalysis.proc_desc in L.internal_error "OOM danger: heap size is %d words, more than the specified threshold of %d words. \ Aborting the analysis of the procedure %a to avoid running out of memory.@\n" heap_size max_heap_size Procname.pp pname ; (* If we'd not compact, then heap remains big, and we'll keep skipping procedures until the runtime decides to compact. *) Gc.compact () ; raise_notrace AboutToOOM | _ -> () ) ; let astates, path, astate_n = exec_instr_aux path astate astate_n analysis_data cfg_node instr in ( List.map astates ~f:(fun exec_state -> (exec_state, PathContext.post_exec_instr path)) , astate_n ) let pp_session_name _node fmt = F.pp_print_string fmt "Pulse" end module Out = struct let channel_ref = ref None let channel () = let output_dir = Filename.concat Config.results_dir "pulse" in Unix.mkdir_p output_dir ; match !channel_ref with | None -> let filename = Format.asprintf "pulse-summary-count-%a.txt" Pid.pp (Unix.getpid ()) in let channel = Filename.concat output_dir filename |> Out_channel.create in let close_channel () = Option.iter !channel_ref ~f:Out_channel.close_no_err ; channel_ref := None in Epilogues.register ~f:close_channel ~description:"close output channel for Pulse" ; channel_ref := Some channel ; channel | Some channel -> channel end module DisjunctiveAnalyzer = AbstractInterpreter.MakeDisjunctive (PulseTransferFunctions) (struct let join_policy = `UnderApproximateAfter Config.pulse_max_disjuncts let widen_policy = `UnderApproximateAfterNumIterations Config.pulse_widen_threshold end) let with_html_debug_node node ~desc ~f = AnalysisCallbacks.html_debug_new_node_session node ~pp_name:(fun fmt -> F.pp_print_string fmt desc) ~f let initial tenv proc_name proc_attrs = let initial_astate = AbductiveDomain.mk_initial tenv proc_name proc_attrs |> PulseSummary.initial_with_positive_self proc_name proc_attrs |> PulseTaintOperations.taint_initial tenv proc_name proc_attrs in [(ContinueProgram initial_astate, PathContext.initial)] let should_analyze proc_desc = let proc_name = Procdesc.get_proc_name proc_desc in let proc_id = Procname.to_unique_id proc_name in let f regex = not (Str.string_match regex proc_id 0) in Option.value_map Config.pulse_skip_procedures ~f ~default:true && (not (Procdesc.is_kotlin proc_desc)) && not (Procdesc.is_too_big Pulse ~max_cfg_size:Config.pulse_max_cfg_size proc_desc) let exit_function analysis_data location posts non_disj_astate = let astates, astate_n = List.fold_left posts ~init:([], non_disj_astate) ~f:(fun (acc_astates, astate_n) (exec_state, path) -> match exec_state with | AbortProgram _ | ExitProgram _ | ExceptionRaised _ | LatentAbortProgram _ | LatentInvalidAccess _ -> (exec_state :: acc_astates, astate_n) | ContinueProgram astate -> let post = (astate.AbductiveDomain.post :> BaseDomain.t) in let vars = BaseStack.fold (fun var _ vars -> if Var.is_return var then vars else var :: vars) post.stack [] in let astates, _, astate_n = PulseTransferFunctions.exit_scope vars location path astate astate_n analysis_data in (PulseTransferFunctions.remove_vars vars location astates @ acc_astates, astate_n) ) in (List.rev astates, astate_n) let analyze ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) = if should_analyze proc_desc then ( AbstractValue.State.reset () ; PulseTopl.Debug.dropped_disjuncts_count := 0 ; let proc_name = Procdesc.get_proc_name proc_desc in let proc_attrs = Procdesc.get_attributes proc_desc in let initial = with_html_debug_node (Procdesc.get_start_node proc_desc) ~desc:"initial state creation" ~f:(fun () -> let initial_disjuncts = initial tenv proc_name proc_attrs in let initial_non_disj = PulseNonDisjunctiveOperations.init_const_refable_parameters proc_desc tenv (List.map initial_disjuncts ~f:fst) NonDisjDomain.bottom in (initial_disjuncts, initial_non_disj) ) in let exit_summaries_opt, exn_sink_summaries_opt = DisjunctiveAnalyzer.compute_post_including_exceptional analysis_data ~initial proc_desc in let process_postconditions node posts_opt ~convert_normal_to_exceptional = match posts_opt with | Some (posts, non_disj_astate) -> let node_loc = Procdesc.Node.get_loc node in let node_id = Procdesc.Node.get_id node in let posts, non_disj_astate = Do final cleanup at the end of procdesc Forget path contexts on the way , we do n't propagate them across functions Forget path contexts on the way, we don't propagate them across functions *) exit_function analysis_data node_loc posts non_disj_astate in let posts = if convert_normal_to_exceptional then List.map posts ~f:(fun edomain -> match edomain with ContinueProgram x -> ExceptionRaised x | _ -> edomain ) else posts in let summary = PulseSummary.of_posts tenv proc_desc err_log node_loc posts in let is_exit_node = Procdesc.Node.equal_id node_id (Procdesc.Node.get_id (Procdesc.get_exit_node proc_desc)) in let summary = if is_exit_node then let objc_nil_summary = PulseSummary.mk_objc_nil_messaging_summary tenv proc_name proc_attrs in Option.to_list objc_nil_summary @ summary else summary in report_topl_errors proc_desc err_log summary ; report_unnecessary_copies proc_desc err_log non_disj_astate ; report_unnecessary_parameter_copies tenv proc_desc err_log non_disj_astate ; summary | None -> [] in let report_on_and_return_summaries (summary : ExecutionDomain.summary list) : ExecutionDomain.summary list option = if Config.trace_topl then L.debug Analysis Quiet "ToplTrace: dropped %d disjuncts in %a@\n" !PulseTopl.Debug.dropped_disjuncts_count Procname.pp_unique_id (Procdesc.get_proc_name proc_desc) ; if Config.pulse_scuba_logging then ScubaLogging.log_count ~label:"pulse_summary" ~value:(List.length summary) ; let summary_count = List.length summary in Stats.add_pulse_summaries_count summary_count ; ( if Config.pulse_log_summary_count then let name = F.asprintf "%a" Procname.pp_verbose proc_name in Printf.fprintf (Out.channel ()) "%s summaries: %d\n" name summary_count ) ; Some summary in let exn_sink_node_opt = Procdesc.get_exn_sink proc_desc in let summaries_at_exn_sink : ExecutionDomain.summary list = (* We extract postconditions from the exceptions sink. *) match exn_sink_node_opt with | Some esink_node -> with_html_debug_node esink_node ~desc:"pulse summary creation (for exception sink node)" ~f:(fun () -> process_postconditions esink_node exn_sink_summaries_opt ~convert_normal_to_exceptional:true ) | None -> [] in let exit_node = Procdesc.get_exit_node proc_desc in with_html_debug_node exit_node ~desc:"pulse summary creation" ~f:(fun () -> let summaries_for_exit = process_postconditions exit_node exit_summaries_opt ~convert_normal_to_exceptional:false in let exit_esink_summaries = summaries_for_exit @ summaries_at_exn_sink in report_on_and_return_summaries exit_esink_summaries ) ) else None let checker ({InterproceduralAnalysis.proc_desc} as analysis_data) = if should_analyze proc_desc then ( try analyze analysis_data with AboutToOOM -> We trigger GC to avoid skipping the next procedure that will be analyzed . Gc.major () ; None ) else None
null
https://raw.githubusercontent.com/facebook/infer/f0f4fc1f34a3ef8bddeaa25af0d842fe11cb1f42/infer/src/pulse/Pulse.ml
ocaml
* raised when we detect that pulse is using too much memory to stop the analysis of the current procedure TODO: Default is set to true for now because we can't get the attributes of library calls right now. [needed_specialization] = current function already needs specialization before the upcoming call (i.e. we did not have enough information to sufficiently specialize a callee). [astate.need_specialization] is false when entering the call. This is to detect calls that need specialization. The value will be set back to true (if it was) in the end by [reset_need_specialization] dereference call expression to catch nil issues We are on an unknown block call, meaning that the block was defined outside the current function and was either passed by the caller as an argument or retrieved from an object. We do not handle blocks inside objects yet so we assume we are in the former case. In this case, we tell the caller that we are missing some information by setting [need_specialization] in the resulting state and the caller will then try to specialize the current function with its available information. this condition may need refining to check that the function comes from the function's parameters or captured variables. The function_pointer_specialization option is there to compensate this / control the specialization's agressivity * has an object just gone out of scope? injected destructors are precisely inserted where an object goes out of scope ignore inner destructors, only trigger out of scope on the final destructor call * [out_of_scope_access_expr] has just gone out of scope and in now invalid invalidate [&x] don't emit Topl event if evals fail if we have a source file then do the look up in the (local) tenv for that source file instead of in the tenv for the current file unresolved function pointer, etc.: skip do interprocedural call then destroy objects going out of scope skip, as above for non-topl special case for objc dispatch models evaluate all actuals Here we add and execute calls to dealloc for Objective-C objects before removing the variables. The return variables of those calls must be removed as welll TODO: Initial global constants only once ignore errors in global initializers an exception has been raised, we skip the other instructions until we enter in exception edge program already exited, simply propagate the exited state upwards [lhs_id := *rhs_exp] [*lhs_exp := rhs_exp] We assume that terminated conditions are well-parenthesised, hence an [EndBranches] instruction terminates the most recently seen terminated conditional. The empty case shouldn't happen but let's not crash by the fault of possible errors in frontends. If we'd not compact, then heap remains big, and we'll keep skipping procedures until the runtime decides to compact. We extract postconditions from the exceptions sink.
* Copyright ( c ) Facebook , Inc. and its 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) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. *) open! IStd module F = Format module L = Logging module IRAttributes = Attributes open PulseBasicInterface open PulseDomainInterface open PulseOperationResult.Import exception AboutToOOM let report_topl_errors proc_desc err_log summary = let f = function | ContinueProgram astate -> PulseTopl.report_errors proc_desc err_log (AbductiveDomain.Topl.get astate) | _ -> () in List.iter ~f summary let is_not_implicit_or_copy_ctor_assignment pname = not (Option.exists (IRAttributes.load pname) ~f:(fun attrs -> attrs.ProcAttributes.is_cpp_implicit || attrs.ProcAttributes.is_cpp_copy_ctor || attrs.ProcAttributes.is_cpp_copy_assignment ) ) let is_non_deleted_copy pname = Option.value_map ~default:true (IRAttributes.load pname) ~f:(fun attrs -> attrs.ProcAttributes.is_cpp_copy_ctor && not attrs.ProcAttributes.is_cpp_deleted ) let is_type_copiable tenv typ = match typ with | {Typ.desc= Tstruct name} | {Typ.desc= Tptr ({desc= Tstruct name}, _)} -> ( match Tenv.lookup tenv name with | None | Some {dummy= true} -> true | Some {methods} -> List.exists ~f:is_non_deleted_copy methods ) | _ -> true let get_loc_instantiated pname = IRAttributes.load pname |> Option.bind ~f:ProcAttributes.get_loc_instantiated let report_unnecessary_copies proc_desc err_log non_disj_astate = let pname = Procdesc.get_proc_name proc_desc in if is_not_implicit_or_copy_ctor_assignment pname then PulseNonDisjunctiveDomain.get_copied non_disj_astate |> List.iter ~f:(fun (copied_into, source_typ, location, copied_location, from) -> let copy_name = Format.asprintf "%a" Attribute.CopiedInto.pp copied_into in let is_suppressed = PulseNonDisjunctiveOperations.has_copy_in copy_name in let location_instantiated = get_loc_instantiated pname in let diagnostic = Diagnostic.UnnecessaryCopy {copied_into; source_typ; location; copied_location; location_instantiated; from} in PulseReport.report ~is_suppressed ~latent:false proc_desc err_log diagnostic ) let report_unnecessary_parameter_copies tenv proc_desc err_log non_disj_astate = let pname = Procdesc.get_proc_name proc_desc in if is_not_implicit_or_copy_ctor_assignment pname then PulseNonDisjunctiveDomain.get_const_refable_parameters non_disj_astate |> List.iter ~f:(fun (param, typ, location) -> if is_type_copiable tenv typ then let diagnostic = if Typ.is_shared_pointer typ then if NonDisjDomain.is_lifetime_extended param non_disj_astate then None else let used_locations = NonDisjDomain.get_loaded_locations param non_disj_astate in Some (Diagnostic.ReadonlySharedPtrParameter {param; typ; location; used_locations}) else Some (Diagnostic.ConstRefableParameter {param; typ; location}) in Option.iter diagnostic ~f:(fun diagnostic -> PulseReport.report ~is_suppressed:false ~latent:false proc_desc err_log diagnostic ) ) let heap_size () = (Gc.quick_stat ()).heap_words module PulseTransferFunctions = struct module CFG = ProcCfg.ExceptionalNoSinkToExitEdge module DisjDomain = AbstractDomain.PairDisjunct (ExecutionDomain) (PathContext) module NonDisjDomain = NonDisjDomain type analysis_data = PulseSummary.t InterproceduralAnalysis.t let get_pvar_formals pname = IRAttributes.load pname |> Option.map ~f:ProcAttributes.get_pvar_formals let need_specialization astates = List.exists astates ~f:(fun res -> match PulseResult.ok res with | Some ( ContinueProgram {AbductiveDomain.need_specialization} | ExceptionRaised {AbductiveDomain.need_specialization} ) -> need_specialization | Some ( ExitProgram astate | AbortProgram astate | LatentAbortProgram {astate} | LatentInvalidAccess {astate} ) -> AbductiveDomain.Summary.need_specialization astate | None -> false ) let reset_need_specialization needed_specialization astates = if needed_specialization then List.map astates ~f:(fun res -> PulseResult.map res ~f:(function | ExceptionRaised astate -> let astate = AbductiveDomain.set_need_specialization astate in ExceptionRaised astate | ContinueProgram astate -> let astate = AbductiveDomain.set_need_specialization astate in ContinueProgram astate | ExitProgram astate -> let astate = AbductiveDomain.Summary.with_need_specialization astate in ExitProgram astate | AbortProgram astate -> let astate = AbductiveDomain.Summary.with_need_specialization astate in AbortProgram astate | LatentAbortProgram latent_abort_program -> let astate = AbductiveDomain.Summary.with_need_specialization latent_abort_program.astate in LatentAbortProgram {latent_abort_program with astate} | LatentInvalidAccess latent_invalid_access -> let astate = AbductiveDomain.Summary.with_need_specialization latent_invalid_access.astate in LatentInvalidAccess {latent_invalid_access with astate} ) ) else astates let interprocedural_call ({InterproceduralAnalysis.analyze_dependency; tenv; proc_desc} as analysis_data) path ret callee_pname call_exp func_args call_loc (flags : CallFlags.t) astate = let actuals = List.map func_args ~f:(fun ProcnameDispatcher.Call.FuncArg.{arg_payload; typ} -> (arg_payload, typ) ) in match callee_pname with | Some callee_pname when not Config.pulse_intraprocedural_only -> let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in let call_kind_of call_exp = match call_exp with | Exp.Closure {captured_vars} -> `Closure captured_vars | Exp.Var id -> `Var id | _ -> `ResolvedProcname in let needed_specialization = astate.AbductiveDomain.need_specialization in let astate = AbductiveDomain.unset_need_specialization astate in let call_kind = call_kind_of call_exp in let maybe_call_with_alias callee_pname call_exp ((res, contradiction) as call_res) = if List.is_empty res then match contradiction with | Some (PulseInterproc.Aliasing _) -> ( L.d_printfln "Trying to alias-specialize %a" Exp.pp call_exp ; match PulseAliasSpecialization.make_specialized_call_exp callee_pname func_args (call_kind_of call_exp) path call_loc astate with | Some (callee_pname, call_exp, astate) -> L.d_printfln "Succesfully alias-specialized %a@\n" Exp.pp call_exp ; let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in let call_res = PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind:(call_kind_of call_exp) astate in (callee_pname, call_exp, call_res) | None -> L.d_printfln "Failed to alias-specialize %a@\n" Exp.pp call_exp ; (callee_pname, call_exp, call_res) ) | _ -> (callee_pname, call_exp, call_res) else (callee_pname, call_exp, call_res) in let maybe_call_specialization callee_pname call_exp ((res, _) as call_res) = if (not needed_specialization) && need_specialization res then ( L.d_printfln "Trying to closure-specialize %a" Exp.pp call_exp ; match PulseClosureSpecialization.make_specialized_call_exp analysis_data func_args callee_pname (call_kind_of call_exp) path call_loc astate with | Some (callee_pname, call_exp, astate) -> L.d_printfln "Succesfully closure-specialized %a@\n" Exp.pp call_exp ; let formals_opt = get_pvar_formals callee_pname in let callee_data = analyze_dependency callee_pname in PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind:(call_kind_of call_exp) astate |> maybe_call_with_alias callee_pname call_exp | None -> L.d_printfln "Failed to closure-specialize %a@\n" Exp.pp call_exp ; (callee_pname, call_exp, call_res) ) else (callee_pname, call_exp, call_res) in let res, _contradiction = let callee_pname, call_exp, call_res = PulseCallOperations.call tenv path ~caller_proc_desc:proc_desc ~callee_data call_loc callee_pname ~ret ~actuals ~formals_opt ~call_kind astate |> maybe_call_with_alias callee_pname call_exp in let _, _, call_res = maybe_call_specialization callee_pname call_exp call_res in call_res in ( reset_need_specialization needed_specialization res , if Option.is_none callee_data then `UnknownCall else `KnownCall ) | _ -> ( (let<**> astate, _ = if flags.cf_is_objc_block then let astate = AbductiveDomain.set_need_specialization astate in PulseOperations.eval_deref path ~must_be_valid_reason:BlockCall call_loc call_exp astate else let astate = if Config.function_pointer_specialization && Language.equal Language.Clang (Procname.get_language (Procdesc.get_proc_name proc_desc)) then AbductiveDomain.set_need_specialization astate else astate in PulseOperations.eval_deref path call_loc call_exp astate in L.d_printfln "Skipping indirect call %a@\n" Exp.pp call_exp ; let astate = let arg_values = List.map actuals ~f:(fun ((value, _), _) -> value) in PulseOperations.conservatively_initialize_args arg_values astate in let<++> astate = PulseCallOperations.unknown_call path call_loc (SkippedUnknownCall call_exp) callee_pname ~ret ~actuals ~formals_opt:None astate in astate ) , `UnknownCall ) let get_out_of_scope_object callee_pname actuals (flags : CallFlags.t) = if flags.cf_injected_destructor then match (callee_pname, actuals) with | Some (Procname.ObjC_Cpp pname), [(Exp.Lvar pvar, typ)] when Pvar.is_local pvar && not (Procname.ObjC_Cpp.is_inner_destructor pname) -> Some (pvar, typ) | _ -> None else None let exec_object_out_of_scope path call_loc (pvar, typ) exec_state = match (exec_state : ExecutionDomain.t) with | ContinueProgram astate | ExceptionRaised astate -> let gone_out_of_scope = Invalidation.GoneOutOfScope (pvar, typ) in let+* astate, out_of_scope_base = PulseOperations.eval path NoAccess call_loc (Exp.Lvar pvar) astate in PulseOperations.invalidate path (StackAddress (Var.of_pvar pvar, ValueHistory.epoch)) call_loc gone_out_of_scope out_of_scope_base astate >>| ExecutionDomain.continue | AbortProgram _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> Sat (Ok exec_state) let topl_small_step loc procname arguments (return, _typ) exec_state_res = let arguments = List.map arguments ~f:(fun {ProcnameDispatcher.Call.FuncArg.arg_payload} -> fst arg_payload) in let return = Var.of_id return in let do_astate astate = let return = Option.map ~f:fst (Stack.find_opt return astate) in let topl_event = PulseTopl.Call {return; arguments; procname} in AbductiveDomain.Topl.small_step loc topl_event astate in let do_one_exec_state (exec_state : ExecutionDomain.t) : ExecutionDomain.t = match exec_state with | ContinueProgram astate -> ContinueProgram (do_astate astate) | AbortProgram _ | LatentAbortProgram _ | ExitProgram _ | ExceptionRaised _ | LatentInvalidAccess _ -> exec_state in List.map ~f:(PulseResult.map ~f:do_one_exec_state) exec_state_res let topl_store_step path loc ~lhs ~rhs:_ astate = match (lhs : Exp.t) with | Lindex (arr, index) -> (let** _astate, (aw_array, _history) = PulseOperations.eval path Read loc arr astate in let++ _astate, (aw_index, _history) = PulseOperations.eval path Read loc index astate in let topl_event = PulseTopl.ArrayWrite {aw_array; aw_index} in AbductiveDomain.Topl.small_step loc topl_event astate ) |> PulseOperationResult.sat_ok | _ -> astate assume that virtual calls are only made on instance methods where it makes sense , in which case the receiver is always the first argument if present the receiver is always the first argument if present *) let get_receiver _proc_name actuals = match actuals with receiver :: _ -> Some receiver | _ -> None let get_dynamic_type_name astate v = match AbductiveDomain.AddressAttributes.get_dynamic_type_source_file v astate with | Some ({desc= Tstruct name}, source_file_opt) -> Some (name, source_file_opt) | Some (t, _) -> L.d_printfln "dynamic type %a of %a is not a Tstruct" (Typ.pp_full Pp.text) t AbstractValue.pp v ; None | None -> L.d_printfln "no dynamic type found for %a" AbstractValue.pp v ; None let find_override tenv astate actuals proc_name proc_name_opt = let open IOption.Let_syntax in let* {ProcnameDispatcher.Call.FuncArg.arg_payload= receiver, _} = get_receiver proc_name actuals in let* dynamic_type_name, source_file_opt = get_dynamic_type_name astate receiver in let* type_name = Procname.get_class_type_name proc_name in if Typ.Name.equal type_name dynamic_type_name then proc_name_opt else let method_exists proc_name methods = List.mem ~equal:Procname.equal methods proc_name in let tenv = Option.bind source_file_opt ~f:Tenv.load |> Option.value ~default:tenv in Tenv.resolve_method ~method_exists tenv dynamic_type_name proc_name let resolve_virtual_call tenv astate actuals proc_name_opt = Option.map proc_name_opt ~f:(fun proc_name -> match find_override tenv astate actuals proc_name proc_name_opt with | Some proc_name' -> L.d_printfln "Dynamic dispatch: %a resolved to %a" Procname.pp proc_name Procname.pp proc_name' ; proc_name' | None -> proc_name ) type model_search_result = | DoliModel of Procname.t | OcamlModel of (PulseModelsImport.model * Procname.t) | NoModel let rec dispatch_call_eval_args ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) path ret call_exp actuals func_args call_loc flags astate callee_pname = let callee_pname = if flags.CallFlags.cf_virtual then resolve_virtual_call tenv astate func_args callee_pname else callee_pname in let astate = match (callee_pname, func_args) with | Some callee_pname, [{ProcnameDispatcher.Call.FuncArg.arg_payload= arg, _}] when Procname.is_std_move callee_pname -> AddressAttributes.add_one arg StdMoved astate | _, _ -> astate in let astate = List.fold func_args ~init:astate ~f:(fun acc {ProcnameDispatcher.Call.FuncArg.arg_payload= arg, _; exp} -> match exp with | Cast (typ, _) when Typ.is_rvalue_reference typ -> AddressAttributes.add_one arg StdMoved acc | _ -> acc ) in let model = match callee_pname with | Some callee_pname -> ( match DoliToTextual.matcher callee_pname with | Some procname -> DoliModel procname | None -> PulseModels.dispatch tenv callee_pname func_args |> Option.value_map ~default:NoModel ~f:(fun model -> OcamlModel (model, callee_pname)) ) | None -> NoModel in let exec_states_res, call_was_unknown = match model with | OcamlModel (model, callee_procname) -> L.d_printfln "Found ocaml model for call@\n" ; let astate = let arg_values = List.map func_args ~f:(fun {ProcnameDispatcher.Call.FuncArg.arg_payload= value, _} -> value ) in PulseOperations.conservatively_initialize_args arg_values astate in ( model { analysis_data ; dispatch_call_eval_args ; path ; callee_procname ; location= call_loc ; ret } astate , `KnownCall ) | DoliModel callee_pname -> L.d_printfln "Found doli model %a for call@\n" Procname.pp callee_pname ; PerfEvent.(log (fun logger -> log_begin_event logger ~name:"pulse interproc call" ())) ; let r = interprocedural_call analysis_data path ret (Some callee_pname) call_exp func_args call_loc flags astate in PerfEvent.(log (fun logger -> log_end_event logger ())) ; r | NoModel -> PerfEvent.(log (fun logger -> log_begin_event logger ~name:"pulse interproc call" ())) ; let r = interprocedural_call analysis_data path ret callee_pname call_exp func_args call_loc flags astate in PerfEvent.(log (fun logger -> log_end_event logger ())) ; r in let exec_states_res = let one_state exec_state_res = let* exec_state = exec_state_res in match exec_state with | ContinueProgram astate -> let call_event = match callee_pname with | None -> Either.First call_exp | Some proc_name -> Either.Second proc_name in let call_was_unknown = match call_was_unknown with `UnknownCall -> true | `KnownCall -> false in let+ astate = PulseTaintOperations.call tenv path call_loc ret ~call_was_unknown call_event func_args astate in ContinueProgram astate | ( ExceptionRaised _ | ExitProgram _ | AbortProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ ) as exec_state -> Ok exec_state in List.map exec_states_res ~f:one_state in let exec_states_res = if Topl.is_active () then match callee_pname with | Some callee_pname -> topl_small_step call_loc callee_pname func_args ret exec_states_res | None -> else exec_states_res in let exec_states_res = match get_out_of_scope_object callee_pname actuals flags with | Some pvar_typ -> L.d_printfln "%a is going out of scope" Pvar.pp_value (fst pvar_typ) ; List.filter_map exec_states_res ~f:(fun exec_state -> exec_state >>>= exec_object_out_of_scope path call_loc pvar_typ |> SatUnsat.sat ) | None -> exec_states_res in if Option.exists callee_pname ~f:IRAttributes.is_no_return then List.filter_map exec_states_res ~f:(fun exec_state_res -> (let+ exec_state = exec_state_res in PulseSummary.force_exit_program tenv proc_desc err_log call_loc exec_state |> SatUnsat.sat ) |> PulseResult.of_some ) else exec_states_res let dispatch_call analysis_data path ret call_exp actuals call_loc flags astate = let<**> astate, callee_pname = PulseOperations.eval_proc_name path call_loc call_exp astate in let callee_pname, call_exp, actuals = match callee_pname with | Some callee_pname when ObjCDispatchModels.is_model callee_pname -> ( match ObjCDispatchModels.get_dispatch_closure_opt actuals with | Some (block_name, closure_exp, args) -> (Some block_name, closure_exp, args) | None -> (Some callee_pname, call_exp, actuals) ) | _ -> (callee_pname, call_exp, actuals) in let<**> astate, rev_func_args = PulseOperationResult.list_fold actuals ~init:(astate, []) ~f:(fun (astate, rev_func_args) (actual_exp, actual_typ) -> let++ astate, actual_evaled = PulseOperations.eval path Read call_loc actual_exp astate in ( astate , ProcnameDispatcher.Call.FuncArg. {exp= actual_exp; arg_payload= actual_evaled; typ= actual_typ} :: rev_func_args ) ) in let func_args = List.rev rev_func_args in dispatch_call_eval_args analysis_data path ret call_exp actuals func_args call_loc flags astate callee_pname [ get_dealloc_from_dynamic_types vars_types ] returns a dealloc procname and vars and type needed to execute a call to dealloc for the given variables for which the dynamic type is an Objective - C class . type needed to execute a call to dealloc for the given variables for which the dynamic type is an Objective-C class. *) let get_dealloc_from_dynamic_types dynamic_types_unreachable = let get_dealloc (var, typ) = Typ.name typ |> Option.bind ~f:(fun name -> let cls_typ = Typ.mk (Typ.Tstruct name) in match Var.get_ident var with | Some id when Typ.is_objc_class cls_typ -> let ret_id = Ident.create_fresh Ident.knormal in let dealloc = Procname.make_objc_dealloc name in let typ = Typ.mk_ptr cls_typ in Some (ret_id, id, typ, dealloc) | _ -> None ) in List.filter_map ~f:get_dealloc dynamic_types_unreachable Count strong references reachable from the stack for each RefCounted object in memory and set that count to their respective _ _ infer_mode_reference_count field by calling the _ _ objc_set_ref_count builtin object in memory and set that count to their respective __infer_mode_reference_count field by calling the __objc_set_ref_count builtin *) let set_ref_counts astate location path ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) = let find_var_opt astate addr = Stack.fold (fun var (var_addr, _) var_opt -> if AbstractValue.equal addr var_addr then Some var else var_opt ) astate None in let ref_counts = PulseRefCounting.count_references tenv astate in AbstractValue.Map.fold (fun addr count (astates, ret_vars) -> let ret_vars = ref ret_vars in let astates = List.concat_map astates ~f:(fun astate -> match astate with | AbortProgram _ | ExceptionRaised _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> [astate] | ContinueProgram astate as default_astate -> let astates : ExecutionDomain.t list option = let open IOption.Let_syntax in let* self_var = find_var_opt astate addr in let+ self_typ, _ = let* attrs = AbductiveDomain.AddressAttributes.find_opt addr astate in Attributes.get_dynamic_type_source_file attrs in let ret_id = Ident.create_fresh Ident.knormal in ret_vars := Var.of_id ret_id :: !ret_vars ; let ret = (ret_id, StdTyp.void) in let call_flags = CallFlags.default in let call_exp = Exp.Const (Cfun BuiltinDecl.__objc_set_ref_count) in let actuals = [ (Var.to_exp self_var, self_typ) ; (Exp.Const (Cint (IntLit.of_int count)), StdTyp.uint) ] in let call_instr = Sil.Call (ret, call_exp, actuals, location, call_flags) in L.d_printfln ~color:Pp.Orange "@\nExecuting injected instr:%a@\n@." (Sil.pp_instr Pp.text ~print_types:true) call_instr ; dispatch_call analysis_data path ret call_exp actuals location call_flags astate |> PulseReport.report_exec_results tenv proc_desc err_log location in Option.value ~default:[default_astate] astates ) in (astates, !ret_vars) ) ref_counts ([ContinueProgram astate], []) In the case of variables that point to Objective - C classes for which we have a dynamic type , we add and execute calls to dealloc . The main advantage of adding this calls is that some memory could be freed in dealloc , and we would be reporting a leak on it if we did n't call it . add and execute calls to dealloc. The main advantage of adding this calls is that some memory could be freed in dealloc, and we would be reporting a leak on it if we didn't call it. *) let execute_injected_dealloc_calls ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) path vars astate location = let used_ids = Stack.keys astate |> List.filter_map ~f:(fun var -> Var.get_ident var) in Ident.update_name_generator used_ids ; let call_dealloc (astate_list : ExecutionDomain.t list) (ret_id, id, typ, dealloc) = let ret = (ret_id, StdTyp.void) in let call_flags = CallFlags.default in let call_exp = Exp.Const (Cfun dealloc) in let actuals = [(Exp.Var id, typ)] in let call_instr = Sil.Call (ret, call_exp, actuals, location, call_flags) in L.d_printfln ~color:Pp.Orange "@\nExecuting injected instr:%a@\n@." (Sil.pp_instr Pp.text ~print_types:true) call_instr ; List.concat_map astate_list ~f:(fun (astate : ExecutionDomain.t) -> match astate with | AbortProgram _ | ExceptionRaised _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> [astate] | ContinueProgram astate -> dispatch_call analysis_data path ret call_exp actuals location call_flags astate |> PulseReport.report_exec_results tenv proc_desc err_log location ) in let dynamic_types_unreachable = PulseOperations.get_dynamic_type_unreachable_values vars astate in let dealloc_data = get_dealloc_from_dynamic_types dynamic_types_unreachable in let ret_vars = List.map ~f:(fun (ret_id, _, _, _) -> Var.of_id ret_id) dealloc_data in L.d_printfln ~color:Pp.Orange "Executing injected call to dealloc for vars (%a) that are exiting the scope@." (Pp.seq ~sep:"," Var.pp) vars ; let astates = List.fold ~f:call_dealloc dealloc_data ~init:[ContinueProgram astate] in (astates, ret_vars) let remove_vars vars location astates = List.map astates ~f:(fun (exec_state : ExecutionDomain.t) -> match exec_state with | AbortProgram _ | ExitProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> exec_state | ContinueProgram astate -> ContinueProgram (PulseOperations.remove_vars vars location astate) | ExceptionRaised astate -> ExceptionRaised (PulseOperations.remove_vars vars location astate) ) let exit_scope vars location path astate astate_n ({InterproceduralAnalysis.proc_desc; tenv} as analysis_data) = if Procname.is_java (Procdesc.get_proc_name proc_desc) then (remove_vars vars location [ContinueProgram astate], path, astate_n) else Some RefCounted variables must not be removed at their ExitScope because they may still be referenced by someone and that reference may be destroyed in the future . In that case , we would miss the opportunity to properly dealloc the object if it were removed from the stack , leading to potential FP memory leaks because they may still be referenced by someone and that reference may be destroyed in the future. In that case, we would miss the opportunity to properly dealloc the object if it were removed from the stack, leading to potential FP memory leaks *) let vars = PulseRefCounting.removable_vars tenv astate vars in Prepare objects in memory before calling any dealloc : - set the number of unique strong references accessible from the stack to each object 's respective _ _ infer_mode_reference_count field by calling the _ _ objc_set_ref_count modelled function This needs to be done before any call to dealloc because dealloc 's behavior depends on this ref count and one 's dealloc may call another 's . Consequently , they each need to be up to date beforehand . The return variables of the calls to _ _ objc_set_ref_count must be removed - set the number of unique strong references accessible from the stack to each object's respective __infer_mode_reference_count field by calling the __objc_set_ref_count modelled function This needs to be done before any call to dealloc because dealloc's behavior depends on this ref count and one's dealloc may call another's. Consequently, they each need to be up to date beforehand. The return variables of the calls to __objc_set_ref_count must be removed *) let astates, ret_vars = set_ref_counts astate location path analysis_data in let astates, ret_vars = List.fold_left astates ~init:([], ret_vars) ~f:(fun ((acc_astates, acc_ret_vars) as acc) astate -> match astate with | ContinueProgram astate -> let astates, ret_vars = execute_injected_dealloc_calls analysis_data path vars astate location in (astates @ acc_astates, ret_vars @ acc_ret_vars) | _ -> acc ) in : avoid re - allocating [ vars ] when [ ret_vars ] is empty ( in particular if no ObjC objects are involved ) , but otherwise assume [ ret_vars ] is potentially larger than [ vars ] and so append [ vars ] to [ ret_vars ] . (in particular if no ObjC objects are involved), but otherwise assume [ret_vars] is potentially larger than [vars] and so append [vars] to [ret_vars]. *) let vars_to_remove = if List.is_empty ret_vars then vars else List.rev_append vars ret_vars in ( remove_vars vars_to_remove location astates , path , PulseNonDisjunctiveOperations.mark_modified_copies_and_parameters vars astates astate_n ) let and_is_int_if_integer_type typ v astate = if Typ.is_int typ then PulseArithmetic.and_is_int v astate else Sat (Ok astate) let check_modified_before_dtor args call_exp astate astate_n = match ((call_exp : Exp.t), args) with | (Const (Cfun proc_name) | Closure {name= proc_name}), (Exp.Lvar pvar, _) :: _ when Procname.is_destructor proc_name -> let var = Var.of_pvar pvar in PulseNonDisjunctiveOperations.mark_modified_copies_and_parameters_on_abductive [var] astate astate_n |> NonDisjDomain.checked_via_dtor var | _ -> astate_n let check_config_usage {InterproceduralAnalysis.proc_desc} loc exp astate = let pname = Procdesc.get_proc_name proc_desc in let trace = Trace.Immediate {location= loc; history= ValueHistory.epoch} in Sequence.fold (Exp.free_vars exp) ~init:(Ok astate) ~f:(fun acc var -> Option.value_map (PulseOperations.read_id var astate) ~default:acc ~f:(fun addr_hist -> let* acc in PulseOperations.check_used_as_branch_cond addr_hist ~pname_using_config:pname ~branch_location:loc ~location:loc trace acc ) ) let set_global_astates path ({InterproceduralAnalysis.proc_desc} as analysis_data) exp typ loc astate = let is_global_constant pvar = Pvar.(is_global pvar && (is_const pvar || is_compile_constant pvar)) in let is_global_func_pointer pvar = Pvar.is_global pvar && Typ.is_pointer_to_function typ && Config.pulse_inline_global_init_func_pointer in match (exp : Exp.t) with | Lvar pvar when is_global_constant pvar || is_global_func_pointer pvar -> ( Inline initializers of global constants or globals function pointers when they are being used . This addresses nullptr false positives by pruning infeasable paths global_var ! = global_constant_value , where global_constant_value is the value of global_var This addresses nullptr false positives by pruning infeasable paths global_var != global_constant_value, where global_constant_value is the value of global_var *) match Pvar.get_initializer_pname pvar with | Some init_pname when not (Procname.equal (Procdesc.get_proc_name proc_desc) init_pname) -> L.d_printfln_escaped "Found initializer for %a" (Pvar.pp Pp.text) pvar ; let call_flags = CallFlags.default in let ret_id_void = (Ident.create_fresh Ident.knormal, StdTyp.void) in let no_error_states = dispatch_call analysis_data path ret_id_void (Const (Cfun init_pname)) [] loc call_flags astate |> List.filter_map ~f:(function | Ok (ContinueProgram astate) -> Some astate | _ -> None ) in if List.is_empty no_error_states then [astate] else no_error_states | _ -> [astate] ) | _ -> [astate] let exec_instr_aux ({PathContext.timestamp} as path) (astate : ExecutionDomain.t) (astate_n : NonDisjDomain.t) ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) _cfg_node (instr : Sil.instr) : ExecutionDomain.t list * PathContext.t * NonDisjDomain.t = match astate with | AbortProgram _ | LatentAbortProgram _ | LatentInvalidAccess _ -> ([astate], path, astate_n) | ExceptionRaised _ | ExitProgram _ -> ([astate], path, astate_n) | ContinueProgram astate -> ( match instr with | Load {id= lhs_id; e= rhs_exp; loc; typ} -> let deref_rhs astate = (let** astate, rhs_addr_hist = PulseOperations.eval_deref path loc rhs_exp astate in and_is_int_if_integer_type typ (fst rhs_addr_hist) astate >>|| PulseOperations.write_id lhs_id rhs_addr_hist ) |> SatUnsat.to_list |> PulseReport.report_results tenv proc_desc err_log loc in let astates = set_global_astates path analysis_data rhs_exp typ loc astate in let astate_n = match rhs_exp with | Lvar pvar -> NonDisjDomain.set_load loc timestamp lhs_id (Var.of_pvar pvar) astate_n | _ -> astate_n in (List.concat_map astates ~f:deref_rhs, path, astate_n) | Store {e1= lhs_exp; e2= rhs_exp; loc; typ} -> let event = match lhs_exp with | Lvar v when Pvar.is_return v -> ValueHistory.Returned (loc, timestamp) | _ -> ValueHistory.Assignment (loc, timestamp) in let astate_n = Exp.program_vars lhs_exp |> Sequence.fold ~init:astate_n ~f:(fun astate_n pvar -> NonDisjDomain.set_store loc timestamp pvar astate_n ) in let result = let<**> astate, (rhs_addr, rhs_history) = PulseOperations.eval path NoAccess loc rhs_exp astate in let<**> ls_astate_lhs_addr_hist = let++ astate, lhs_addr_hist = PulseOperations.eval path Write loc lhs_exp astate in [Ok (astate, lhs_addr_hist)] in let hist = ValueHistory.sequence ~context:path.conditions event rhs_history in let astates = List.concat_map ls_astate_lhs_addr_hist ~f:(fun result -> let<*> astate, lhs_addr_hist = result in let<**> astate = and_is_int_if_integer_type typ rhs_addr astate in [ PulseOperations.write_deref path loc ~ref:lhs_addr_hist ~obj:(rhs_addr, hist) astate ] ) in let astates = if Topl.is_active () then List.map astates ~f:(fun result -> let+ astate = result in topl_store_step path loc ~lhs:lhs_exp ~rhs:rhs_exp astate ) else astates in match lhs_exp with | Lvar pvar when Pvar.is_return pvar -> List.map astates ~f:(fun result -> let* astate = result in PulseOperations.check_address_escape loc proc_desc rhs_addr rhs_history astate ) | _ -> astates in let astate_n = NonDisjDomain.set_captured_variables rhs_exp astate_n in (PulseReport.report_results tenv proc_desc err_log loc result, path, astate_n) | Call (ret, call_exp, actuals, loc, call_flags) -> let astate_n = check_modified_before_dtor actuals call_exp astate astate_n in let astates = List.fold actuals ~init:[astate] ~f:(fun astates (exp, typ) -> List.concat_map astates ~f:(fun astate -> set_global_astates path analysis_data exp typ loc astate ) ) in let astates = List.concat_map astates ~f:(fun astate -> dispatch_call analysis_data path ret call_exp actuals loc call_flags astate ) |> PulseReport.report_exec_results tenv proc_desc err_log loc in let astate_n, astates = PulseNonDisjunctiveOperations.call tenv proc_desc path loc ~call_exp ~actuals astates astate_n in let astate_n = NonDisjDomain.set_passed_to loc timestamp call_exp actuals astate_n in (astates, path, astate_n) | Prune (condition, loc, is_then_branch, if_kind) -> let prune_result = let=* astate = check_config_usage analysis_data loc condition astate in PulseOperations.prune path loc ~condition astate in let path = match PulseOperationResult.sat_ok prune_result with | None -> path | Some (_, hist) -> if Sil.is_terminated_if_kind if_kind then let hist = ValueHistory.sequence (ConditionPassed {if_kind; is_then_branch; location= loc; timestamp}) hist in {path with conditions= hist :: path.conditions} else path in let results = let<++> astate, _ = prune_result in astate in (PulseReport.report_exec_results tenv proc_desc err_log loc results, path, astate_n) | Metadata EndBranches -> let path = {path with conditions= List.tl path.conditions |> Option.value ~default:[]} in ([ContinueProgram astate], path, astate_n) | Metadata (ExitScope (vars, location)) -> exit_scope vars location path astate astate_n analysis_data | Metadata (VariableLifetimeBegins (pvar, typ, location)) when not (Pvar.is_global pvar) -> ( [ PulseOperations.realloc_pvar tenv path pvar typ location astate |> ExecutionDomain.continue ] , path , astate_n ) | Metadata ( Abstract _ | CatchEntry _ | Nullify _ | Skip | TryEntry _ | TryExit _ | VariableLifetimeBegins _ ) -> ([ContinueProgram astate], path, astate_n) ) let exec_instr ((astate, path), astate_n) analysis_data cfg_node instr : DisjDomain.t list * NonDisjDomain.t = let heap_size = heap_size () in ( match Config.pulse_max_heap with | Some max_heap_size when heap_size > max_heap_size -> let pname = Procdesc.get_proc_name analysis_data.InterproceduralAnalysis.proc_desc in L.internal_error "OOM danger: heap size is %d words, more than the specified threshold of %d words. \ Aborting the analysis of the procedure %a to avoid running out of memory.@\n" heap_size max_heap_size Procname.pp pname ; Gc.compact () ; raise_notrace AboutToOOM | _ -> () ) ; let astates, path, astate_n = exec_instr_aux path astate astate_n analysis_data cfg_node instr in ( List.map astates ~f:(fun exec_state -> (exec_state, PathContext.post_exec_instr path)) , astate_n ) let pp_session_name _node fmt = F.pp_print_string fmt "Pulse" end module Out = struct let channel_ref = ref None let channel () = let output_dir = Filename.concat Config.results_dir "pulse" in Unix.mkdir_p output_dir ; match !channel_ref with | None -> let filename = Format.asprintf "pulse-summary-count-%a.txt" Pid.pp (Unix.getpid ()) in let channel = Filename.concat output_dir filename |> Out_channel.create in let close_channel () = Option.iter !channel_ref ~f:Out_channel.close_no_err ; channel_ref := None in Epilogues.register ~f:close_channel ~description:"close output channel for Pulse" ; channel_ref := Some channel ; channel | Some channel -> channel end module DisjunctiveAnalyzer = AbstractInterpreter.MakeDisjunctive (PulseTransferFunctions) (struct let join_policy = `UnderApproximateAfter Config.pulse_max_disjuncts let widen_policy = `UnderApproximateAfterNumIterations Config.pulse_widen_threshold end) let with_html_debug_node node ~desc ~f = AnalysisCallbacks.html_debug_new_node_session node ~pp_name:(fun fmt -> F.pp_print_string fmt desc) ~f let initial tenv proc_name proc_attrs = let initial_astate = AbductiveDomain.mk_initial tenv proc_name proc_attrs |> PulseSummary.initial_with_positive_self proc_name proc_attrs |> PulseTaintOperations.taint_initial tenv proc_name proc_attrs in [(ContinueProgram initial_astate, PathContext.initial)] let should_analyze proc_desc = let proc_name = Procdesc.get_proc_name proc_desc in let proc_id = Procname.to_unique_id proc_name in let f regex = not (Str.string_match regex proc_id 0) in Option.value_map Config.pulse_skip_procedures ~f ~default:true && (not (Procdesc.is_kotlin proc_desc)) && not (Procdesc.is_too_big Pulse ~max_cfg_size:Config.pulse_max_cfg_size proc_desc) let exit_function analysis_data location posts non_disj_astate = let astates, astate_n = List.fold_left posts ~init:([], non_disj_astate) ~f:(fun (acc_astates, astate_n) (exec_state, path) -> match exec_state with | AbortProgram _ | ExitProgram _ | ExceptionRaised _ | LatentAbortProgram _ | LatentInvalidAccess _ -> (exec_state :: acc_astates, astate_n) | ContinueProgram astate -> let post = (astate.AbductiveDomain.post :> BaseDomain.t) in let vars = BaseStack.fold (fun var _ vars -> if Var.is_return var then vars else var :: vars) post.stack [] in let astates, _, astate_n = PulseTransferFunctions.exit_scope vars location path astate astate_n analysis_data in (PulseTransferFunctions.remove_vars vars location astates @ acc_astates, astate_n) ) in (List.rev astates, astate_n) let analyze ({InterproceduralAnalysis.tenv; proc_desc; err_log} as analysis_data) = if should_analyze proc_desc then ( AbstractValue.State.reset () ; PulseTopl.Debug.dropped_disjuncts_count := 0 ; let proc_name = Procdesc.get_proc_name proc_desc in let proc_attrs = Procdesc.get_attributes proc_desc in let initial = with_html_debug_node (Procdesc.get_start_node proc_desc) ~desc:"initial state creation" ~f:(fun () -> let initial_disjuncts = initial tenv proc_name proc_attrs in let initial_non_disj = PulseNonDisjunctiveOperations.init_const_refable_parameters proc_desc tenv (List.map initial_disjuncts ~f:fst) NonDisjDomain.bottom in (initial_disjuncts, initial_non_disj) ) in let exit_summaries_opt, exn_sink_summaries_opt = DisjunctiveAnalyzer.compute_post_including_exceptional analysis_data ~initial proc_desc in let process_postconditions node posts_opt ~convert_normal_to_exceptional = match posts_opt with | Some (posts, non_disj_astate) -> let node_loc = Procdesc.Node.get_loc node in let node_id = Procdesc.Node.get_id node in let posts, non_disj_astate = Do final cleanup at the end of procdesc Forget path contexts on the way , we do n't propagate them across functions Forget path contexts on the way, we don't propagate them across functions *) exit_function analysis_data node_loc posts non_disj_astate in let posts = if convert_normal_to_exceptional then List.map posts ~f:(fun edomain -> match edomain with ContinueProgram x -> ExceptionRaised x | _ -> edomain ) else posts in let summary = PulseSummary.of_posts tenv proc_desc err_log node_loc posts in let is_exit_node = Procdesc.Node.equal_id node_id (Procdesc.Node.get_id (Procdesc.get_exit_node proc_desc)) in let summary = if is_exit_node then let objc_nil_summary = PulseSummary.mk_objc_nil_messaging_summary tenv proc_name proc_attrs in Option.to_list objc_nil_summary @ summary else summary in report_topl_errors proc_desc err_log summary ; report_unnecessary_copies proc_desc err_log non_disj_astate ; report_unnecessary_parameter_copies tenv proc_desc err_log non_disj_astate ; summary | None -> [] in let report_on_and_return_summaries (summary : ExecutionDomain.summary list) : ExecutionDomain.summary list option = if Config.trace_topl then L.debug Analysis Quiet "ToplTrace: dropped %d disjuncts in %a@\n" !PulseTopl.Debug.dropped_disjuncts_count Procname.pp_unique_id (Procdesc.get_proc_name proc_desc) ; if Config.pulse_scuba_logging then ScubaLogging.log_count ~label:"pulse_summary" ~value:(List.length summary) ; let summary_count = List.length summary in Stats.add_pulse_summaries_count summary_count ; ( if Config.pulse_log_summary_count then let name = F.asprintf "%a" Procname.pp_verbose proc_name in Printf.fprintf (Out.channel ()) "%s summaries: %d\n" name summary_count ) ; Some summary in let exn_sink_node_opt = Procdesc.get_exn_sink proc_desc in let summaries_at_exn_sink : ExecutionDomain.summary list = match exn_sink_node_opt with | Some esink_node -> with_html_debug_node esink_node ~desc:"pulse summary creation (for exception sink node)" ~f:(fun () -> process_postconditions esink_node exn_sink_summaries_opt ~convert_normal_to_exceptional:true ) | None -> [] in let exit_node = Procdesc.get_exit_node proc_desc in with_html_debug_node exit_node ~desc:"pulse summary creation" ~f:(fun () -> let summaries_for_exit = process_postconditions exit_node exit_summaries_opt ~convert_normal_to_exceptional:false in let exit_esink_summaries = summaries_for_exit @ summaries_at_exn_sink in report_on_and_return_summaries exit_esink_summaries ) ) else None let checker ({InterproceduralAnalysis.proc_desc} as analysis_data) = if should_analyze proc_desc then ( try analyze analysis_data with AboutToOOM -> We trigger GC to avoid skipping the next procedure that will be analyzed . Gc.major () ; None ) else None
4d9183bd28bf44325c88e20eeccd4b432ae08def7b78097b765e3be09a7a8bf6
wireapp/wire-server
ConversationsIntra.hs
-- This file is part of the Wire Server implementation. -- -- Copyright (C) 2023 Wire Swiss GmbH <> -- -- This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any -- later version. -- -- This program is distributed in the hope that it will be useful, but WITHOUT -- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more -- details. -- You should have received a copy of the GNU Affero General Public License along -- with this program. If not, see </>. module Wire.API.Routes.Internal.Galley.ConversationsIntra ( DesiredMembership (..), Actor (..), UpsertOne2OneConversationRequest (..), UpsertOne2OneConversationResponse (..), ) where import qualified Data.Aeson as A import Data.Aeson.Types (FromJSON, ToJSON) import Data.Id (ConvId, UserId) import Data.Qualified import Data.Schema import qualified Data.Swagger as Swagger import Imports data DesiredMembership = Included | Excluded deriving (Show, Eq, Generic) deriving (FromJSON, ToJSON) via Schema DesiredMembership instance ToSchema DesiredMembership where schema = enum @Text "DesiredMembership" $ mconcat [ element "included" Included, element "excluded" Excluded ] data Actor = LocalActor | RemoteActor deriving (Show, Eq, Generic) deriving (FromJSON, ToJSON) via Schema Actor instance ToSchema Actor where schema = enum @Text "Actor" $ mconcat [ element "local_actor" LocalActor, element "remote_actor" RemoteActor ] data UpsertOne2OneConversationRequest = UpsertOne2OneConversationRequest { uooLocalUser :: Local UserId, uooRemoteUser :: Remote UserId, uooActor :: Actor, uooActorDesiredMembership :: DesiredMembership, uooConvId :: Maybe (Qualified ConvId) } deriving (Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpsertOne2OneConversationRequest instance ToSchema UpsertOne2OneConversationRequest where schema = object "UpsertOne2OneConversationRequest" $ UpsertOne2OneConversationRequest <$> (tUntagged . uooLocalUser) .= field "local_user" (qTagUnsafe <$> schema) <*> (tUntagged . uooRemoteUser) .= field "remote_user" (qTagUnsafe <$> schema) <*> uooActor .= field "actor" schema <*> uooActorDesiredMembership .= field "actor_desired_membership" schema <*> uooConvId .= optField "conversation_id" (maybeWithDefault A.Null schema) newtype UpsertOne2OneConversationResponse = UpsertOne2OneConversationResponse { uuorConvId :: Qualified ConvId } deriving (Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpsertOne2OneConversationResponse instance ToSchema UpsertOne2OneConversationResponse where schema = object "UpsertOne2OneConversationResponse" $ UpsertOne2OneConversationResponse <$> uuorConvId .= field "conversation_id" schema
null
https://raw.githubusercontent.com/wireapp/wire-server/bd9d33f7650f1bc47700601a029df2672d4998a6/libs/wire-api/src/Wire/API/Routes/Internal/Galley/ConversationsIntra.hs
haskell
This file is part of the Wire Server implementation. Copyright (C) 2023 Wire Swiss GmbH <> This program is free software: you can redistribute it and/or modify it under later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. with this program. If not, see </>.
the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any You should have received a copy of the GNU Affero General Public License along module Wire.API.Routes.Internal.Galley.ConversationsIntra ( DesiredMembership (..), Actor (..), UpsertOne2OneConversationRequest (..), UpsertOne2OneConversationResponse (..), ) where import qualified Data.Aeson as A import Data.Aeson.Types (FromJSON, ToJSON) import Data.Id (ConvId, UserId) import Data.Qualified import Data.Schema import qualified Data.Swagger as Swagger import Imports data DesiredMembership = Included | Excluded deriving (Show, Eq, Generic) deriving (FromJSON, ToJSON) via Schema DesiredMembership instance ToSchema DesiredMembership where schema = enum @Text "DesiredMembership" $ mconcat [ element "included" Included, element "excluded" Excluded ] data Actor = LocalActor | RemoteActor deriving (Show, Eq, Generic) deriving (FromJSON, ToJSON) via Schema Actor instance ToSchema Actor where schema = enum @Text "Actor" $ mconcat [ element "local_actor" LocalActor, element "remote_actor" RemoteActor ] data UpsertOne2OneConversationRequest = UpsertOne2OneConversationRequest { uooLocalUser :: Local UserId, uooRemoteUser :: Remote UserId, uooActor :: Actor, uooActorDesiredMembership :: DesiredMembership, uooConvId :: Maybe (Qualified ConvId) } deriving (Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpsertOne2OneConversationRequest instance ToSchema UpsertOne2OneConversationRequest where schema = object "UpsertOne2OneConversationRequest" $ UpsertOne2OneConversationRequest <$> (tUntagged . uooLocalUser) .= field "local_user" (qTagUnsafe <$> schema) <*> (tUntagged . uooRemoteUser) .= field "remote_user" (qTagUnsafe <$> schema) <*> uooActor .= field "actor" schema <*> uooActorDesiredMembership .= field "actor_desired_membership" schema <*> uooConvId .= optField "conversation_id" (maybeWithDefault A.Null schema) newtype UpsertOne2OneConversationResponse = UpsertOne2OneConversationResponse { uuorConvId :: Qualified ConvId } deriving (Show, Generic) deriving (FromJSON, ToJSON, Swagger.ToSchema) via Schema UpsertOne2OneConversationResponse instance ToSchema UpsertOne2OneConversationResponse where schema = object "UpsertOne2OneConversationResponse" $ UpsertOne2OneConversationResponse <$> uuorConvId .= field "conversation_id" schema
e4f3dc949f034d6adbf0ae1eff11894852a614251e6ae0d048a2624b3da1e9ab
radicle-dev/radicle-alpha
Eval.hs
module Radicle.Lang.Eval ( eval , baseEval , callFn , ($$) , createModule ) where import Protolude hiding (Constructor, Handle, TypeError, (<>)) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map as Map import Data.Semigroup ((<>)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified GHC.Exts as GhcExts import Radicle.Lang.Core import qualified Radicle.Lang.Doc as Doc import Radicle.Lang.Identifier (Ident(..)) import Radicle.Lang.Internal.Orphans () -- | The built-in, original, eval. baseEval :: Monad m => Value -> Lang m Value baseEval val = logValPos val $ case val of Atom i -> lookupAtom i List (f:vs) -> f $$ vs List xs -> throwErrorHere $ WrongNumberOfArgs ("application: " <> show xs) 2 (length xs) Vec xs -> Vec <$> traverse baseEval xs Dict mp -> do let evalBoth (a,b) = (,) <$> baseEval a <*> baseEval b kvs <- traverse evalBoth (Map.toList mp) dict $ Map.fromList kvs autoquote -> pure autoquote -- | The buck-passing eval. Uses whatever 'eval' is in scope. eval :: Monad m => Value -> Lang m Value eval val = do e <- lookupAtom (Ident "eval") logValPos e $ do st <- gets bindingsToRadicle result <- callFn e [val, st] case result of List [val', newSt] -> do setBindings newSt pure val' _ -> throwErrorHere $ OtherError "eval: should return list with value and new env" specialForms :: forall m. (Monad m) => Map Ident ([Value] -> Lang m Value) specialForms = Map.fromList $ first Ident <$> [ ( "fn" , \case args : b : bs -> do e <- gets bindingsEnv let toLambda argNames = pure (Lambda argNames (b :| bs) e) case args of Vec atoms_ -> do atoms <- traverse isAtom (toList atoms_) ?? toLangError (SpecialForm "fn" "One of the arguments was not an atom") toLambda (PosArgs atoms) Atom name -> do toLambda (VarArgs name) _ -> throwErrorHere $ SpecialForm "fn" "Function parameters must be one atom or a vector of atoms" _ -> throwErrorHere $ SpecialForm "fn" "Function needs parameters (one atom or a vector of atoms) and a body" ) , ( "module", createModule ) , ("quote", \case [v] -> pure v xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs)) , ("def", \case [Atom name, val] -> def name Nothing val [_, _] -> throwErrorHere $ OtherError "def expects atom for first arg" [Atom name, String d, val] -> def name (Just d) val xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs)) , ( "def-rec" , \case [Atom name, val] -> defRec name Nothing val [_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg" [Atom name, String d, val] -> defRec name (Just d) val xs -> throwErrorHere $ WrongNumberOfArgs "def-rec" 2 (length xs) ) , ("do", (lastDef nil <$>) . traverse baseEval) , ("catch", \case [l, form, handler] -> do mlabel <- baseEval l s <- get case mlabel of TODO reify stack Atom label -> baseEval form `catchError` \err@(LangError _stack e) -> do (thrownLabel, thrownValue) <- errorDataToValue e if thrownLabel == label || label == Ident "any" then do put s handlerclo <- baseEval handler callFn handlerclo [thrownValue] else throwError err _ -> throwErrorHere $ SpecialForm "catch" "first argument must be atom" xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs)) , ("if", \case [condition, t, f] -> do b <- baseEval condition I hate this as much as everyone that might ever read , but in a lot of things that one might object to are True ... if b == Boolean False then baseEval f else baseEval t xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs)) , ( "cond", (cond =<<) . evenArgs "cond" ) , ( "match", match ) ] where cond = \case [] -> pure nil (c,e):ps -> do b <- baseEval c if b /= Boolean False then baseEval e else cond ps match = \case v : cases -> do cs <- evenArgs "match" cases v' <- baseEval v goMatches v' cs _ -> throwErrorHere $ PatternMatchError NoValue goMatches _ [] = throwErrorHere (PatternMatchError NoMatch) goMatches v ((m, body):cases) = do patFn <- baseEval m matchPat <- lookupAtom (Ident "match-pat") res <- callFn matchPat [patFn, v] let res_ = fromRad res case res_ of Right (Just (Dict binds)) -> do b <- bindsToEnv m binds addBinds b *> baseEval body Right Nothing -> goMatches v cases _ -> throwErrorHere $ PatternMatchError (BadBindings m) bindsToEnv pat m = do is <- traverse isBind (Map.toList m) pure $ Env (Map.fromList is) where isBind (Atom x, v) = pure (x, Doc.Docd Nothing v) isBind _ = throwErrorHere $ PatternMatchError (BadBindings pat) addBinds e = modify (\s -> s { bindingsEnv = e <> bindingsEnv s }) def name doc_ val = do val' <- baseEval val defineAtom name doc_ val' pure nil defRec name doc_ val = do val' <- baseEval val case val' of Lambda is b e -> do defineAtom name doc_ $ LambdaRec name is b e pure nil LambdaRec{} -> throwErrorHere $ OtherError "'def-rec' cannot be used to alias functions. Use 'def' instead" _ -> throwErrorHere $ OtherError "'def-rec' can only be used to define functions" data ModuleMeta = ModuleMeta { name :: Ident , exports :: [Ident] , doc :: Text } | Given a list of forms , the first of which should be module declaration , -- runs the rest of the forms in a new scope, and then defs the module value -- according to the name in the declaration. createModule :: forall m. Monad m => [Value] -> Lang m Value createModule = \case (m : forms) -> do m' <- baseEval m >>= meta e <- withEnv identity $ traverse_ eval forms *> gets bindingsEnv let exportsSet = Set.fromList (exports m') let undefinedExports = Set.difference exportsSet (Map.keysSet (fromEnv e)) env <- if null undefinedExports then pure . VEnv . Env $ Map.restrictKeys (fromEnv e) exportsSet else throwErrorHere (ModuleError (UndefinedExports (name m') (Set.toList undefinedExports))) let modu = Dict $ Map.fromList [ (Keyword (Ident "module"), Atom (name m')) , (Keyword (Ident "env"), env) , (Keyword (Ident "exports"), Vec (Seq.fromList (Atom <$> exports m'))) ] defineAtom (name m') (Just (doc m')) modu pure modu _ -> throwErrorHere (ModuleError MissingDeclaration) where meta v@(Dict d) = do name <- modLookup v "module" d "missing `:module` key" doc <- modLookup v "doc" d "missing `:doc` key" exports <- modLookup v "exports" d "Missing `:exports` key" case (name, doc, exports) of (Atom n, String ds, Vec es) -> do is <- traverse isAtom es ?? toLangError (ModuleError (InvalidDeclaration "`:exports` must be a vector of atoms" v)) pure $ ModuleMeta n (toList is) ds _ -> throwErrorHere (ModuleError (InvalidDeclaration "`:module` must be an atom, `:doc` must be a string and `:exports` must be a vector" v)) meta v = throwErrorHere (ModuleError (InvalidDeclaration "must be dict" v)) modLookup v k d e = kwLookup k d ?? toLangError (ModuleError (InvalidDeclaration e v)) | Call a lambda or primitive function @f@ with @arguments@. @f@ and -- @argumenst@ are not evaluated. callFn :: forall m. Monad m => Value -> [Value] -> Lang m Value callFn f arguments = case f of Lambda argNames body closure -> do args <- argumentBindings argNames evalManyWithEnv (args <> closure) body LambdaRec self argNames body closure -> do args <- argumentBindings argNames let selfBinding = GhcExts.fromList (Doc.noDocs [(self, f)]) evalManyWithEnv (args <> selfBinding <> closure) body PrimFn i -> do fn <- lookupPrimop i fn arguments _ -> throwErrorHere $ NonFunctionCalled f where evalManyWithEnv :: Env Value -> NonEmpty Value -> Lang m Value evalManyWithEnv env exprs = NonEmpty.last <$> withEnv (const env) (traverse baseEval exprs) argumentBindings :: LambdaArgs -> Lang m (Env Value) argumentBindings argNames = case argNames of PosArgs names -> if length names /= length arguments then throwErrorHere $ WrongNumberOfArgs "lambda" (length names) (length arguments) else toArgs $ zip names arguments VarArgs name -> toArgs [(name, Vec $ Seq.fromList arguments)] where toArgs = pure . GhcExts.fromList . Doc.noDocs | Process special forms or call function . If @f@ is an atom that -- indicates a special form that special form is processed. Otherwise @f@ and @vs@ are evaluated in ' callFn ' is called . infixr 1 $$ ($$) :: Monad m => Value -> [Value] -> Lang m Value f $$ vs = case f of Atom i -> case Map.lookup i specialForms of Just form -> form vs Nothing -> fnApp _ -> fnApp where fnApp = do f' <- baseEval f vs' <- traverse baseEval vs callFn f' vs'
null
https://raw.githubusercontent.com/radicle-dev/radicle-alpha/b38a360d9830a938fa83fc066c1d131ec903b5e1/radicle-lang/src/Radicle/Lang/Eval.hs
haskell
| The built-in, original, eval. | The buck-passing eval. Uses whatever 'eval' is in scope. runs the rest of the forms in a new scope, and then defs the module value according to the name in the declaration. @argumenst@ are not evaluated. indicates a special form that special form is processed. Otherwise
module Radicle.Lang.Eval ( eval , baseEval , callFn , ($$) , createModule ) where import Protolude hiding (Constructor, Handle, TypeError, (<>)) import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map as Map import Data.Semigroup ((<>)) import qualified Data.Sequence as Seq import qualified Data.Set as Set import qualified GHC.Exts as GhcExts import Radicle.Lang.Core import qualified Radicle.Lang.Doc as Doc import Radicle.Lang.Identifier (Ident(..)) import Radicle.Lang.Internal.Orphans () baseEval :: Monad m => Value -> Lang m Value baseEval val = logValPos val $ case val of Atom i -> lookupAtom i List (f:vs) -> f $$ vs List xs -> throwErrorHere $ WrongNumberOfArgs ("application: " <> show xs) 2 (length xs) Vec xs -> Vec <$> traverse baseEval xs Dict mp -> do let evalBoth (a,b) = (,) <$> baseEval a <*> baseEval b kvs <- traverse evalBoth (Map.toList mp) dict $ Map.fromList kvs autoquote -> pure autoquote eval :: Monad m => Value -> Lang m Value eval val = do e <- lookupAtom (Ident "eval") logValPos e $ do st <- gets bindingsToRadicle result <- callFn e [val, st] case result of List [val', newSt] -> do setBindings newSt pure val' _ -> throwErrorHere $ OtherError "eval: should return list with value and new env" specialForms :: forall m. (Monad m) => Map Ident ([Value] -> Lang m Value) specialForms = Map.fromList $ first Ident <$> [ ( "fn" , \case args : b : bs -> do e <- gets bindingsEnv let toLambda argNames = pure (Lambda argNames (b :| bs) e) case args of Vec atoms_ -> do atoms <- traverse isAtom (toList atoms_) ?? toLangError (SpecialForm "fn" "One of the arguments was not an atom") toLambda (PosArgs atoms) Atom name -> do toLambda (VarArgs name) _ -> throwErrorHere $ SpecialForm "fn" "Function parameters must be one atom or a vector of atoms" _ -> throwErrorHere $ SpecialForm "fn" "Function needs parameters (one atom or a vector of atoms) and a body" ) , ( "module", createModule ) , ("quote", \case [v] -> pure v xs -> throwErrorHere $ WrongNumberOfArgs "quote" 1 (length xs)) , ("def", \case [Atom name, val] -> def name Nothing val [_, _] -> throwErrorHere $ OtherError "def expects atom for first arg" [Atom name, String d, val] -> def name (Just d) val xs -> throwErrorHere $ WrongNumberOfArgs "def" 2 (length xs)) , ( "def-rec" , \case [Atom name, val] -> defRec name Nothing val [_, _] -> throwErrorHere $ OtherError "def-rec expects atom for first arg" [Atom name, String d, val] -> defRec name (Just d) val xs -> throwErrorHere $ WrongNumberOfArgs "def-rec" 2 (length xs) ) , ("do", (lastDef nil <$>) . traverse baseEval) , ("catch", \case [l, form, handler] -> do mlabel <- baseEval l s <- get case mlabel of TODO reify stack Atom label -> baseEval form `catchError` \err@(LangError _stack e) -> do (thrownLabel, thrownValue) <- errorDataToValue e if thrownLabel == label || label == Ident "any" then do put s handlerclo <- baseEval handler callFn handlerclo [thrownValue] else throwError err _ -> throwErrorHere $ SpecialForm "catch" "first argument must be atom" xs -> throwErrorHere $ WrongNumberOfArgs "catch" 3 (length xs)) , ("if", \case [condition, t, f] -> do b <- baseEval condition I hate this as much as everyone that might ever read , but in a lot of things that one might object to are True ... if b == Boolean False then baseEval f else baseEval t xs -> throwErrorHere $ WrongNumberOfArgs "if" 3 (length xs)) , ( "cond", (cond =<<) . evenArgs "cond" ) , ( "match", match ) ] where cond = \case [] -> pure nil (c,e):ps -> do b <- baseEval c if b /= Boolean False then baseEval e else cond ps match = \case v : cases -> do cs <- evenArgs "match" cases v' <- baseEval v goMatches v' cs _ -> throwErrorHere $ PatternMatchError NoValue goMatches _ [] = throwErrorHere (PatternMatchError NoMatch) goMatches v ((m, body):cases) = do patFn <- baseEval m matchPat <- lookupAtom (Ident "match-pat") res <- callFn matchPat [patFn, v] let res_ = fromRad res case res_ of Right (Just (Dict binds)) -> do b <- bindsToEnv m binds addBinds b *> baseEval body Right Nothing -> goMatches v cases _ -> throwErrorHere $ PatternMatchError (BadBindings m) bindsToEnv pat m = do is <- traverse isBind (Map.toList m) pure $ Env (Map.fromList is) where isBind (Atom x, v) = pure (x, Doc.Docd Nothing v) isBind _ = throwErrorHere $ PatternMatchError (BadBindings pat) addBinds e = modify (\s -> s { bindingsEnv = e <> bindingsEnv s }) def name doc_ val = do val' <- baseEval val defineAtom name doc_ val' pure nil defRec name doc_ val = do val' <- baseEval val case val' of Lambda is b e -> do defineAtom name doc_ $ LambdaRec name is b e pure nil LambdaRec{} -> throwErrorHere $ OtherError "'def-rec' cannot be used to alias functions. Use 'def' instead" _ -> throwErrorHere $ OtherError "'def-rec' can only be used to define functions" data ModuleMeta = ModuleMeta { name :: Ident , exports :: [Ident] , doc :: Text } | Given a list of forms , the first of which should be module declaration , createModule :: forall m. Monad m => [Value] -> Lang m Value createModule = \case (m : forms) -> do m' <- baseEval m >>= meta e <- withEnv identity $ traverse_ eval forms *> gets bindingsEnv let exportsSet = Set.fromList (exports m') let undefinedExports = Set.difference exportsSet (Map.keysSet (fromEnv e)) env <- if null undefinedExports then pure . VEnv . Env $ Map.restrictKeys (fromEnv e) exportsSet else throwErrorHere (ModuleError (UndefinedExports (name m') (Set.toList undefinedExports))) let modu = Dict $ Map.fromList [ (Keyword (Ident "module"), Atom (name m')) , (Keyword (Ident "env"), env) , (Keyword (Ident "exports"), Vec (Seq.fromList (Atom <$> exports m'))) ] defineAtom (name m') (Just (doc m')) modu pure modu _ -> throwErrorHere (ModuleError MissingDeclaration) where meta v@(Dict d) = do name <- modLookup v "module" d "missing `:module` key" doc <- modLookup v "doc" d "missing `:doc` key" exports <- modLookup v "exports" d "Missing `:exports` key" case (name, doc, exports) of (Atom n, String ds, Vec es) -> do is <- traverse isAtom es ?? toLangError (ModuleError (InvalidDeclaration "`:exports` must be a vector of atoms" v)) pure $ ModuleMeta n (toList is) ds _ -> throwErrorHere (ModuleError (InvalidDeclaration "`:module` must be an atom, `:doc` must be a string and `:exports` must be a vector" v)) meta v = throwErrorHere (ModuleError (InvalidDeclaration "must be dict" v)) modLookup v k d e = kwLookup k d ?? toLangError (ModuleError (InvalidDeclaration e v)) | Call a lambda or primitive function @f@ with @arguments@. @f@ and callFn :: forall m. Monad m => Value -> [Value] -> Lang m Value callFn f arguments = case f of Lambda argNames body closure -> do args <- argumentBindings argNames evalManyWithEnv (args <> closure) body LambdaRec self argNames body closure -> do args <- argumentBindings argNames let selfBinding = GhcExts.fromList (Doc.noDocs [(self, f)]) evalManyWithEnv (args <> selfBinding <> closure) body PrimFn i -> do fn <- lookupPrimop i fn arguments _ -> throwErrorHere $ NonFunctionCalled f where evalManyWithEnv :: Env Value -> NonEmpty Value -> Lang m Value evalManyWithEnv env exprs = NonEmpty.last <$> withEnv (const env) (traverse baseEval exprs) argumentBindings :: LambdaArgs -> Lang m (Env Value) argumentBindings argNames = case argNames of PosArgs names -> if length names /= length arguments then throwErrorHere $ WrongNumberOfArgs "lambda" (length names) (length arguments) else toArgs $ zip names arguments VarArgs name -> toArgs [(name, Vec $ Seq.fromList arguments)] where toArgs = pure . GhcExts.fromList . Doc.noDocs | Process special forms or call function . If @f@ is an atom that @f@ and @vs@ are evaluated in ' callFn ' is called . infixr 1 $$ ($$) :: Monad m => Value -> [Value] -> Lang m Value f $$ vs = case f of Atom i -> case Map.lookup i specialForms of Just form -> form vs Nothing -> fnApp _ -> fnApp where fnApp = do f' <- baseEval f vs' <- traverse baseEval vs callFn f' vs'
6629243bfe8b396bac680d6c2fcb461f8c6acfb058c6bfa0b9f24cd150c4ea30
ocaml-multicore/ocaml-tsan
str.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 Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Regular expressions and high-level string processing *) * { 1 Regular expressions } * The { ! } library provides regular expressions on sequences of bytes . It is , in general , unsuitable to match Unicode characters . The {!Str} library provides regular expressions on sequences of bytes. It is, in general, unsuitable to match Unicode characters. *) type regexp (** The type of compiled regular expressions. *) val regexp : string -> regexp * Compile a regular expression . The following constructs are recognized : - [ . ] Matches any character except newline . - [ * ] ( postfix ) Matches the preceding expression zero , one or several times - [ + ] ( postfix ) Matches the preceding expression one or several times - [ ? ] ( postfix ) Matches the preceding expression once or not at all - [ [ .. ] ] Character set . Ranges are denoted with [ - ] , as in [ [ a - z ] ] . An initial [ ^ ] , as in [ [ ^0 - 9 ] ] , complements the set . To include a [ \ ] ] character in a set , make it the first character of the set . To include a [ - ] character in a set , make it the first or the last character of the set . - [ ^ ] Matches at beginning of line : either at the beginning of the matched string , or just after a ' \n ' character . - [ $ ] Matches at end of line : either at the end of the matched string , or just before a ' \n ' character . - [ \| ] ( infix ) Alternative between two expressions . - [ \( .. \ ) ] Grouping and naming of the enclosed expression . - [ \1 ] The text matched by the first [ \( ... \ ) ] expression ( [ \2 ] for the second expression , and so on up to [ \9 ] ) . - [ \b ] Matches word boundaries . - [ \ ] Quotes special characters . The special characters are [ $ ^\.*+ ? [ ] ] . In regular expressions you will often use backslash characters ; it 's easier to use a quoted string literal [ { | ... | } ] to avoid having to escape backslashes . For example , the following expression : { [ let r = Str.regexp { |hello \([A - Za - z]+\)| } in Str.replace_first r { |\1| } " hello world " ] } returns the string [ " world " ] . If you want a regular expression that matches a literal backslash character , you need to double it : [ Str.regexp { |\\| } ] . You can use regular string literals [ " ... " ] too , however you will have to escape backslashes . The example above can be rewritten with a regular string literal as : { [ let r = Str.regexp " hello \\([A - Za - z]+\\ ) " in Str.replace_first r " \\1 " " hello world " ] } And the regular expression for matching a backslash becomes a quadruple backslash : [ Str.regexp " \\\\ " ] . recognized: - [. ] Matches any character except newline. - [* ] (postfix) Matches the preceding expression zero, one or several times - [+ ] (postfix) Matches the preceding expression one or several times - [? ] (postfix) Matches the preceding expression once or not at all - [[..] ] Character set. Ranges are denoted with [-], as in [[a-z]]. An initial [^], as in [[^0-9]], complements the set. To include a [\]] character in a set, make it the first character of the set. To include a [-] character in a set, make it the first or the last character of the set. - [^ ] Matches at beginning of line: either at the beginning of the matched string, or just after a '\n' character. - [$ ] Matches at end of line: either at the end of the matched string, or just before a '\n' character. - [\| ] (infix) Alternative between two expressions. - [\(..\)] Grouping and naming of the enclosed expression. - [\1 ] The text matched by the first [\(...\)] expression ([\2] for the second expression, and so on up to [\9]). - [\b ] Matches word boundaries. - [\ ] Quotes special characters. The special characters are [$^\.*+?[]]. In regular expressions you will often use backslash characters; it's easier to use a quoted string literal [{|...|}] to avoid having to escape backslashes. For example, the following expression: {[ let r = Str.regexp {|hello \([A-Za-z]+\)|} in Str.replace_first r {|\1|} "hello world" ]} returns the string ["world"]. If you want a regular expression that matches a literal backslash character, you need to double it: [Str.regexp {|\\|}]. You can use regular string literals ["..."] too, however you will have to escape backslashes. The example above can be rewritten with a regular string literal as: {[ let r = Str.regexp "hello \\([A-Za-z]+\\)" in Str.replace_first r "\\1" "hello world" ]} And the regular expression for matching a backslash becomes a quadruple backslash: [Str.regexp "\\\\"]. *) val regexp_case_fold : string -> regexp (** Same as [regexp], but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent. *) val quote : string -> string (** [Str.quote s] returns a regexp string that matches exactly [s] and nothing else. *) val regexp_string : string -> regexp * [ Str.regexp_string s ] returns a regular expression that matches exactly [ s ] and nothing else . that matches exactly [s] and nothing else.*) val regexp_string_case_fold : string -> regexp (** [Str.regexp_string_case_fold] is similar to {!Str.regexp_string}, but the regexp matches in a case-insensitive way. *) * { 1 String matching and searching } val string_match : regexp -> string -> int -> bool * [ string_match r s start ] tests whether a substring of [ s ] that starts at position [ start ] matches the regular expression [ r ] . The first character of a string has position [ 0 ] , as usual . starts at position [start] matches the regular expression [r]. The first character of a string has position [0], as usual. *) val search_forward : regexp -> string -> int -> int * [ search_forward r s start ] searches the string [ s ] for a substring matching the regular expression [ r ] . The search starts at position [ start ] and proceeds towards the end of the string . Return the position of the first character of the matched substring . @raise Not_found if no substring matches . matching the regular expression [r]. The search starts at position [start] and proceeds towards the end of the string. Return the position of the first character of the matched substring. @raise Not_found if no substring matches. *) val search_backward : regexp -> string -> int -> int * [ search_backward r s last ] searches the string [ s ] for a substring matching the regular expression [ r ] . The search first considers substrings that start at position [ last ] and proceeds towards the beginning of string . Return the position of the first character of the matched substring . @raise Not_found if no substring matches . substring matching the regular expression [r]. The search first considers substrings that start at position [last] and proceeds towards the beginning of string. Return the position of the first character of the matched substring. @raise Not_found if no substring matches. *) val string_partial_match : regexp -> string -> int -> bool (** Similar to {!Str.string_match}, but also returns true if the argument string is a prefix of a string that matches. This includes the case of a true complete match. *) val matched_string : string -> string * [ matched_string s ] returns the substring of [ s ] that was matched by the last call to one of the following matching or searching functions : - { ! Str.string_match } - { ! Str.search_forward } - { ! Str.search_backward } - { ! Str.string_partial_match } - { ! Str.global_substitute } - { ! Str.substitute_first } provided that none of the following functions was called in between : - { ! Str.global_replace } - { ! Str.replace_first } - { ! Str.split } - { ! Str.bounded_split } - { ! Str.split_delim } - { ! Str.bounded_split_delim } - { ! Str.full_split } - { ! Str.bounded_full_split } Note : in the case of [ global_substitute ] and [ substitute_first ] , a call to [ matched_string ] is only valid within the [ subst ] argument , not after [ global_substitute ] or [ substitute_first ] returns . The user must make sure that the parameter [ s ] is the same string that was passed to the matching or searching function . by the last call to one of the following matching or searching functions: - {!Str.string_match} - {!Str.search_forward} - {!Str.search_backward} - {!Str.string_partial_match} - {!Str.global_substitute} - {!Str.substitute_first} provided that none of the following functions was called in between: - {!Str.global_replace} - {!Str.replace_first} - {!Str.split} - {!Str.bounded_split} - {!Str.split_delim} - {!Str.bounded_split_delim} - {!Str.full_split} - {!Str.bounded_full_split} Note: in the case of [global_substitute] and [substitute_first], a call to [matched_string] is only valid within the [subst] argument, not after [global_substitute] or [substitute_first] returns. The user must make sure that the parameter [s] is the same string that was passed to the matching or searching function. *) val match_beginning : unit -> int * [ match_beginning ( ) ] returns the position of the first character of the substring that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . of the substring that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). *) val match_end : unit -> int (** [match_end()] returns the position of the character following the last character of the substring that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). *) val matched_group : int -> string -> string * [ matched_group n s ] returns the substring of [ s ] that was matched by the [ n]th group [ \( ... \ ) ] of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . When [ n ] is [ 0 ] , it returns the substring matched by the whole regular expression . The user must make sure that the parameter [ s ] is the same string that was passed to the matching or searching function . @raise Not_found if the [ n]th group of the regular expression was not matched . This can happen with groups inside alternatives [ \| ] , options [ ? ] or repetitions [ * ] . For instance , the empty string will match [ ) * ] , but [ matched_group 1 " " ] will raise [ Not_found ] because the first group itself was not matched . by the [n]th group [\(...\)] of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). When [n] is [0], it returns the substring matched by the whole regular expression. The user must make sure that the parameter [s] is the same string that was passed to the matching or searching function. @raise Not_found if the [n]th group of the regular expression was not matched. This can happen with groups inside alternatives [\|], options [?] or repetitions [*]. For instance, the empty string will match [\(a\)*], but [matched_group 1 ""] will raise [Not_found] because the first group itself was not matched. *) val group_beginning : int -> int * [ group_beginning n ] returns the position of the first character of the substring that was matched by the [ n]th group of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . @raise Not_found if the [ n]th group of the regular expression was not matched . @raise Invalid_argument if there are fewer than [ n ] groups in the regular expression . of the substring that was matched by the [n]th group of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). @raise Not_found if the [n]th group of the regular expression was not matched. @raise Invalid_argument if there are fewer than [n] groups in the regular expression. *) val group_end : int -> int * [ group_end n ] returns the position of the character following the last character of substring that was matched by the [ n]th group of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . @raise Not_found if the [ n]th group of the regular expression was not matched . @raise Invalid_argument if there are fewer than [ n ] groups in the regular expression . the position of the character following the last character of substring that was matched by the [n]th group of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). @raise Not_found if the [n]th group of the regular expression was not matched. @raise Invalid_argument if there are fewer than [n] groups in the regular expression. *) (** {1 Replacement} *) val global_replace : regexp -> string -> string -> string (** [global_replace regexp templ s] returns a string identical to [s], except that all substrings of [s] that match [regexp] have been replaced by [templ]. The replacement template [templ] can contain [\1], [\2], etc; these sequences will be replaced by the text matched by the corresponding group in the regular expression. [\0] stands for the text matched by the whole regular expression. *) val replace_first : regexp -> string -> string -> string * Same as { ! Str.global_replace } , except that only the first substring matching the regular expression is replaced . matching the regular expression is replaced. *) val global_substitute : regexp -> (string -> string) -> string -> string (** [global_substitute regexp subst s] returns a string identical to [s], except that all substrings of [s] that match [regexp] have been replaced by the result of function [subst]. The function [subst] is called once for each matching substring, and receives [s] (the whole text) as argument. *) val substitute_first : regexp -> (string -> string) -> string -> string * Same as { ! Str.global_substitute } , except that only the first substring matching the regular expression is replaced . matching the regular expression is replaced. *) val replace_matched : string -> string -> string * [ replace_matched repl s ] returns the replacement text [ repl ] in which [ \1 ] , [ \2 ] , etc . have been replaced by the text matched by the corresponding groups in the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . [ s ] must be the same string that was passed to the matching or searching function . in which [\1], [\2], etc. have been replaced by the text matched by the corresponding groups in the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). [s] must be the same string that was passed to the matching or searching function. *) (** {1 Splitting} *) val split : regexp -> string -> string list (** [split r s] splits [s] into substrings, taking as delimiters the substrings that match [r], and returns the list of substrings. For instance, [split (regexp "[ \t]+") s] splits [s] into blank-separated words. An occurrence of the delimiter at the beginning or at the end of the string is ignored. *) val bounded_split : regexp -> string -> int -> string list (** Same as {!Str.split}, but splits into at most [n] substrings, where [n] is the extra integer parameter. *) val split_delim : regexp -> string -> string list * Same as { ! Str.split } but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result . For instance , [ split_delim ( regexp " " ) " abc " ] returns [ [ " " ; " abc " ; " " ] ] , while [ split ] with the same arguments returns [ [ " abc " ] ] . delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. For instance, [split_delim (regexp " ") " abc "] returns [[""; "abc"; ""]], while [split] with the same arguments returns [["abc"]]. *) val bounded_split_delim : regexp -> string -> int -> string list * Same as { ! } , but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result . delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. *) type split_result = Text of string | Delim of string val full_split : regexp -> string -> split_result list * Same as { ! Str.split_delim } , but returns the delimiters as well as the substrings contained between delimiters . The former are tagged [ Delim ] in the result list ; the latter are tagged [ Text ] . For instance , [ full_split ( regexp " [ { } ] " ) " { ab } " ] returns [ [ Delim " { " ; Text " ab " ; " } " ] ] . the delimiters as well as the substrings contained between delimiters. The former are tagged [Delim] in the result list; the latter are tagged [Text]. For instance, [full_split (regexp "[{}]") "{ab}"] returns [[Delim "{"; Text "ab"; Delim "}"]]. *) val bounded_full_split : regexp -> string -> int -> split_result list (** Same as {!Str.bounded_split_delim}, but returns the delimiters as well as the substrings contained between delimiters. The former are tagged [Delim] in the result list; the latter are tagged [Text]. *) * { 1 Extracting substrings } val string_before : string -> int -> string (** [string_before s n] returns the substring of all characters of [s] that precede position [n] (excluding the character at position [n]). *) val string_after : string -> int -> string (** [string_after s n] returns the substring of all characters of [s] that follow position [n] (including the character at position [n]). *) val first_chars : string -> int -> string * [ first_chars s n ] returns the first [ n ] characters of [ s ] . This is the same function as { ! Str.string_before } . This is the same function as {!Str.string_before}. *) val last_chars : string -> int -> string (** [last_chars s n] returns the last [n] characters of [s]. *)
null
https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/ae9c1502103845550162a49fcd3f76276cdfa866/otherlibs/str/str.mli
ocaml
************************************************************************ OCaml en Automatique. All rights reserved. This file is distributed under the terms of special exception on linking described in the file LICENSE. ************************************************************************ * Regular expressions and high-level string processing * The type of compiled regular expressions. * Same as [regexp], but the compiled expression will match text in a case-insensitive way: uppercase and lowercase letters will be considered equivalent. * [Str.quote s] returns a regexp string that matches exactly [s] and nothing else. * [Str.regexp_string_case_fold] is similar to {!Str.regexp_string}, but the regexp matches in a case-insensitive way. * Similar to {!Str.string_match}, but also returns true if the argument string is a prefix of a string that matches. This includes the case of a true complete match. * [match_end()] returns the position of the character following the last character of the substring that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). * {1 Replacement} * [global_replace regexp templ s] returns a string identical to [s], except that all substrings of [s] that match [regexp] have been replaced by [templ]. The replacement template [templ] can contain [\1], [\2], etc; these sequences will be replaced by the text matched by the corresponding group in the regular expression. [\0] stands for the text matched by the whole regular expression. * [global_substitute regexp subst s] returns a string identical to [s], except that all substrings of [s] that match [regexp] have been replaced by the result of function [subst]. The function [subst] is called once for each matching substring, and receives [s] (the whole text) as argument. * {1 Splitting} * [split r s] splits [s] into substrings, taking as delimiters the substrings that match [r], and returns the list of substrings. For instance, [split (regexp "[ \t]+") s] splits [s] into blank-separated words. An occurrence of the delimiter at the beginning or at the end of the string is ignored. * Same as {!Str.split}, but splits into at most [n] substrings, where [n] is the extra integer parameter. * Same as {!Str.bounded_split_delim}, but returns the delimiters as well as the substrings contained between delimiters. The former are tagged [Delim] in the result list; the latter are tagged [Text]. * [string_before s n] returns the substring of all characters of [s] that precede position [n] (excluding the character at position [n]). * [string_after s n] returns the substring of all characters of [s] that follow position [n] (including the character at position [n]). * [last_chars s n] returns the last [n] characters of [s].
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the * { 1 Regular expressions } * The { ! } library provides regular expressions on sequences of bytes . It is , in general , unsuitable to match Unicode characters . The {!Str} library provides regular expressions on sequences of bytes. It is, in general, unsuitable to match Unicode characters. *) type regexp val regexp : string -> regexp * Compile a regular expression . The following constructs are recognized : - [ . ] Matches any character except newline . - [ * ] ( postfix ) Matches the preceding expression zero , one or several times - [ + ] ( postfix ) Matches the preceding expression one or several times - [ ? ] ( postfix ) Matches the preceding expression once or not at all - [ [ .. ] ] Character set . Ranges are denoted with [ - ] , as in [ [ a - z ] ] . An initial [ ^ ] , as in [ [ ^0 - 9 ] ] , complements the set . To include a [ \ ] ] character in a set , make it the first character of the set . To include a [ - ] character in a set , make it the first or the last character of the set . - [ ^ ] Matches at beginning of line : either at the beginning of the matched string , or just after a ' \n ' character . - [ $ ] Matches at end of line : either at the end of the matched string , or just before a ' \n ' character . - [ \| ] ( infix ) Alternative between two expressions . - [ \( .. \ ) ] Grouping and naming of the enclosed expression . - [ \1 ] The text matched by the first [ \( ... \ ) ] expression ( [ \2 ] for the second expression , and so on up to [ \9 ] ) . - [ \b ] Matches word boundaries . - [ \ ] Quotes special characters . The special characters are [ $ ^\.*+ ? [ ] ] . In regular expressions you will often use backslash characters ; it 's easier to use a quoted string literal [ { | ... | } ] to avoid having to escape backslashes . For example , the following expression : { [ let r = Str.regexp { |hello \([A - Za - z]+\)| } in Str.replace_first r { |\1| } " hello world " ] } returns the string [ " world " ] . If you want a regular expression that matches a literal backslash character , you need to double it : [ Str.regexp { |\\| } ] . You can use regular string literals [ " ... " ] too , however you will have to escape backslashes . The example above can be rewritten with a regular string literal as : { [ let r = Str.regexp " hello \\([A - Za - z]+\\ ) " in Str.replace_first r " \\1 " " hello world " ] } And the regular expression for matching a backslash becomes a quadruple backslash : [ Str.regexp " \\\\ " ] . recognized: - [. ] Matches any character except newline. - [* ] (postfix) Matches the preceding expression zero, one or several times - [+ ] (postfix) Matches the preceding expression one or several times - [? ] (postfix) Matches the preceding expression once or not at all - [[..] ] Character set. Ranges are denoted with [-], as in [[a-z]]. An initial [^], as in [[^0-9]], complements the set. To include a [\]] character in a set, make it the first character of the set. To include a [-] character in a set, make it the first or the last character of the set. - [^ ] Matches at beginning of line: either at the beginning of the matched string, or just after a '\n' character. - [$ ] Matches at end of line: either at the end of the matched string, or just before a '\n' character. - [\| ] (infix) Alternative between two expressions. - [\(..\)] Grouping and naming of the enclosed expression. - [\1 ] The text matched by the first [\(...\)] expression ([\2] for the second expression, and so on up to [\9]). - [\b ] Matches word boundaries. - [\ ] Quotes special characters. The special characters are [$^\.*+?[]]. In regular expressions you will often use backslash characters; it's easier to use a quoted string literal [{|...|}] to avoid having to escape backslashes. For example, the following expression: {[ let r = Str.regexp {|hello \([A-Za-z]+\)|} in Str.replace_first r {|\1|} "hello world" ]} returns the string ["world"]. If you want a regular expression that matches a literal backslash character, you need to double it: [Str.regexp {|\\|}]. You can use regular string literals ["..."] too, however you will have to escape backslashes. The example above can be rewritten with a regular string literal as: {[ let r = Str.regexp "hello \\([A-Za-z]+\\)" in Str.replace_first r "\\1" "hello world" ]} And the regular expression for matching a backslash becomes a quadruple backslash: [Str.regexp "\\\\"]. *) val regexp_case_fold : string -> regexp val quote : string -> string val regexp_string : string -> regexp * [ Str.regexp_string s ] returns a regular expression that matches exactly [ s ] and nothing else . that matches exactly [s] and nothing else.*) val regexp_string_case_fold : string -> regexp * { 1 String matching and searching } val string_match : regexp -> string -> int -> bool * [ string_match r s start ] tests whether a substring of [ s ] that starts at position [ start ] matches the regular expression [ r ] . The first character of a string has position [ 0 ] , as usual . starts at position [start] matches the regular expression [r]. The first character of a string has position [0], as usual. *) val search_forward : regexp -> string -> int -> int * [ search_forward r s start ] searches the string [ s ] for a substring matching the regular expression [ r ] . The search starts at position [ start ] and proceeds towards the end of the string . Return the position of the first character of the matched substring . @raise Not_found if no substring matches . matching the regular expression [r]. The search starts at position [start] and proceeds towards the end of the string. Return the position of the first character of the matched substring. @raise Not_found if no substring matches. *) val search_backward : regexp -> string -> int -> int * [ search_backward r s last ] searches the string [ s ] for a substring matching the regular expression [ r ] . The search first considers substrings that start at position [ last ] and proceeds towards the beginning of string . Return the position of the first character of the matched substring . @raise Not_found if no substring matches . substring matching the regular expression [r]. The search first considers substrings that start at position [last] and proceeds towards the beginning of string. Return the position of the first character of the matched substring. @raise Not_found if no substring matches. *) val string_partial_match : regexp -> string -> int -> bool val matched_string : string -> string * [ matched_string s ] returns the substring of [ s ] that was matched by the last call to one of the following matching or searching functions : - { ! Str.string_match } - { ! Str.search_forward } - { ! Str.search_backward } - { ! Str.string_partial_match } - { ! Str.global_substitute } - { ! Str.substitute_first } provided that none of the following functions was called in between : - { ! Str.global_replace } - { ! Str.replace_first } - { ! Str.split } - { ! Str.bounded_split } - { ! Str.split_delim } - { ! Str.bounded_split_delim } - { ! Str.full_split } - { ! Str.bounded_full_split } Note : in the case of [ global_substitute ] and [ substitute_first ] , a call to [ matched_string ] is only valid within the [ subst ] argument , not after [ global_substitute ] or [ substitute_first ] returns . The user must make sure that the parameter [ s ] is the same string that was passed to the matching or searching function . by the last call to one of the following matching or searching functions: - {!Str.string_match} - {!Str.search_forward} - {!Str.search_backward} - {!Str.string_partial_match} - {!Str.global_substitute} - {!Str.substitute_first} provided that none of the following functions was called in between: - {!Str.global_replace} - {!Str.replace_first} - {!Str.split} - {!Str.bounded_split} - {!Str.split_delim} - {!Str.bounded_split_delim} - {!Str.full_split} - {!Str.bounded_full_split} Note: in the case of [global_substitute] and [substitute_first], a call to [matched_string] is only valid within the [subst] argument, not after [global_substitute] or [substitute_first] returns. The user must make sure that the parameter [s] is the same string that was passed to the matching or searching function. *) val match_beginning : unit -> int * [ match_beginning ( ) ] returns the position of the first character of the substring that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . of the substring that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). *) val match_end : unit -> int val matched_group : int -> string -> string * [ matched_group n s ] returns the substring of [ s ] that was matched by the [ n]th group [ \( ... \ ) ] of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . When [ n ] is [ 0 ] , it returns the substring matched by the whole regular expression . The user must make sure that the parameter [ s ] is the same string that was passed to the matching or searching function . @raise Not_found if the [ n]th group of the regular expression was not matched . This can happen with groups inside alternatives [ \| ] , options [ ? ] or repetitions [ * ] . For instance , the empty string will match [ ) * ] , but [ matched_group 1 " " ] will raise [ Not_found ] because the first group itself was not matched . by the [n]th group [\(...\)] of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). When [n] is [0], it returns the substring matched by the whole regular expression. The user must make sure that the parameter [s] is the same string that was passed to the matching or searching function. @raise Not_found if the [n]th group of the regular expression was not matched. This can happen with groups inside alternatives [\|], options [?] or repetitions [*]. For instance, the empty string will match [\(a\)*], but [matched_group 1 ""] will raise [Not_found] because the first group itself was not matched. *) val group_beginning : int -> int * [ group_beginning n ] returns the position of the first character of the substring that was matched by the [ n]th group of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . @raise Not_found if the [ n]th group of the regular expression was not matched . @raise Invalid_argument if there are fewer than [ n ] groups in the regular expression . of the substring that was matched by the [n]th group of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). @raise Not_found if the [n]th group of the regular expression was not matched. @raise Invalid_argument if there are fewer than [n] groups in the regular expression. *) val group_end : int -> int * [ group_end n ] returns the position of the character following the last character of substring that was matched by the [ n]th group of the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . @raise Not_found if the [ n]th group of the regular expression was not matched . @raise Invalid_argument if there are fewer than [ n ] groups in the regular expression . the position of the character following the last character of substring that was matched by the [n]th group of the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). @raise Not_found if the [n]th group of the regular expression was not matched. @raise Invalid_argument if there are fewer than [n] groups in the regular expression. *) val global_replace : regexp -> string -> string -> string val replace_first : regexp -> string -> string -> string * Same as { ! Str.global_replace } , except that only the first substring matching the regular expression is replaced . matching the regular expression is replaced. *) val global_substitute : regexp -> (string -> string) -> string -> string val substitute_first : regexp -> (string -> string) -> string -> string * Same as { ! Str.global_substitute } , except that only the first substring matching the regular expression is replaced . matching the regular expression is replaced. *) val replace_matched : string -> string -> string * [ replace_matched repl s ] returns the replacement text [ repl ] in which [ \1 ] , [ \2 ] , etc . have been replaced by the text matched by the corresponding groups in the regular expression that was matched by the last call to a matching or searching function ( see { ! Str.matched_string } for details ) . [ s ] must be the same string that was passed to the matching or searching function . in which [\1], [\2], etc. have been replaced by the text matched by the corresponding groups in the regular expression that was matched by the last call to a matching or searching function (see {!Str.matched_string} for details). [s] must be the same string that was passed to the matching or searching function. *) val split : regexp -> string -> string list val bounded_split : regexp -> string -> int -> string list val split_delim : regexp -> string -> string list * Same as { ! Str.split } but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result . For instance , [ split_delim ( regexp " " ) " abc " ] returns [ [ " " ; " abc " ; " " ] ] , while [ split ] with the same arguments returns [ [ " abc " ] ] . delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. For instance, [split_delim (regexp " ") " abc "] returns [[""; "abc"; ""]], while [split] with the same arguments returns [["abc"]]. *) val bounded_split_delim : regexp -> string -> int -> string list * Same as { ! } , but occurrences of the delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result . delimiter at the beginning and at the end of the string are recognized and returned as empty strings in the result. *) type split_result = Text of string | Delim of string val full_split : regexp -> string -> split_result list * Same as { ! Str.split_delim } , but returns the delimiters as well as the substrings contained between delimiters . The former are tagged [ Delim ] in the result list ; the latter are tagged [ Text ] . For instance , [ full_split ( regexp " [ { } ] " ) " { ab } " ] returns [ [ Delim " { " ; Text " ab " ; " } " ] ] . the delimiters as well as the substrings contained between delimiters. The former are tagged [Delim] in the result list; the latter are tagged [Text]. For instance, [full_split (regexp "[{}]") "{ab}"] returns [[Delim "{"; Text "ab"; Delim "}"]]. *) val bounded_full_split : regexp -> string -> int -> split_result list * { 1 Extracting substrings } val string_before : string -> int -> string val string_after : string -> int -> string val first_chars : string -> int -> string * [ first_chars s n ] returns the first [ n ] characters of [ s ] . This is the same function as { ! Str.string_before } . This is the same function as {!Str.string_before}. *) val last_chars : string -> int -> string
1c8ed910ce1911f066a165bb8e65db2d356ef6907f5f3fb3e565b38dd5e00e8e
esl/MongooseIM
mongoose_router.erl
-module(mongoose_router). -define(TABLE, ?MODULE). -export([start/0, default_routing_modules/0]). -export([get_all_domains/0, lookup_route/1, is_registered_route/1, register_route/2, unregister_route/1]). -spec get_all_domains() -> [jid:lserver()]. get_all_domains() -> ets:select(?TABLE, [{{'$1', '_'}, [], ['$1']}]). -spec lookup_route(jid:lserver()) -> no_route | mongoose_packet_handler:t(). lookup_route(LDomain) -> case ets:lookup(?TABLE, LDomain) of [] -> no_route; [{_, Handler}] -> Handler end. -spec register_route(jid:server(), mongoose_packet_handler:t()) -> any(). register_route(Domain, Handler) -> case jid:nameprep(Domain) of error -> {error, invalid_domain, Domain}; LDomain -> ets:insert(?TABLE, {LDomain, Handler}) end. -spec unregister_route(jid:server()) -> any(). unregister_route(Domain) -> case jid:nameprep(Domain) of error -> {error, invalid_domain, Domain}; LDomain -> ets:delete(?TABLE, LDomain) end. -spec is_registered_route(jid:lserver()) -> boolean(). is_registered_route(LDomain) -> ets:member(?TABLE, LDomain). %% start/stop start() -> ets:new(?TABLE, [named_table, public, set, {read_concurrency, true}]), mongoose_metrics:ensure_metric(global, routingErrors, spiral). default_routing_modules() -> [mongoose_router_global, mongoose_router_localdomain, mongoose_router_external_localnode, mongoose_router_external, mongoose_router_dynamic_domains, ejabberd_s2s].
null
https://raw.githubusercontent.com/esl/MongooseIM/4f6a8451705389e3de9c95e951bad42a97d7f681/src/mongoose_router.erl
erlang
start/stop
-module(mongoose_router). -define(TABLE, ?MODULE). -export([start/0, default_routing_modules/0]). -export([get_all_domains/0, lookup_route/1, is_registered_route/1, register_route/2, unregister_route/1]). -spec get_all_domains() -> [jid:lserver()]. get_all_domains() -> ets:select(?TABLE, [{{'$1', '_'}, [], ['$1']}]). -spec lookup_route(jid:lserver()) -> no_route | mongoose_packet_handler:t(). lookup_route(LDomain) -> case ets:lookup(?TABLE, LDomain) of [] -> no_route; [{_, Handler}] -> Handler end. -spec register_route(jid:server(), mongoose_packet_handler:t()) -> any(). register_route(Domain, Handler) -> case jid:nameprep(Domain) of error -> {error, invalid_domain, Domain}; LDomain -> ets:insert(?TABLE, {LDomain, Handler}) end. -spec unregister_route(jid:server()) -> any(). unregister_route(Domain) -> case jid:nameprep(Domain) of error -> {error, invalid_domain, Domain}; LDomain -> ets:delete(?TABLE, LDomain) end. -spec is_registered_route(jid:lserver()) -> boolean(). is_registered_route(LDomain) -> ets:member(?TABLE, LDomain). start() -> ets:new(?TABLE, [named_table, public, set, {read_concurrency, true}]), mongoose_metrics:ensure_metric(global, routingErrors, spiral). default_routing_modules() -> [mongoose_router_global, mongoose_router_localdomain, mongoose_router_external_localnode, mongoose_router_external, mongoose_router_dynamic_domains, ejabberd_s2s].
5fb086766a87dadc62686c457cb605ab515b30734b93f694f0f86d36c3981ba9
dgtized/shimmers
_svg_template.cljs
(ns shimmers.sketches._svg-template (:require [shimmers.common.svg :as csvg :include-macros true] [shimmers.common.ui.controls :as ctrl] [shimmers.sketch :as sketch :include-macros true] [shimmers.view.sketch :as view-sketch] [thi.ng.geom.vector :as gv])) (def width 800) (def height 600) (defn rv [x y] (gv/vec2 (* width x) (* height y))) (defn shapes [] []) (defn scene [] (csvg/timed (csvg/svg {:width width :height height :stroke "black" :fill "white" :stroke-width 0.5} (shapes)))) (sketch/definition svg-template {:created-at "2023-" :type :svg :tags #{}} (ctrl/mount (view-sketch/page-for scene :svg-template) "sketch-host"))
null
https://raw.githubusercontent.com/dgtized/shimmers/a56f1f4d711bef182fd32030cc5d0d5b18d33f73/src/shimmers/sketches/_svg_template.cljs
clojure
(ns shimmers.sketches._svg-template (:require [shimmers.common.svg :as csvg :include-macros true] [shimmers.common.ui.controls :as ctrl] [shimmers.sketch :as sketch :include-macros true] [shimmers.view.sketch :as view-sketch] [thi.ng.geom.vector :as gv])) (def width 800) (def height 600) (defn rv [x y] (gv/vec2 (* width x) (* height y))) (defn shapes [] []) (defn scene [] (csvg/timed (csvg/svg {:width width :height height :stroke "black" :fill "white" :stroke-width 0.5} (shapes)))) (sketch/definition svg-template {:created-at "2023-" :type :svg :tags #{}} (ctrl/mount (view-sketch/page-for scene :svg-template) "sketch-host"))
dc97369b3172ebd980d975b598e2a35bcce700b66ccdc04a5d91c388c7e4e0d8
ericcervin/getting-started-with-sketching
pg064.rkt
#lang sketching (define (setup) (size 240 120) (smoothing 'smoothed) (set-frame-rate! 60) ) (define x 80) (define y 30) (define w 80) (define h 60) (define (draw) (background 204) (if (and (> mouse-x x) (< mouse-x (+ x w)) (> mouse-y y) (< mouse-y (+ y h))) (fill 0) (fill 255)) (rect x y w h) )
null
https://raw.githubusercontent.com/ericcervin/getting-started-with-sketching/aa6107bc2ba6caf12f5d14c395d2e7eb173c1ba7/pg064.rkt
racket
#lang sketching (define (setup) (size 240 120) (smoothing 'smoothed) (set-frame-rate! 60) ) (define x 80) (define y 30) (define w 80) (define h 60) (define (draw) (background 204) (if (and (> mouse-x x) (< mouse-x (+ x w)) (> mouse-y y) (< mouse-y (+ y h))) (fill 0) (fill 255)) (rect x y w h) )
364728549b761067aa4383090065cf935f542387f08cfa71e704a3ee16824cbd
adamdoupe/find_ear_rails
merge_tp.ml
open Merge_tp_parser open Merge_tp_lexer open Parse_tree let () = Printf.printf " Example of disambiguation with a merge function Prints a parse tree Grammar : S -> E E -> int E -> E + E E -> E * E example : 1+2*3 yields (1+(2*3)) 'q' to quit " let () = flush stdout let lexbuf = Lexing.from_channel stdin let _ = flush stdout let _ = try while true do (Lexing.flush_input lexbuf; try let pf = Merge_tp_parser.main Merge_tp_lexer.token lexbuf in let _ = List.iter print_tree (List.map (fun (x,_) -> x) pf) in print_newline () with | Failure s -> Printf.printf "Failure - %s\n\n" s | Dyp.Syntax_error -> Printf.printf "Syntax error\n\n" ); flush stdout done with Merge_tp_lexer.Eof -> exit 0
null
https://raw.githubusercontent.com/adamdoupe/find_ear_rails/38f892f9962ad415a583973caf24fbab1a011be1/diamondback-ruby-0.20090726/dypgen-20070627/demos/merge_times_plus/merge_tp.ml
ocaml
open Merge_tp_parser open Merge_tp_lexer open Parse_tree let () = Printf.printf " Example of disambiguation with a merge function Prints a parse tree Grammar : S -> E E -> int E -> E + E E -> E * E example : 1+2*3 yields (1+(2*3)) 'q' to quit " let () = flush stdout let lexbuf = Lexing.from_channel stdin let _ = flush stdout let _ = try while true do (Lexing.flush_input lexbuf; try let pf = Merge_tp_parser.main Merge_tp_lexer.token lexbuf in let _ = List.iter print_tree (List.map (fun (x,_) -> x) pf) in print_newline () with | Failure s -> Printf.printf "Failure - %s\n\n" s | Dyp.Syntax_error -> Printf.printf "Syntax error\n\n" ); flush stdout done with Merge_tp_lexer.Eof -> exit 0