_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
|
---|---|---|---|---|---|---|---|---|
d053219e8d1d7e2b814716a8666e6b6f155e2b2df5a2ece9d144af904207fffe | andreer/lispbox | asdf-extensions.lisp | (defpackage :com.gigamonkeys.asdf-extensions
(:use :cl :asdf)
(:export :register-source-directory))
(in-package :com.gigamonkeys.asdf-extensions)
;;; Method for finding ASD files that doesn't depend on symlinks.
(defvar *top-level-directories* ())
(defun sysdef-crawl-directories (system)
(let ((name (asdf::coerce-name system)))
(block found
(flet ((found-p (file)
(when (and
(equal (pathname-name file) name)
(equal (pathname-type file) "asd"))
(return-from found file))))
(dolist (dir *top-level-directories*)
(walk-directory dir #'found-p))))))
(defun register-source-directory (dir)
(push (pathname-as-directory dir) *top-level-directories*))
(setf *system-definition-search-functions* '(sysdef-crawl-directories))
;;; Build FASLs into a implementation specific directory.
(defparameter *fasl-directory*
(merge-pathnames
(make-pathname
:directory `(:relative ".lispbox" "fasl" ,(swank-loader::unique-dir-name)))
(user-homedir-pathname)))
(defmethod output-files :around ((operation compile-op) (c source-file))
(let ((defaults (merge-pathnames
(make-relative (component-pathname c))
*fasl-directory*)))
(flet ((relocate-fasl (file)
(make-pathname
:type (pathname-type file) :defaults defaults)))
(mapcar #'relocate-fasl (call-next-method)))))
;; Static files
(defmethod output-files :around ((operation compile-op) (c static-file))
(list
(merge-pathnames (make-relative (component-pathname c)) *fasl-directory*)))
(defmethod perform :after ((operation compile-op) (c static-file))
(let ((source-file (component-pathname c))
(output-file (car (output-files operation c))))
(ensure-directories-exist output-file)
(with-open-file (in source-file :element-type '(unsigned-byte 8))
(with-open-file (out output-file :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede)
(loop for octet = (read-byte in nil nil)
while octet do (write-byte octet out))))))
(defun make-relative (pathname)
(make-pathname
:directory (cons :relative (rest (pathname-directory pathname)))
:defaults pathname))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Portable pathnames lib . Unfortunately we ca n't use ASDF to load it
;;; so we have to inline it here.
(defun list-directory (dirname)
"Return a list of the contents of the directory named by dirname.
Names of subdirectories will be returned in `directory normal
form'. Unlike CL:DIRECTORY, LIST-DIRECTORY does not accept
wildcard pathnames; `dirname' should simply be a pathname that
names a directory. It can be in either file or directory form."
(when (wild-pathname-p dirname)
(error "Can only list concrete directory names."))
(let ((wildcard (directory-wildcard dirname)))
#+(or sbcl cmu lispworks)
SBCL , CMUCL , and Lispworks return subdirectories in directory
;; form just the way we want.
(directory wildcard)
#+openmcl
;; OpenMCl by default doesn't return subdirectories at all. But
;; when prodded to do so with the special argument :directories,
;; it returns them in directory form.
(directory wildcard :directories t)
#+allegro
Allegro normally return directories in file form but we can
;; change that with the :directories-are-files argument.
(directory wildcard :directories-are-files nil)
#+clisp
CLISP has a particularly idiosyncratic view of things . But we
;; can bludgeon even it into doing what we want.
(nconc
CLISP wo n't list files without an extension when : type is
;; wild so we make a special wildcard for it.
(directory wildcard)
And CLISP does n't consider subdirectories to match unless
;; there is a :wild in the directory component.
(directory (clisp-subdirectories-wildcard wildcard)))
#-(or sbcl cmu lispworks openmcl allegro clisp)
(error "list-directory not implemented")))
(defun file-exists-p (pathname)
"Similar to CL:PROBE-FILE except it always returns directory names
in `directory normal form'. Returns truename which will be in
`directory form' if file named is, in fact, a directory."
#+(or sbcl lispworks openmcl)
These implementations do " The Right Thing " as far as we are
;; concerned. They return a truename of the file or directory if it
;; exists and the truename of a directory is in directory normal
;; form.
(probe-file pathname)
#+(or allegro cmu)
;; These implementations accept the name of a directory in either
;; form and return the name in the form given. However the name of a
file must be given in file form . So we try first with a directory
;; name which will return NIL if either the file doesn't exist at
;; all or exists and is not a directory. Then we try with a file
;; form name.
(or (probe-file (pathname-as-directory pathname))
(probe-file pathname))
#+clisp
Once again CLISP takes a particularly unforgiving approach ,
signalling ERRORs at the slightest provocation .
;; pathname in file form and actually a file -- (probe-file file) ==> truename
;; pathname in file form and doesn't exist -- (probe-file file) ==> NIL
;; pathname in dir form and actually a directory -- (probe-directory file) ==> truename
;; pathname in dir form and doesn't exist -- (probe-directory file) ==> NIL
;; pathname in file form and actually a directory -- (probe-file file) ==> ERROR
;; pathname in dir form and actually a file -- (probe-directory file) ==> ERROR
(or (ignore-errors
;; PROBE-FILE will return the truename if file exists and is a
file or NIL if it does n't exist at all . If it exists but is
;; a directory PROBE-FILE will signal an error which we
;; ignore.
(probe-file (pathname-as-file pathname)))
(ignore-errors
;; PROBE-DIRECTORY returns T if the file exists and is a
directory or NIL if it does n't exist at all . If it exists
;; but is a file, PROBE-DIRECTORY will signal an error.
(let ((directory-form (pathname-as-directory pathname)))
(when (ext:probe-directory directory-form)
directory-form))))
#-(or sbcl cmu lispworks openmcl allegro clisp)
(error "list-directory not implemented"))
(defun directory-wildcard (dirname)
(make-pathname
:name :wild
:type #-clisp :wild #+clisp nil
:defaults (pathname-as-directory dirname)))
#+clisp
(defun clisp-subdirectories-wildcard (wildcard)
(make-pathname
:directory (append (pathname-directory wildcard) (list :wild))
:name nil
:type nil
:defaults wildcard))
(defun directory-pathname-p (p)
"Is the given pathname the name of a directory? This function can
usefully be used to test whether a name returned by LIST-DIRECTORIES
or passed to the function in WALK-DIRECTORY is the name of a directory
in the file system since they always return names in `directory normal
form'."
(flet ((component-present-p (value)
(and value (not (eql value :unspecific)))))
(and
(not (component-present-p (pathname-name p)))
(not (component-present-p (pathname-type p)))
p)))
(defun file-pathname-p (p)
(unless (directory-pathname-p p) p))
(defun pathname-as-directory (name)
"Return a pathname reperesenting the given pathname in
`directory normal form', i.e. with all the name elements in the
directory component and NIL in the name and type components. Can
not be used on wild pathnames because there's not portable way to
convert wildcards in the name and type into a single directory
component. Returns its argument if name and type are both nil or
:unspecific."
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (not (directory-pathname-p name))
(make-pathname
:directory (append (or (pathname-directory pathname) (list :relative))
(list (file-namestring pathname)))
:name nil
:type nil
:defaults pathname)
pathname)))
(defun pathname-as-file (name)
"Return a pathname reperesenting the given pathname in `file form',
i.e. with the name elements in the name and type component. Can't
convert wild pathnames because of problems mapping wild directory
component into name and type components. Returns its argument if
it is already in file form."
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (directory-pathname-p name)
(let* ((directory (pathname-directory pathname))
(name-and-type (pathname (first (last directory)))))
(make-pathname
:directory (butlast directory)
:name (pathname-name name-and-type)
:type (pathname-type name-and-type)
:defaults pathname))
pathname)))
(defun walk-directory (dirname fn &key directories (test (constantly t)))
"Walk a directory invoking `fn' on each pathname found. If `test' is
supplied fn is invoked only on pathnames for which `test' returns
true. If `directories' is t invokes `test' and `fn' on directory
pathnames as well."
(labels
((walk (name)
(cond
((directory-pathname-p name)
(when (and directories (funcall test name))
(funcall fn name))
(dolist (x (list-directory name)) (walk x)))
((funcall test name) (funcall fn name)))))
(walk (pathname-as-directory dirname))))
(defun directory-p (name)
"Is `name' the name of an existing directory."
(let ((truename (file-exists-p name)))
(and truename (directory-pathname-p name))))
(defun file-p (name)
"Is `name' the name of an existing file, i.e. not a directory."
(let ((truename (file-exists-p name)))
(and truename (file-pathname-p name))))
(pushnew :com.gigamonkeys.asdf-extensions *features*)
| null | https://raw.githubusercontent.com/andreer/lispbox/215de614dc7ba693b5578f6b149465aa47718f60/asdf-extensions.lisp | lisp | Method for finding ASD files that doesn't depend on symlinks.
Build FASLs into a implementation specific directory.
Static files
so we have to inline it here.
`dirname' should simply be a pathname that
form just the way we want.
OpenMCl by default doesn't return subdirectories at all. But
when prodded to do so with the special argument :directories,
it returns them in directory form.
change that with the :directories-are-files argument.
can bludgeon even it into doing what we want.
wild so we make a special wildcard for it.
there is a :wild in the directory component.
concerned. They return a truename of the file or directory if it
exists and the truename of a directory is in directory normal
form.
These implementations accept the name of a directory in either
form and return the name in the form given. However the name of a
name which will return NIL if either the file doesn't exist at
all or exists and is not a directory. Then we try with a file
form name.
pathname in file form and actually a file -- (probe-file file) ==> truename
pathname in file form and doesn't exist -- (probe-file file) ==> NIL
pathname in dir form and actually a directory -- (probe-directory file) ==> truename
pathname in dir form and doesn't exist -- (probe-directory file) ==> NIL
pathname in file form and actually a directory -- (probe-file file) ==> ERROR
pathname in dir form and actually a file -- (probe-directory file) ==> ERROR
PROBE-FILE will return the truename if file exists and is a
a directory PROBE-FILE will signal an error which we
ignore.
PROBE-DIRECTORY returns T if the file exists and is a
but is a file, PROBE-DIRECTORY will signal an error. | (defpackage :com.gigamonkeys.asdf-extensions
(:use :cl :asdf)
(:export :register-source-directory))
(in-package :com.gigamonkeys.asdf-extensions)
(defvar *top-level-directories* ())
(defun sysdef-crawl-directories (system)
(let ((name (asdf::coerce-name system)))
(block found
(flet ((found-p (file)
(when (and
(equal (pathname-name file) name)
(equal (pathname-type file) "asd"))
(return-from found file))))
(dolist (dir *top-level-directories*)
(walk-directory dir #'found-p))))))
(defun register-source-directory (dir)
(push (pathname-as-directory dir) *top-level-directories*))
(setf *system-definition-search-functions* '(sysdef-crawl-directories))
(defparameter *fasl-directory*
(merge-pathnames
(make-pathname
:directory `(:relative ".lispbox" "fasl" ,(swank-loader::unique-dir-name)))
(user-homedir-pathname)))
(defmethod output-files :around ((operation compile-op) (c source-file))
(let ((defaults (merge-pathnames
(make-relative (component-pathname c))
*fasl-directory*)))
(flet ((relocate-fasl (file)
(make-pathname
:type (pathname-type file) :defaults defaults)))
(mapcar #'relocate-fasl (call-next-method)))))
(defmethod output-files :around ((operation compile-op) (c static-file))
(list
(merge-pathnames (make-relative (component-pathname c)) *fasl-directory*)))
(defmethod perform :after ((operation compile-op) (c static-file))
(let ((source-file (component-pathname c))
(output-file (car (output-files operation c))))
(ensure-directories-exist output-file)
(with-open-file (in source-file :element-type '(unsigned-byte 8))
(with-open-file (out output-file :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede)
(loop for octet = (read-byte in nil nil)
while octet do (write-byte octet out))))))
(defun make-relative (pathname)
(make-pathname
:directory (cons :relative (rest (pathname-directory pathname)))
:defaults pathname))
Portable pathnames lib . Unfortunately we ca n't use ASDF to load it
(defun list-directory (dirname)
"Return a list of the contents of the directory named by dirname.
Names of subdirectories will be returned in `directory normal
form'. Unlike CL:DIRECTORY, LIST-DIRECTORY does not accept
names a directory. It can be in either file or directory form."
(when (wild-pathname-p dirname)
(error "Can only list concrete directory names."))
(let ((wildcard (directory-wildcard dirname)))
#+(or sbcl cmu lispworks)
SBCL , CMUCL , and Lispworks return subdirectories in directory
(directory wildcard)
#+openmcl
(directory wildcard :directories t)
#+allegro
Allegro normally return directories in file form but we can
(directory wildcard :directories-are-files nil)
#+clisp
CLISP has a particularly idiosyncratic view of things . But we
(nconc
CLISP wo n't list files without an extension when : type is
(directory wildcard)
And CLISP does n't consider subdirectories to match unless
(directory (clisp-subdirectories-wildcard wildcard)))
#-(or sbcl cmu lispworks openmcl allegro clisp)
(error "list-directory not implemented")))
(defun file-exists-p (pathname)
"Similar to CL:PROBE-FILE except it always returns directory names
in `directory normal form'. Returns truename which will be in
`directory form' if file named is, in fact, a directory."
#+(or sbcl lispworks openmcl)
These implementations do " The Right Thing " as far as we are
(probe-file pathname)
#+(or allegro cmu)
file must be given in file form . So we try first with a directory
(or (probe-file (pathname-as-directory pathname))
(probe-file pathname))
#+clisp
Once again CLISP takes a particularly unforgiving approach ,
signalling ERRORs at the slightest provocation .
(or (ignore-errors
file or NIL if it does n't exist at all . If it exists but is
(probe-file (pathname-as-file pathname)))
(ignore-errors
directory or NIL if it does n't exist at all . If it exists
(let ((directory-form (pathname-as-directory pathname)))
(when (ext:probe-directory directory-form)
directory-form))))
#-(or sbcl cmu lispworks openmcl allegro clisp)
(error "list-directory not implemented"))
(defun directory-wildcard (dirname)
(make-pathname
:name :wild
:type #-clisp :wild #+clisp nil
:defaults (pathname-as-directory dirname)))
#+clisp
(defun clisp-subdirectories-wildcard (wildcard)
(make-pathname
:directory (append (pathname-directory wildcard) (list :wild))
:name nil
:type nil
:defaults wildcard))
(defun directory-pathname-p (p)
"Is the given pathname the name of a directory? This function can
usefully be used to test whether a name returned by LIST-DIRECTORIES
or passed to the function in WALK-DIRECTORY is the name of a directory
in the file system since they always return names in `directory normal
form'."
(flet ((component-present-p (value)
(and value (not (eql value :unspecific)))))
(and
(not (component-present-p (pathname-name p)))
(not (component-present-p (pathname-type p)))
p)))
(defun file-pathname-p (p)
(unless (directory-pathname-p p) p))
(defun pathname-as-directory (name)
"Return a pathname reperesenting the given pathname in
`directory normal form', i.e. with all the name elements in the
directory component and NIL in the name and type components. Can
not be used on wild pathnames because there's not portable way to
convert wildcards in the name and type into a single directory
component. Returns its argument if name and type are both nil or
:unspecific."
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (not (directory-pathname-p name))
(make-pathname
:directory (append (or (pathname-directory pathname) (list :relative))
(list (file-namestring pathname)))
:name nil
:type nil
:defaults pathname)
pathname)))
(defun pathname-as-file (name)
"Return a pathname reperesenting the given pathname in `file form',
i.e. with the name elements in the name and type component. Can't
convert wild pathnames because of problems mapping wild directory
component into name and type components. Returns its argument if
it is already in file form."
(let ((pathname (pathname name)))
(when (wild-pathname-p pathname)
(error "Can't reliably convert wild pathnames."))
(if (directory-pathname-p name)
(let* ((directory (pathname-directory pathname))
(name-and-type (pathname (first (last directory)))))
(make-pathname
:directory (butlast directory)
:name (pathname-name name-and-type)
:type (pathname-type name-and-type)
:defaults pathname))
pathname)))
(defun walk-directory (dirname fn &key directories (test (constantly t)))
"Walk a directory invoking `fn' on each pathname found. If `test' is
supplied fn is invoked only on pathnames for which `test' returns
true. If `directories' is t invokes `test' and `fn' on directory
pathnames as well."
(labels
((walk (name)
(cond
((directory-pathname-p name)
(when (and directories (funcall test name))
(funcall fn name))
(dolist (x (list-directory name)) (walk x)))
((funcall test name) (funcall fn name)))))
(walk (pathname-as-directory dirname))))
(defun directory-p (name)
"Is `name' the name of an existing directory."
(let ((truename (file-exists-p name)))
(and truename (directory-pathname-p name))))
(defun file-p (name)
"Is `name' the name of an existing file, i.e. not a directory."
(let ((truename (file-exists-p name)))
(and truename (file-pathname-p name))))
(pushnew :com.gigamonkeys.asdf-extensions *features*)
|
b4be1623722433b8720811dca7e58ee935ecee3f985409f31957e56b584ccbf8 | GaloisInc/cryptol | Env.hs | -- |
Module : . Eval . Env
Copyright : ( c ) 2013 - 2016 Galois , Inc.
-- License : BSD3
-- Maintainer :
-- Stability : provisional
-- Portability : portable
# LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
module Cryptol.Eval.Env where
import Cryptol.Backend
import Cryptol.Eval.Prims
import Cryptol.Eval.Type
import Cryptol.Eval.Value
import Cryptol.ModuleSystem.Name
import Cryptol.TypeCheck.AST
import Cryptol.TypeCheck.Solver.InfNat
import Cryptol.Utils.PP
import qualified Data.IntMap.Strict as IntMap
import Data.Semigroup
import GHC.Generics (Generic)
import Prelude ()
import Prelude.Compat
-- Evaluation Environment ------------------------------------------------------
data GenEvalEnv sym = EvalEnv
{ envVars :: !(IntMap.IntMap (Either (Prim sym) (SEval sym (GenValue sym))))
, envTypes :: !TypeEnv
} deriving Generic
instance Semigroup (GenEvalEnv sym) where
l <> r = EvalEnv
{ envVars = IntMap.union (envVars l) (envVars r)
, envTypes = envTypes l <> envTypes r
}
instance Monoid (GenEvalEnv sym) where
mempty = EvalEnv
{ envVars = IntMap.empty
, envTypes = mempty
}
mappend = (<>)
ppEnv :: Backend sym => sym -> PPOpts -> GenEvalEnv sym -> SEval sym Doc
ppEnv sym opts env = brackets . fsep <$> mapM bind (IntMap.toList (envVars env))
where
bind (k,Left _) =
do return (int k <+> text "<<prim>>")
bind (k,Right v) =
do vdoc <- ppValue sym opts =<< v
return (int k <+> text "->" <+> vdoc)
-- | Evaluation environment with no bindings
emptyEnv :: GenEvalEnv sym
emptyEnv = mempty
-- | Bind a variable in the evaluation environment.
bindVar ::
Backend sym =>
sym ->
Name ->
SEval sym (GenValue sym) ->
GenEvalEnv sym ->
SEval sym (GenEvalEnv sym)
bindVar sym n val env = do
let nm = show $ ppLocName n
val' <- sDelayFill sym val Nothing nm
return $ env{ envVars = IntMap.insert (nameUnique n) (Right val') (envVars env) }
-- | Bind a variable to a value in the evaluation environment, without
-- creating a thunk.
bindVarDirect ::
Backend sym =>
Name ->
Prim sym ->
GenEvalEnv sym ->
GenEvalEnv sym
bindVarDirect n val env = do
env{ envVars = IntMap.insert (nameUnique n) (Left val) (envVars env) }
-- | Lookup a variable in the environment.
# INLINE lookupVar #
lookupVar :: Name -> GenEvalEnv sym -> Maybe (Either (Prim sym) (SEval sym (GenValue sym)))
lookupVar n env = IntMap.lookup (nameUnique n) (envVars env)
-- | Bind a type variable of kind *.
# INLINE bindType #
bindType :: TVar -> Either Nat' TValue -> GenEvalEnv sym -> GenEvalEnv sym
bindType p ty env = env{ envTypes = bindTypeVar p ty (envTypes env) }
-- | Lookup a type variable.
# INLINE lookupType #
lookupType :: TVar -> GenEvalEnv sym -> Maybe (Either Nat' TValue)
lookupType p env = lookupTypeVar p (envTypes env)
| null | https://raw.githubusercontent.com/GaloisInc/cryptol/8cca24568ad499f06032c2e4eaa7dfd4c542efb6/src/Cryptol/Eval/Env.hs | haskell | |
License : BSD3
Maintainer :
Stability : provisional
Portability : portable
# LANGUAGE DeriveAnyClass #
Evaluation Environment ------------------------------------------------------
| Evaluation environment with no bindings
| Bind a variable in the evaluation environment.
| Bind a variable to a value in the evaluation environment, without
creating a thunk.
| Lookup a variable in the environment.
| Bind a type variable of kind *.
| Lookup a type variable. | Module : . Eval . Env
Copyright : ( c ) 2013 - 2016 Galois , Inc.
# LANGUAGE CPP #
# LANGUAGE FlexibleInstances #
# LANGUAGE DeriveGeneric #
module Cryptol.Eval.Env where
import Cryptol.Backend
import Cryptol.Eval.Prims
import Cryptol.Eval.Type
import Cryptol.Eval.Value
import Cryptol.ModuleSystem.Name
import Cryptol.TypeCheck.AST
import Cryptol.TypeCheck.Solver.InfNat
import Cryptol.Utils.PP
import qualified Data.IntMap.Strict as IntMap
import Data.Semigroup
import GHC.Generics (Generic)
import Prelude ()
import Prelude.Compat
data GenEvalEnv sym = EvalEnv
{ envVars :: !(IntMap.IntMap (Either (Prim sym) (SEval sym (GenValue sym))))
, envTypes :: !TypeEnv
} deriving Generic
instance Semigroup (GenEvalEnv sym) where
l <> r = EvalEnv
{ envVars = IntMap.union (envVars l) (envVars r)
, envTypes = envTypes l <> envTypes r
}
instance Monoid (GenEvalEnv sym) where
mempty = EvalEnv
{ envVars = IntMap.empty
, envTypes = mempty
}
mappend = (<>)
ppEnv :: Backend sym => sym -> PPOpts -> GenEvalEnv sym -> SEval sym Doc
ppEnv sym opts env = brackets . fsep <$> mapM bind (IntMap.toList (envVars env))
where
bind (k,Left _) =
do return (int k <+> text "<<prim>>")
bind (k,Right v) =
do vdoc <- ppValue sym opts =<< v
return (int k <+> text "->" <+> vdoc)
emptyEnv :: GenEvalEnv sym
emptyEnv = mempty
bindVar ::
Backend sym =>
sym ->
Name ->
SEval sym (GenValue sym) ->
GenEvalEnv sym ->
SEval sym (GenEvalEnv sym)
bindVar sym n val env = do
let nm = show $ ppLocName n
val' <- sDelayFill sym val Nothing nm
return $ env{ envVars = IntMap.insert (nameUnique n) (Right val') (envVars env) }
bindVarDirect ::
Backend sym =>
Name ->
Prim sym ->
GenEvalEnv sym ->
GenEvalEnv sym
bindVarDirect n val env = do
env{ envVars = IntMap.insert (nameUnique n) (Left val) (envVars env) }
# INLINE lookupVar #
lookupVar :: Name -> GenEvalEnv sym -> Maybe (Either (Prim sym) (SEval sym (GenValue sym)))
lookupVar n env = IntMap.lookup (nameUnique n) (envVars env)
# INLINE bindType #
bindType :: TVar -> Either Nat' TValue -> GenEvalEnv sym -> GenEvalEnv sym
bindType p ty env = env{ envTypes = bindTypeVar p ty (envTypes env) }
# INLINE lookupType #
lookupType :: TVar -> GenEvalEnv sym -> Maybe (Either Nat' TValue)
lookupType p env = lookupTypeVar p (envTypes env)
|
cf15deac3f6b6201f8881132a698b8dbf4a3d39b5241e03fea7070b17c64f632 | synduce/Synduce | count_lt.ml | * @synduce -NB -n 10
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
type 'a tree_memo =
| MLeaf of int * 'a
| MNode of int * 'a * 'a tree_memo * 'a tree_memo
let rec is_memo_count_lt_2 = function
| MLeaf (n, a) -> n >= 0 && if a < 2 then n = 1 else n = 0
| MNode (n, a, l, r) ->
n >= 0
&& (n = memo l + memo r + if a < 2 then 1 else 0)
&& is_memo_count_lt_2 l
&& is_memo_count_lt_2 r
and memo = function
| MLeaf (n, a) -> n
| MNode (n, a, l, r) -> n
;;
let rec repr = function
| MLeaf (n, a) -> Leaf a
| MNode (n, a, tl, tr) -> Node (a, repr tl, repr tr)
;;
let rec spec = function
| Leaf a -> if a < 2 then 1 else 0
| Node (a, l, r) -> if a < 2 then 1 + spec l + spec r else spec l + spec r
[@@ensures fun x -> x >= 0]
;;
let rec target = function
| MLeaf (n, a) -> if a < 2 then [%synt c0] else [%synt c1]
| MNode (n, a, l, r) -> if a < 2 then [%synt f1] n else [%synt f2] n
[@@requires is_memo_count_lt_2]
;;
| null | https://raw.githubusercontent.com/synduce/Synduce/d453b04cfb507395908a270b1906f5ac34298d29/benchmarks/constraints/memo/count_lt.ml | ocaml | * @synduce -NB -n 10
type 'a tree =
| Leaf of 'a
| Node of 'a * 'a tree * 'a tree
type 'a tree_memo =
| MLeaf of int * 'a
| MNode of int * 'a * 'a tree_memo * 'a tree_memo
let rec is_memo_count_lt_2 = function
| MLeaf (n, a) -> n >= 0 && if a < 2 then n = 1 else n = 0
| MNode (n, a, l, r) ->
n >= 0
&& (n = memo l + memo r + if a < 2 then 1 else 0)
&& is_memo_count_lt_2 l
&& is_memo_count_lt_2 r
and memo = function
| MLeaf (n, a) -> n
| MNode (n, a, l, r) -> n
;;
let rec repr = function
| MLeaf (n, a) -> Leaf a
| MNode (n, a, tl, tr) -> Node (a, repr tl, repr tr)
;;
let rec spec = function
| Leaf a -> if a < 2 then 1 else 0
| Node (a, l, r) -> if a < 2 then 1 + spec l + spec r else spec l + spec r
[@@ensures fun x -> x >= 0]
;;
let rec target = function
| MLeaf (n, a) -> if a < 2 then [%synt c0] else [%synt c1]
| MNode (n, a, l, r) -> if a < 2 then [%synt f1] n else [%synt f2] n
[@@requires is_memo_count_lt_2]
;;
|
|
f339f7c8949ac78af726ec497a3ee0d06f70d7462f7bd43730f2c5f9f844b231 | tmattio/dream-encoding | accept.mli | From -httpadapter/blob/master/src/http.mli
Copyright ( c ) 2019 < >
Permission to use , copy , modify , and distribute this software for any purpose
with or without fee is hereby granted , provided that the above copyright
notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT ,
INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR
OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE .
Copyright (c) 2019 Carine Morel <>
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. *)
type p = string * string
type encoding =
| Encoding of string
| Gzip
| Compress
| Deflate
| Identity
| Any
(** Accept-Encoding HTTP header parsing and generation *)
type q = int
* Qualities are integers between 0 and 1000 . A header with [ " q=0.7 " ]
corresponds to a quality of [ 700 ] .
corresponds to a quality of [700]. *)
type 'a qlist = (q * 'a) list
(** Lists, annotated with qualities. *)
val qsort : 'a qlist -> 'a qlist
* Sort by quality , biggest first . Respect the initial ordering .
val encodings : string option -> encoding qlist
val string_of_encoding : ?q:q -> encoding -> string
val string_of_encodings : encoding qlist -> string
| null | https://raw.githubusercontent.com/tmattio/dream-encoding/0085ff4115f66723bd35d275f98c14075ffa7327/lib/accept.mli | ocaml | * Accept-Encoding HTTP header parsing and generation
* Lists, annotated with qualities. | From -httpadapter/blob/master/src/http.mli
Copyright ( c ) 2019 < >
Permission to use , copy , modify , and distribute this software for any purpose
with or without fee is hereby granted , provided that the above copyright
notice and this permission notice appear in all copies .
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT ,
INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE , DATA OR PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR
OTHER TORTIOUS ACTION , ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE .
Copyright (c) 2019 Carine Morel <>
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE. *)
type p = string * string
type encoding =
| Encoding of string
| Gzip
| Compress
| Deflate
| Identity
| Any
type q = int
* Qualities are integers between 0 and 1000 . A header with [ " q=0.7 " ]
corresponds to a quality of [ 700 ] .
corresponds to a quality of [700]. *)
type 'a qlist = (q * 'a) list
val qsort : 'a qlist -> 'a qlist
* Sort by quality , biggest first . Respect the initial ordering .
val encodings : string option -> encoding qlist
val string_of_encoding : ?q:q -> encoding -> string
val string_of_encodings : encoding qlist -> string
|
1653028e89dfe36179bbf3fe18df6b5184f67975f543759693dfdf726b192e73 | pedestal/samples | behavior.clj | Copyright 2013 Relevance , Inc.
; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( )
; which can be found in the file epl-v10.html at the root of this distribution.
;
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
;
; You must not remove this notice, or any other, from this software.
(ns ^:shared chat-client.behavior
(:require [clojure.string :as string]
[io.pedestal.app :as app]
[io.pedestal.app.dataflow :as d]
[io.pedestal.app.util.platform :as platform]
[io.pedestal.app.util.log :as log]
[io.pedestal.app.messages :as msg]
[clojure.set :as set]
[chat-client.util :as util]))
;; Transforms
(defn nickname-transform
[_ message]
(:nickname message))
(defn send-message
[old-value message]
(let [msg {:id (util/random-id)
:time (platform/date)
:nickname (:nickname message)
:text (:text message)
:status :pending}]
(-> old-value
(update-in [:sent] conj msg)
(assoc :sending msg))))
(defn clear-outbound-messages
[old-value _]
(-> old-value
(assoc :sent [])
(dissoc :sending)))
(defn clear-inbound-messages
[old-value _]
(assoc old-value :received []))
(defn receive-inbound
[old-value message]
(let [msg {:id (:id message) :time (platform/date)
:nickname (:nickname message) :text (:text message)}]
(update-in old-value [:received] conj msg)))
;; Derives
(defn diff-by [f new old]
(let [o (set (map f old))
n (set (map f new))
new-keys (set/difference n o)]
(filter (comp new-keys f) new)))
(defn new-msgs [{:keys [old new]} k]
(let [o (set (k old))
n (set (k new))]
(diff-by :id n o)))
(defn new-messages [_ inputs]
(let [in (new-msgs (d/old-and-new inputs [:inbound]) :received)]
(sort-by :time in)))
(defn- index-by [coll key]
(reduce
(fn [a x]
(assoc a (key x) x))
{}
coll))
(defn- updated-message? [reference-messages msg]
(when-let [reference-msg (reference-messages (:id msg))]
(not= (:time reference-msg) (:time msg))))
(defn updated-messages [state inputs]
(let [new-msgs (:new-messages inputs)
out-msgs-index (index-by (get-in inputs [:outbound :sent]) :id)
updated-msgs (filter (partial updated-message? out-msgs-index) new-msgs)]
(map #(assoc % :status :confirmed) updated-msgs)))
(defn deleted-msgs [{:keys [old new]} k]
(let [o (set (k old))
n (set (k new))]
(diff-by :id o n)))
(defn deleted-messages [_ inputs]
(let [in (deleted-msgs (d/old-and-new inputs [:inbound]) :received)
out (deleted-msgs (d/old-and-new inputs [:outbound]) :sent)]
(concat in out)))
;; Effects
(defn send-message-to-server [outbound]
[{msg/topic [:server] :out-message (:sending outbound)}])
;; Emitters
(defn init-app-model [_]
[{:chat
{:log {}
:form
{:clear-messages
{:transforms
{:clear-messages [{msg/topic [:outbound]} {msg/topic [:inbound]}]}}
:set-nickname
{:transforms
{:set-nickname [{msg/topic [:nickname] (msg/param :nickname) {}}]}}}}}])
(defn- new-deltas [value]
(vec (mapcat (fn [{:keys [id] :as msg}]
[[:node-create [:chat :log id] :map]
[:value [:chat :log id] msg]])
value)))
(defn- update-deltas [value]
(mapv (fn [{:keys [id] :as msg}]
[:value [:chat :log id] msg]) value))
(defn set-nickname-deltas
[nickname]
[[:node-create [:chat :nickname] :map]
[:value [:chat :nickname] nickname]
[:transform-enable [:chat :form :clear-nickname] :clear-nickname [{msg/topic [:nickname]}]]
[:transform-enable [:chat :form :send-message] :send-message [{msg/topic [:outbound]
(msg/param :text) {}
:nickname nickname}]]
[:transform-disable [:chat :form :set-nickname] :set-nickname]])
(def clear-nickname-deltas
[[:node-destroy [:chat :nickname]]
[:transform-disable [:chat :form :clear-nickname] :clear-nickname]
[:transform-disable [:chat :form :send-message] :send-message]
[:transform-enable [:chat :form :set-nickname] :set-nickname [{msg/topic [:nickname]
(msg/param :nickname) {}}]]])
(defn- nickname-deltas [nickname]
(if nickname (set-nickname-deltas nickname) clear-nickname-deltas))
(defn- delete-deltas [value]
(vec (mapcat (fn [{:keys [id] :as msg}]
[[:node-destroy [:chat :log id]]])
value)))
(def sort-order
{[:new-messages] 0
[:deleted-messages] 1
[:updated-messages] 2})
(defn chat-emit
[inputs]
(reduce (fn [a [input-path new-value]]
(concat a (case input-path
[:new-messages] (new-deltas new-value)
[:deleted-messages] (delete-deltas new-value)
[:updated-messages] (update-deltas new-value)
[:nickname] (nickname-deltas new-value)
[])))
[]
(sort-by #(get sort-order (key %))
;; Alternatively this could be done by pulling
;; :added and :updated sets from inputs.
(merge (d/added-inputs inputs) (d/updated-inputs inputs)))))
;; Data Model Paths:
;; [:nickname] - Nickname for chat user
;; [:inbound :received] - Received inbound messages
;; [:outbound :sent] - Sent outbound messages
;; [:outbound :sending] - Pending message that effect looks to send
;; [:new-messages] - Messages that are new, determined by id
;; [:deleted-messages] - Messages that have been deleted, determined by id
;; [:updated-messages] - Messages that have been updated - not used by UI
App Model Paths :
;; [:chat :log :*] - Chat messages by id
;; [:chat :form :*] - Rendering transforms that chat user interacts with
;; [:chat :nickname] - Displays chat user
(def example-app
{:version 2
:transform [[:set-nickname [:nickname] nickname-transform]
[:clear-nickname [:nickname] (constantly nil)]
[:received [:inbound] receive-inbound]
[:clear-messages [:inbound] clear-inbound-messages]
[:send-message [:outbound] send-message]
[:clear-messages [:outbound] clear-outbound-messages]]
:derive #{[#{[:inbound] [:outbound]} [:new-messages] new-messages]
[{[:new-messages] :new-messages [:outbound] :outbound} [:updated-messages] updated-messages :map]
[#{[:outbound] [:inbound]} [:deleted-messages] deleted-messages]}
:effect #{[#{[:outbound]} send-message-to-server :single-val]}
:emit [{:init init-app-model}
[#{[:nickname] [:new-messages] [:updated-messages] [:deleted-messages]} chat-emit]]})
| null | https://raw.githubusercontent.com/pedestal/samples/caaf04afe255586f8f4e1235deeb0c1904179355/chat/chat-client/app/src/chat_client/behavior.clj | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
Transforms
Derives
Effects
Emitters
Alternatively this could be done by pulling
:added and :updated sets from inputs.
Data Model Paths:
[:nickname] - Nickname for chat user
[:inbound :received] - Received inbound messages
[:outbound :sent] - Sent outbound messages
[:outbound :sending] - Pending message that effect looks to send
[:new-messages] - Messages that are new, determined by id
[:deleted-messages] - Messages that have been deleted, determined by id
[:updated-messages] - Messages that have been updated - not used by UI
[:chat :log :*] - Chat messages by id
[:chat :form :*] - Rendering transforms that chat user interacts with
[:chat :nickname] - Displays chat user | Copyright 2013 Relevance , Inc.
Eclipse Public License 1.0 ( )
(ns ^:shared chat-client.behavior
(:require [clojure.string :as string]
[io.pedestal.app :as app]
[io.pedestal.app.dataflow :as d]
[io.pedestal.app.util.platform :as platform]
[io.pedestal.app.util.log :as log]
[io.pedestal.app.messages :as msg]
[clojure.set :as set]
[chat-client.util :as util]))
(defn nickname-transform
[_ message]
(:nickname message))
(defn send-message
[old-value message]
(let [msg {:id (util/random-id)
:time (platform/date)
:nickname (:nickname message)
:text (:text message)
:status :pending}]
(-> old-value
(update-in [:sent] conj msg)
(assoc :sending msg))))
(defn clear-outbound-messages
[old-value _]
(-> old-value
(assoc :sent [])
(dissoc :sending)))
(defn clear-inbound-messages
[old-value _]
(assoc old-value :received []))
(defn receive-inbound
[old-value message]
(let [msg {:id (:id message) :time (platform/date)
:nickname (:nickname message) :text (:text message)}]
(update-in old-value [:received] conj msg)))
(defn diff-by [f new old]
(let [o (set (map f old))
n (set (map f new))
new-keys (set/difference n o)]
(filter (comp new-keys f) new)))
(defn new-msgs [{:keys [old new]} k]
(let [o (set (k old))
n (set (k new))]
(diff-by :id n o)))
(defn new-messages [_ inputs]
(let [in (new-msgs (d/old-and-new inputs [:inbound]) :received)]
(sort-by :time in)))
(defn- index-by [coll key]
(reduce
(fn [a x]
(assoc a (key x) x))
{}
coll))
(defn- updated-message? [reference-messages msg]
(when-let [reference-msg (reference-messages (:id msg))]
(not= (:time reference-msg) (:time msg))))
(defn updated-messages [state inputs]
(let [new-msgs (:new-messages inputs)
out-msgs-index (index-by (get-in inputs [:outbound :sent]) :id)
updated-msgs (filter (partial updated-message? out-msgs-index) new-msgs)]
(map #(assoc % :status :confirmed) updated-msgs)))
(defn deleted-msgs [{:keys [old new]} k]
(let [o (set (k old))
n (set (k new))]
(diff-by :id o n)))
(defn deleted-messages [_ inputs]
(let [in (deleted-msgs (d/old-and-new inputs [:inbound]) :received)
out (deleted-msgs (d/old-and-new inputs [:outbound]) :sent)]
(concat in out)))
(defn send-message-to-server [outbound]
[{msg/topic [:server] :out-message (:sending outbound)}])
(defn init-app-model [_]
[{:chat
{:log {}
:form
{:clear-messages
{:transforms
{:clear-messages [{msg/topic [:outbound]} {msg/topic [:inbound]}]}}
:set-nickname
{:transforms
{:set-nickname [{msg/topic [:nickname] (msg/param :nickname) {}}]}}}}}])
(defn- new-deltas [value]
(vec (mapcat (fn [{:keys [id] :as msg}]
[[:node-create [:chat :log id] :map]
[:value [:chat :log id] msg]])
value)))
(defn- update-deltas [value]
(mapv (fn [{:keys [id] :as msg}]
[:value [:chat :log id] msg]) value))
(defn set-nickname-deltas
[nickname]
[[:node-create [:chat :nickname] :map]
[:value [:chat :nickname] nickname]
[:transform-enable [:chat :form :clear-nickname] :clear-nickname [{msg/topic [:nickname]}]]
[:transform-enable [:chat :form :send-message] :send-message [{msg/topic [:outbound]
(msg/param :text) {}
:nickname nickname}]]
[:transform-disable [:chat :form :set-nickname] :set-nickname]])
(def clear-nickname-deltas
[[:node-destroy [:chat :nickname]]
[:transform-disable [:chat :form :clear-nickname] :clear-nickname]
[:transform-disable [:chat :form :send-message] :send-message]
[:transform-enable [:chat :form :set-nickname] :set-nickname [{msg/topic [:nickname]
(msg/param :nickname) {}}]]])
(defn- nickname-deltas [nickname]
(if nickname (set-nickname-deltas nickname) clear-nickname-deltas))
(defn- delete-deltas [value]
(vec (mapcat (fn [{:keys [id] :as msg}]
[[:node-destroy [:chat :log id]]])
value)))
(def sort-order
{[:new-messages] 0
[:deleted-messages] 1
[:updated-messages] 2})
(defn chat-emit
[inputs]
(reduce (fn [a [input-path new-value]]
(concat a (case input-path
[:new-messages] (new-deltas new-value)
[:deleted-messages] (delete-deltas new-value)
[:updated-messages] (update-deltas new-value)
[:nickname] (nickname-deltas new-value)
[])))
[]
(sort-by #(get sort-order (key %))
(merge (d/added-inputs inputs) (d/updated-inputs inputs)))))
App Model Paths :
(def example-app
{:version 2
:transform [[:set-nickname [:nickname] nickname-transform]
[:clear-nickname [:nickname] (constantly nil)]
[:received [:inbound] receive-inbound]
[:clear-messages [:inbound] clear-inbound-messages]
[:send-message [:outbound] send-message]
[:clear-messages [:outbound] clear-outbound-messages]]
:derive #{[#{[:inbound] [:outbound]} [:new-messages] new-messages]
[{[:new-messages] :new-messages [:outbound] :outbound} [:updated-messages] updated-messages :map]
[#{[:outbound] [:inbound]} [:deleted-messages] deleted-messages]}
:effect #{[#{[:outbound]} send-message-to-server :single-val]}
:emit [{:init init-app-model}
[#{[:nickname] [:new-messages] [:updated-messages] [:deleted-messages]} chat-emit]]})
|
b76376bfc692b1643bb15f05ac0673bb49f908818f6e738db4fa01a7512a5d81 | bldl/magnolisp | type-infer.rkt | #lang racket/base
#|
|#
(require racket/contract/base
racket/dict
racket/function
racket/list
racket/match
racket/set
"ir-ast.rkt"
"ir-transform.rkt"
"strategy-stratego.rkt"
"strategy.rkt"
"util.rkt")
;;;
;;; utilities
;;;
(define (lookup-def-from-defs defs x)
(assert (Var? x))
(define def (ast-identifier-lookup defs (Var-id x)))
(unless def
(raise-language-error/ast
"reference to unbound name" x))
def)
(define (lookup-type-from-defs defs x)
(def-get-type (lookup-def-from-defs defs x)))
(define (type=? x y)
(cond
((VarT? x) #t)
((VarT? y) #t)
((and (NameT? x) (NameT? y))
(Id-bind=? (NameT-id x) (NameT-id y)))
((and (FunT? x) (FunT? y))
(define x-rt (FunT-rt x))
(define y-rt (FunT-rt y))
(define x-ats (FunT-ats x))
(define y-ats (FunT-ats y))
(and (= (length x-ats) (length y-ats))
(type=? x-rt y-rt)
(andmap type=? x-ats y-ats)))
((and (ParamT? x) (ParamT? y))
(define x-t (ParamT-t x))
(define y-t (ParamT-t y))
(define x-ats (ParamT-ats x))
(define y-ats (ParamT-ats y))
(and (type=? x-t y-t)
(= (length x-ats) (length y-ats))
(andmap type=? x-ats y-ats)))
(else #f)))
;; Augments type expression `t` with the type facts available in `h`.
;; Intended for more informative reporting of type errors.
(define (type-concretely h t)
(let loop ([ast t])
(match ast
[(VarT _ sym)
(if-let n-ast (hash-ref h sym #f)
(loop n-ast)
ast)]
[(FunT a rt ats)
(FunT a (loop rt) (map loop ats))]
[(ParamT a t ps)
(ParamT a (loop t) (map loop ps))]
[(PhiT a t u)
(PhiT a (loop t) (loop u))]
[_ ast])))
;;;
;;; generics specialization
;;;
The ` param - syms ` field is the list of VarT syms corresponding to
;; the particular instantiation of the relevant universal type
;; parameters.
(struct ApplyInfo (param-syms) #:transparent)
(define-with-contract
(-> hash? Var? (values (or/c #f ApplyInfo?) Type?))
(lookup-use-type-from-defs defs x)
(define def (lookup-def-from-defs defs x))
(match def
[(Defun (? (lambda (a) (hash-has-key? a 'univ-type-params)) as) _ _ _ _)
(define g-t (hash-ref as 'generic-type))
(define-values (bind->sym n-def)
(type-expr-rm-ForAllT/use g-t))
(define info
(and (hash-ref as 'return-type-overloaded? #f)
(let* ((ns (hash-ref as 'univ-type-params))
(syms (for/list ((n ns))
(define id (NameT-id n))
(define bind (Id-bind id))
(hash-ref bind->sym bind))))
(ApplyInfo syms))))
(values info n-def)]
[_
(values #f (def-get-type def))]))
(define (defs-add-type<> var-h apply-h defs)
(define rw-type<>
(topdown
(lambda (ast)
(match ast
[(ApplyExpr (and (app (lambda (a)
(define uid (hash-ref a 'uid))
(hash-ref apply-h uid #f))
(? identity info))
annos) f args)
(define syms (ApplyInfo-param-syms info))
(define params
(for/list ((sym syms))
(define var (annoless VarT sym))
(type-rm-VarT var-h var var)))
(define n-annos
(hash-set annos 'type<> params))
(ApplyExpr n-annos f args)]
[_ ast]))))
(defs-map/bind rw-type<> defs))
;;;
;;; init with fresh type variables
;;;
(define (fresh-VarT)
(annoless VarT (gensym "t")))
(define type-AnyT->VarT
(topdown
(lambda (t)
(cond
[(AnyT? t) (fresh-VarT)]
[else t]))))
(define (type-add-VarT t)
(cond
((not t) (fresh-VarT))
((AnyT? t) (fresh-VarT))
(else (type-AnyT->VarT t))))
For each expression in ' def ' , if it has no type expression , add one
;; referring to a fresh type variable. For any existing type
;; expressions in 'def', replace AnyT type expressions with fresh
;; type variables.
(define (ast-expr-add-VarT defs-t def)
(define rw
(topdown
(lambda (ast)
(match ast
[(? Expr?)
(define t (type-add-VarT (Expr-type ast)))
(set-Expr-type ast t)]
[_ ast]))))
(rw def))
(define (def-add-VarT def)
(define rw
(topdown
(lambda (ast)
(match ast
handles associated nodes also
(define n-t
(cond
((AnyT? t)
(annoless FunT
(map (lambda (x) (fresh-VarT)) ps)
(fresh-VarT)))
((FunT? t)
(unless (= (length ps) (length (FunT-ats t)))
(raise-language-error/ast
"arity mismatch between function and its type"
ast t))
(type-add-VarT t))
(else
(raise-language-error/ast
"illegal type for a function"
ast t))))
(define n-ps
(map
(lambda (p t)
(match p
[(Param a n o-t)
(assert (AnyT? o-t))
(Param a n t)]))
ps (FunT-ats n-t)))
(Defun a id n-t n-ps b))
((DefVar a id t v)
(DefVar a id (type-add-VarT t) v))
(_ ast)))))
(rw def))
(define (defs-add-VarT defs)
First add types for bindings .
(set! defs (defs-map/bind def-add-VarT defs))
Sync local definitions info into ' defs ' table .
(set! defs (defs-table-update-locals/Id defs))
;; Now add types to expressions.
(set! defs (defs-map/bind (fix ast-expr-add-VarT defs) defs))
defs)
;;;
;;; constraint solver
;;;
;; Simplifies type `t` using any applicable substitutions in `h`,
;; which maps (unique) `VarT` symbols to type expressions.
;; Substitutions are applied recursively. As a side effect, may update
;; `h` for purposes of memoization, to replace more complex type
;; expressions with simpler ones. Returns the simplified version of
;; type `t`. The `eq?` operation may be used to determine if any
;; simplification took place. `VarT` nodes will still remain in `t` if
;; not all the appearing type variables had assignments in `h`.
(define-with-contract
(-> hash? Type? Type?)
(subst! h t)
( ` ( subst ! , h , t ) )
(define (lookup sym)
(hash-ref h sym #f))
(define (memoize! sym ast)
(hash-set! h sym ast))
(let loop ([vars (seteq)] [ast t])
( ` ( loop , vars , ast ) )
(match ast
[(VarT _ sym)
(define h-ast (lookup sym))
(cond
((not h-ast) ast)
(else
(when (set-member? vars sym)
(error 'subst! "recursive type ~a: ~s ≡ ~s"
(ast-~a t) ast h-ast))
(define n-ast (loop (set-add vars sym) h-ast))
(unless (eq? ast n-ast)
(memoize! sym n-ast))
n-ast))]
[(? NameT?)
ast]
[(FunT a ats rt)
(define n-ats (map (fix loop vars) ats))
(define n-rt (loop vars rt))
(if (and (eq? rt n-rt) (andmap eq? ats n-ats))
ast
(FunT a n-ats n-rt))]
[(PhiT a t u)
(define n-t (loop vars t))
(define n-u (loop vars u))
(if (and (eq? t n-t) (eq? u n-u))
ast
(PhiT a n-t n-u))]
[(ParamT a bt ats)
(define n-bt (loop vars bt))
(define n-ats (map (fix loop vars) ats))
(if (and (eq? bt n-bt) (andmap eq? ats n-ats))
ast
(ParamT a n-bt n-ats))]
[else
(error
'subst!
"expected (or/c FunT? NameT? ParamT? PhiT? VarT?): ~s"
ast)])))
(define (unify-with-PhiT? x)
(or (NameT? x)
(and (ParamT? x)
(NameT? (ParamT-t x)))))
types ' x ' and ' y ' , in the context of the given
;; substitutions [h mutable (hash/c symbol? Type?)]. As a side effect,
;; may modify 'h' to add new substitutions. Returns #t if 'x' and 'y'
;; are unifiable, and #f otherwise.
(define (unify! h x y)
;; 'x' and 'y' must have any substitutions applied.
(define (f x y)
(cond
((and (VarT? x) (VarT? y))
(define x-sym (VarT-sym x))
(define y-sym (VarT-sym y))
(unless (eq? x-sym y-sym)
(hash-set! h x-sym y))
#t)
((VarT? x)
(define x-sym (VarT-sym x))
(hash-set! h x-sym y)
#t)
((VarT? y)
(define y-sym (VarT-sym y))
(hash-set! h y-sym x)
#t)
((and (NameT? x) (NameT? y))
(Id-bind=? (NameT-id x) (NameT-id y)))
((and (FunT? x) (FunT? y))
(define x-rt (FunT-rt x))
(define y-rt (FunT-rt y))
(define x-ats (FunT-ats x))
(define y-ats (FunT-ats y))
(and
(= (length x-ats) (length y-ats))
(unify! h x-rt y-rt)
(andmap (fix unify! h) x-ats y-ats)))
((and (ParamT? x) (ParamT? y))
(define x-t (ParamT-t x))
(define y-t (ParamT-t y))
(define x-ats (ParamT-ats x))
(define y-ats (ParamT-ats y))
(and
(= (length x-ats) (length y-ats))
(unify! h x-t y-t)
(andmap (fix unify! h) x-ats y-ats)))
((and (PhiT? x) (unify-with-PhiT? y))
(and (unify! (PhiT-t1 x) y)
(unify! (PhiT-t2 x) y)))
((and (PhiT? y) (unify-with-PhiT? x))
(and (unify! x (PhiT-t1 y))
(unify! x (PhiT-t2 y))))
(else
#f)))
(define s-x (subst! h x))
(define s-y (subst! h y))
(f s-x s-y))
;;;
;;; VarT removal
;;;
;; Ensures that no VarT type expressions remain in type expression
;; 't'. It is an error for any appearing VarT to not have an entry in
;; 'var-h', as that means that the program's (concrete) types cannot
;; be fully determined. Simplifies PhiT type expressions where it is
;; possible to do so. 'ctx-ast' is the expression or definition whose
;; type is being simplified; it is only used for error reporting.
(define (type-rm-VarT var-h t ctx-ast)
(define f
(innermost-rewriter
(lambda (ast)
(match ast
[(? VarT?)
(define n-ast (subst! var-h ast))
(when (VarT? n-ast)
(raise-language-error/ast
"cannot resolve concrete type"
#:continued "program is not fully typed"
ctx-ast t))
n-ast]
[(PhiT _ t u)
#:when (equal? t u)
(assert (not (VarT? t)))
t]
[_
#f]))))
(f t))
;; Uses the 'var-h' table to substitute any VarT nodes in the type
;; fields and annotations of the program tree 'ast' with concrete type
;; expressions. For nodes that end up with the unit type, checks that
;; they are allowed to have such a type.
(define (ast-rm-VarT var-h ast)
(define (rw ast t)
(define n-t (type-rm-VarT var-h t ast))
(when (and (Void-type? n-t)
(or (Var? ast) (Literal? ast)
(DefVar? ast) (Param? ast)))
(raise-language-error/ast
"illegal type for a variable or literal"
ast n-t))
n-t)
(ast-map-type-expr rw ast))
;;;
;;; API
;;;
;; Takes a definition table containing just the program, and
checks / infers its types . ' defs ' itself is used as the type
;; environment. The input may contain AnyT values, long as their
;; meaning can be inferred. Returns a fully typed program, with
;; definitions having resolved type fields (where appropriate), and
;; expressions having resolved 'type' annotations.
(define-with-contract*
(-> hash? hash?)
(defs-type-infer defs)
( pretty - print ( dict->list ) )
(define (lookup x)
(lookup-type-from-defs defs x))
(define (lookup-use x)
(lookup-use-type-from-defs defs x))
ApplyExpr ` uid`s as keys , ApplyInfo objects as values . Only
;; contains entries for return type overloaded calls.
(define apply-h (make-hasheq))
;; A mutable fact database of sorts, with VarT symbols as keys, and
;; (possibly incomplete) type expressions as values.
(define var-h (make-hasheq))
;; Possibly adds constraints between types 'x' and 'y'. Returns #t
;; if the constraints are possibly solvable, and #f otherwise.
(define (type-unifies!? x y) ;; Type? Type? -> boolean?
(unify! var-h x y))
(define (type-unify! x y)
(unify! var-h x y)
y)
(define (expr-unify! e t)
(define e-t (Expr-type e))
(assert e-t)
(unless (type-unifies!? e-t t)
(raise-language-error/ast
"expression's type does not match its context"
#:fields (list (list "type of expression"
(ast-displayable/datum e-t))
(list "type required for context"
(ast-displayable/datum t)))
e))
t)
(define (ti-def ast) ;; Def? -> void?
(match ast
((? ForeignTypeDecl?)
;; Type can always be derived from 'id'.
(void))
((? Param?)
;; We cannot learn any new information here.
(void))
((Defun a id t ps b)
;; Type kind and arity correctness wrt parameters has already
;; been checked earlier. There is only any checking to do now
;; if there is a body.
(unless (NoBody? b)
(define r-t (FunT-rt t))
(define b-t (ti-expr b))
(unless (type-unifies!? r-t b-t)
(raise-language-error/ast
"function return type does not match body expression"
#:fields (list
(list "function" id)
(list "declared return type"
(ast-displayable/datum r-t))
(list "actual return type"
(ast-displayable/datum b-t)))
ast b)))
(void))
((DefVar _ id t v)
(define v-t (ti-expr v))
(unless (type-unifies!? t v-t)
(raise-language-error/ast
"declared variable type does not match value expression"
#:fields (list (list "declared type"
(ast-displayable/datum t))
(list "actual type of value"
(ast-displayable/datum v-t)))
ast v))
(void))
(else
(raise-argument-error
'ti-def "supported Def?" ast))))
(define (ti-stat ast) ;; Stat? -> void?
(match ast
((SeqStat _ ss)
(for-each ti-stat ss))
((LetStat _ b ss)
(ti-def b)
(for-each ti-stat ss))
((IfStat _ c t e)
(define c-t (ti-expr c))
(unless (type-unifies!? the-Bool-type c-t)
(raise-language-error/ast
(format "expected type '~a' for conditional"
(Id-name the-Bool-id))
ast c
#:fields (list (list "actual type"
(ast-displayable/datum c-t)))))
(ti-stat t)
(ti-stat e))
((? NopStat?)
(void))
(else
(raise-argument-error
'ti-stat "supported Stat?" ast))))
( ? ) - > Type ?
(define len (length ast-lst))
(assert (> len 0))
(let-values (((heads tail) (split-at ast-lst (- len 1))))
(for-each ti-expr heads)
(let ((t (ti-expr (car tail))))
t)))
(define (ti-expr ast) ;; Ast? -> Type?
(match ast
((SeqExpr _ es)
(define t (ti-expr-seq es))
(expr-unify! ast t))
((LetExpr _ b es)
(ti-def b)
(define t (ti-expr-seq es))
(expr-unify! ast t))
((? Var?)
(define t (lookup ast))
(when (FunT? t)
(raise-language-error/ast
"reference to a function as a value"
#:fields (list (list "type" (ast-displayable t)))
ast))
(expr-unify! ast t))
((ApplyExpr a f as)
;; We bypass invoking (ti-expr f) here, as we only want to
;; allow FunT typed expressions in this context. We must still
;; be sure to set up a constraint for the expression 'f', lest
;; its type be left unresolved.
(define-values (info f-t) (lookup-use f))
(when info
(hash-set! apply-h (hash-ref a 'uid) info))
( ( list ) )
(expr-unify! f f-t)
;; We have done prior work to ensure that a function
;; declaration always has FunT type. This check should not
;; fail.
(unless (FunT? f-t)
(raise-language-error/ast
"application of a non-function"
#:fields (list (list "type" (ast-displayable f-t)))
ast f))
;; Now we can unify against the argument expressions' types,
;; and also the type of this expression. We could construct a
;; FunT instance from said information and leave the checking
;; to 'unify!', but we get better error messages by doing some
;; extra work here. We make sure to add the same constraints
;; separately here.
(unless (= (length as) (length (FunT-ats f-t)))
(raise-language-error/ast
"function arity does not match number of arguments"
#:fields (list (list "function type"
(ast-displayable f-t)))
ast))
(for ([e as] [p-t (FunT-ats f-t)])
(define e-t (ti-expr e))
(unless (type-unifies!? p-t e-t)
(raise-language-error/ast
"parameter type does not match that of argument"
#:fields (list (list "parameter type"
(ast-displayable p-t))
(list "argument type"
(ast-displayable e-t))
(list "argument type (AST)"
e-t))
ast e)))
The type of the ApplyExpr expression must unify with the
;; return type of the function.
(define t (FunT-rt f-t))
( ( type - concretely var - h t ) )
(expr-unify! ast t))
((Literal _ dat)
May have an explicit type annotation , instead of an
;; auto-assigned type variable. In any case, we cannot learn
;; anything new here, not unless the literal is of the built-in
;; boolean type.
(cond
((boolean? dat)
(expr-unify! ast the-Bool-type))
(else
(define l-t (Expr-type ast))
(assert l-t)
l-t)))
((IfExpr _ c t e)
(define c-t (ti-expr c))
(unless (type-unifies!? the-Bool-type c-t)
(raise-language-error/ast
(format "expected type '~a' for conditional"
(Id-name the-Bool-id))
ast c
#:fields (list (list "actual type"
(ast-displayable/datum
(type-concretely var-h c-t))))))
(define t-t (ti-expr t))
(define e-t (ti-expr e))
(define discarded? (get-result-discarded ast))
(define ast-t (Expr-type ast))
(cond
[(and discarded?
(cond
((VarT? ast-t)
Overall IfExpr type does not matter , and branch
;; expression types need not unify.
#t)
((NameT? ast-t)
A type for the IfExpr has been given explicitly ,
;; and branches must also be of that type.
#f)
(else
(raise-language-error/ast
"unexpected type for conditional"
ast ast-t))))
(define n-t (annoless PhiT t-t e-t))
(type-unify! ast-t n-t)]
[else
(unless (type-unifies!? t-t e-t)
(raise-language-error/ast
"expected same type for both 'if' branches"
ast
#:fields (list
(list "THEN branch type" (ast-displayable/datum t-t))
(list "ELSE branch type" (ast-displayable/datum e-t))
)))
(type-unify! ast-t t-t)]))
((VoidExpr _)
(expr-unify! ast the-Void-type))
((AssignExpr _ lhs rhs)
(define lhs-t (ti-expr lhs))
(define rhs-t (ti-expr rhs))
(unless (type-unifies!? lhs-t rhs-t)
(raise-language-error/ast
"assignment between different types"
ast
#:fields (list (list "lvalue type" (ast-displayable/datum lhs-t))
(list "rvalue type" (ast-displayable/datum rhs-t)))))
(expr-unify! ast the-Void-type))
((? RacketExpr?)
(Expr-type ast))
;; Statements can appear in an expression position. They are
;; always of the unit type.
((? Stat?)
(ti-stat ast)
the-Void-type)
(else
(raise-argument-error
'ti-expr "supported Expr? or Stat?" ast))))
(set! defs (defs-add-VarT defs))
(defs-for-each/bind ti-def defs)
(set! defs (defs-map/bind (fix ast-rm-VarT var-h) defs))
(unless (hash-empty? apply-h)
(set! defs (defs-add-type<> var-h apply-h defs)))
defs)
| null | https://raw.githubusercontent.com/bldl/magnolisp/191d529486e688e5dda2be677ad8fe3b654e0d4f/type-infer.rkt | racket |
utilities
Augments type expression `t` with the type facts available in `h`.
Intended for more informative reporting of type errors.
generics specialization
the particular instantiation of the relevant universal type
parameters.
init with fresh type variables
referring to a fresh type variable. For any existing type
expressions in 'def', replace AnyT type expressions with fresh
type variables.
Now add types to expressions.
constraint solver
Simplifies type `t` using any applicable substitutions in `h`,
which maps (unique) `VarT` symbols to type expressions.
Substitutions are applied recursively. As a side effect, may update
`h` for purposes of memoization, to replace more complex type
expressions with simpler ones. Returns the simplified version of
type `t`. The `eq?` operation may be used to determine if any
simplification took place. `VarT` nodes will still remain in `t` if
not all the appearing type variables had assignments in `h`.
substitutions [h mutable (hash/c symbol? Type?)]. As a side effect,
may modify 'h' to add new substitutions. Returns #t if 'x' and 'y'
are unifiable, and #f otherwise.
'x' and 'y' must have any substitutions applied.
VarT removal
Ensures that no VarT type expressions remain in type expression
't'. It is an error for any appearing VarT to not have an entry in
'var-h', as that means that the program's (concrete) types cannot
be fully determined. Simplifies PhiT type expressions where it is
possible to do so. 'ctx-ast' is the expression or definition whose
type is being simplified; it is only used for error reporting.
Uses the 'var-h' table to substitute any VarT nodes in the type
fields and annotations of the program tree 'ast' with concrete type
expressions. For nodes that end up with the unit type, checks that
they are allowed to have such a type.
API
Takes a definition table containing just the program, and
environment. The input may contain AnyT values, long as their
meaning can be inferred. Returns a fully typed program, with
definitions having resolved type fields (where appropriate), and
expressions having resolved 'type' annotations.
contains entries for return type overloaded calls.
A mutable fact database of sorts, with VarT symbols as keys, and
(possibly incomplete) type expressions as values.
Possibly adds constraints between types 'x' and 'y'. Returns #t
if the constraints are possibly solvable, and #f otherwise.
Type? Type? -> boolean?
Def? -> void?
Type can always be derived from 'id'.
We cannot learn any new information here.
Type kind and arity correctness wrt parameters has already
been checked earlier. There is only any checking to do now
if there is a body.
Stat? -> void?
Ast? -> Type?
We bypass invoking (ti-expr f) here, as we only want to
allow FunT typed expressions in this context. We must still
be sure to set up a constraint for the expression 'f', lest
its type be left unresolved.
We have done prior work to ensure that a function
declaration always has FunT type. This check should not
fail.
Now we can unify against the argument expressions' types,
and also the type of this expression. We could construct a
FunT instance from said information and leave the checking
to 'unify!', but we get better error messages by doing some
extra work here. We make sure to add the same constraints
separately here.
return type of the function.
auto-assigned type variable. In any case, we cannot learn
anything new here, not unless the literal is of the built-in
boolean type.
expression types need not unify.
and branches must also be of that type.
Statements can appear in an expression position. They are
always of the unit type. | #lang racket/base
(require racket/contract/base
racket/dict
racket/function
racket/list
racket/match
racket/set
"ir-ast.rkt"
"ir-transform.rkt"
"strategy-stratego.rkt"
"strategy.rkt"
"util.rkt")
(define (lookup-def-from-defs defs x)
(assert (Var? x))
(define def (ast-identifier-lookup defs (Var-id x)))
(unless def
(raise-language-error/ast
"reference to unbound name" x))
def)
(define (lookup-type-from-defs defs x)
(def-get-type (lookup-def-from-defs defs x)))
(define (type=? x y)
(cond
((VarT? x) #t)
((VarT? y) #t)
((and (NameT? x) (NameT? y))
(Id-bind=? (NameT-id x) (NameT-id y)))
((and (FunT? x) (FunT? y))
(define x-rt (FunT-rt x))
(define y-rt (FunT-rt y))
(define x-ats (FunT-ats x))
(define y-ats (FunT-ats y))
(and (= (length x-ats) (length y-ats))
(type=? x-rt y-rt)
(andmap type=? x-ats y-ats)))
((and (ParamT? x) (ParamT? y))
(define x-t (ParamT-t x))
(define y-t (ParamT-t y))
(define x-ats (ParamT-ats x))
(define y-ats (ParamT-ats y))
(and (type=? x-t y-t)
(= (length x-ats) (length y-ats))
(andmap type=? x-ats y-ats)))
(else #f)))
(define (type-concretely h t)
(let loop ([ast t])
(match ast
[(VarT _ sym)
(if-let n-ast (hash-ref h sym #f)
(loop n-ast)
ast)]
[(FunT a rt ats)
(FunT a (loop rt) (map loop ats))]
[(ParamT a t ps)
(ParamT a (loop t) (map loop ps))]
[(PhiT a t u)
(PhiT a (loop t) (loop u))]
[_ ast])))
The ` param - syms ` field is the list of VarT syms corresponding to
(struct ApplyInfo (param-syms) #:transparent)
(define-with-contract
(-> hash? Var? (values (or/c #f ApplyInfo?) Type?))
(lookup-use-type-from-defs defs x)
(define def (lookup-def-from-defs defs x))
(match def
[(Defun (? (lambda (a) (hash-has-key? a 'univ-type-params)) as) _ _ _ _)
(define g-t (hash-ref as 'generic-type))
(define-values (bind->sym n-def)
(type-expr-rm-ForAllT/use g-t))
(define info
(and (hash-ref as 'return-type-overloaded? #f)
(let* ((ns (hash-ref as 'univ-type-params))
(syms (for/list ((n ns))
(define id (NameT-id n))
(define bind (Id-bind id))
(hash-ref bind->sym bind))))
(ApplyInfo syms))))
(values info n-def)]
[_
(values #f (def-get-type def))]))
(define (defs-add-type<> var-h apply-h defs)
(define rw-type<>
(topdown
(lambda (ast)
(match ast
[(ApplyExpr (and (app (lambda (a)
(define uid (hash-ref a 'uid))
(hash-ref apply-h uid #f))
(? identity info))
annos) f args)
(define syms (ApplyInfo-param-syms info))
(define params
(for/list ((sym syms))
(define var (annoless VarT sym))
(type-rm-VarT var-h var var)))
(define n-annos
(hash-set annos 'type<> params))
(ApplyExpr n-annos f args)]
[_ ast]))))
(defs-map/bind rw-type<> defs))
(define (fresh-VarT)
(annoless VarT (gensym "t")))
(define type-AnyT->VarT
(topdown
(lambda (t)
(cond
[(AnyT? t) (fresh-VarT)]
[else t]))))
(define (type-add-VarT t)
(cond
((not t) (fresh-VarT))
((AnyT? t) (fresh-VarT))
(else (type-AnyT->VarT t))))
For each expression in ' def ' , if it has no type expression , add one
(define (ast-expr-add-VarT defs-t def)
(define rw
(topdown
(lambda (ast)
(match ast
[(? Expr?)
(define t (type-add-VarT (Expr-type ast)))
(set-Expr-type ast t)]
[_ ast]))))
(rw def))
(define (def-add-VarT def)
(define rw
(topdown
(lambda (ast)
(match ast
handles associated nodes also
(define n-t
(cond
((AnyT? t)
(annoless FunT
(map (lambda (x) (fresh-VarT)) ps)
(fresh-VarT)))
((FunT? t)
(unless (= (length ps) (length (FunT-ats t)))
(raise-language-error/ast
"arity mismatch between function and its type"
ast t))
(type-add-VarT t))
(else
(raise-language-error/ast
"illegal type for a function"
ast t))))
(define n-ps
(map
(lambda (p t)
(match p
[(Param a n o-t)
(assert (AnyT? o-t))
(Param a n t)]))
ps (FunT-ats n-t)))
(Defun a id n-t n-ps b))
((DefVar a id t v)
(DefVar a id (type-add-VarT t) v))
(_ ast)))))
(rw def))
(define (defs-add-VarT defs)
First add types for bindings .
(set! defs (defs-map/bind def-add-VarT defs))
Sync local definitions info into ' defs ' table .
(set! defs (defs-table-update-locals/Id defs))
(set! defs (defs-map/bind (fix ast-expr-add-VarT defs) defs))
defs)
(define-with-contract
(-> hash? Type? Type?)
(subst! h t)
( ` ( subst ! , h , t ) )
(define (lookup sym)
(hash-ref h sym #f))
(define (memoize! sym ast)
(hash-set! h sym ast))
(let loop ([vars (seteq)] [ast t])
( ` ( loop , vars , ast ) )
(match ast
[(VarT _ sym)
(define h-ast (lookup sym))
(cond
((not h-ast) ast)
(else
(when (set-member? vars sym)
(error 'subst! "recursive type ~a: ~s ≡ ~s"
(ast-~a t) ast h-ast))
(define n-ast (loop (set-add vars sym) h-ast))
(unless (eq? ast n-ast)
(memoize! sym n-ast))
n-ast))]
[(? NameT?)
ast]
[(FunT a ats rt)
(define n-ats (map (fix loop vars) ats))
(define n-rt (loop vars rt))
(if (and (eq? rt n-rt) (andmap eq? ats n-ats))
ast
(FunT a n-ats n-rt))]
[(PhiT a t u)
(define n-t (loop vars t))
(define n-u (loop vars u))
(if (and (eq? t n-t) (eq? u n-u))
ast
(PhiT a n-t n-u))]
[(ParamT a bt ats)
(define n-bt (loop vars bt))
(define n-ats (map (fix loop vars) ats))
(if (and (eq? bt n-bt) (andmap eq? ats n-ats))
ast
(ParamT a n-bt n-ats))]
[else
(error
'subst!
"expected (or/c FunT? NameT? ParamT? PhiT? VarT?): ~s"
ast)])))
(define (unify-with-PhiT? x)
(or (NameT? x)
(and (ParamT? x)
(NameT? (ParamT-t x)))))
types ' x ' and ' y ' , in the context of the given
(define (unify! h x y)
(define (f x y)
(cond
((and (VarT? x) (VarT? y))
(define x-sym (VarT-sym x))
(define y-sym (VarT-sym y))
(unless (eq? x-sym y-sym)
(hash-set! h x-sym y))
#t)
((VarT? x)
(define x-sym (VarT-sym x))
(hash-set! h x-sym y)
#t)
((VarT? y)
(define y-sym (VarT-sym y))
(hash-set! h y-sym x)
#t)
((and (NameT? x) (NameT? y))
(Id-bind=? (NameT-id x) (NameT-id y)))
((and (FunT? x) (FunT? y))
(define x-rt (FunT-rt x))
(define y-rt (FunT-rt y))
(define x-ats (FunT-ats x))
(define y-ats (FunT-ats y))
(and
(= (length x-ats) (length y-ats))
(unify! h x-rt y-rt)
(andmap (fix unify! h) x-ats y-ats)))
((and (ParamT? x) (ParamT? y))
(define x-t (ParamT-t x))
(define y-t (ParamT-t y))
(define x-ats (ParamT-ats x))
(define y-ats (ParamT-ats y))
(and
(= (length x-ats) (length y-ats))
(unify! h x-t y-t)
(andmap (fix unify! h) x-ats y-ats)))
((and (PhiT? x) (unify-with-PhiT? y))
(and (unify! (PhiT-t1 x) y)
(unify! (PhiT-t2 x) y)))
((and (PhiT? y) (unify-with-PhiT? x))
(and (unify! x (PhiT-t1 y))
(unify! x (PhiT-t2 y))))
(else
#f)))
(define s-x (subst! h x))
(define s-y (subst! h y))
(f s-x s-y))
(define (type-rm-VarT var-h t ctx-ast)
(define f
(innermost-rewriter
(lambda (ast)
(match ast
[(? VarT?)
(define n-ast (subst! var-h ast))
(when (VarT? n-ast)
(raise-language-error/ast
"cannot resolve concrete type"
#:continued "program is not fully typed"
ctx-ast t))
n-ast]
[(PhiT _ t u)
#:when (equal? t u)
(assert (not (VarT? t)))
t]
[_
#f]))))
(f t))
(define (ast-rm-VarT var-h ast)
(define (rw ast t)
(define n-t (type-rm-VarT var-h t ast))
(when (and (Void-type? n-t)
(or (Var? ast) (Literal? ast)
(DefVar? ast) (Param? ast)))
(raise-language-error/ast
"illegal type for a variable or literal"
ast n-t))
n-t)
(ast-map-type-expr rw ast))
checks / infers its types . ' defs ' itself is used as the type
(define-with-contract*
(-> hash? hash?)
(defs-type-infer defs)
( pretty - print ( dict->list ) )
(define (lookup x)
(lookup-type-from-defs defs x))
(define (lookup-use x)
(lookup-use-type-from-defs defs x))
ApplyExpr ` uid`s as keys , ApplyInfo objects as values . Only
(define apply-h (make-hasheq))
(define var-h (make-hasheq))
(unify! var-h x y))
(define (type-unify! x y)
(unify! var-h x y)
y)
(define (expr-unify! e t)
(define e-t (Expr-type e))
(assert e-t)
(unless (type-unifies!? e-t t)
(raise-language-error/ast
"expression's type does not match its context"
#:fields (list (list "type of expression"
(ast-displayable/datum e-t))
(list "type required for context"
(ast-displayable/datum t)))
e))
t)
(match ast
((? ForeignTypeDecl?)
(void))
((? Param?)
(void))
((Defun a id t ps b)
(unless (NoBody? b)
(define r-t (FunT-rt t))
(define b-t (ti-expr b))
(unless (type-unifies!? r-t b-t)
(raise-language-error/ast
"function return type does not match body expression"
#:fields (list
(list "function" id)
(list "declared return type"
(ast-displayable/datum r-t))
(list "actual return type"
(ast-displayable/datum b-t)))
ast b)))
(void))
((DefVar _ id t v)
(define v-t (ti-expr v))
(unless (type-unifies!? t v-t)
(raise-language-error/ast
"declared variable type does not match value expression"
#:fields (list (list "declared type"
(ast-displayable/datum t))
(list "actual type of value"
(ast-displayable/datum v-t)))
ast v))
(void))
(else
(raise-argument-error
'ti-def "supported Def?" ast))))
(match ast
((SeqStat _ ss)
(for-each ti-stat ss))
((LetStat _ b ss)
(ti-def b)
(for-each ti-stat ss))
((IfStat _ c t e)
(define c-t (ti-expr c))
(unless (type-unifies!? the-Bool-type c-t)
(raise-language-error/ast
(format "expected type '~a' for conditional"
(Id-name the-Bool-id))
ast c
#:fields (list (list "actual type"
(ast-displayable/datum c-t)))))
(ti-stat t)
(ti-stat e))
((? NopStat?)
(void))
(else
(raise-argument-error
'ti-stat "supported Stat?" ast))))
( ? ) - > Type ?
(define len (length ast-lst))
(assert (> len 0))
(let-values (((heads tail) (split-at ast-lst (- len 1))))
(for-each ti-expr heads)
(let ((t (ti-expr (car tail))))
t)))
(match ast
((SeqExpr _ es)
(define t (ti-expr-seq es))
(expr-unify! ast t))
((LetExpr _ b es)
(ti-def b)
(define t (ti-expr-seq es))
(expr-unify! ast t))
((? Var?)
(define t (lookup ast))
(when (FunT? t)
(raise-language-error/ast
"reference to a function as a value"
#:fields (list (list "type" (ast-displayable t)))
ast))
(expr-unify! ast t))
((ApplyExpr a f as)
(define-values (info f-t) (lookup-use f))
(when info
(hash-set! apply-h (hash-ref a 'uid) info))
( ( list ) )
(expr-unify! f f-t)
(unless (FunT? f-t)
(raise-language-error/ast
"application of a non-function"
#:fields (list (list "type" (ast-displayable f-t)))
ast f))
(unless (= (length as) (length (FunT-ats f-t)))
(raise-language-error/ast
"function arity does not match number of arguments"
#:fields (list (list "function type"
(ast-displayable f-t)))
ast))
(for ([e as] [p-t (FunT-ats f-t)])
(define e-t (ti-expr e))
(unless (type-unifies!? p-t e-t)
(raise-language-error/ast
"parameter type does not match that of argument"
#:fields (list (list "parameter type"
(ast-displayable p-t))
(list "argument type"
(ast-displayable e-t))
(list "argument type (AST)"
e-t))
ast e)))
The type of the ApplyExpr expression must unify with the
(define t (FunT-rt f-t))
( ( type - concretely var - h t ) )
(expr-unify! ast t))
((Literal _ dat)
May have an explicit type annotation , instead of an
(cond
((boolean? dat)
(expr-unify! ast the-Bool-type))
(else
(define l-t (Expr-type ast))
(assert l-t)
l-t)))
((IfExpr _ c t e)
(define c-t (ti-expr c))
(unless (type-unifies!? the-Bool-type c-t)
(raise-language-error/ast
(format "expected type '~a' for conditional"
(Id-name the-Bool-id))
ast c
#:fields (list (list "actual type"
(ast-displayable/datum
(type-concretely var-h c-t))))))
(define t-t (ti-expr t))
(define e-t (ti-expr e))
(define discarded? (get-result-discarded ast))
(define ast-t (Expr-type ast))
(cond
[(and discarded?
(cond
((VarT? ast-t)
Overall IfExpr type does not matter , and branch
#t)
((NameT? ast-t)
A type for the IfExpr has been given explicitly ,
#f)
(else
(raise-language-error/ast
"unexpected type for conditional"
ast ast-t))))
(define n-t (annoless PhiT t-t e-t))
(type-unify! ast-t n-t)]
[else
(unless (type-unifies!? t-t e-t)
(raise-language-error/ast
"expected same type for both 'if' branches"
ast
#:fields (list
(list "THEN branch type" (ast-displayable/datum t-t))
(list "ELSE branch type" (ast-displayable/datum e-t))
)))
(type-unify! ast-t t-t)]))
((VoidExpr _)
(expr-unify! ast the-Void-type))
((AssignExpr _ lhs rhs)
(define lhs-t (ti-expr lhs))
(define rhs-t (ti-expr rhs))
(unless (type-unifies!? lhs-t rhs-t)
(raise-language-error/ast
"assignment between different types"
ast
#:fields (list (list "lvalue type" (ast-displayable/datum lhs-t))
(list "rvalue type" (ast-displayable/datum rhs-t)))))
(expr-unify! ast the-Void-type))
((? RacketExpr?)
(Expr-type ast))
((? Stat?)
(ti-stat ast)
the-Void-type)
(else
(raise-argument-error
'ti-expr "supported Expr? or Stat?" ast))))
(set! defs (defs-add-VarT defs))
(defs-for-each/bind ti-def defs)
(set! defs (defs-map/bind (fix ast-rm-VarT var-h) defs))
(unless (hash-empty? apply-h)
(set! defs (defs-add-type<> var-h apply-h defs)))
defs)
|
62c3c35ab81110aea8ae9200d4af9abdde1537058899ca8c8a3fbc878fe12c55 | iskandr/parakeet-retired | SSA_Analysis.ml | (* pp: -parser o pa_macro.cmo *)
open Base
open PhiNode
open TypedSSA
type direction = Forward | Backward
(* 'a = environment, *)
(* 'b = information about value nodes *)
(* 'c = information about exp nodes *)
type ('a, 'b) helpers = {
eval_block : 'a -> block -> 'a * bool;
eval_stmt : 'a -> stmt_node -> 'a option;
eval_values : 'a -> value_node list -> 'b list;
iter_exp_children : 'a -> exp_node -> unit;
iter_values : 'a -> value_node list -> unit;
}
module type ANALYSIS = sig
type env
type exp_info
type value_info
val dir : direction
(* should analysis be repeated until environment stops changing? *)
val iterative : bool
val init : fn -> env
val value : env -> value_node -> value_info
val exp : env -> exp_node -> (env, value_info) helpers -> exp_info
val stmt : env -> stmt_node -> (env, value_info) helpers -> env option
val phi_set : env -> ID.t -> value_info -> env option
val phi_merge : env -> ID.t -> value_info -> value_info -> env option
end
module MkEvaluator(A : ANALYSIS) = struct
let rec eval_block initEnv block =
let changed = ref false in
let fold_stmts env stmtNode =
match A.stmt env stmtNode helpers with
| Some env' -> changed := true; env'
| None -> env
in
let env' =
match A.dir with
| Forward -> Block.fold_forward fold_stmts initEnv block
| Backward -> Block.fold_backward fold_stmts initEnv block
in
env', !changed
and eval_loop_header ?(changed=false) envOut envIn = function
| [] -> envOut, changed
| phiNode::rest ->
let valInfo = A.value envIn phiNode.phi_left in
let currEnvOut = A.phi_set envOut phiNode.phi_id valInfo in
let envOut' = Option.default envOut currEnvOut in
let currChanged = changed || Option.is_some currEnvOut in
eval_loop_header ~changed:currChanged envOut' envIn rest
and eval_phi_nodes ?(changed=false) envOut envLeft envRight = function
| [] -> if changed then Some envOut else None
| phiNode::rest ->
let leftInfo = A.value envLeft phiNode.phi_left in
let rightInfo = A.value envRight phiNode.phi_right in
let currEnvOut =
A.phi_merge envOut phiNode.phi_id leftInfo rightInfo
in
let envOut' = Option.default envOut currEnvOut in
let currChanged = changed || Option.is_some currEnvOut in
eval_phi_nodes ~changed:currChanged envOut' envLeft envRight rest
and default_stmt env stmtNode = match stmtNode.stmt with
(* by default don't do anything to the env *)
| Set (ids, rhs) ->
(* evaluate rhs for possible side effects *)
let _ = A.exp env rhs helpers in
None
| If(cond, tBlock, fBlock, merge) ->
ignore (A.value env cond);
let tEnv, tChanged = eval_block env tBlock in
let fEnv, fChanged = eval_block tEnv fBlock in
eval_phi_nodes ~changed:(tChanged || fChanged) fEnv tEnv fEnv merge
| WhileLoop(condBlock, condVal, body, header) ->
if A.iterative then (
let maxIters = 100 in
let iter = ref 0 in
let headerEnv, headerChanged = eval_loop_header env env header in
let condEnv, condChanged = eval_block headerEnv condBlock in
(* evaluate for side effects *)
ignore (A.value condEnv condVal);
let loopEnv = ref condEnv in
let changed = ref true in
while !changed do
iter := !iter + 1;
if !iter > maxIters then
failwith $ "loop analysis failed to terminate"
;
let bodyEnv, bodyChanged = eval_block !loopEnv body in
let phiEnv, phiChanged =
match eval_phi_nodes bodyEnv headerEnv bodyEnv header with
| Some env -> env, true
| None -> bodyEnv, false
in
let condEnv, condChanged = eval_block phiEnv condBlock in
loopEnv := condEnv;
changed := bodyChanged || phiChanged || condChanged
done;
if !iter > 1 then Some !loopEnv else None
)
else (
let headerEnv, headerChanged =
match eval_phi_nodes env env env header with
| None -> env, false
| Some env' -> env', true
in
let condEnv, condChanged = eval_block headerEnv condBlock in
ignore (A.value condEnv condVal);
let bodyEnv, bodyChanged = eval_block condEnv body in
let changed = headerChanged || condChanged || bodyChanged in
if changed then Some bodyEnv else None
)
| SetIdx (lhs, indices, rhs) ->
ignore (A.value env lhs);
iter_values env indices;
ignore (A.exp env rhs);
None
and iter_exp_children env expNode =
match expNode.exp with
| Cast(_, v) -> ignore $ A.value env v
| Call(_, xs)
| PrimApp(_,xs)
| Values xs
| Arr xs -> iter_values env xs
| Tuple xs -> iter_values env xs
| Adverb adverb -> iter_adverb env adverb
and iter_adverb env {Adverb.fixed; init; axes; args} =
iter_values env fixed;
iter_values env args;
iter_values env axes;
match init with
| Some vs -> iter_values env vs
| None -> ()
and iter_values env = function
| [] -> () | v::vs -> let _ = A.value env v in iter_values env vs
and eval_values env = function
| [] -> [] | v::vs -> (A.value env v) :: (eval_values env vs)
and helpers = {
eval_block = eval_block;
eval_stmt = default_stmt;
eval_values = eval_values;
iter_values = iter_values;
iter_exp_children = iter_exp_children;
}
let eval_fn fn =
let env = A.init fn in
let env', _ = eval_block env fn.body in
env'
end
| null | https://raw.githubusercontent.com/iskandr/parakeet-retired/3d7e6e5b699f83ce8a1c01290beed0b78c0d0945/SSA/SSA_Analysis.ml | ocaml | pp: -parser o pa_macro.cmo
'a = environment,
'b = information about value nodes
'c = information about exp nodes
should analysis be repeated until environment stops changing?
by default don't do anything to the env
evaluate rhs for possible side effects
evaluate for side effects |
open Base
open PhiNode
open TypedSSA
type direction = Forward | Backward
type ('a, 'b) helpers = {
eval_block : 'a -> block -> 'a * bool;
eval_stmt : 'a -> stmt_node -> 'a option;
eval_values : 'a -> value_node list -> 'b list;
iter_exp_children : 'a -> exp_node -> unit;
iter_values : 'a -> value_node list -> unit;
}
module type ANALYSIS = sig
type env
type exp_info
type value_info
val dir : direction
val iterative : bool
val init : fn -> env
val value : env -> value_node -> value_info
val exp : env -> exp_node -> (env, value_info) helpers -> exp_info
val stmt : env -> stmt_node -> (env, value_info) helpers -> env option
val phi_set : env -> ID.t -> value_info -> env option
val phi_merge : env -> ID.t -> value_info -> value_info -> env option
end
module MkEvaluator(A : ANALYSIS) = struct
let rec eval_block initEnv block =
let changed = ref false in
let fold_stmts env stmtNode =
match A.stmt env stmtNode helpers with
| Some env' -> changed := true; env'
| None -> env
in
let env' =
match A.dir with
| Forward -> Block.fold_forward fold_stmts initEnv block
| Backward -> Block.fold_backward fold_stmts initEnv block
in
env', !changed
and eval_loop_header ?(changed=false) envOut envIn = function
| [] -> envOut, changed
| phiNode::rest ->
let valInfo = A.value envIn phiNode.phi_left in
let currEnvOut = A.phi_set envOut phiNode.phi_id valInfo in
let envOut' = Option.default envOut currEnvOut in
let currChanged = changed || Option.is_some currEnvOut in
eval_loop_header ~changed:currChanged envOut' envIn rest
and eval_phi_nodes ?(changed=false) envOut envLeft envRight = function
| [] -> if changed then Some envOut else None
| phiNode::rest ->
let leftInfo = A.value envLeft phiNode.phi_left in
let rightInfo = A.value envRight phiNode.phi_right in
let currEnvOut =
A.phi_merge envOut phiNode.phi_id leftInfo rightInfo
in
let envOut' = Option.default envOut currEnvOut in
let currChanged = changed || Option.is_some currEnvOut in
eval_phi_nodes ~changed:currChanged envOut' envLeft envRight rest
and default_stmt env stmtNode = match stmtNode.stmt with
| Set (ids, rhs) ->
let _ = A.exp env rhs helpers in
None
| If(cond, tBlock, fBlock, merge) ->
ignore (A.value env cond);
let tEnv, tChanged = eval_block env tBlock in
let fEnv, fChanged = eval_block tEnv fBlock in
eval_phi_nodes ~changed:(tChanged || fChanged) fEnv tEnv fEnv merge
| WhileLoop(condBlock, condVal, body, header) ->
if A.iterative then (
let maxIters = 100 in
let iter = ref 0 in
let headerEnv, headerChanged = eval_loop_header env env header in
let condEnv, condChanged = eval_block headerEnv condBlock in
ignore (A.value condEnv condVal);
let loopEnv = ref condEnv in
let changed = ref true in
while !changed do
iter := !iter + 1;
if !iter > maxIters then
failwith $ "loop analysis failed to terminate"
;
let bodyEnv, bodyChanged = eval_block !loopEnv body in
let phiEnv, phiChanged =
match eval_phi_nodes bodyEnv headerEnv bodyEnv header with
| Some env -> env, true
| None -> bodyEnv, false
in
let condEnv, condChanged = eval_block phiEnv condBlock in
loopEnv := condEnv;
changed := bodyChanged || phiChanged || condChanged
done;
if !iter > 1 then Some !loopEnv else None
)
else (
let headerEnv, headerChanged =
match eval_phi_nodes env env env header with
| None -> env, false
| Some env' -> env', true
in
let condEnv, condChanged = eval_block headerEnv condBlock in
ignore (A.value condEnv condVal);
let bodyEnv, bodyChanged = eval_block condEnv body in
let changed = headerChanged || condChanged || bodyChanged in
if changed then Some bodyEnv else None
)
| SetIdx (lhs, indices, rhs) ->
ignore (A.value env lhs);
iter_values env indices;
ignore (A.exp env rhs);
None
and iter_exp_children env expNode =
match expNode.exp with
| Cast(_, v) -> ignore $ A.value env v
| Call(_, xs)
| PrimApp(_,xs)
| Values xs
| Arr xs -> iter_values env xs
| Tuple xs -> iter_values env xs
| Adverb adverb -> iter_adverb env adverb
and iter_adverb env {Adverb.fixed; init; axes; args} =
iter_values env fixed;
iter_values env args;
iter_values env axes;
match init with
| Some vs -> iter_values env vs
| None -> ()
and iter_values env = function
| [] -> () | v::vs -> let _ = A.value env v in iter_values env vs
and eval_values env = function
| [] -> [] | v::vs -> (A.value env v) :: (eval_values env vs)
and helpers = {
eval_block = eval_block;
eval_stmt = default_stmt;
eval_values = eval_values;
iter_values = iter_values;
iter_exp_children = iter_exp_children;
}
let eval_fn fn =
let env = A.init fn in
let env', _ = eval_block env fn.body in
env'
end
|
c93793458221f3859b9540f6eee3c4780783071ae4aa6465ad6445619fb61bf9 | dyzsr/ocaml-selectml | main.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* The lexer generator. Command-line parsing. *)
open Syntax
let ml_automata = ref false
let source_name = ref None
let output_name = ref None
let usage = "usage: ocamllex [options] sourcefile"
let print_version_string () =
print_string "The OCaml lexer generator, version ";
print_string Sys.ocaml_version ; print_newline();
exit 0
let print_version_num () =
print_endline Sys.ocaml_version;
exit 0;
;;
let specs =
["-ml", Arg.Set ml_automata,
" Output code that does not use the Lexing module built-in automata \
interpreter";
"-o", Arg.String (fun x -> output_name := Some x),
" <file> Set output file name to <file>";
"-q", Arg.Set Common.quiet_mode, " Do not display informational messages";
"-v", Arg.Unit print_version_string, " Print version and exit";
"-version", Arg.Unit print_version_string, " Print version and exit";
"-vnum", Arg.Unit print_version_num, " Print version number and exit";
]
let _ =
Arg.parse
specs
(fun name -> source_name := Some name)
usage
let main () =
let source_name = match !source_name with
| None -> Arg.usage specs usage ; exit 2
| Some name -> name in
let dest_name = match !output_name with
| Some name -> name
| None ->
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
let ic = open_in_bin source_name in
let oc = open_out dest_name in
let tr = Common.open_tracker dest_name oc in
let lexbuf = Lexing.from_channel ic in
lexbuf.Lexing.lex_curr_p <-
{Lexing.pos_fname = source_name; Lexing.pos_lnum = 1;
Lexing.pos_bol = 0; Lexing.pos_cnum = 0};
try
let def = Parser.lexer_definition Lexer.main lexbuf in
let (entries, transitions) = Lexgen.make_dfa def.entrypoints in
if !ml_automata then begin
Outputbis.output_lexdef
ic oc tr
def.header def.refill_handler entries transitions def.trailer
end else begin
let tables = Compact.compact_tables transitions in
Output.output_lexdef ic oc tr
def.header def.refill_handler tables entries def.trailer
end;
close_in ic;
close_out oc;
Common.close_tracker tr;
with exn ->
let bt = Printexc.get_raw_backtrace () in
close_in ic;
close_out oc;
Common.close_tracker tr;
Sys.remove dest_name;
begin match exn with
| Cset.Bad ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: character set expected.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Parsing.Parse_error ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: syntax error.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Lexer.Lexical_error(msg, file, line, col) ->
Printf.fprintf stderr
"File \"%s\", line %d, character %d: %s.\n"
file line col msg
| Lexgen.Memory_overflow ->
Printf.fprintf stderr
"File \"%s\":\n Position memory overflow, too many bindings\n"
source_name
| Output.Table_overflow ->
Printf.fprintf stderr
"File \"%s\":\ntransition table overflow, automaton is too big\n"
source_name
| _ ->
Printexc.raise_with_backtrace exn bt
end;
exit 3
let _ = (* Printexc.catch *) main (); exit 0
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/lex/main.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
The lexer generator. Command-line parsing.
Printexc.catch | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Syntax
let ml_automata = ref false
let source_name = ref None
let output_name = ref None
let usage = "usage: ocamllex [options] sourcefile"
let print_version_string () =
print_string "The OCaml lexer generator, version ";
print_string Sys.ocaml_version ; print_newline();
exit 0
let print_version_num () =
print_endline Sys.ocaml_version;
exit 0;
;;
let specs =
["-ml", Arg.Set ml_automata,
" Output code that does not use the Lexing module built-in automata \
interpreter";
"-o", Arg.String (fun x -> output_name := Some x),
" <file> Set output file name to <file>";
"-q", Arg.Set Common.quiet_mode, " Do not display informational messages";
"-v", Arg.Unit print_version_string, " Print version and exit";
"-version", Arg.Unit print_version_string, " Print version and exit";
"-vnum", Arg.Unit print_version_num, " Print version number and exit";
]
let _ =
Arg.parse
specs
(fun name -> source_name := Some name)
usage
let main () =
let source_name = match !source_name with
| None -> Arg.usage specs usage ; exit 2
| Some name -> name in
let dest_name = match !output_name with
| Some name -> name
| None ->
if Filename.check_suffix source_name ".mll" then
Filename.chop_suffix source_name ".mll" ^ ".ml"
else
source_name ^ ".ml" in
let ic = open_in_bin source_name in
let oc = open_out dest_name in
let tr = Common.open_tracker dest_name oc in
let lexbuf = Lexing.from_channel ic in
lexbuf.Lexing.lex_curr_p <-
{Lexing.pos_fname = source_name; Lexing.pos_lnum = 1;
Lexing.pos_bol = 0; Lexing.pos_cnum = 0};
try
let def = Parser.lexer_definition Lexer.main lexbuf in
let (entries, transitions) = Lexgen.make_dfa def.entrypoints in
if !ml_automata then begin
Outputbis.output_lexdef
ic oc tr
def.header def.refill_handler entries transitions def.trailer
end else begin
let tables = Compact.compact_tables transitions in
Output.output_lexdef ic oc tr
def.header def.refill_handler tables entries def.trailer
end;
close_in ic;
close_out oc;
Common.close_tracker tr;
with exn ->
let bt = Printexc.get_raw_backtrace () in
close_in ic;
close_out oc;
Common.close_tracker tr;
Sys.remove dest_name;
begin match exn with
| Cset.Bad ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: character set expected.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Parsing.Parse_error ->
let p = Lexing.lexeme_start_p lexbuf in
Printf.fprintf stderr
"File \"%s\", line %d, character %d: syntax error.\n"
p.Lexing.pos_fname p.Lexing.pos_lnum
(p.Lexing.pos_cnum - p.Lexing.pos_bol)
| Lexer.Lexical_error(msg, file, line, col) ->
Printf.fprintf stderr
"File \"%s\", line %d, character %d: %s.\n"
file line col msg
| Lexgen.Memory_overflow ->
Printf.fprintf stderr
"File \"%s\":\n Position memory overflow, too many bindings\n"
source_name
| Output.Table_overflow ->
Printf.fprintf stderr
"File \"%s\":\ntransition table overflow, automaton is too big\n"
source_name
| _ ->
Printexc.raise_with_backtrace exn bt
end;
exit 3
|
b08f5da5ee85f7dbdbc4d60bd973cd55870f6a755d2b8cfbd56d3262331cd35e | stathissideris/positano | fun.clj | (ns positano.integration-test4.fun)
(defn baz [x]
(inc x))
(defn bar [x]
(* (baz (/ x 2.0)) 3))
(defn foo
"I don't do a whole lot."
[x]
(println "Hello, World!")
(bar (first x)))
| null | https://raw.githubusercontent.com/stathissideris/positano/ca5126714b4bcf108726d930ab61a875759214ae/test/positano/integration_test4/fun.clj | clojure | (ns positano.integration-test4.fun)
(defn baz [x]
(inc x))
(defn bar [x]
(* (baz (/ x 2.0)) 3))
(defn foo
"I don't do a whole lot."
[x]
(println "Hello, World!")
(bar (first x)))
|
|
76879b83726fb72b98ff5b9ce0d78c6488e9c965ca6f3487c62bfa6ae1da3c83 | gregr/ina | extended-test.scm | ((require language:base module:base-primitive module:base language:extended
premodule module:premodule module-apply namespace-link* test))
(define ns (namespace-link* '() (list module:base-primitive module:base)))
(define name=>lang (list (cons 'base language:base)
(cons 'extended language:extended)))
(define (ev form)
(define pm (premodule '() #f '() #f '(base extended) (list form)))
(module-apply (module:premodule name=>lang pm) ns))
(test 'cond-3
(ev '(cond (#f 3)
(8)
(4 5)))
8)
(test 'cond-4
(ev '(cond (#f 3)
((car '(#f 4)) 5)
(else 6)))
6)
(test 'cond-5
(ev '(cond (#f 3)
((car '(#f 4)) 5)
('the => (lambda (v) (cons v 'answer)))
(else 6)))
'(the . answer))
(test 'qq-1
(ev '`one)
'one)
(test 'qq-2
(ev '`((a 1) (b 2)))
'((a 1) (b 2)))
(test 'qq-3
(ev '`((a 1) ,(cons 'b `(3))))
'((a 1) (b 3)))
(test 'qq-4
(ev '`(1 `,(cons 2 3) ,(cons 4 5) `(,(cons 6 ,(cons 7 8))) 100))
(list 1 '`,(cons 2 3) (cons 4 5)
(list 'quasiquote (list (list 'unquote (list 'cons 6 (cons 7 8)))))
100))
(test 'qq-5
(ev '`(1 ,@(cons 2 (cons 3 '())) 4))
'(1 2 3 4))
(test 'qq-6
(ev '`#(1 ,(cons 2 (cons 3 '())) 4))
'#(1 (2 3) 4))
(test 'qq-7
(ev '`#(1 ,@(cons 2 (cons 3 '())) 4))
'#(1 2 3 4))
(test 'case-1
(ev '(case 3 (else 'ok)))
'ok)
(test 'case-2
(ev '(case 3
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'three)
(test 'case-3
(ev '(case 'foo
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'foobar)
(test 'case-4
(ev '(case 'bar
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'foobar)
(test 'case-5
(ev '(case 'baz
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'fail)
(test 'case-6
(ev '(case '(3 4)
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'multiple)
| null | https://raw.githubusercontent.com/gregr/ina/5e0a5b7ec44c8c9575b22ce5c394f7a96b766545/nscheme/old/old-5/lib/extended-test.scm | scheme | ((require language:base module:base-primitive module:base language:extended
premodule module:premodule module-apply namespace-link* test))
(define ns (namespace-link* '() (list module:base-primitive module:base)))
(define name=>lang (list (cons 'base language:base)
(cons 'extended language:extended)))
(define (ev form)
(define pm (premodule '() #f '() #f '(base extended) (list form)))
(module-apply (module:premodule name=>lang pm) ns))
(test 'cond-3
(ev '(cond (#f 3)
(8)
(4 5)))
8)
(test 'cond-4
(ev '(cond (#f 3)
((car '(#f 4)) 5)
(else 6)))
6)
(test 'cond-5
(ev '(cond (#f 3)
((car '(#f 4)) 5)
('the => (lambda (v) (cons v 'answer)))
(else 6)))
'(the . answer))
(test 'qq-1
(ev '`one)
'one)
(test 'qq-2
(ev '`((a 1) (b 2)))
'((a 1) (b 2)))
(test 'qq-3
(ev '`((a 1) ,(cons 'b `(3))))
'((a 1) (b 3)))
(test 'qq-4
(ev '`(1 `,(cons 2 3) ,(cons 4 5) `(,(cons 6 ,(cons 7 8))) 100))
(list 1 '`,(cons 2 3) (cons 4 5)
(list 'quasiquote (list (list 'unquote (list 'cons 6 (cons 7 8)))))
100))
(test 'qq-5
(ev '`(1 ,@(cons 2 (cons 3 '())) 4))
'(1 2 3 4))
(test 'qq-6
(ev '`#(1 ,(cons 2 (cons 3 '())) 4))
'#(1 (2 3) 4))
(test 'qq-7
(ev '`#(1 ,@(cons 2 (cons 3 '())) 4))
'#(1 2 3 4))
(test 'case-1
(ev '(case 3 (else 'ok)))
'ok)
(test 'case-2
(ev '(case 3
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'three)
(test 'case-3
(ev '(case 'foo
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'foobar)
(test 'case-4
(ev '(case 'bar
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'foobar)
(test 'case-5
(ev '(case 'baz
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'fail)
(test 'case-6
(ev '(case '(3 4)
((4) 'four)
(((3 4)) 'multiple)
((3) 'three)
((foo bar) 'foobar)
(else 'fail)))
'multiple)
|
|
60f4d02bc614a3c06479ebc67d1efa64c0d67c755b914a130a0ca5c6415f922e | backtracking/ocaml-bazaar | arrays.ml |
(** Additional functions over arrays *)
let build n f =
if n = 0 then [||] else
let a = Array.make n (f (fun _ -> invalid_arg "build") 0) in
for i = 1 to n - 1 do
let get j = if j < 0 || j >= i then invalid_arg "build"; a.(j) in
a.(i) <- f get i
done;
a
type color = Undefined | Inprogress | Defined
let fix n f =
let a = ref [||] in
let color = Array.make n Undefined in
let rec get i =
if i < 0 || i >= n then invalid_arg "fix";
match color.(i) with
| Inprogress -> invalid_arg "fix"
| Defined -> !a.(i)
| Undefined ->
color.(i) <- Inprogress;
let v = f get i in
if !a = [||] then a := Array.make n v else !a.(i) <- v;
color.(i) <- Defined; v in
for i = 0 to n - 1 do ignore (get i) done;
!a
let shuffle a =
let n = Array.length a in
let swap i j = let t = a.(i) in a.(i) <- a.(j); a.(j) <- t in
for k = 1 to n - 1 do swap (Random.int (k + 1)) k done
Inverse of a permutation , in place
Algorithm I
The Art of Computer Programming , volume 1 , Sec . 1.3.3 , page 176
Inverse of a permutation, in place
Algorithm I
The Art of Computer Programming, volume 1, Sec. 1.3.3, page 176
*)
let inverse_in_place a =
let n = Array.length a in
for m = n-1 downto 0 do
let i = ref a.(m) in
if !i >= 0 then begin
a.(m) <- -1; (* sentinel *)
let j = ref (lnot m) in
let k = ref !i in
i := a.(!i);
while !i >= 0 do
a.(!k) <- !j;
j := lnot !k;
k := !i;
i := a.(!k)
done;
i := !j
end;
a.(m) <- lnot !i
done
| null | https://raw.githubusercontent.com/backtracking/ocaml-bazaar/e7bab112f29840593c3b59b70162af73a7d6a607/arrays.ml | ocaml | * Additional functions over arrays
sentinel |
let build n f =
if n = 0 then [||] else
let a = Array.make n (f (fun _ -> invalid_arg "build") 0) in
for i = 1 to n - 1 do
let get j = if j < 0 || j >= i then invalid_arg "build"; a.(j) in
a.(i) <- f get i
done;
a
type color = Undefined | Inprogress | Defined
let fix n f =
let a = ref [||] in
let color = Array.make n Undefined in
let rec get i =
if i < 0 || i >= n then invalid_arg "fix";
match color.(i) with
| Inprogress -> invalid_arg "fix"
| Defined -> !a.(i)
| Undefined ->
color.(i) <- Inprogress;
let v = f get i in
if !a = [||] then a := Array.make n v else !a.(i) <- v;
color.(i) <- Defined; v in
for i = 0 to n - 1 do ignore (get i) done;
!a
let shuffle a =
let n = Array.length a in
let swap i j = let t = a.(i) in a.(i) <- a.(j); a.(j) <- t in
for k = 1 to n - 1 do swap (Random.int (k + 1)) k done
Inverse of a permutation , in place
Algorithm I
The Art of Computer Programming , volume 1 , Sec . 1.3.3 , page 176
Inverse of a permutation, in place
Algorithm I
The Art of Computer Programming, volume 1, Sec. 1.3.3, page 176
*)
let inverse_in_place a =
let n = Array.length a in
for m = n-1 downto 0 do
let i = ref a.(m) in
if !i >= 0 then begin
let j = ref (lnot m) in
let k = ref !i in
i := a.(!i);
while !i >= 0 do
a.(!k) <- !j;
j := lnot !k;
k := !i;
i := a.(!k)
done;
i := !j
end;
a.(m) <- lnot !i
done
|
17ac9dc003ed550a4f3f226c9a3c0f38fc3afaf36ffe75a40996a949eb506bce | ghcjs/ghcjs | num010.hs |
module Main(main) where
main = sequence_ [ f x y | x <- [0,
1000,
> 2 ^ 32
> 2 ^ 64
-1000,
< -2 ^ 32
< -2 ^ 64
, y <- [0, -10, 10] ]
f :: Integer -> Int -> IO ()
f x y = do putStrLn "------------------------"
print x
print y
let d :: Double
d = encodeFloat x y
(xd, yd) = decodeFloat d
{- let f :: Float
f = encodeFloat x y
(xf, yf) = decodeFloat f -}
print d
print xd
print yd
-- print f
-- print xf
-- print yf
| null | https://raw.githubusercontent.com/ghcjs/ghcjs/e4cd4232a31f6371c761acd93853702f4c7ca74c/test/pkg/base/Numeric/num010.hs | haskell | let f :: Float
f = encodeFloat x y
(xf, yf) = decodeFloat f
print f
print xf
print yf |
module Main(main) where
main = sequence_ [ f x y | x <- [0,
1000,
> 2 ^ 32
> 2 ^ 64
-1000,
< -2 ^ 32
< -2 ^ 64
, y <- [0, -10, 10] ]
f :: Integer -> Int -> IO ()
f x y = do putStrLn "------------------------"
print x
print y
let d :: Double
d = encodeFloat x y
(xd, yd) = decodeFloat d
print d
print xd
print yd
|
8daed808e2453f1aaa06727d01df592fe0a023ff6d8f28a717219a80fd2eea53 | alanz/ghc-exactprint | MatchSemis.hs | module MatchSemis where
{
a 0 = 1;
a _ = 2;
}
| null | https://raw.githubusercontent.com/alanz/ghc-exactprint/103bc706c82300639985a15ba6cf762316352c92/tests/examples/ghc92/MatchSemis.hs | haskell | module MatchSemis where
{
a 0 = 1;
a _ = 2;
}
|
|
97928c828c5015980a743a91ebb11a394995a6302d9a336f8849f0374747c7b2 | agda/agda | Definitions.hs | {-# LANGUAGE GADTs #-}
| Preprocess ' Agda . Syntax . Concrete . Declaration 's , producing ' NiceDeclaration 's .
--
-- * Attach fixity and syntax declarations to the definition they refer to.
--
-- * Distribute the following attributes to the individual definitions:
-- @abstract@,
-- @instance@,
-- @postulate@,
-- @primitive@,
-- @private@,
-- termination pragmas.
--
* Gather the function clauses belonging to one function definition .
--
-- * Expand ellipsis @...@ in function clauses following @with@.
--
-- * Infer mutual blocks.
-- A block starts when a lone signature is encountered, and ends when
-- all lone signatures have seen their definition.
--
-- * Handle interleaved mutual blocks.
-- In an `interleaved mutual' block we:
-- * leave the data and fun sigs in place
-- * classify signatures in `constructor' block based on their return type
-- and group them all as a data def at the position in the block where the
first constructor for the data sig in question occured
-- * classify fun clauses based on the declared function used and group them
all as a fundef at the position in the block where the first such fun
-- clause appeared
--
-- * Report basic well-formedness error,
when one of the above transformation fails .
-- When possible, errors should be deferred to the scope checking phase
( ConcreteToAbstract ) , where we are in the TCM and can produce more
-- informative error messages.
module Agda.Syntax.Concrete.Definitions
( NiceDeclaration(..)
, NiceConstructor, NiceTypeSignature
, Clause(..)
, DeclarationException(..)
, DeclarationWarning(..), DeclarationWarning'(..), unsafeDeclarationWarning
, Nice, runNice
, niceDeclarations
, notSoNiceDeclarations
, niceHasAbstract
, Measure
, declarationWarningName
) where
import Prelude hiding (null)
import Control.Monad ( forM, guard, unless, void, when )
import Control.Monad.Except ( )
import Control.Monad.State ( MonadState(..), gets, StateT, runStateT )
import Control.Monad.Trans ( lift )
import Data.Bifunctor
import Data.Either (isLeft, isRight)
import Data.Function (on)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import Data.Semigroup ( Semigroup(..) )
import qualified Data.List as List
import qualified Data.Foldable as Fold
import qualified Data.Traversable as Trav
import Agda.Syntax.Concrete
import Agda.Syntax.Concrete.Pattern
import Agda.Syntax.Common hiding (TerminationCheck())
import qualified Agda.Syntax.Common as Common
import Agda.Syntax.Position
import Agda.Syntax.Notation
import Agda.Syntax.Concrete.Pretty () --instance only
import Agda.Syntax.Concrete.Fixity
import Agda.Syntax.Concrete.Definitions.Errors
import Agda.Syntax.Concrete.Definitions.Monad
import Agda.Syntax.Concrete.Definitions.Types
import Agda.Interaction.Options.Warnings
import Agda.Utils.AffineHole
import Agda.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List (isSublistOf, spanJust)
import Agda.Utils.List1 (List1, pattern (:|), (<|))
import qualified Agda.Utils.List1 as List1
import Agda.Utils.Maybe
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Three
import Agda.Utils.Tuple
import Agda.Utils.Update
import Agda.Utils.Impossible
{--------------------------------------------------------------------------
The niceifier
--------------------------------------------------------------------------}
-- | Check that declarations in a mutual block are consistently
-- equipped with MEASURE pragmas, or whether there is a
-- NO_TERMINATION_CHECK pragma.
combineTerminationChecks :: Range -> [TerminationCheck] -> Nice TerminationCheck
combineTerminationChecks r tcs = loop tcs where
loop :: [TerminationCheck] -> Nice TerminationCheck
loop [] = return TerminationCheck
loop (tc : tcs) = do
let failure r = declarationException $ InvalidMeasureMutual r
tc' <- loop tcs
case (tc, tc') of
(TerminationCheck , tc' ) -> return tc'
(tc , TerminationCheck ) -> return tc
(NonTerminating , NonTerminating ) -> return NonTerminating
(NoTerminationCheck , NoTerminationCheck ) -> return NoTerminationCheck
(NoTerminationCheck , Terminating ) -> return Terminating
(Terminating , NoTerminationCheck ) -> return Terminating
(Terminating , Terminating ) -> return Terminating
(TerminationMeasure{} , TerminationMeasure{} ) -> return tc
(TerminationMeasure r _, NoTerminationCheck ) -> failure r
(TerminationMeasure r _, Terminating ) -> failure r
(NoTerminationCheck , TerminationMeasure r _) -> failure r
(Terminating , TerminationMeasure r _) -> failure r
(TerminationMeasure r _, NonTerminating ) -> failure r
(NonTerminating , TerminationMeasure r _) -> failure r
(NoTerminationCheck , NonTerminating ) -> failure r
(Terminating , NonTerminating ) -> failure r
(NonTerminating , NoTerminationCheck ) -> failure r
(NonTerminating , Terminating ) -> failure r
combineCoverageChecks :: [CoverageCheck] -> CoverageCheck
combineCoverageChecks = Fold.fold
combinePositivityChecks :: [PositivityCheck] -> PositivityCheck
combinePositivityChecks = Fold.fold
data DeclKind
= LoneSigDecl Range DataRecOrFun Name
| LoneDefs DataRecOrFun [Name]
| OtherDecl
deriving (Eq, Show)
declKind :: NiceDeclaration -> DeclKind
declKind (FunSig r _ _ _ _ _ tc cc x _) = LoneSigDecl r (FunName tc cc) x
declKind (NiceRecSig r _ _ _ pc uc x _ _) = LoneSigDecl r (RecName pc uc) x
declKind (NiceDataSig r _ _ _ pc uc x _ _) = LoneSigDecl r (DataName pc uc) x
declKind (FunDef r _ abs ins tc cc x _) = LoneDefs (FunName tc cc) [x]
declKind (NiceDataDef _ _ _ pc uc x pars _) = LoneDefs (DataName pc uc) [x]
declKind (NiceUnquoteData _ _ _ pc uc x _ _) = LoneDefs (DataName pc uc) [x]
declKind (NiceRecDef _ _ _ pc uc x _ pars _) = LoneDefs (RecName pc uc) [x]
declKind (NiceUnquoteDef _ _ _ tc cc xs _) = LoneDefs (FunName tc cc) xs
declKind Axiom{} = OtherDecl
declKind NiceField{} = OtherDecl
declKind PrimitiveFunction{} = OtherDecl
declKind NiceMutual{} = OtherDecl
declKind NiceModule{} = OtherDecl
declKind NiceModuleMacro{} = OtherDecl
declKind NiceOpen{} = OtherDecl
declKind NiceImport{} = OtherDecl
declKind NicePragma{} = OtherDecl
declKind NiceFunClause{} = OtherDecl
declKind NicePatternSyn{} = OtherDecl
declKind NiceGeneralize{} = OtherDecl
declKind NiceUnquoteDecl{} = OtherDecl
declKind NiceLoneConstructor{} = OtherDecl
| Replace ( Data / Rec / Fun)Sigs with Axioms for postulated names
The first argument is a list of axioms only .
replaceSigs
^ Lone signatures to be turned into Axioms
-> [NiceDeclaration] -- ^ Declarations containing them
-> [NiceDeclaration] -- ^ In the output, everything should be defined
replaceSigs ps = if Map.null ps then id else \case
[] -> __IMPOSSIBLE__
(d:ds) ->
case replaceable d of
-- If declaration d of x is mentioned in the map of lone signatures then replace
-- it with an axiom
Just (x, axiom)
| (Just (LoneSig _ x' _), ps') <- Map.updateLookupWithKey (\ _ _ -> Nothing) x ps
, getRange x == getRange x'
Use the range as UID to ensure we do not replace the wrong signature .
-- This could happen if the user wrote a duplicate definition.
-> axiom : replaceSigs ps' ds
_ -> d : replaceSigs ps ds
where
-- A @replaceable@ declaration is a signature. It has a name and we can make an
-- @Axiom@ out of it.
replaceable :: NiceDeclaration -> Maybe (Name, NiceDeclaration)
replaceable = \case
FunSig r acc abst inst _ argi _ _ x' e ->
-- #4881: Don't use the unique NameId for NoName lookups.
let x = if isNoName x' then noName (nameRange x') else x' in
Just (x, Axiom r acc abst inst argi x' e)
NiceRecSig r erased acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef
(setQuantity (asQuantity erased) defaultArgInfo) x e)
NiceDataSig r erased acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef
(setQuantity (asQuantity erased) defaultArgInfo) x e)
_ -> Nothing
| Main . ( or more precisely syntax declarations ) are needed when
-- grouping function clauses.
niceDeclarations :: Fixities -> [Declaration] -> Nice [NiceDeclaration]
niceDeclarations fixs ds = do
-- Run the nicifier in an initial environment. But keep the warnings.
st <- get
put $ initNiceEnv { niceWarn = niceWarn st }
nds <- nice ds
-- Check that every signature got its definition.
ps <- use loneSigs
checkLoneSigs ps
We postulate the missing ones and insert them in place of the corresponding
let ds = replaceSigs ps nds
-- Note that loneSigs is ensured to be empty.
-- (Important, since inferMutualBlocks also uses loneSigs state).
res <- inferMutualBlocks ds
-- Restore the old state, but keep the warnings.
warns <- gets niceWarn
put $ st { niceWarn = warns }
return res
where
inferMutualBlocks :: [NiceDeclaration] -> Nice [NiceDeclaration]
inferMutualBlocks [] = return []
inferMutualBlocks (d : ds) =
case declKind d of
OtherDecl -> (d :) <$> inferMutualBlocks ds
, 2017 - 10 - 09 , issue # 2576 : report error in ConcreteToAbstract
LoneSigDecl r k x -> do
_ <- addLoneSig r x k
InferredMutual checks nds0 ds1 <- untilAllDefined (mutualChecks k) ds
-- If we still have lone signatures without any accompanying definition,
-- we postulate the definition and substitute the axiom for the lone signature
ps <- use loneSigs
checkLoneSigs ps
NB : do n't forget the LoneSig the block started with !
-- We then keep processing the rest of the block
tc <- combineTerminationChecks (getRange d) (mutualTermination checks)
let cc = combineCoverageChecks (mutualCoverage checks)
let pc = combinePositivityChecks (mutualPositivity checks)
(NiceMutual (getRange ds0) tc cc pc ds0 :) <$> inferMutualBlocks ds1
where
untilAllDefined :: MutualChecks -> [NiceDeclaration] -> Nice InferredMutual
untilAllDefined checks ds = do
done <- noLoneSigs
if done then return (InferredMutual checks [] ds) else
case ds of
[] -> return (InferredMutual checks [] ds)
d : ds -> case declKind d of
LoneSigDecl r k x -> do
void $ addLoneSig r x k
extendInferredBlock d <$> untilAllDefined (mutualChecks k <> checks) ds
LoneDefs k xs -> do
mapM_ removeLoneSig xs
extendInferredBlock d <$> untilAllDefined (mutualChecks k <> checks) ds
OtherDecl -> extendInferredBlock d <$> untilAllDefined checks ds
nice :: [Declaration] -> Nice [NiceDeclaration]
nice [] = return []
nice ds = do
(xs , ys) <- nice1 ds
(xs ++) <$> nice ys
nice1 :: [Declaration] -> Nice ([NiceDeclaration], [Declaration])
, 2017 - 09 - 16 , issue # 2759 : no longer _ _ IMPOSSIBLE _ _
nice1 (d:ds) = do
let justWarning :: HasCallStack => DeclarationWarning' -> Nice ([NiceDeclaration], [Declaration])
justWarning w = do
-- NOTE: This is the location of the invoker of justWarning, not here.
withCallerCallStack $ declarationWarning' w
nice1 ds
case d of
TypeSig info _tac x t -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
, 2020 - 09 - 28 , issue # 4950 : take only range of identifier ,
-- since parser expands type signatures with several identifiers
-- (like @x y z : A@) into several type signatures (with imprecise ranges).
let r = getRange x
-- register x as lone type signature, to recognize clauses later
x' <- addLoneSig r x $ FunName termCheck covCheck
return ([FunSig r PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x' t] , ds)
Should not show up : all FieldSig are part of a Field block
FieldSig{} -> __IMPOSSIBLE__
Generalize r [] -> justWarning $ EmptyGeneralize r
Generalize r sigs -> do
gs <- forM sigs $ \case
sig@(TypeSig info tac x t) -> do
, 2022 - 03 - 25 , issue # 5850 :
-- Warn about @variable {x} : A@ which is equivalent to @variable x : A@.
when (getHiding info == Hidden) $
declarationWarning $ HiddenGeneralize $ getRange x
return $ NiceGeneralize (getRange sig) PublicAccess info tac x t
_ -> __IMPOSSIBLE__
return (gs, ds)
(FunClause lhs _ _ _) -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
catchall <- popCatchallPragma
xs <- loneFuns <$> use loneSigs
-- for each type signature 'x' waiting for clauses, we try
-- if we have some clauses for 'x'
case [ (x, (x', fits, rest))
| (x, x') <- xs
, let (fits, rest) =
Anonymous declarations only have 1 clause each !
if isNoName x then ([d], ds)
else span (couldBeFunClauseOf (Map.lookup x fixs) x) (d : ds)
, not (null fits)
] of
case : clauses match none of the sigs
[] -> case lhs of
Subcase : The lhs is single identifier ( potentially anonymous ) .
-- Treat it as a function clause without a type signature.
LHS p [] [] | Just x <- isSingleIdentifierP p -> do
d <- mkFunDef (setOrigin Inserted defaultArgInfo) termCheck covCheck x Nothing [d] -- fun def without type signature is relevant
return (d , ds)
Subcase : The lhs is a proper pattern .
-- This could be a let-pattern binding. Pass it on.
A missing type signature error might be raise in ConcreteToAbstract
_ -> do
return ([NiceFunClause (getRange d) PublicAccess ConcreteDef termCheck covCheck catchall d] , ds)
case : clauses match exactly one of the sigs
[(x,(x',fits,rest))] -> do
-- The x'@NoName{} is the unique version of x@NoName{}.
removeLoneSig x
ds <- expandEllipsis fits
cs <- mkClauses x' ds False
return ([FunDef (getRange fits) fits ConcreteDef NotInstanceDef termCheck covCheck x' cs] , rest)
case : clauses match more than one sigs ( ambiguity )
xf:xfs -> declarationException $ AmbiguousFunClauses lhs $ List1.reverse $ fmap fst $ xf :| xfs
" ambiguous function clause ; can not assign it uniquely to one type signature "
Field r [] -> justWarning $ EmptyField r
Field _ fs -> (,ds) <$> niceAxioms FieldBlock fs
DataSig r erased x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
_ <- addLoneSig r x $ DataName pc uc
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig erased) (niceAxioms DataBlock) r
x (Just (tel, t)) Nothing
Data r erased x tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x (Just t)
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig erased) (niceAxioms DataBlock) r
x ((tel,) <$> mt) (Just (tel, cs))
DataDef r x tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x Nothing
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig defaultErased)
(niceAxioms DataBlock) r x ((tel,) <$> mt)
(Just (tel, cs))
RecordSig r erased x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
_ <- addLoneSig r x $ RecName pc uc
return ( [NiceRecSig r erased PublicAccess ConcreteDef pc uc x
tel t]
, ds
)
Record r erased x dir tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x (Just t)
(,ds) <$> dataOrRec pc uc
(\r o a pc uc x tel cs ->
NiceRecDef r o a pc uc x dir tel cs)
(flip NiceRecSig erased) return r x
((tel,) <$> mt) (Just (tel, cs))
RecordDef r x dir tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
-- Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
Universe check is performed if both the current value of
-- 'universeCheckPragma' AND the one from the signature say so.
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x Nothing
(,ds) <$> dataOrRec pc uc
(\r o a pc uc x tel cs ->
NiceRecDef r o a pc uc x dir tel cs)
(flip NiceRecSig defaultErased) return r x
((tel,) <$> mt) (Just (tel, cs))
RecordDirective r -> justWarning $ InvalidRecordDirective (getRange r)
Mutual r ds' -> do
-- The lone signatures encountered so far are not in scope
-- for the mutual definition
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkOldMutual r =<< nice ds'))
InterleavedMutual r ds' -> do
-- The lone signatures encountered so far are not in scope
-- for the mutual definition
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkInterleavedMutual r =<< nice ds'))
LoneConstructor r [] -> justWarning $ EmptyConstructor r
LoneConstructor r ds' ->
((,ds) . singleton . NiceLoneConstructor r) <$> niceAxioms ConstructorBlock ds'
Abstract r [] -> justWarning $ EmptyAbstract r
Abstract r ds' ->
(,ds) <$> (abstractBlock r =<< nice ds')
Private r UserWritten [] -> justWarning $ EmptyPrivate r
Private r o ds' ->
(,ds) <$> (privateBlock r o =<< nice ds')
InstanceB r [] -> justWarning $ EmptyInstance r
InstanceB r ds' ->
(,ds) <$> (instanceBlock r =<< nice ds')
Macro r [] -> justWarning $ EmptyMacro r
Macro r ds' ->
(,ds) <$> (macroBlock r =<< nice ds')
Postulate r [] -> justWarning $ EmptyPostulate r
Postulate _ ds' ->
(,ds) <$> niceAxioms PostulateBlock ds'
Primitive r [] -> justWarning $ EmptyPrimitive r
Primitive _ ds' -> (,ds) <$> (map toPrim <$> niceAxioms PrimitiveBlock ds')
Module r erased x tel ds' -> return $
([NiceModule r PublicAccess ConcreteDef erased x tel ds'], ds)
ModuleMacro r erased x modapp op is -> return $
([NiceModuleMacro r PublicAccess erased x modapp op is], ds)
-- Fixity and syntax declarations and polarity pragmas have
-- already been processed.
Infix _ _ -> return ([], ds)
Syntax _ _ -> return ([], ds)
PatternSyn r n as p -> do
return ([NicePatternSyn r PublicAccess n as p] , ds)
Open r x is -> return ([NiceOpen r x is] , ds)
Import r x as op is -> return ([NiceImport r x as op is] , ds)
UnquoteDecl r xs e -> do
tc <- use terminationCheckPragma
cc <- use coverageCheckPragma
return ([NiceUnquoteDecl r PublicAccess ConcreteDef NotInstanceDef tc cc xs e] , ds)
UnquoteDef r xs e -> do
sigs <- map fst . loneFuns <$> use loneSigs
List1.ifNotNull (filter (`notElem` sigs) xs)
{-then-} (declarationException . UnquoteDefRequiresSignature)
{-else-} $ do
mapM_ removeLoneSig xs
return ([NiceUnquoteDef r PublicAccess ConcreteDef TerminationCheck YesCoverageCheck xs e] , ds)
UnquoteData r xs cs e -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
return ([NiceUnquoteData r PublicAccess ConcreteDef pc uc xs cs e], ds)
Pragma p -> nicePragma p ds
nicePragma :: Pragma -> [Declaration] -> Nice ([NiceDeclaration], [Declaration])
nicePragma (TerminationCheckPragma r (TerminationMeasure _ x)) ds =
if canHaveTerminationMeasure ds then
withTerminationCheckPragma (TerminationMeasure r x) $ nice1 ds
else do
declarationWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (TerminationCheckPragma r NoTerminationCheck) ds = do
This PRAGMA has been deprecated in favour of ( NON_)TERMINATING
-- We warn the user about it and then assume the function is NON_TERMINATING.
declarationWarning $ PragmaNoTerminationCheck r
nicePragma (TerminationCheckPragma r NonTerminating) ds
nicePragma (TerminationCheckPragma r tc) ds =
if canHaveTerminationCheckPragma ds then
withTerminationCheckPragma tc $ nice1 ds
else do
declarationWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (NoCoverageCheckPragma r) ds =
if canHaveCoverageCheckPragma ds then
withCoverageCheckPragma NoCoverageCheck $ nice1 ds
else do
declarationWarning $ InvalidCoverageCheckPragma r
nice1 ds
nicePragma (CatchallPragma r) ds =
if canHaveCatchallPragma ds then
withCatchallPragma True $ nice1 ds
else do
declarationWarning $ InvalidCatchallPragma r
nice1 ds
nicePragma (NoPositivityCheckPragma r) ds =
if canHaveNoPositivityCheckPragma ds then
withPositivityCheckPragma NoPositivityCheck $ nice1 ds
else do
declarationWarning $ InvalidNoPositivityCheckPragma r
nice1 ds
nicePragma (NoUniverseCheckPragma r) ds =
if canHaveNoUniverseCheckPragma ds then
withUniverseCheckPragma NoUniverseCheck $ nice1 ds
else do
declarationWarning $ InvalidNoUniverseCheckPragma r
nice1 ds
nicePragma p@CompilePragma{} ds = do
declarationWarning $ PragmaCompiled (getRange p)
return ([NicePragma (getRange p) p], ds)
nicePragma (PolarityPragma{}) ds = return ([], ds)
nicePragma (BuiltinPragma r str qn@(QName x)) ds = do
return ([NicePragma r (BuiltinPragma r str qn)], ds)
nicePragma p ds = return ([NicePragma (getRange p) p], ds)
canHaveTerminationMeasure :: [Declaration] -> Bool
canHaveTerminationMeasure [] = False
canHaveTerminationMeasure (d:ds) = case d of
TypeSig{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationMeasure ds
_ -> False
canHaveTerminationCheckPragma :: [Declaration] -> Bool
canHaveTerminationCheckPragma [] = False
canHaveTerminationCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveTerminationCheckPragma . singleton) ds
TypeSig{} -> True
FunClause{} -> True
UnquoteDecl{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationCheckPragma ds
_ -> False
canHaveCoverageCheckPragma :: [Declaration] -> Bool
canHaveCoverageCheckPragma = canHaveTerminationCheckPragma
canHaveCatchallPragma :: [Declaration] -> Bool
canHaveCatchallPragma [] = False
canHaveCatchallPragma (d:ds) = case d of
FunClause{} -> True
(Pragma p) | isAttachedPragma p -> canHaveCatchallPragma ds
_ -> False
canHaveNoPositivityCheckPragma :: [Declaration] -> Bool
canHaveNoPositivityCheckPragma [] = False
canHaveNoPositivityCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveNoPositivityCheckPragma . singleton) ds
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
canHaveNoUniverseCheckPragma :: [Declaration] -> Bool
canHaveNoUniverseCheckPragma [] = False
canHaveNoUniverseCheckPragma (d:ds) = case d of
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
Pragma that attaches to the following declaration .
isAttachedPragma :: Pragma -> Bool
isAttachedPragma = \case
TerminationCheckPragma{} -> True
CatchallPragma{} -> True
NoPositivityCheckPragma{} -> True
NoUniverseCheckPragma{} -> True
_ -> False
-- We could add a default type signature here, but at the moment we can't
-- infer the type of a record or datatype, so better to just fail here.
defaultTypeSig :: DataRecOrFun -> Name -> Maybe Expr -> Nice (Maybe Expr)
defaultTypeSig k x t@Just{} = return t
defaultTypeSig k x Nothing = do
caseMaybeM (getSig x) (return Nothing) $ \ k' -> do
unless (sameKind k k') $ declarationException $ WrongDefinition x k' k
Nothing <$ removeLoneSig x
dataOrRec
:: forall a decl
. PositivityCheck
-> UniverseCheck
-> (Range -> Origin -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> [decl] -> NiceDeclaration)
Construct definition .
-> (Range -> Access -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> Expr -> NiceDeclaration)
Construct signature .
-> ([a] -> Nice [decl]) -- Constructor checking.
-> Range
-> Name -- Data/record type name.
-> Maybe ([LamBinding], Expr) -- Parameters and type. If not @Nothing@ a signature is created.
-> Maybe ([LamBinding], [a]) -- Parameters and constructors. If not @Nothing@, a definition body is created.
-> Nice [NiceDeclaration]
dataOrRec pc uc mkDef mkSig niceD r x mt mcs = do
mds <- Trav.forM mcs $ \ (tel, cs) -> (tel,) <$> niceD cs
We set origin to UserWritten if the user split the data / rec herself ,
-- and to Inserted if the she wrote a single declaration that we're
-- splitting up here. We distinguish these because the scoping rules for
-- generalizable variables differ in these cases.
let o | isJust mt && isJust mcs = Inserted
| otherwise = UserWritten
return $ catMaybes $
[ mt <&> \ (tel, t) -> mkSig (fuseRange x t) PublicAccess ConcreteDef pc uc x tel t
, mds <&> \ (tel, ds) -> mkDef r o ConcreteDef pc uc x (caseMaybe mt tel $ const $ concatMap dropTypeAndModality tel) ds
If a type is given ( mt /= Nothing ) , we have to delete the types in @tel@
for the data definition , lest we duplicate them . And also drop modalities ( # 1886 ) .
]
Translate axioms
niceAxioms :: KindOfBlock -> [TypeSignatureOrInstanceBlock] -> Nice [NiceDeclaration]
niceAxioms b ds = List.concat <$> mapM (niceAxiom b) ds
niceAxiom :: KindOfBlock -> TypeSignatureOrInstanceBlock -> Nice [NiceDeclaration]
niceAxiom b = \case
d@(TypeSig rel _tac x t) -> do
return [ Axiom (getRange d) PublicAccess ConcreteDef NotInstanceDef rel x t ]
d@(FieldSig i tac x argt) | b == FieldBlock -> do
return [ NiceField (getRange d) PublicAccess ConcreteDef i tac x argt ]
InstanceB r decls -> do
instanceBlock r =<< niceAxioms InstanceBlock decls
Pragma p@(RewritePragma r _ _) -> do
return [ NicePragma r p ]
d -> declarationException $ WrongContentBlock b $ getRange d
toPrim :: NiceDeclaration -> NiceDeclaration
toPrim (Axiom r p a i rel x t) = PrimitiveFunction r p a x (Arg rel t)
toPrim _ = __IMPOSSIBLE__
-- Create a function definition.
mkFunDef info termCheck covCheck x mt ds0 = do
ds <- expandEllipsis ds0
cs <- mkClauses x ds False
return [ FunSig (fuseRange x t) PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t
, FunDef (getRange ds0) ds0 ConcreteDef NotInstanceDef termCheck covCheck x cs ]
where
t = fromMaybe (underscore (getRange x)) mt
underscore r = Underscore r Nothing
expandEllipsis :: [Declaration] -> Nice [Declaration]
expandEllipsis [] = return []
expandEllipsis (d@(FunClause lhs@(LHS p _ _) _ _ _) : ds)
| hasEllipsis p = (d :) <$> expandEllipsis ds
| otherwise = (d :) <$> expand (killRange p) ds
where
expand :: Pattern -> [Declaration] -> Nice [Declaration]
expand _ [] = return []
expand p (d : ds) = do
case d of
Pragma (CatchallPragma _) -> do
(d :) <$> expand p ds
FunClause (LHS p0 eqs es) rhs wh ca -> do
case hasEllipsis' p0 of
ManyHoles -> declarationException $ MultipleEllipses p0
OneHole cxt ~(EllipsisP r Nothing) -> do
Replace the ellipsis by @p@.
let p1 = cxt $ EllipsisP r $ Just $ setRange r p
let d' = FunClause (LHS p1 eqs es) rhs wh ca
-- If we have with-expressions (es /= []) then the following
-- ellipses also get the additional patterns in p0.
(d' :) <$> expand (if null es then p else killRange p1) ds
ZeroHoles _ -> do
-- We can have ellipses after a fun clause without.
-- They refer to the last clause that introduced new with-expressions.
-- Same here: If we have new with-expressions, the next ellipses will
-- refer to us.
Andreas , Jesper , 2017 - 05 - 13 , issue # 2578
-- Need to update the range also on the next with-patterns.
(d :) <$> expand (if null es then p else killRange p0) ds
_ -> __IMPOSSIBLE__
expandEllipsis _ = __IMPOSSIBLE__
-- Turn function clauses into nice function clauses.
mkClauses :: Name -> [Declaration] -> Catchall -> Nice [Clause]
mkClauses _ [] _ = return []
mkClauses x (Pragma (CatchallPragma r) : cs) True = do
declarationWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (Pragma (CatchallPragma r) : cs) False = do
when (null cs) $ declarationWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (FunClause lhs rhs wh ca : cs) catchall
| null (lhsWithExpr lhs) || hasEllipsis lhs =
(Clause x (ca || catchall) lhs rhs wh [] :) <$> mkClauses x cs False -- Will result in an error later.
mkClauses x (FunClause lhs rhs wh ca : cs) catchall = do
when (null withClauses) $ declarationException $ MissingWithClauses x lhs
wcs <- mkClauses x withClauses False
(Clause x (ca || catchall) lhs rhs wh wcs :) <$> mkClauses x cs' False
where
(withClauses, cs') = subClauses cs
-- A clause is a subclause if the number of with-patterns is
-- greater or equal to the current number of with-patterns plus the
-- number of with arguments.
numWith = numberOfWithPatterns p + length (filter visible es) where LHS p _ es = lhs
subClauses :: [Declaration] -> ([Declaration],[Declaration])
subClauses (c@(FunClause (LHS p0 _ _) _ _ _) : cs)
| isEllipsis p0 ||
numberOfWithPatterns p0 >= numWith = mapFst (c:) (subClauses cs)
| otherwise = ([], c:cs)
subClauses (c@(Pragma (CatchallPragma r)) : cs) = case subClauses cs of
([], cs') -> ([], c:cs')
(cs, cs') -> (c:cs, cs')
subClauses [] = ([],[])
subClauses _ = __IMPOSSIBLE__
mkClauses _ _ _ = __IMPOSSIBLE__
couldBeCallOf :: Maybe Fixity' -> Name -> Pattern -> Bool
couldBeCallOf mFixity x p =
let
pns = patternNames p
xStrings = nameStringParts x
patStrings = concatMap nameStringParts pns
in
-- trace ("x = " ++ prettyShow x) $
-- trace ("pns = " ++ show pns) $
trace ( " xStrings = " + + show xStrings ) $
trace ( " patStrings = " + + show ) $
-- trace ("mFixity = " ++ show mFixity) $
case (listToMaybe pns, mFixity) of
first identifier in the patterns is the fun.symbol ?
(Just y, _) | x == y -> True -- trace ("couldBe since y = " ++ prettyShow y) $ True
are the parts of x contained in p
_ | xStrings `isSublistOf` patStrings -> True -- trace ("couldBe since isSublistOf") $ True
-- looking for a mixfix fun.symb
(_, Just fix) -> -- also matches in case of a postfix
let notStrings = stringParts (theNotation fix)
trace ( " notStrings = " + + show ) $
trace ( " patStrings = " + + show ) $
not (null notStrings) && (notStrings `isSublistOf` patStrings)
-- not a notation, not first id: give up
_ -> False -- trace ("couldBe not (case default)") $ False
-- for finding nice clauses for a type sig in mutual blocks
couldBeNiceFunClauseOf :: Maybe Fixity' -> Name -> NiceDeclaration
-> Maybe (MutualChecks, Declaration)
couldBeNiceFunClauseOf mf n (NiceFunClause _ _ _ tc cc _ d)
= (MutualChecks [tc] [cc] [], d) <$ guard (couldBeFunClauseOf mf n d)
couldBeNiceFunClauseOf _ _ _ = Nothing
-- for finding clauses for a type sig in mutual blocks
couldBeFunClauseOf :: Maybe Fixity' -> Name -> Declaration -> Bool
couldBeFunClauseOf mFixity x (Pragma (CatchallPragma{})) = True
couldBeFunClauseOf mFixity x (FunClause (LHS p _ _) _ _ _) =
hasEllipsis p || couldBeCallOf mFixity x p
couldBeFunClauseOf _ _ _ = False -- trace ("couldBe not (fun default)") $ False
-- Turn a new style `interleaved mutual' block into a new style mutual block
-- by grouping the declarations in blocks.
mkInterleavedMutual
:: Range -- Range of the whole @mutual@ block.
-> [NiceDeclaration] -- Declarations inside the block.
-> Nice NiceDeclaration -- Returns a 'NiceMutual'.
mkInterleavedMutual r ds' = do
(other, (m, checks, _)) <- runStateT (groupByBlocks r ds') (empty, mempty, 0)
let idecls = other ++ concatMap (uncurry interleavedDecl) (Map.toList m)
let decls0 = map snd $ List.sortBy (compare `on` fst) idecls
ps <- use loneSigs
checkLoneSigs ps
let decls = replaceSigs ps decls0
-- process the checks
tc <- combineTerminationChecks r (mutualTermination checks)
let cc = combineCoverageChecks (mutualCoverage checks)
let pc = combinePositivityChecks (mutualPositivity checks)
pure $ NiceMutual r tc cc pc decls
where
------------------------------------------------------------------------------
-- Adding Signatures
addType :: Name -> (DeclNum -> a) -> MutualChecks
-> StateT (Map Name a, MutualChecks, DeclNum) Nice ()
addType n c mc = do
(m, checks, i) <- get
when (isJust $ Map.lookup n m) $ lift $ declarationException $ DuplicateDefinition n
put (Map.insert n (c i) m, mc <> checks, i+1)
addFunType d@(FunSig _ _ _ _ _ _ tc cc n _) = do
let checks = MutualChecks [tc] [cc] []
addType n (\ i -> InterleavedFun i d Nothing) checks
addFunType _ = __IMPOSSIBLE__
addDataType d@(NiceDataSig _ _ _ _ pc uc n _ _) = do
let checks = MutualChecks [] [] [pc]
addType n (\ i -> InterleavedData i d Nothing) checks
addDataType _ = __IMPOSSIBLE__
------------------------------------------------------------------------------
-- Adding constructors & clauses
addDataConstructors :: Maybe Range -- Range of the `data A where` (if any)
-> Maybe Name -- Data type the constructors belong to
-> [NiceConstructor] -- Constructors to add
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice ()
-- if we know the type's name, we can go ahead
addDataConstructors mr (Just n) ds = do
(m, checks, i) <- get
case Map.lookup n m of
Just (InterleavedData i0 sig cs) -> do
lift $ removeLoneSig n
-- add the constructors to the existing ones (if any)
let (cs', i') = case cs of
Nothing -> ((i , ds :| [] ), i+1)
Just (i1, ds1) -> ((i1, ds <| ds1), i)
put (Map.insert n (InterleavedData i0 sig (Just cs')) m, checks, i')
_ -> lift $ declarationWarning $ MissingDeclarations $ case mr of
Just r -> [(n, r)]
Nothing -> flip foldMap ds $ \case
Axiom r _ _ _ _ n _ -> [(n, r)]
_ -> __IMPOSSIBLE__
addDataConstructors mr Nothing [] = pure ()
-- Otherwise we try to guess which datasig the constructor is referring to
addDataConstructors mr Nothing (d : ds) = do
-- get the candidate data types that are in this interleaved mutual block
(m, _, _) <- get
let sigs = mapMaybe (\ (n, d) -> n <$ isInterleavedData d) $ Map.toList m
-- check whether this constructor matches any of them
case isConstructor sigs d of
Right n -> do
-- if so grab the whole block that may work and add them
let (ds0, ds1) = span (isRight . isConstructor [n]) ds
addDataConstructors Nothing (Just n) (d : ds0)
-- and then repeat the process for the rest of the block
addDataConstructors Nothing Nothing ds1
Left (n, ns) -> lift $ declarationException $ AmbiguousConstructor (getRange d) n ns
addFunDef :: NiceDeclaration -> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice ()
addFunDef (FunDef _ ds _ _ tc cc n cs) = do
let check = MutualChecks [tc] [cc] []
(m, checks, i) <- get
case Map.lookup n m of
Just (InterleavedFun i0 sig cs0) -> do
let (cs', i') = case cs0 of
Nothing -> ((i, (ds, cs) :| [] ), i+1)
Just (i1, cs1) -> ((i1, (ds, cs) <| cs1), i)
put (Map.insert n (InterleavedFun i0 sig (Just cs')) m, check <> checks, i')
A FunDef always come after an existing FunSig !
addFunDef _ = __IMPOSSIBLE__
addFunClauses :: Range -> [NiceDeclaration]
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice [(DeclNum, NiceDeclaration)]
addFunClauses r (nd@(NiceFunClause _ _ _ tc cc _ d@(FunClause lhs _ _ _)) : ds) = do
-- get the candidate functions that are in this interleaved mutual block
(m, checks, i) <- get
let sigs = mapMaybe (\ (n, d) -> n <$ isInterleavedFun d) $ Map.toList m
-- find the funsig candidates for the funclause of interest
case [ (x, fits, rest)
| x <- sigs
, let (fits, rest) = spanJust (couldBeNiceFunClauseOf (Map.lookup x fixs) x) (nd : ds)
, not (null fits)
] of
-- no candidate: keep the isolated fun clause, we'll complain about it later
[] -> do
let check = MutualChecks [tc] [cc] []
put (m, check <> checks, i+1)
((i,nd) :) <$> groupByBlocks r ds
exactly one candidate : attach the funclause to the definition
[(n, fits0, rest)] -> do
let (checkss, fits) = unzip fits0
ds <- lift $ expandEllipsis fits
cs <- lift $ mkClauses n ds False
case Map.lookup n m of
Just (InterleavedFun i0 sig cs0) -> do
let (cs', i') = case cs0 of
Nothing -> ((i, (fits,cs) :| [] ), i+1)
Just (i1, cs1) -> ((i1, (fits,cs) <| cs1), i)
let checks' = Fold.fold checkss
put (Map.insert n (InterleavedFun i0 sig (Just cs')) m, checks' <> checks, i')
_ -> __IMPOSSIBLE__
groupByBlocks r rest
more than one candidate : fail , complaining about the ambiguity !
xf:xfs -> lift $ declarationException
$ AmbiguousFunClauses lhs
$ List1.reverse $ fmap (\ (a,_,_) -> a) $ xf :| xfs
addFunClauses _ _ = __IMPOSSIBLE__
groupByBlocks :: Range -> [NiceDeclaration]
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice [(DeclNum, NiceDeclaration)]
groupByBlocks r [] = pure []
groupByBlocks r (d : ds) = do
for most branches we deal with the one declaration and move on
let oneOff act = act >>= \ ns -> (ns ++) <$> groupByBlocks r ds
case d of
NiceDataSig{} -> oneOff $ [] <$ addDataType d
NiceDataDef r _ _ _ _ n _ ds -> oneOff $ [] <$ addDataConstructors (Just r) (Just n) ds
NiceLoneConstructor r ds -> oneOff $ [] <$ addDataConstructors Nothing Nothing ds
FunSig{} -> oneOff $ [] <$ addFunType d
FunDef _ _ _ _ _ _ n cs
| not (isNoName n) -> oneOff $ [] <$ addFunDef d
-- It's a bit different for fun clauses because we may need to grab a lot
-- of clauses to handle ellipses properly.
NiceFunClause{} -> addFunClauses r (d:ds)
We do not need to worry about RecSig vs. RecDef : we know there 's exactly one
-- of each for record definitions and leaving them in place should be enough!
_ -> oneOff $ do
(m, c, i) <- get -- TODO: grab checks from c?
put (m, c, i+1)
pure [(i,d)]
-- Extract the name of the return type (if any) of a potential constructor.
-- In case of failure return the name of the constructor and the list of candidates
-- for the return type.
A ` constructor ' block should only contain NiceConstructors so we crash with
-- an IMPOSSIBLE otherwise
isConstructor :: [Name] -> NiceDeclaration -> Either (Name, [Name]) Name
isConstructor ns (Axiom _ _ _ _ _ n e)
extract the return type & see it as an LHS - style pattern
| Just p <- exprToPatternWithHoles <$> returnExpr e =
case [ x | x <- ns
, couldBeCallOf (Map.lookup x fixs) x p
] of
[x] -> Right x
xs -> Left (n, xs)
-- which may fail (e.g. if the "return type" is a hole
| otherwise = Left (n, [])
isConstructor _ _ = __IMPOSSIBLE__
-- Turn an old-style mutual block into a new style mutual block
-- by pushing the definitions to the end.
mkOldMutual
:: Range -- Range of the whole @mutual@ block.
-> [NiceDeclaration] -- Declarations inside the block.
-> Nice NiceDeclaration -- Returns a 'NiceMutual'.
mkOldMutual r ds' = do
-- Postulate the missing definitions
let ps = loneSigsFromLoneNames loneNames
checkLoneSigs ps
let ds = replaceSigs ps ds'
-- -- Remove the declarations that aren't allowed in old style mutual blocks
ds < - fmap $ forM ds $ \ d - > let success = pure ( Just d ) in case d of
-- , 2013 - 11 - 23 allow postulates in mutual blocks
Axiom { } - > success
-- , 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
-- in ConcreteToAbstract rather than here .
-- NiceFunClause{} -> success
-- , 2018 - 05 - 11 , issue # 3052 , allow pat.syn.s in mutual blocks
-- NicePatternSyn{} -> success
-- -- Otherwise, only categorized signatures and definitions are allowed:
-- -- Data, Record, Fun
-- _ -> if (declKind d /= OtherDecl) then success
-- else Nothing <$ declarationWarning (NotAllowedInMutual (getRange d) $ declName d)
-- Sort the declarations in the mutual block.
-- Declarations of names go to the top. (Includes module definitions.)
-- Definitions of names go to the bottom.
-- Some declarations are forbidden, as their positioning could confuse
-- the user.
(top, bottom, invalid) <- forEither3M ds $ \ d -> do
let top = return (In1 d)
bottom = return (In2 d)
invalid s = In3 d <$ do declarationWarning $ NotAllowedInMutual (getRange d) s
case d of
, 2013 - 11 - 23 allow postulates in mutual blocks
Axiom{} -> top
NiceField{} -> top
PrimitiveFunction{} -> top
, 2019 - 07 - 23 issue # 3932 :
-- Nested mutual blocks are not supported.
NiceMutual{} -> invalid "mutual blocks"
, 2018 - 10 - 29 , issue # 3246
-- We could allow modules (top), but this is potentially confusing.
NiceModule{} -> invalid "Module definitions"
-- Lone constructors are only allowed in new-style mutual blocks
NiceLoneConstructor{} -> invalid "Lone constructors"
NiceModuleMacro{} -> top
NiceOpen{} -> top
NiceImport{} -> top
NiceRecSig{} -> top
NiceDataSig{} -> top
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> bottom
FunSig{} -> top
FunDef{} -> bottom
NiceDataDef{} -> bottom
NiceRecDef{} -> bottom
, 2018 - 05 - 11 , issue # 3051 , allow pat.syn.s in mutual blocks
, 2018 - 10 - 29 : We shift pattern synonyms to the bottom
-- since they might refer to constructors defined in a data types
-- just above them.
NicePatternSyn{} -> bottom
NiceGeneralize{} -> top
NiceUnquoteDecl{} -> top
NiceUnquoteDef{} -> bottom
NiceUnquoteData{} -> top
NicePragma r pragma -> case pragma of
OptionsPragma{} -> top -- error thrown in the type checker
-- Some builtins require a definition, and they affect type checking
-- Thus, we do not handle BUILTINs in mutual blocks (at least for now).
BuiltinPragma{} -> invalid "BUILTIN pragmas"
-- The REWRITE pragma behaves differently before or after the def.
-- and affects type checking. Thus, we refuse it here.
RewritePragma{} -> invalid "REWRITE pragmas"
-- Compiler pragmas are not needed for type checking, thus,
-- can go to the bottom.
ForeignPragma{} -> bottom
CompilePragma{} -> bottom
StaticPragma{} -> bottom
InlinePragma{} -> bottom
NotProjectionLikePragma{} -> bottom
ImpossiblePragma{} -> top -- error thrown in scope checker
EtaPragma{} -> bottom -- needs record definition
WarningOnUsage{} -> top
WarningOnImport{} -> top
InjectivePragma{} -> top -- only needs name, not definition
DisplayPragma{} -> top -- only for printing
-- The attached pragmas have already been handled at this point.
CatchallPragma{} -> __IMPOSSIBLE__
TerminationCheckPragma{} -> __IMPOSSIBLE__
NoPositivityCheckPragma{} -> __IMPOSSIBLE__
PolarityPragma{} -> __IMPOSSIBLE__
NoUniverseCheckPragma{} -> __IMPOSSIBLE__
NoCoverageCheckPragma{} -> __IMPOSSIBLE__
-- -- Pull type signatures to the top
let ( sigs , other ) = List.partition isTypeSig ds
-- -- Push definitions to the bottom
let ( other , defs ) = flip List.partition ds $ \case
-- FunDef{} -> False
-- NiceDataDef{} -> False
-- NiceRecDef{} -> False
-- NiceFunClause{} -> False
-- NicePatternSyn{} -> False
-- NiceUnquoteDef{} -> False
-- _ -> True
-- Compute termination checking flag for mutual block
tc0 <- use terminationCheckPragma
let tcs = map termCheck ds
tc <- combineTerminationChecks r (tc0:tcs)
-- Compute coverage checking flag for mutual block
cc0 <- use coverageCheckPragma
let ccs = map covCheck ds
let cc = combineCoverageChecks (cc0:ccs)
-- Compute positivity checking flag for mutual block
pc0 <- use positivityCheckPragma
let pcs = map positivityCheckOldMutual ds
let pc = combinePositivityChecks (pc0:pcs)
return $ NiceMutual r tc cc pc $ top ++ bottom
-- return $ NiceMutual r tc pc $ other ++ defs
-- return $ NiceMutual r tc pc $ sigs ++ other
where
isTypeSig Axiom { } = True
isTypeSig d | { } < - declKind d = True
-- isTypeSig _ = False
sigNames = [ (r, x, k) | LoneSigDecl r k x <- map declKind ds' ]
defNames = [ (x, k) | LoneDefs k xs <- map declKind ds', x <- xs ]
-- compute the set difference with equality just on names
loneNames = [ (r, x, k) | (r, x, k) <- sigNames, List.all ((x /=) . fst) defNames ]
termCheck :: NiceDeclaration -> TerminationCheck
, 2013 - 02 - 28 ( issue 804 ):
-- do not termination check a mutual block if any of its
inner declarations comes with a { - # NO_TERMINATION_CHECK # - }
termCheck (FunSig _ _ _ _ _ _ tc _ _ _) = tc
termCheck (FunDef _ _ _ _ tc _ _ _) = tc
ASR ( 28 December 2015 ): Is this equation necessary ?
termCheck (NiceMutual _ tc _ _ _) = tc
termCheck (NiceUnquoteDecl _ _ _ _ tc _ _ _) = tc
termCheck (NiceUnquoteDef _ _ _ tc _ _ _) = tc
termCheck Axiom{} = TerminationCheck
termCheck NiceField{} = TerminationCheck
termCheck PrimitiveFunction{} = TerminationCheck
termCheck NiceModule{} = TerminationCheck
termCheck NiceModuleMacro{} = TerminationCheck
termCheck NiceOpen{} = TerminationCheck
termCheck NiceImport{} = TerminationCheck
termCheck NicePragma{} = TerminationCheck
termCheck NiceRecSig{} = TerminationCheck
termCheck NiceDataSig{} = TerminationCheck
termCheck NiceFunClause{} = TerminationCheck
termCheck NiceDataDef{} = TerminationCheck
termCheck NiceRecDef{} = TerminationCheck
termCheck NicePatternSyn{} = TerminationCheck
termCheck NiceGeneralize{} = TerminationCheck
termCheck NiceLoneConstructor{} = TerminationCheck
termCheck NiceUnquoteData{} = TerminationCheck
covCheck :: NiceDeclaration -> CoverageCheck
covCheck (FunSig _ _ _ _ _ _ _ cc _ _) = cc
covCheck (FunDef _ _ _ _ _ cc _ _) = cc
ASR ( 28 December 2015 ): Is this equation necessary ?
covCheck (NiceMutual _ _ cc _ _) = cc
covCheck (NiceUnquoteDecl _ _ _ _ _ cc _ _) = cc
covCheck (NiceUnquoteDef _ _ _ _ cc _ _) = cc
covCheck Axiom{} = YesCoverageCheck
covCheck NiceField{} = YesCoverageCheck
covCheck PrimitiveFunction{} = YesCoverageCheck
covCheck NiceModule{} = YesCoverageCheck
covCheck NiceModuleMacro{} = YesCoverageCheck
covCheck NiceOpen{} = YesCoverageCheck
covCheck NiceImport{} = YesCoverageCheck
covCheck NicePragma{} = YesCoverageCheck
covCheck NiceRecSig{} = YesCoverageCheck
covCheck NiceDataSig{} = YesCoverageCheck
covCheck NiceFunClause{} = YesCoverageCheck
covCheck NiceDataDef{} = YesCoverageCheck
covCheck NiceRecDef{} = YesCoverageCheck
covCheck NicePatternSyn{} = YesCoverageCheck
covCheck NiceGeneralize{} = YesCoverageCheck
covCheck NiceLoneConstructor{} = YesCoverageCheck
covCheck NiceUnquoteData{} = YesCoverageCheck
ASR ( 26 December 2015 ): Do not positivity check a mutual
-- block if any of its inner declarations comes with a
NO_POSITIVITY_CHECK pragma . See Issue 1614 .
positivityCheckOldMutual :: NiceDeclaration -> PositivityCheck
positivityCheckOldMutual (NiceDataDef _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceDataSig _ _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceMutual _ _ _ pc _) = pc
positivityCheckOldMutual (NiceRecSig _ _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceRecDef _ _ _ pc _ _ _ _ _) = pc
positivityCheckOldMutual _ = YesPositivityCheck
-- A mutual block cannot have a measure,
-- but it can skip termination check.
abstractBlock _ [] = return []
abstractBlock r ds = do
(ds', anyChange) <- runChangeT $ mkAbstract ds
let inherited = r == noRange
if anyChange then return ds' else do
-- hack to avoid failing on inherited abstract blocks in where clauses
unless inherited $ declarationWarning $ UselessAbstract r
return ds -- no change!
privateBlock _ _ [] = return []
privateBlock r o ds = do
(ds', anyChange) <- runChangeT $ mkPrivate o ds
if anyChange then return ds' else do
when (o == UserWritten) $ declarationWarning $ UselessPrivate r
return ds -- no change!
instanceBlock
:: Range -- Range of @instance@ keyword.
-> [NiceDeclaration]
-> Nice [NiceDeclaration]
instanceBlock _ [] = return []
instanceBlock r ds = do
let (ds', anyChange) = runChange $ mapM (mkInstance r) ds
if anyChange then return ds' else do
declarationWarning $ UselessInstance r
return ds -- no change!
-- Make a declaration eligible for instance search.
mkInstance
:: Range -- Range of @instance@ keyword.
-> Updater NiceDeclaration
mkInstance r0 = \case
Axiom r p a i rel x e -> (\ i -> Axiom r p a i rel x e) <$> setInstance r0 i
FunSig r p a i m rel tc cc x e -> (\ i -> FunSig r p a i m rel tc cc x e) <$> setInstance r0 i
NiceUnquoteDecl r p a i tc cc x e -> (\ i -> NiceUnquoteDecl r p a i tc cc x e) <$> setInstance r0 i
NiceMutual r tc cc pc ds -> NiceMutual r tc cc pc <$> mapM (mkInstance r0) ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mapM (mkInstance r0) ds
d@NiceFunClause{} -> return d
FunDef r ds a i tc cc x cs -> (\ i -> FunDef r ds a i tc cc x cs) <$> setInstance r0 i
Field instance are handled by the parser
d@PrimitiveFunction{} -> return d
d@NiceUnquoteDef{} -> return d
d@NiceRecSig{} -> return d
d@NiceDataSig{} -> return d
d@NiceModuleMacro{} -> return d
d@NiceModule{} -> return d
d@NicePragma{} -> return d
d@NiceOpen{} -> return d
d@NiceImport{} -> return d
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
d@NiceUnquoteData{} -> return d
setInstance
:: Range -- Range of @instance@ keyword.
-> Updater IsInstance
setInstance r0 = \case
i@InstanceDef{} -> return i
_ -> dirty $ InstanceDef r0
macroBlock r ds = mapM mkMacro ds
mkMacro :: NiceDeclaration -> Nice NiceDeclaration
mkMacro = \case
FunSig r p a i _ rel tc cc x e -> return $ FunSig r p a i MacroDef rel tc cc x e
d@FunDef{} -> return d
d -> declarationException (BadMacroDef d)
-- | Make a declaration abstract.
--
-- Mark computation as 'dirty' if there was a declaration that could be made abstract.
If no abstraction is taking place , we want to complain about ' UselessAbstract ' .
--
-- Alternatively, we could only flag 'dirty' if a non-abstract thing was abstracted.
-- Then, nested @abstract@s would sometimes also be complained about.
class MakeAbstract a where
mkAbstract :: UpdaterT Nice a
default mkAbstract :: (Traversable f, MakeAbstract a', a ~ f a') => UpdaterT Nice a
mkAbstract = traverse mkAbstract
instance MakeAbstract a => MakeAbstract [a]
Leads to overlap with ' WhereClause ' :
instance ( f , MakeAbstract a ) = > MakeAbstract ( f a ) where
-- mkAbstract = traverse mkAbstract
instance MakeAbstract IsAbstract where
mkAbstract = \case
a@AbstractDef -> return a
ConcreteDef -> dirty $ AbstractDef
instance MakeAbstract NiceDeclaration where
mkAbstract = \case
NiceMutual r termCheck cc pc ds -> NiceMutual r termCheck cc pc <$> mkAbstract ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mkAbstract ds
FunDef r ds a i tc cc x cs -> (\ a -> FunDef r ds a i tc cc x) <$> mkAbstract a <*> mkAbstract cs
NiceDataDef r o a pc uc x ps cs -> (\ a -> NiceDataDef r o a pc uc x ps) <$> mkAbstract a <*> mkAbstract cs
NiceRecDef r o a pc uc x dir ps cs -> (\ a -> NiceRecDef r o a pc uc x dir ps cs) <$> mkAbstract a
NiceFunClause r p a tc cc catchall d -> (\ a -> NiceFunClause r p a tc cc catchall d) <$> mkAbstract a
-- The following declarations have an @InAbstract@ field
-- but are not really definitions, so we do count them into
-- the declarations which can be made abstract
( thus , do not notify progress with @dirty@ ) .
Axiom r p a i rel x e -> return $ Axiom r p AbstractDef i rel x e
FunSig r p a i m rel tc cc x e -> return $ FunSig r p AbstractDef i m rel tc cc x e
NiceRecSig r er p a pc uc x ls t -> return $ NiceRecSig r er p AbstractDef pc uc x ls t
NiceDataSig r er p a pc uc x ls t -> return $ NiceDataSig r er p AbstractDef pc uc x ls t
NiceField r p _ i tac x e -> return $ NiceField r p AbstractDef i tac x e
PrimitiveFunction r p _ x e -> return $ PrimitiveFunction r p AbstractDef x e
, 2016 - 07 - 17 it does have effect on unquoted defs .
-- Need to set updater state to dirty!
NiceUnquoteDecl r p _ i tc cc x e -> tellDirty $> NiceUnquoteDecl r p AbstractDef i tc cc x e
NiceUnquoteDef r p _ tc cc x e -> tellDirty $> NiceUnquoteDef r p AbstractDef tc cc x e
NiceUnquoteData r p _ tc cc x xs e -> tellDirty $> NiceUnquoteData r p AbstractDef tc cc x xs e
d@NiceModule{} -> return d
d@NiceModuleMacro{} -> return d
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . declarationWarning . OpenPublicAbstract
return d
d@NiceImport{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
instance MakeAbstract Clause where
mkAbstract (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkAbstract wh <*> mkAbstract with
-- | Contents of a @where@ clause are abstract if the parent is.
instance MakeAbstract WhereClause where
mkAbstract NoWhere = return $ NoWhere
mkAbstract (AnyWhere r ds) = dirty $ AnyWhere r
[Abstract noRange ds]
mkAbstract (SomeWhere r e m a ds) = dirty $ SomeWhere r e m a
[Abstract noRange ds]
-- | Make a declaration private.
--
, 2012 - 11 - 17 :
-- Mark computation as 'dirty' if there was a declaration that could be privatized.
-- If no privatization is taking place, we want to complain about 'UselessPrivate'.
--
-- Alternatively, we could only flag 'dirty' if a non-private thing was privatized.
Then , nested would sometimes also be complained about .
class MakePrivate a where
mkPrivate :: Origin -> UpdaterT Nice a
default mkPrivate :: (Traversable f, MakePrivate a', a ~ f a') => Origin -> UpdaterT Nice a
mkPrivate o = traverse $ mkPrivate o
instance MakePrivate a => MakePrivate [a]
Leads to overlap with ' WhereClause ' :
instance ( f , MakePrivate a ) = > MakePrivate ( f a ) where
mkPrivate = traverse mkPrivate
instance MakePrivate Access where
mkPrivate o = \case
OR ? return o
_ -> dirty $ PrivateAccess o
instance MakePrivate NiceDeclaration where
mkPrivate o = \case
Axiom r p a i rel x e -> (\ p -> Axiom r p a i rel x e) <$> mkPrivate o p
NiceField r p a i tac x e -> (\ p -> NiceField r p a i tac x e) <$> mkPrivate o p
PrimitiveFunction r p a x e -> (\ p -> PrimitiveFunction r p a x e) <$> mkPrivate o p
NiceMutual r tc cc pc ds -> (\ ds-> NiceMutual r tc cc pc ds) <$> mkPrivate o ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mkPrivate o ds
NiceModule r p a e x tel ds -> (\ p -> NiceModule r p a e x tel ds) <$> mkPrivate o p
NiceModuleMacro r p e x ma op is -> (\ p -> NiceModuleMacro r p e x ma op is) <$> mkPrivate o p
FunSig r p a i m rel tc cc x e -> (\ p -> FunSig r p a i m rel tc cc x e) <$> mkPrivate o p
NiceRecSig r er p a pc uc x ls t -> (\ p -> NiceRecSig r er p a pc uc x ls t) <$> mkPrivate o p
NiceDataSig r er p a pc uc x ls t -> (\ p -> NiceDataSig r er p a pc uc x ls t) <$> mkPrivate o p
NiceFunClause r p a tc cc catchall d -> (\ p -> NiceFunClause r p a tc cc catchall d) <$> mkPrivate o p
NiceUnquoteDecl r p a i tc cc x e -> (\ p -> NiceUnquoteDecl r p a i tc cc x e) <$> mkPrivate o p
NiceUnquoteDef r p a tc cc x e -> (\ p -> NiceUnquoteDef r p a tc cc x e) <$> mkPrivate o p
NicePatternSyn r p x xs p' -> (\ p -> NicePatternSyn r p x xs p') <$> mkPrivate o p
NiceGeneralize r p i tac x t -> (\ p -> NiceGeneralize r p i tac x t) <$> mkPrivate o p
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . declarationWarning . OpenPublicPrivate
return d
d@NiceImport{} -> return d
, 2016 - 07 - 08 , issue # 2089
-- we need to propagate 'private' to the named where modules
FunDef r ds a i tc cc x cls -> FunDef r ds a i tc cc x <$> mkPrivate o cls
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NiceUnquoteData{} -> return d
instance MakePrivate Clause where
mkPrivate o (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkPrivate o wh <*> mkPrivate o with
instance MakePrivate WhereClause where
mkPrivate o = \case
d@NoWhere -> return d
-- @where@-declarations are protected behind an anonymous module,
-- thus, they are effectively private by default.
d@AnyWhere{} -> return d
, 2016 - 07 - 08
A @where@-module is private if the parent function is private .
-- The contents of this module are not private, unless declared so!
Thus , we do not recurse into the @ds@ ( could not anyway ) .
SomeWhere r e m a ds ->
mkPrivate o a <&> \a' -> SomeWhere r e m a' ds
The following function is ( at the time of writing ) only used three
-- times: for building Lets, and for printing error messages.
| ( Approximately ) convert a ' NiceDeclaration ' back to a list of
' Declaration 's .
notSoNiceDeclarations :: NiceDeclaration -> [Declaration]
notSoNiceDeclarations = \case
Axiom _ _ _ i rel x e -> inst i [TypeSig rel Nothing x e]
NiceField _ _ _ i tac x argt -> [FieldSig i tac x argt]
PrimitiveFunction r _ _ x e -> [Primitive r [TypeSig (argInfo e) Nothing x (unArg e)]]
NiceMutual r _ _ _ ds -> [Mutual r $ concatMap notSoNiceDeclarations ds]
NiceLoneConstructor r ds -> [LoneConstructor r $ concatMap notSoNiceDeclarations ds]
NiceModule r _ _ e x tel ds -> [Module r e x tel ds]
NiceModuleMacro r _ e x ma o dir
-> [ModuleMacro r e x ma o dir]
NiceOpen r x dir -> [Open r x dir]
NiceImport r x as o dir -> [Import r x as o dir]
NicePragma _ p -> [Pragma p]
NiceRecSig r er _ _ _ _ x bs e -> [RecordSig r er x bs e]
NiceDataSig r er _ _ _ _ x bs e -> [DataSig r er x bs e]
NiceFunClause _ _ _ _ _ _ d -> [d]
FunSig _ _ _ i _ rel _ _ x e -> inst i [TypeSig rel Nothing x e]
FunDef _ ds _ _ _ _ _ _ -> ds
NiceDataDef r _ _ _ _ x bs cs -> [DataDef r x bs $ concatMap notSoNiceDeclarations cs]
NiceRecDef r _ _ _ _ x dir bs ds -> [RecordDef r x dir bs ds]
NicePatternSyn r _ n as p -> [PatternSyn r n as p]
NiceGeneralize r _ i tac n e -> [Generalize r [TypeSig i tac n e]]
NiceUnquoteDecl r _ _ i _ _ x e -> inst i [UnquoteDecl r x e]
NiceUnquoteDef r _ _ _ _ x e -> [UnquoteDef r x e]
NiceUnquoteData r _ _ _ _ x xs e -> [UnquoteData r x xs e]
where
inst (InstanceDef r) ds = [InstanceB r ds]
inst NotInstanceDef ds = ds
| Has the ' NiceDeclaration ' a field of type ' IsAbstract ' ?
niceHasAbstract :: NiceDeclaration -> Maybe IsAbstract
niceHasAbstract = \case
Axiom{} -> Nothing
NiceField _ _ a _ _ _ _ -> Just a
PrimitiveFunction _ _ a _ _ -> Just a
NiceMutual{} -> Nothing
NiceLoneConstructor{} -> Nothing
NiceModule _ _ a _ _ _ _ -> Just a
NiceModuleMacro{} -> Nothing
NiceOpen{} -> Nothing
NiceImport{} -> Nothing
NicePragma{} -> Nothing
NiceRecSig{} -> Nothing
NiceDataSig{} -> Nothing
NiceFunClause _ _ a _ _ _ _ -> Just a
FunSig{} -> Nothing
FunDef _ _ a _ _ _ _ _ -> Just a
NiceDataDef _ _ a _ _ _ _ _ -> Just a
NiceRecDef _ _ a _ _ _ _ _ _ -> Just a
NicePatternSyn{} -> Nothing
NiceGeneralize{} -> Nothing
NiceUnquoteDecl _ _ a _ _ _ _ _ -> Just a
NiceUnquoteDef _ _ a _ _ _ _ -> Just a
NiceUnquoteData _ _ a _ _ _ _ _ -> Just a
| null | https://raw.githubusercontent.com/agda/agda/c71e83595629789b963fa5a8a1c42180f05a6956/src/full/Agda/Syntax/Concrete/Definitions.hs | haskell | # LANGUAGE GADTs #
* Attach fixity and syntax declarations to the definition they refer to.
* Distribute the following attributes to the individual definitions:
@abstract@,
@instance@,
@postulate@,
@primitive@,
@private@,
termination pragmas.
* Expand ellipsis @...@ in function clauses following @with@.
* Infer mutual blocks.
A block starts when a lone signature is encountered, and ends when
all lone signatures have seen their definition.
* Handle interleaved mutual blocks.
In an `interleaved mutual' block we:
* leave the data and fun sigs in place
* classify signatures in `constructor' block based on their return type
and group them all as a data def at the position in the block where the
* classify fun clauses based on the declared function used and group them
clause appeared
* Report basic well-formedness error,
When possible, errors should be deferred to the scope checking phase
informative error messages.
instance only
-------------------------------------------------------------------------
The niceifier
-------------------------------------------------------------------------
| Check that declarations in a mutual block are consistently
equipped with MEASURE pragmas, or whether there is a
NO_TERMINATION_CHECK pragma.
^ Declarations containing them
^ In the output, everything should be defined
If declaration d of x is mentioned in the map of lone signatures then replace
it with an axiom
This could happen if the user wrote a duplicate definition.
A @replaceable@ declaration is a signature. It has a name and we can make an
@Axiom@ out of it.
#4881: Don't use the unique NameId for NoName lookups.
grouping function clauses.
Run the nicifier in an initial environment. But keep the warnings.
Check that every signature got its definition.
Note that loneSigs is ensured to be empty.
(Important, since inferMutualBlocks also uses loneSigs state).
Restore the old state, but keep the warnings.
If we still have lone signatures without any accompanying definition,
we postulate the definition and substitute the axiom for the lone signature
We then keep processing the rest of the block
NOTE: This is the location of the invoker of justWarning, not here.
since parser expands type signatures with several identifiers
(like @x y z : A@) into several type signatures (with imprecise ranges).
register x as lone type signature, to recognize clauses later
Warn about @variable {x} : A@ which is equivalent to @variable x : A@.
for each type signature 'x' waiting for clauses, we try
if we have some clauses for 'x'
Treat it as a function clause without a type signature.
fun def without type signature is relevant
This could be a let-pattern binding. Pass it on.
The x'@NoName{} is the unique version of x@NoName{}.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
Propagate {-# NO_UNIVERSE_CHECK #-} pragma from signature to definition.
'universeCheckPragma' AND the one from the signature say so.
The lone signatures encountered so far are not in scope
for the mutual definition
The lone signatures encountered so far are not in scope
for the mutual definition
Fixity and syntax declarations and polarity pragmas have
already been processed.
then
else
We warn the user about it and then assume the function is NON_TERMINATING.
We could add a default type signature here, but at the moment we can't
infer the type of a record or datatype, so better to just fail here.
Constructor checking.
Data/record type name.
Parameters and type. If not @Nothing@ a signature is created.
Parameters and constructors. If not @Nothing@, a definition body is created.
and to Inserted if the she wrote a single declaration that we're
splitting up here. We distinguish these because the scoping rules for
generalizable variables differ in these cases.
Create a function definition.
If we have with-expressions (es /= []) then the following
ellipses also get the additional patterns in p0.
We can have ellipses after a fun clause without.
They refer to the last clause that introduced new with-expressions.
Same here: If we have new with-expressions, the next ellipses will
refer to us.
Need to update the range also on the next with-patterns.
Turn function clauses into nice function clauses.
Will result in an error later.
A clause is a subclause if the number of with-patterns is
greater or equal to the current number of with-patterns plus the
number of with arguments.
trace ("x = " ++ prettyShow x) $
trace ("pns = " ++ show pns) $
trace ("mFixity = " ++ show mFixity) $
trace ("couldBe since y = " ++ prettyShow y) $ True
trace ("couldBe since isSublistOf") $ True
looking for a mixfix fun.symb
also matches in case of a postfix
not a notation, not first id: give up
trace ("couldBe not (case default)") $ False
for finding nice clauses for a type sig in mutual blocks
for finding clauses for a type sig in mutual blocks
trace ("couldBe not (fun default)") $ False
Turn a new style `interleaved mutual' block into a new style mutual block
by grouping the declarations in blocks.
Range of the whole @mutual@ block.
Declarations inside the block.
Returns a 'NiceMutual'.
process the checks
----------------------------------------------------------------------------
Adding Signatures
----------------------------------------------------------------------------
Adding constructors & clauses
Range of the `data A where` (if any)
Data type the constructors belong to
Constructors to add
if we know the type's name, we can go ahead
add the constructors to the existing ones (if any)
Otherwise we try to guess which datasig the constructor is referring to
get the candidate data types that are in this interleaved mutual block
check whether this constructor matches any of them
if so grab the whole block that may work and add them
and then repeat the process for the rest of the block
get the candidate functions that are in this interleaved mutual block
find the funsig candidates for the funclause of interest
no candidate: keep the isolated fun clause, we'll complain about it later
It's a bit different for fun clauses because we may need to grab a lot
of clauses to handle ellipses properly.
of each for record definitions and leaving them in place should be enough!
TODO: grab checks from c?
Extract the name of the return type (if any) of a potential constructor.
In case of failure return the name of the constructor and the list of candidates
for the return type.
an IMPOSSIBLE otherwise
which may fail (e.g. if the "return type" is a hole
Turn an old-style mutual block into a new style mutual block
by pushing the definitions to the end.
Range of the whole @mutual@ block.
Declarations inside the block.
Returns a 'NiceMutual'.
Postulate the missing definitions
-- Remove the declarations that aren't allowed in old style mutual blocks
, 2013 - 11 - 23 allow postulates in mutual blocks
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> success
, 2018 - 05 - 11 , issue # 3052 , allow pat.syn.s in mutual blocks
NicePatternSyn{} -> success
-- Otherwise, only categorized signatures and definitions are allowed:
-- Data, Record, Fun
_ -> if (declKind d /= OtherDecl) then success
else Nothing <$ declarationWarning (NotAllowedInMutual (getRange d) $ declName d)
Sort the declarations in the mutual block.
Declarations of names go to the top. (Includes module definitions.)
Definitions of names go to the bottom.
Some declarations are forbidden, as their positioning could confuse
the user.
Nested mutual blocks are not supported.
We could allow modules (top), but this is potentially confusing.
Lone constructors are only allowed in new-style mutual blocks
since they might refer to constructors defined in a data types
just above them.
error thrown in the type checker
Some builtins require a definition, and they affect type checking
Thus, we do not handle BUILTINs in mutual blocks (at least for now).
The REWRITE pragma behaves differently before or after the def.
and affects type checking. Thus, we refuse it here.
Compiler pragmas are not needed for type checking, thus,
can go to the bottom.
error thrown in scope checker
needs record definition
only needs name, not definition
only for printing
The attached pragmas have already been handled at this point.
-- Pull type signatures to the top
-- Push definitions to the bottom
FunDef{} -> False
NiceDataDef{} -> False
NiceRecDef{} -> False
NiceFunClause{} -> False
NicePatternSyn{} -> False
NiceUnquoteDef{} -> False
_ -> True
Compute termination checking flag for mutual block
Compute coverage checking flag for mutual block
Compute positivity checking flag for mutual block
return $ NiceMutual r tc pc $ other ++ defs
return $ NiceMutual r tc pc $ sigs ++ other
isTypeSig _ = False
compute the set difference with equality just on names
do not termination check a mutual block if any of its
block if any of its inner declarations comes with a
A mutual block cannot have a measure,
but it can skip termination check.
hack to avoid failing on inherited abstract blocks in where clauses
no change!
no change!
Range of @instance@ keyword.
no change!
Make a declaration eligible for instance search.
Range of @instance@ keyword.
Range of @instance@ keyword.
| Make a declaration abstract.
Mark computation as 'dirty' if there was a declaration that could be made abstract.
Alternatively, we could only flag 'dirty' if a non-abstract thing was abstracted.
Then, nested @abstract@s would sometimes also be complained about.
mkAbstract = traverse mkAbstract
The following declarations have an @InAbstract@ field
but are not really definitions, so we do count them into
the declarations which can be made abstract
Need to set updater state to dirty!
| Contents of a @where@ clause are abstract if the parent is.
| Make a declaration private.
Mark computation as 'dirty' if there was a declaration that could be privatized.
If no privatization is taking place, we want to complain about 'UselessPrivate'.
Alternatively, we could only flag 'dirty' if a non-private thing was privatized.
we need to propagate 'private' to the named where modules
@where@-declarations are protected behind an anonymous module,
thus, they are effectively private by default.
The contents of this module are not private, unless declared so!
times: for building Lets, and for printing error messages. |
| Preprocess ' Agda . Syntax . Concrete . Declaration 's , producing ' NiceDeclaration 's .
* Gather the function clauses belonging to one function definition .
first constructor for the data sig in question occured
all as a fundef at the position in the block where the first such fun
when one of the above transformation fails .
( ConcreteToAbstract ) , where we are in the TCM and can produce more
module Agda.Syntax.Concrete.Definitions
( NiceDeclaration(..)
, NiceConstructor, NiceTypeSignature
, Clause(..)
, DeclarationException(..)
, DeclarationWarning(..), DeclarationWarning'(..), unsafeDeclarationWarning
, Nice, runNice
, niceDeclarations
, notSoNiceDeclarations
, niceHasAbstract
, Measure
, declarationWarningName
) where
import Prelude hiding (null)
import Control.Monad ( forM, guard, unless, void, when )
import Control.Monad.Except ( )
import Control.Monad.State ( MonadState(..), gets, StateT, runStateT )
import Control.Monad.Trans ( lift )
import Data.Bifunctor
import Data.Either (isLeft, isRight)
import Data.Function (on)
import qualified Data.Map as Map
import Data.Map (Map)
import Data.Maybe
import Data.Semigroup ( Semigroup(..) )
import qualified Data.List as List
import qualified Data.Foldable as Fold
import qualified Data.Traversable as Trav
import Agda.Syntax.Concrete
import Agda.Syntax.Concrete.Pattern
import Agda.Syntax.Common hiding (TerminationCheck())
import qualified Agda.Syntax.Common as Common
import Agda.Syntax.Position
import Agda.Syntax.Notation
import Agda.Syntax.Concrete.Fixity
import Agda.Syntax.Concrete.Definitions.Errors
import Agda.Syntax.Concrete.Definitions.Monad
import Agda.Syntax.Concrete.Definitions.Types
import Agda.Interaction.Options.Warnings
import Agda.Utils.AffineHole
import Agda.Utils.CallStack ( CallStack, HasCallStack, withCallerCallStack )
import Agda.Utils.Functor
import Agda.Utils.Lens
import Agda.Utils.List (isSublistOf, spanJust)
import Agda.Utils.List1 (List1, pattern (:|), (<|))
import qualified Agda.Utils.List1 as List1
import Agda.Utils.Maybe
import Agda.Utils.Null
import Agda.Utils.Pretty
import Agda.Utils.Singleton
import Agda.Utils.Three
import Agda.Utils.Tuple
import Agda.Utils.Update
import Agda.Utils.Impossible
combineTerminationChecks :: Range -> [TerminationCheck] -> Nice TerminationCheck
combineTerminationChecks r tcs = loop tcs where
loop :: [TerminationCheck] -> Nice TerminationCheck
loop [] = return TerminationCheck
loop (tc : tcs) = do
let failure r = declarationException $ InvalidMeasureMutual r
tc' <- loop tcs
case (tc, tc') of
(TerminationCheck , tc' ) -> return tc'
(tc , TerminationCheck ) -> return tc
(NonTerminating , NonTerminating ) -> return NonTerminating
(NoTerminationCheck , NoTerminationCheck ) -> return NoTerminationCheck
(NoTerminationCheck , Terminating ) -> return Terminating
(Terminating , NoTerminationCheck ) -> return Terminating
(Terminating , Terminating ) -> return Terminating
(TerminationMeasure{} , TerminationMeasure{} ) -> return tc
(TerminationMeasure r _, NoTerminationCheck ) -> failure r
(TerminationMeasure r _, Terminating ) -> failure r
(NoTerminationCheck , TerminationMeasure r _) -> failure r
(Terminating , TerminationMeasure r _) -> failure r
(TerminationMeasure r _, NonTerminating ) -> failure r
(NonTerminating , TerminationMeasure r _) -> failure r
(NoTerminationCheck , NonTerminating ) -> failure r
(Terminating , NonTerminating ) -> failure r
(NonTerminating , NoTerminationCheck ) -> failure r
(NonTerminating , Terminating ) -> failure r
combineCoverageChecks :: [CoverageCheck] -> CoverageCheck
combineCoverageChecks = Fold.fold
combinePositivityChecks :: [PositivityCheck] -> PositivityCheck
combinePositivityChecks = Fold.fold
data DeclKind
= LoneSigDecl Range DataRecOrFun Name
| LoneDefs DataRecOrFun [Name]
| OtherDecl
deriving (Eq, Show)
declKind :: NiceDeclaration -> DeclKind
declKind (FunSig r _ _ _ _ _ tc cc x _) = LoneSigDecl r (FunName tc cc) x
declKind (NiceRecSig r _ _ _ pc uc x _ _) = LoneSigDecl r (RecName pc uc) x
declKind (NiceDataSig r _ _ _ pc uc x _ _) = LoneSigDecl r (DataName pc uc) x
declKind (FunDef r _ abs ins tc cc x _) = LoneDefs (FunName tc cc) [x]
declKind (NiceDataDef _ _ _ pc uc x pars _) = LoneDefs (DataName pc uc) [x]
declKind (NiceUnquoteData _ _ _ pc uc x _ _) = LoneDefs (DataName pc uc) [x]
declKind (NiceRecDef _ _ _ pc uc x _ pars _) = LoneDefs (RecName pc uc) [x]
declKind (NiceUnquoteDef _ _ _ tc cc xs _) = LoneDefs (FunName tc cc) xs
declKind Axiom{} = OtherDecl
declKind NiceField{} = OtherDecl
declKind PrimitiveFunction{} = OtherDecl
declKind NiceMutual{} = OtherDecl
declKind NiceModule{} = OtherDecl
declKind NiceModuleMacro{} = OtherDecl
declKind NiceOpen{} = OtherDecl
declKind NiceImport{} = OtherDecl
declKind NicePragma{} = OtherDecl
declKind NiceFunClause{} = OtherDecl
declKind NicePatternSyn{} = OtherDecl
declKind NiceGeneralize{} = OtherDecl
declKind NiceUnquoteDecl{} = OtherDecl
declKind NiceLoneConstructor{} = OtherDecl
| Replace ( Data / Rec / Fun)Sigs with Axioms for postulated names
The first argument is a list of axioms only .
replaceSigs
^ Lone signatures to be turned into Axioms
replaceSigs ps = if Map.null ps then id else \case
[] -> __IMPOSSIBLE__
(d:ds) ->
case replaceable d of
Just (x, axiom)
| (Just (LoneSig _ x' _), ps') <- Map.updateLookupWithKey (\ _ _ -> Nothing) x ps
, getRange x == getRange x'
Use the range as UID to ensure we do not replace the wrong signature .
-> axiom : replaceSigs ps' ds
_ -> d : replaceSigs ps ds
where
replaceable :: NiceDeclaration -> Maybe (Name, NiceDeclaration)
replaceable = \case
FunSig r acc abst inst _ argi _ _ x' e ->
let x = if isNoName x' then noName (nameRange x') else x' in
Just (x, Axiom r acc abst inst argi x' e)
NiceRecSig r erased acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef
(setQuantity (asQuantity erased) defaultArgInfo) x e)
NiceDataSig r erased acc abst _ _ x pars t ->
let e = Generalized $ makePi (lamBindingsToTelescope r pars) t in
Just (x, Axiom r acc abst NotInstanceDef
(setQuantity (asQuantity erased) defaultArgInfo) x e)
_ -> Nothing
| Main . ( or more precisely syntax declarations ) are needed when
niceDeclarations :: Fixities -> [Declaration] -> Nice [NiceDeclaration]
niceDeclarations fixs ds = do
st <- get
put $ initNiceEnv { niceWarn = niceWarn st }
nds <- nice ds
ps <- use loneSigs
checkLoneSigs ps
We postulate the missing ones and insert them in place of the corresponding
let ds = replaceSigs ps nds
res <- inferMutualBlocks ds
warns <- gets niceWarn
put $ st { niceWarn = warns }
return res
where
inferMutualBlocks :: [NiceDeclaration] -> Nice [NiceDeclaration]
inferMutualBlocks [] = return []
inferMutualBlocks (d : ds) =
case declKind d of
OtherDecl -> (d :) <$> inferMutualBlocks ds
, 2017 - 10 - 09 , issue # 2576 : report error in ConcreteToAbstract
LoneSigDecl r k x -> do
_ <- addLoneSig r x k
InferredMutual checks nds0 ds1 <- untilAllDefined (mutualChecks k) ds
ps <- use loneSigs
checkLoneSigs ps
NB : do n't forget the LoneSig the block started with !
tc <- combineTerminationChecks (getRange d) (mutualTermination checks)
let cc = combineCoverageChecks (mutualCoverage checks)
let pc = combinePositivityChecks (mutualPositivity checks)
(NiceMutual (getRange ds0) tc cc pc ds0 :) <$> inferMutualBlocks ds1
where
untilAllDefined :: MutualChecks -> [NiceDeclaration] -> Nice InferredMutual
untilAllDefined checks ds = do
done <- noLoneSigs
if done then return (InferredMutual checks [] ds) else
case ds of
[] -> return (InferredMutual checks [] ds)
d : ds -> case declKind d of
LoneSigDecl r k x -> do
void $ addLoneSig r x k
extendInferredBlock d <$> untilAllDefined (mutualChecks k <> checks) ds
LoneDefs k xs -> do
mapM_ removeLoneSig xs
extendInferredBlock d <$> untilAllDefined (mutualChecks k <> checks) ds
OtherDecl -> extendInferredBlock d <$> untilAllDefined checks ds
nice :: [Declaration] -> Nice [NiceDeclaration]
nice [] = return []
nice ds = do
(xs , ys) <- nice1 ds
(xs ++) <$> nice ys
nice1 :: [Declaration] -> Nice ([NiceDeclaration], [Declaration])
, 2017 - 09 - 16 , issue # 2759 : no longer _ _ IMPOSSIBLE _ _
nice1 (d:ds) = do
let justWarning :: HasCallStack => DeclarationWarning' -> Nice ([NiceDeclaration], [Declaration])
justWarning w = do
withCallerCallStack $ declarationWarning' w
nice1 ds
case d of
TypeSig info _tac x t -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
, 2020 - 09 - 28 , issue # 4950 : take only range of identifier ,
let r = getRange x
x' <- addLoneSig r x $ FunName termCheck covCheck
return ([FunSig r PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x' t] , ds)
Should not show up : all FieldSig are part of a Field block
FieldSig{} -> __IMPOSSIBLE__
Generalize r [] -> justWarning $ EmptyGeneralize r
Generalize r sigs -> do
gs <- forM sigs $ \case
sig@(TypeSig info tac x t) -> do
, 2022 - 03 - 25 , issue # 5850 :
when (getHiding info == Hidden) $
declarationWarning $ HiddenGeneralize $ getRange x
return $ NiceGeneralize (getRange sig) PublicAccess info tac x t
_ -> __IMPOSSIBLE__
return (gs, ds)
(FunClause lhs _ _ _) -> do
termCheck <- use terminationCheckPragma
covCheck <- use coverageCheckPragma
catchall <- popCatchallPragma
xs <- loneFuns <$> use loneSigs
case [ (x, (x', fits, rest))
| (x, x') <- xs
, let (fits, rest) =
Anonymous declarations only have 1 clause each !
if isNoName x then ([d], ds)
else span (couldBeFunClauseOf (Map.lookup x fixs) x) (d : ds)
, not (null fits)
] of
case : clauses match none of the sigs
[] -> case lhs of
Subcase : The lhs is single identifier ( potentially anonymous ) .
LHS p [] [] | Just x <- isSingleIdentifierP p -> do
return (d , ds)
Subcase : The lhs is a proper pattern .
A missing type signature error might be raise in ConcreteToAbstract
_ -> do
return ([NiceFunClause (getRange d) PublicAccess ConcreteDef termCheck covCheck catchall d] , ds)
case : clauses match exactly one of the sigs
[(x,(x',fits,rest))] -> do
removeLoneSig x
ds <- expandEllipsis fits
cs <- mkClauses x' ds False
return ([FunDef (getRange fits) fits ConcreteDef NotInstanceDef termCheck covCheck x' cs] , rest)
case : clauses match more than one sigs ( ambiguity )
xf:xfs -> declarationException $ AmbiguousFunClauses lhs $ List1.reverse $ fmap fst $ xf :| xfs
" ambiguous function clause ; can not assign it uniquely to one type signature "
Field r [] -> justWarning $ EmptyField r
Field _ fs -> (,ds) <$> niceAxioms FieldBlock fs
DataSig r erased x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
_ <- addLoneSig r x $ DataName pc uc
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig erased) (niceAxioms DataBlock) r
x (Just (tel, t)) Nothing
Data r erased x tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x (Just t)
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig erased) (niceAxioms DataBlock) r
x ((tel,) <$> mt) (Just (tel, cs))
DataDef r x tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (DataName pc uc) x Nothing
(,ds) <$> dataOrRec pc uc NiceDataDef
(flip NiceDataSig defaultErased)
(niceAxioms DataBlock) r x ((tel,) <$> mt)
(Just (tel, cs))
RecordSig r erased x tel t -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
_ <- addLoneSig r x $ RecName pc uc
return ( [NiceRecSig r erased PublicAccess ConcreteDef pc uc x
tel t]
, ds
)
Record r erased x dir tel t cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x (Just t)
(,ds) <$> dataOrRec pc uc
(\r o a pc uc x tel cs ->
NiceRecDef r o a pc uc x dir tel cs)
(flip NiceRecSig erased) return r x
((tel,) <$> mt) (Just (tel, cs))
RecordDef r x dir tel cs -> do
pc <- use positivityCheckPragma
, 2018 - 10 - 27 , issue # 3327
Universe check is performed if both the current value of
uc <- use universeCheckPragma
uc <- if uc == NoUniverseCheck then return uc else getUniverseCheckFromSig x
mt <- defaultTypeSig (RecName pc uc) x Nothing
(,ds) <$> dataOrRec pc uc
(\r o a pc uc x tel cs ->
NiceRecDef r o a pc uc x dir tel cs)
(flip NiceRecSig defaultErased) return r x
((tel,) <$> mt) (Just (tel, cs))
RecordDirective r -> justWarning $ InvalidRecordDirective (getRange r)
Mutual r ds' -> do
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkOldMutual r =<< nice ds'))
InterleavedMutual r ds' -> do
forgetLoneSigs
case ds' of
[] -> justWarning $ EmptyMutual r
_ -> (,ds) <$> (singleton <$> (mkInterleavedMutual r =<< nice ds'))
LoneConstructor r [] -> justWarning $ EmptyConstructor r
LoneConstructor r ds' ->
((,ds) . singleton . NiceLoneConstructor r) <$> niceAxioms ConstructorBlock ds'
Abstract r [] -> justWarning $ EmptyAbstract r
Abstract r ds' ->
(,ds) <$> (abstractBlock r =<< nice ds')
Private r UserWritten [] -> justWarning $ EmptyPrivate r
Private r o ds' ->
(,ds) <$> (privateBlock r o =<< nice ds')
InstanceB r [] -> justWarning $ EmptyInstance r
InstanceB r ds' ->
(,ds) <$> (instanceBlock r =<< nice ds')
Macro r [] -> justWarning $ EmptyMacro r
Macro r ds' ->
(,ds) <$> (macroBlock r =<< nice ds')
Postulate r [] -> justWarning $ EmptyPostulate r
Postulate _ ds' ->
(,ds) <$> niceAxioms PostulateBlock ds'
Primitive r [] -> justWarning $ EmptyPrimitive r
Primitive _ ds' -> (,ds) <$> (map toPrim <$> niceAxioms PrimitiveBlock ds')
Module r erased x tel ds' -> return $
([NiceModule r PublicAccess ConcreteDef erased x tel ds'], ds)
ModuleMacro r erased x modapp op is -> return $
([NiceModuleMacro r PublicAccess erased x modapp op is], ds)
Infix _ _ -> return ([], ds)
Syntax _ _ -> return ([], ds)
PatternSyn r n as p -> do
return ([NicePatternSyn r PublicAccess n as p] , ds)
Open r x is -> return ([NiceOpen r x is] , ds)
Import r x as op is -> return ([NiceImport r x as op is] , ds)
UnquoteDecl r xs e -> do
tc <- use terminationCheckPragma
cc <- use coverageCheckPragma
return ([NiceUnquoteDecl r PublicAccess ConcreteDef NotInstanceDef tc cc xs e] , ds)
UnquoteDef r xs e -> do
sigs <- map fst . loneFuns <$> use loneSigs
List1.ifNotNull (filter (`notElem` sigs) xs)
mapM_ removeLoneSig xs
return ([NiceUnquoteDef r PublicAccess ConcreteDef TerminationCheck YesCoverageCheck xs e] , ds)
UnquoteData r xs cs e -> do
pc <- use positivityCheckPragma
uc <- use universeCheckPragma
return ([NiceUnquoteData r PublicAccess ConcreteDef pc uc xs cs e], ds)
Pragma p -> nicePragma p ds
nicePragma :: Pragma -> [Declaration] -> Nice ([NiceDeclaration], [Declaration])
nicePragma (TerminationCheckPragma r (TerminationMeasure _ x)) ds =
if canHaveTerminationMeasure ds then
withTerminationCheckPragma (TerminationMeasure r x) $ nice1 ds
else do
declarationWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (TerminationCheckPragma r NoTerminationCheck) ds = do
This PRAGMA has been deprecated in favour of ( NON_)TERMINATING
declarationWarning $ PragmaNoTerminationCheck r
nicePragma (TerminationCheckPragma r NonTerminating) ds
nicePragma (TerminationCheckPragma r tc) ds =
if canHaveTerminationCheckPragma ds then
withTerminationCheckPragma tc $ nice1 ds
else do
declarationWarning $ InvalidTerminationCheckPragma r
nice1 ds
nicePragma (NoCoverageCheckPragma r) ds =
if canHaveCoverageCheckPragma ds then
withCoverageCheckPragma NoCoverageCheck $ nice1 ds
else do
declarationWarning $ InvalidCoverageCheckPragma r
nice1 ds
nicePragma (CatchallPragma r) ds =
if canHaveCatchallPragma ds then
withCatchallPragma True $ nice1 ds
else do
declarationWarning $ InvalidCatchallPragma r
nice1 ds
nicePragma (NoPositivityCheckPragma r) ds =
if canHaveNoPositivityCheckPragma ds then
withPositivityCheckPragma NoPositivityCheck $ nice1 ds
else do
declarationWarning $ InvalidNoPositivityCheckPragma r
nice1 ds
nicePragma (NoUniverseCheckPragma r) ds =
if canHaveNoUniverseCheckPragma ds then
withUniverseCheckPragma NoUniverseCheck $ nice1 ds
else do
declarationWarning $ InvalidNoUniverseCheckPragma r
nice1 ds
nicePragma p@CompilePragma{} ds = do
declarationWarning $ PragmaCompiled (getRange p)
return ([NicePragma (getRange p) p], ds)
nicePragma (PolarityPragma{}) ds = return ([], ds)
nicePragma (BuiltinPragma r str qn@(QName x)) ds = do
return ([NicePragma r (BuiltinPragma r str qn)], ds)
nicePragma p ds = return ([NicePragma (getRange p) p], ds)
canHaveTerminationMeasure :: [Declaration] -> Bool
canHaveTerminationMeasure [] = False
canHaveTerminationMeasure (d:ds) = case d of
TypeSig{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationMeasure ds
_ -> False
canHaveTerminationCheckPragma :: [Declaration] -> Bool
canHaveTerminationCheckPragma [] = False
canHaveTerminationCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveTerminationCheckPragma . singleton) ds
TypeSig{} -> True
FunClause{} -> True
UnquoteDecl{} -> True
(Pragma p) | isAttachedPragma p -> canHaveTerminationCheckPragma ds
_ -> False
canHaveCoverageCheckPragma :: [Declaration] -> Bool
canHaveCoverageCheckPragma = canHaveTerminationCheckPragma
canHaveCatchallPragma :: [Declaration] -> Bool
canHaveCatchallPragma [] = False
canHaveCatchallPragma (d:ds) = case d of
FunClause{} -> True
(Pragma p) | isAttachedPragma p -> canHaveCatchallPragma ds
_ -> False
canHaveNoPositivityCheckPragma :: [Declaration] -> Bool
canHaveNoPositivityCheckPragma [] = False
canHaveNoPositivityCheckPragma (d:ds) = case d of
Mutual _ ds -> any (canHaveNoPositivityCheckPragma . singleton) ds
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
canHaveNoUniverseCheckPragma :: [Declaration] -> Bool
canHaveNoUniverseCheckPragma [] = False
canHaveNoUniverseCheckPragma (d:ds) = case d of
Data{} -> True
DataSig{} -> True
DataDef{} -> True
Record{} -> True
RecordSig{} -> True
RecordDef{} -> True
Pragma p | isAttachedPragma p -> canHaveNoPositivityCheckPragma ds
_ -> False
Pragma that attaches to the following declaration .
isAttachedPragma :: Pragma -> Bool
isAttachedPragma = \case
TerminationCheckPragma{} -> True
CatchallPragma{} -> True
NoPositivityCheckPragma{} -> True
NoUniverseCheckPragma{} -> True
_ -> False
defaultTypeSig :: DataRecOrFun -> Name -> Maybe Expr -> Nice (Maybe Expr)
defaultTypeSig k x t@Just{} = return t
defaultTypeSig k x Nothing = do
caseMaybeM (getSig x) (return Nothing) $ \ k' -> do
unless (sameKind k k') $ declarationException $ WrongDefinition x k' k
Nothing <$ removeLoneSig x
dataOrRec
:: forall a decl
. PositivityCheck
-> UniverseCheck
-> (Range -> Origin -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> [decl] -> NiceDeclaration)
Construct definition .
-> (Range -> Access -> IsAbstract -> PositivityCheck -> UniverseCheck -> Name -> [LamBinding] -> Expr -> NiceDeclaration)
Construct signature .
-> Range
-> Nice [NiceDeclaration]
dataOrRec pc uc mkDef mkSig niceD r x mt mcs = do
mds <- Trav.forM mcs $ \ (tel, cs) -> (tel,) <$> niceD cs
We set origin to UserWritten if the user split the data / rec herself ,
let o | isJust mt && isJust mcs = Inserted
| otherwise = UserWritten
return $ catMaybes $
[ mt <&> \ (tel, t) -> mkSig (fuseRange x t) PublicAccess ConcreteDef pc uc x tel t
, mds <&> \ (tel, ds) -> mkDef r o ConcreteDef pc uc x (caseMaybe mt tel $ const $ concatMap dropTypeAndModality tel) ds
If a type is given ( mt /= Nothing ) , we have to delete the types in @tel@
for the data definition , lest we duplicate them . And also drop modalities ( # 1886 ) .
]
Translate axioms
niceAxioms :: KindOfBlock -> [TypeSignatureOrInstanceBlock] -> Nice [NiceDeclaration]
niceAxioms b ds = List.concat <$> mapM (niceAxiom b) ds
niceAxiom :: KindOfBlock -> TypeSignatureOrInstanceBlock -> Nice [NiceDeclaration]
niceAxiom b = \case
d@(TypeSig rel _tac x t) -> do
return [ Axiom (getRange d) PublicAccess ConcreteDef NotInstanceDef rel x t ]
d@(FieldSig i tac x argt) | b == FieldBlock -> do
return [ NiceField (getRange d) PublicAccess ConcreteDef i tac x argt ]
InstanceB r decls -> do
instanceBlock r =<< niceAxioms InstanceBlock decls
Pragma p@(RewritePragma r _ _) -> do
return [ NicePragma r p ]
d -> declarationException $ WrongContentBlock b $ getRange d
toPrim :: NiceDeclaration -> NiceDeclaration
toPrim (Axiom r p a i rel x t) = PrimitiveFunction r p a x (Arg rel t)
toPrim _ = __IMPOSSIBLE__
mkFunDef info termCheck covCheck x mt ds0 = do
ds <- expandEllipsis ds0
cs <- mkClauses x ds False
return [ FunSig (fuseRange x t) PublicAccess ConcreteDef NotInstanceDef NotMacroDef info termCheck covCheck x t
, FunDef (getRange ds0) ds0 ConcreteDef NotInstanceDef termCheck covCheck x cs ]
where
t = fromMaybe (underscore (getRange x)) mt
underscore r = Underscore r Nothing
expandEllipsis :: [Declaration] -> Nice [Declaration]
expandEllipsis [] = return []
expandEllipsis (d@(FunClause lhs@(LHS p _ _) _ _ _) : ds)
| hasEllipsis p = (d :) <$> expandEllipsis ds
| otherwise = (d :) <$> expand (killRange p) ds
where
expand :: Pattern -> [Declaration] -> Nice [Declaration]
expand _ [] = return []
expand p (d : ds) = do
case d of
Pragma (CatchallPragma _) -> do
(d :) <$> expand p ds
FunClause (LHS p0 eqs es) rhs wh ca -> do
case hasEllipsis' p0 of
ManyHoles -> declarationException $ MultipleEllipses p0
OneHole cxt ~(EllipsisP r Nothing) -> do
Replace the ellipsis by @p@.
let p1 = cxt $ EllipsisP r $ Just $ setRange r p
let d' = FunClause (LHS p1 eqs es) rhs wh ca
(d' :) <$> expand (if null es then p else killRange p1) ds
ZeroHoles _ -> do
Andreas , Jesper , 2017 - 05 - 13 , issue # 2578
(d :) <$> expand (if null es then p else killRange p0) ds
_ -> __IMPOSSIBLE__
expandEllipsis _ = __IMPOSSIBLE__
mkClauses :: Name -> [Declaration] -> Catchall -> Nice [Clause]
mkClauses _ [] _ = return []
mkClauses x (Pragma (CatchallPragma r) : cs) True = do
declarationWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (Pragma (CatchallPragma r) : cs) False = do
when (null cs) $ declarationWarning $ InvalidCatchallPragma r
mkClauses x cs True
mkClauses x (FunClause lhs rhs wh ca : cs) catchall
| null (lhsWithExpr lhs) || hasEllipsis lhs =
mkClauses x (FunClause lhs rhs wh ca : cs) catchall = do
when (null withClauses) $ declarationException $ MissingWithClauses x lhs
wcs <- mkClauses x withClauses False
(Clause x (ca || catchall) lhs rhs wh wcs :) <$> mkClauses x cs' False
where
(withClauses, cs') = subClauses cs
numWith = numberOfWithPatterns p + length (filter visible es) where LHS p _ es = lhs
subClauses :: [Declaration] -> ([Declaration],[Declaration])
subClauses (c@(FunClause (LHS p0 _ _) _ _ _) : cs)
| isEllipsis p0 ||
numberOfWithPatterns p0 >= numWith = mapFst (c:) (subClauses cs)
| otherwise = ([], c:cs)
subClauses (c@(Pragma (CatchallPragma r)) : cs) = case subClauses cs of
([], cs') -> ([], c:cs')
(cs, cs') -> (c:cs, cs')
subClauses [] = ([],[])
subClauses _ = __IMPOSSIBLE__
mkClauses _ _ _ = __IMPOSSIBLE__
couldBeCallOf :: Maybe Fixity' -> Name -> Pattern -> Bool
couldBeCallOf mFixity x p =
let
pns = patternNames p
xStrings = nameStringParts x
patStrings = concatMap nameStringParts pns
in
trace ( " xStrings = " + + show xStrings ) $
trace ( " patStrings = " + + show ) $
case (listToMaybe pns, mFixity) of
first identifier in the patterns is the fun.symbol ?
are the parts of x contained in p
let notStrings = stringParts (theNotation fix)
trace ( " notStrings = " + + show ) $
trace ( " patStrings = " + + show ) $
not (null notStrings) && (notStrings `isSublistOf` patStrings)
couldBeNiceFunClauseOf :: Maybe Fixity' -> Name -> NiceDeclaration
-> Maybe (MutualChecks, Declaration)
couldBeNiceFunClauseOf mf n (NiceFunClause _ _ _ tc cc _ d)
= (MutualChecks [tc] [cc] [], d) <$ guard (couldBeFunClauseOf mf n d)
couldBeNiceFunClauseOf _ _ _ = Nothing
couldBeFunClauseOf :: Maybe Fixity' -> Name -> Declaration -> Bool
couldBeFunClauseOf mFixity x (Pragma (CatchallPragma{})) = True
couldBeFunClauseOf mFixity x (FunClause (LHS p _ _) _ _ _) =
hasEllipsis p || couldBeCallOf mFixity x p
mkInterleavedMutual
mkInterleavedMutual r ds' = do
(other, (m, checks, _)) <- runStateT (groupByBlocks r ds') (empty, mempty, 0)
let idecls = other ++ concatMap (uncurry interleavedDecl) (Map.toList m)
let decls0 = map snd $ List.sortBy (compare `on` fst) idecls
ps <- use loneSigs
checkLoneSigs ps
let decls = replaceSigs ps decls0
tc <- combineTerminationChecks r (mutualTermination checks)
let cc = combineCoverageChecks (mutualCoverage checks)
let pc = combinePositivityChecks (mutualPositivity checks)
pure $ NiceMutual r tc cc pc decls
where
addType :: Name -> (DeclNum -> a) -> MutualChecks
-> StateT (Map Name a, MutualChecks, DeclNum) Nice ()
addType n c mc = do
(m, checks, i) <- get
when (isJust $ Map.lookup n m) $ lift $ declarationException $ DuplicateDefinition n
put (Map.insert n (c i) m, mc <> checks, i+1)
addFunType d@(FunSig _ _ _ _ _ _ tc cc n _) = do
let checks = MutualChecks [tc] [cc] []
addType n (\ i -> InterleavedFun i d Nothing) checks
addFunType _ = __IMPOSSIBLE__
addDataType d@(NiceDataSig _ _ _ _ pc uc n _ _) = do
let checks = MutualChecks [] [] [pc]
addType n (\ i -> InterleavedData i d Nothing) checks
addDataType _ = __IMPOSSIBLE__
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice ()
addDataConstructors mr (Just n) ds = do
(m, checks, i) <- get
case Map.lookup n m of
Just (InterleavedData i0 sig cs) -> do
lift $ removeLoneSig n
let (cs', i') = case cs of
Nothing -> ((i , ds :| [] ), i+1)
Just (i1, ds1) -> ((i1, ds <| ds1), i)
put (Map.insert n (InterleavedData i0 sig (Just cs')) m, checks, i')
_ -> lift $ declarationWarning $ MissingDeclarations $ case mr of
Just r -> [(n, r)]
Nothing -> flip foldMap ds $ \case
Axiom r _ _ _ _ n _ -> [(n, r)]
_ -> __IMPOSSIBLE__
addDataConstructors mr Nothing [] = pure ()
addDataConstructors mr Nothing (d : ds) = do
(m, _, _) <- get
let sigs = mapMaybe (\ (n, d) -> n <$ isInterleavedData d) $ Map.toList m
case isConstructor sigs d of
Right n -> do
let (ds0, ds1) = span (isRight . isConstructor [n]) ds
addDataConstructors Nothing (Just n) (d : ds0)
addDataConstructors Nothing Nothing ds1
Left (n, ns) -> lift $ declarationException $ AmbiguousConstructor (getRange d) n ns
addFunDef :: NiceDeclaration -> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice ()
addFunDef (FunDef _ ds _ _ tc cc n cs) = do
let check = MutualChecks [tc] [cc] []
(m, checks, i) <- get
case Map.lookup n m of
Just (InterleavedFun i0 sig cs0) -> do
let (cs', i') = case cs0 of
Nothing -> ((i, (ds, cs) :| [] ), i+1)
Just (i1, cs1) -> ((i1, (ds, cs) <| cs1), i)
put (Map.insert n (InterleavedFun i0 sig (Just cs')) m, check <> checks, i')
A FunDef always come after an existing FunSig !
addFunDef _ = __IMPOSSIBLE__
addFunClauses :: Range -> [NiceDeclaration]
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice [(DeclNum, NiceDeclaration)]
addFunClauses r (nd@(NiceFunClause _ _ _ tc cc _ d@(FunClause lhs _ _ _)) : ds) = do
(m, checks, i) <- get
let sigs = mapMaybe (\ (n, d) -> n <$ isInterleavedFun d) $ Map.toList m
case [ (x, fits, rest)
| x <- sigs
, let (fits, rest) = spanJust (couldBeNiceFunClauseOf (Map.lookup x fixs) x) (nd : ds)
, not (null fits)
] of
[] -> do
let check = MutualChecks [tc] [cc] []
put (m, check <> checks, i+1)
((i,nd) :) <$> groupByBlocks r ds
exactly one candidate : attach the funclause to the definition
[(n, fits0, rest)] -> do
let (checkss, fits) = unzip fits0
ds <- lift $ expandEllipsis fits
cs <- lift $ mkClauses n ds False
case Map.lookup n m of
Just (InterleavedFun i0 sig cs0) -> do
let (cs', i') = case cs0 of
Nothing -> ((i, (fits,cs) :| [] ), i+1)
Just (i1, cs1) -> ((i1, (fits,cs) <| cs1), i)
let checks' = Fold.fold checkss
put (Map.insert n (InterleavedFun i0 sig (Just cs')) m, checks' <> checks, i')
_ -> __IMPOSSIBLE__
groupByBlocks r rest
more than one candidate : fail , complaining about the ambiguity !
xf:xfs -> lift $ declarationException
$ AmbiguousFunClauses lhs
$ List1.reverse $ fmap (\ (a,_,_) -> a) $ xf :| xfs
addFunClauses _ _ = __IMPOSSIBLE__
groupByBlocks :: Range -> [NiceDeclaration]
-> StateT (InterleavedMutual, MutualChecks, DeclNum) Nice [(DeclNum, NiceDeclaration)]
groupByBlocks r [] = pure []
groupByBlocks r (d : ds) = do
for most branches we deal with the one declaration and move on
let oneOff act = act >>= \ ns -> (ns ++) <$> groupByBlocks r ds
case d of
NiceDataSig{} -> oneOff $ [] <$ addDataType d
NiceDataDef r _ _ _ _ n _ ds -> oneOff $ [] <$ addDataConstructors (Just r) (Just n) ds
NiceLoneConstructor r ds -> oneOff $ [] <$ addDataConstructors Nothing Nothing ds
FunSig{} -> oneOff $ [] <$ addFunType d
FunDef _ _ _ _ _ _ n cs
| not (isNoName n) -> oneOff $ [] <$ addFunDef d
NiceFunClause{} -> addFunClauses r (d:ds)
We do not need to worry about RecSig vs. RecDef : we know there 's exactly one
_ -> oneOff $ do
put (m, c, i+1)
pure [(i,d)]
A ` constructor ' block should only contain NiceConstructors so we crash with
isConstructor :: [Name] -> NiceDeclaration -> Either (Name, [Name]) Name
isConstructor ns (Axiom _ _ _ _ _ n e)
extract the return type & see it as an LHS - style pattern
| Just p <- exprToPatternWithHoles <$> returnExpr e =
case [ x | x <- ns
, couldBeCallOf (Map.lookup x fixs) x p
] of
[x] -> Right x
xs -> Left (n, xs)
| otherwise = Left (n, [])
isConstructor _ _ = __IMPOSSIBLE__
mkOldMutual
mkOldMutual r ds' = do
let ps = loneSigsFromLoneNames loneNames
checkLoneSigs ps
let ds = replaceSigs ps ds'
ds < - fmap $ forM ds $ \ d - > let success = pure ( Just d ) in case d of
Axiom { } - > success
(top, bottom, invalid) <- forEither3M ds $ \ d -> do
let top = return (In1 d)
bottom = return (In2 d)
invalid s = In3 d <$ do declarationWarning $ NotAllowedInMutual (getRange d) s
case d of
, 2013 - 11 - 23 allow postulates in mutual blocks
Axiom{} -> top
NiceField{} -> top
PrimitiveFunction{} -> top
, 2019 - 07 - 23 issue # 3932 :
NiceMutual{} -> invalid "mutual blocks"
, 2018 - 10 - 29 , issue # 3246
NiceModule{} -> invalid "Module definitions"
NiceLoneConstructor{} -> invalid "Lone constructors"
NiceModuleMacro{} -> top
NiceOpen{} -> top
NiceImport{} -> top
NiceRecSig{} -> top
NiceDataSig{} -> top
, 2017 - 10 - 09 , issue # 2576 , raise error about missing type signature
in ConcreteToAbstract rather than here .
NiceFunClause{} -> bottom
FunSig{} -> top
FunDef{} -> bottom
NiceDataDef{} -> bottom
NiceRecDef{} -> bottom
, 2018 - 05 - 11 , issue # 3051 , allow pat.syn.s in mutual blocks
, 2018 - 10 - 29 : We shift pattern synonyms to the bottom
NicePatternSyn{} -> bottom
NiceGeneralize{} -> top
NiceUnquoteDecl{} -> top
NiceUnquoteDef{} -> bottom
NiceUnquoteData{} -> top
NicePragma r pragma -> case pragma of
BuiltinPragma{} -> invalid "BUILTIN pragmas"
RewritePragma{} -> invalid "REWRITE pragmas"
ForeignPragma{} -> bottom
CompilePragma{} -> bottom
StaticPragma{} -> bottom
InlinePragma{} -> bottom
NotProjectionLikePragma{} -> bottom
WarningOnUsage{} -> top
WarningOnImport{} -> top
CatchallPragma{} -> __IMPOSSIBLE__
TerminationCheckPragma{} -> __IMPOSSIBLE__
NoPositivityCheckPragma{} -> __IMPOSSIBLE__
PolarityPragma{} -> __IMPOSSIBLE__
NoUniverseCheckPragma{} -> __IMPOSSIBLE__
NoCoverageCheckPragma{} -> __IMPOSSIBLE__
let ( sigs , other ) = List.partition isTypeSig ds
let ( other , defs ) = flip List.partition ds $ \case
tc0 <- use terminationCheckPragma
let tcs = map termCheck ds
tc <- combineTerminationChecks r (tc0:tcs)
cc0 <- use coverageCheckPragma
let ccs = map covCheck ds
let cc = combineCoverageChecks (cc0:ccs)
pc0 <- use positivityCheckPragma
let pcs = map positivityCheckOldMutual ds
let pc = combinePositivityChecks (pc0:pcs)
return $ NiceMutual r tc cc pc $ top ++ bottom
where
isTypeSig Axiom { } = True
isTypeSig d | { } < - declKind d = True
sigNames = [ (r, x, k) | LoneSigDecl r k x <- map declKind ds' ]
defNames = [ (x, k) | LoneDefs k xs <- map declKind ds', x <- xs ]
loneNames = [ (r, x, k) | (r, x, k) <- sigNames, List.all ((x /=) . fst) defNames ]
termCheck :: NiceDeclaration -> TerminationCheck
, 2013 - 02 - 28 ( issue 804 ):
inner declarations comes with a { - # NO_TERMINATION_CHECK # - }
termCheck (FunSig _ _ _ _ _ _ tc _ _ _) = tc
termCheck (FunDef _ _ _ _ tc _ _ _) = tc
ASR ( 28 December 2015 ): Is this equation necessary ?
termCheck (NiceMutual _ tc _ _ _) = tc
termCheck (NiceUnquoteDecl _ _ _ _ tc _ _ _) = tc
termCheck (NiceUnquoteDef _ _ _ tc _ _ _) = tc
termCheck Axiom{} = TerminationCheck
termCheck NiceField{} = TerminationCheck
termCheck PrimitiveFunction{} = TerminationCheck
termCheck NiceModule{} = TerminationCheck
termCheck NiceModuleMacro{} = TerminationCheck
termCheck NiceOpen{} = TerminationCheck
termCheck NiceImport{} = TerminationCheck
termCheck NicePragma{} = TerminationCheck
termCheck NiceRecSig{} = TerminationCheck
termCheck NiceDataSig{} = TerminationCheck
termCheck NiceFunClause{} = TerminationCheck
termCheck NiceDataDef{} = TerminationCheck
termCheck NiceRecDef{} = TerminationCheck
termCheck NicePatternSyn{} = TerminationCheck
termCheck NiceGeneralize{} = TerminationCheck
termCheck NiceLoneConstructor{} = TerminationCheck
termCheck NiceUnquoteData{} = TerminationCheck
covCheck :: NiceDeclaration -> CoverageCheck
covCheck (FunSig _ _ _ _ _ _ _ cc _ _) = cc
covCheck (FunDef _ _ _ _ _ cc _ _) = cc
ASR ( 28 December 2015 ): Is this equation necessary ?
covCheck (NiceMutual _ _ cc _ _) = cc
covCheck (NiceUnquoteDecl _ _ _ _ _ cc _ _) = cc
covCheck (NiceUnquoteDef _ _ _ _ cc _ _) = cc
covCheck Axiom{} = YesCoverageCheck
covCheck NiceField{} = YesCoverageCheck
covCheck PrimitiveFunction{} = YesCoverageCheck
covCheck NiceModule{} = YesCoverageCheck
covCheck NiceModuleMacro{} = YesCoverageCheck
covCheck NiceOpen{} = YesCoverageCheck
covCheck NiceImport{} = YesCoverageCheck
covCheck NicePragma{} = YesCoverageCheck
covCheck NiceRecSig{} = YesCoverageCheck
covCheck NiceDataSig{} = YesCoverageCheck
covCheck NiceFunClause{} = YesCoverageCheck
covCheck NiceDataDef{} = YesCoverageCheck
covCheck NiceRecDef{} = YesCoverageCheck
covCheck NicePatternSyn{} = YesCoverageCheck
covCheck NiceGeneralize{} = YesCoverageCheck
covCheck NiceLoneConstructor{} = YesCoverageCheck
covCheck NiceUnquoteData{} = YesCoverageCheck
ASR ( 26 December 2015 ): Do not positivity check a mutual
NO_POSITIVITY_CHECK pragma . See Issue 1614 .
positivityCheckOldMutual :: NiceDeclaration -> PositivityCheck
positivityCheckOldMutual (NiceDataDef _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceDataSig _ _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceMutual _ _ _ pc _) = pc
positivityCheckOldMutual (NiceRecSig _ _ _ _ pc _ _ _ _) = pc
positivityCheckOldMutual (NiceRecDef _ _ _ pc _ _ _ _ _) = pc
positivityCheckOldMutual _ = YesPositivityCheck
abstractBlock _ [] = return []
abstractBlock r ds = do
(ds', anyChange) <- runChangeT $ mkAbstract ds
let inherited = r == noRange
if anyChange then return ds' else do
unless inherited $ declarationWarning $ UselessAbstract r
privateBlock _ _ [] = return []
privateBlock r o ds = do
(ds', anyChange) <- runChangeT $ mkPrivate o ds
if anyChange then return ds' else do
when (o == UserWritten) $ declarationWarning $ UselessPrivate r
instanceBlock
-> [NiceDeclaration]
-> Nice [NiceDeclaration]
instanceBlock _ [] = return []
instanceBlock r ds = do
let (ds', anyChange) = runChange $ mapM (mkInstance r) ds
if anyChange then return ds' else do
declarationWarning $ UselessInstance r
mkInstance
-> Updater NiceDeclaration
mkInstance r0 = \case
Axiom r p a i rel x e -> (\ i -> Axiom r p a i rel x e) <$> setInstance r0 i
FunSig r p a i m rel tc cc x e -> (\ i -> FunSig r p a i m rel tc cc x e) <$> setInstance r0 i
NiceUnquoteDecl r p a i tc cc x e -> (\ i -> NiceUnquoteDecl r p a i tc cc x e) <$> setInstance r0 i
NiceMutual r tc cc pc ds -> NiceMutual r tc cc pc <$> mapM (mkInstance r0) ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mapM (mkInstance r0) ds
d@NiceFunClause{} -> return d
FunDef r ds a i tc cc x cs -> (\ i -> FunDef r ds a i tc cc x cs) <$> setInstance r0 i
Field instance are handled by the parser
d@PrimitiveFunction{} -> return d
d@NiceUnquoteDef{} -> return d
d@NiceRecSig{} -> return d
d@NiceDataSig{} -> return d
d@NiceModuleMacro{} -> return d
d@NiceModule{} -> return d
d@NicePragma{} -> return d
d@NiceOpen{} -> return d
d@NiceImport{} -> return d
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
d@NiceUnquoteData{} -> return d
setInstance
-> Updater IsInstance
setInstance r0 = \case
i@InstanceDef{} -> return i
_ -> dirty $ InstanceDef r0
macroBlock r ds = mapM mkMacro ds
mkMacro :: NiceDeclaration -> Nice NiceDeclaration
mkMacro = \case
FunSig r p a i _ rel tc cc x e -> return $ FunSig r p a i MacroDef rel tc cc x e
d@FunDef{} -> return d
d -> declarationException (BadMacroDef d)
If no abstraction is taking place , we want to complain about ' UselessAbstract ' .
class MakeAbstract a where
mkAbstract :: UpdaterT Nice a
default mkAbstract :: (Traversable f, MakeAbstract a', a ~ f a') => UpdaterT Nice a
mkAbstract = traverse mkAbstract
instance MakeAbstract a => MakeAbstract [a]
Leads to overlap with ' WhereClause ' :
instance ( f , MakeAbstract a ) = > MakeAbstract ( f a ) where
instance MakeAbstract IsAbstract where
mkAbstract = \case
a@AbstractDef -> return a
ConcreteDef -> dirty $ AbstractDef
instance MakeAbstract NiceDeclaration where
mkAbstract = \case
NiceMutual r termCheck cc pc ds -> NiceMutual r termCheck cc pc <$> mkAbstract ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mkAbstract ds
FunDef r ds a i tc cc x cs -> (\ a -> FunDef r ds a i tc cc x) <$> mkAbstract a <*> mkAbstract cs
NiceDataDef r o a pc uc x ps cs -> (\ a -> NiceDataDef r o a pc uc x ps) <$> mkAbstract a <*> mkAbstract cs
NiceRecDef r o a pc uc x dir ps cs -> (\ a -> NiceRecDef r o a pc uc x dir ps cs) <$> mkAbstract a
NiceFunClause r p a tc cc catchall d -> (\ a -> NiceFunClause r p a tc cc catchall d) <$> mkAbstract a
( thus , do not notify progress with @dirty@ ) .
Axiom r p a i rel x e -> return $ Axiom r p AbstractDef i rel x e
FunSig r p a i m rel tc cc x e -> return $ FunSig r p AbstractDef i m rel tc cc x e
NiceRecSig r er p a pc uc x ls t -> return $ NiceRecSig r er p AbstractDef pc uc x ls t
NiceDataSig r er p a pc uc x ls t -> return $ NiceDataSig r er p AbstractDef pc uc x ls t
NiceField r p _ i tac x e -> return $ NiceField r p AbstractDef i tac x e
PrimitiveFunction r p _ x e -> return $ PrimitiveFunction r p AbstractDef x e
, 2016 - 07 - 17 it does have effect on unquoted defs .
NiceUnquoteDecl r p _ i tc cc x e -> tellDirty $> NiceUnquoteDecl r p AbstractDef i tc cc x e
NiceUnquoteDef r p _ tc cc x e -> tellDirty $> NiceUnquoteDef r p AbstractDef tc cc x e
NiceUnquoteData r p _ tc cc x xs e -> tellDirty $> NiceUnquoteData r p AbstractDef tc cc x xs e
d@NiceModule{} -> return d
d@NiceModuleMacro{} -> return d
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . declarationWarning . OpenPublicAbstract
return d
d@NiceImport{} -> return d
d@NicePatternSyn{} -> return d
d@NiceGeneralize{} -> return d
instance MakeAbstract Clause where
mkAbstract (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkAbstract wh <*> mkAbstract with
instance MakeAbstract WhereClause where
mkAbstract NoWhere = return $ NoWhere
mkAbstract (AnyWhere r ds) = dirty $ AnyWhere r
[Abstract noRange ds]
mkAbstract (SomeWhere r e m a ds) = dirty $ SomeWhere r e m a
[Abstract noRange ds]
, 2012 - 11 - 17 :
Then , nested would sometimes also be complained about .
class MakePrivate a where
mkPrivate :: Origin -> UpdaterT Nice a
default mkPrivate :: (Traversable f, MakePrivate a', a ~ f a') => Origin -> UpdaterT Nice a
mkPrivate o = traverse $ mkPrivate o
instance MakePrivate a => MakePrivate [a]
Leads to overlap with ' WhereClause ' :
instance ( f , MakePrivate a ) = > MakePrivate ( f a ) where
mkPrivate = traverse mkPrivate
instance MakePrivate Access where
mkPrivate o = \case
OR ? return o
_ -> dirty $ PrivateAccess o
instance MakePrivate NiceDeclaration where
mkPrivate o = \case
Axiom r p a i rel x e -> (\ p -> Axiom r p a i rel x e) <$> mkPrivate o p
NiceField r p a i tac x e -> (\ p -> NiceField r p a i tac x e) <$> mkPrivate o p
PrimitiveFunction r p a x e -> (\ p -> PrimitiveFunction r p a x e) <$> mkPrivate o p
NiceMutual r tc cc pc ds -> (\ ds-> NiceMutual r tc cc pc ds) <$> mkPrivate o ds
NiceLoneConstructor r ds -> NiceLoneConstructor r <$> mkPrivate o ds
NiceModule r p a e x tel ds -> (\ p -> NiceModule r p a e x tel ds) <$> mkPrivate o p
NiceModuleMacro r p e x ma op is -> (\ p -> NiceModuleMacro r p e x ma op is) <$> mkPrivate o p
FunSig r p a i m rel tc cc x e -> (\ p -> FunSig r p a i m rel tc cc x e) <$> mkPrivate o p
NiceRecSig r er p a pc uc x ls t -> (\ p -> NiceRecSig r er p a pc uc x ls t) <$> mkPrivate o p
NiceDataSig r er p a pc uc x ls t -> (\ p -> NiceDataSig r er p a pc uc x ls t) <$> mkPrivate o p
NiceFunClause r p a tc cc catchall d -> (\ p -> NiceFunClause r p a tc cc catchall d) <$> mkPrivate o p
NiceUnquoteDecl r p a i tc cc x e -> (\ p -> NiceUnquoteDecl r p a i tc cc x e) <$> mkPrivate o p
NiceUnquoteDef r p a tc cc x e -> (\ p -> NiceUnquoteDef r p a tc cc x e) <$> mkPrivate o p
NicePatternSyn r p x xs p' -> (\ p -> NicePatternSyn r p x xs p') <$> mkPrivate o p
NiceGeneralize r p i tac x t -> (\ p -> NiceGeneralize r p i tac x t) <$> mkPrivate o p
d@NicePragma{} -> return d
d@(NiceOpen _ _ directives) -> do
whenJust (publicOpen directives) $ lift . declarationWarning . OpenPublicPrivate
return d
d@NiceImport{} -> return d
, 2016 - 07 - 08 , issue # 2089
FunDef r ds a i tc cc x cls -> FunDef r ds a i tc cc x <$> mkPrivate o cls
d@NiceDataDef{} -> return d
d@NiceRecDef{} -> return d
d@NiceUnquoteData{} -> return d
instance MakePrivate Clause where
mkPrivate o (Clause x catchall lhs rhs wh with) = do
Clause x catchall lhs rhs <$> mkPrivate o wh <*> mkPrivate o with
instance MakePrivate WhereClause where
mkPrivate o = \case
d@NoWhere -> return d
d@AnyWhere{} -> return d
, 2016 - 07 - 08
A @where@-module is private if the parent function is private .
Thus , we do not recurse into the @ds@ ( could not anyway ) .
SomeWhere r e m a ds ->
mkPrivate o a <&> \a' -> SomeWhere r e m a' ds
The following function is ( at the time of writing ) only used three
| ( Approximately ) convert a ' NiceDeclaration ' back to a list of
' Declaration 's .
notSoNiceDeclarations :: NiceDeclaration -> [Declaration]
notSoNiceDeclarations = \case
Axiom _ _ _ i rel x e -> inst i [TypeSig rel Nothing x e]
NiceField _ _ _ i tac x argt -> [FieldSig i tac x argt]
PrimitiveFunction r _ _ x e -> [Primitive r [TypeSig (argInfo e) Nothing x (unArg e)]]
NiceMutual r _ _ _ ds -> [Mutual r $ concatMap notSoNiceDeclarations ds]
NiceLoneConstructor r ds -> [LoneConstructor r $ concatMap notSoNiceDeclarations ds]
NiceModule r _ _ e x tel ds -> [Module r e x tel ds]
NiceModuleMacro r _ e x ma o dir
-> [ModuleMacro r e x ma o dir]
NiceOpen r x dir -> [Open r x dir]
NiceImport r x as o dir -> [Import r x as o dir]
NicePragma _ p -> [Pragma p]
NiceRecSig r er _ _ _ _ x bs e -> [RecordSig r er x bs e]
NiceDataSig r er _ _ _ _ x bs e -> [DataSig r er x bs e]
NiceFunClause _ _ _ _ _ _ d -> [d]
FunSig _ _ _ i _ rel _ _ x e -> inst i [TypeSig rel Nothing x e]
FunDef _ ds _ _ _ _ _ _ -> ds
NiceDataDef r _ _ _ _ x bs cs -> [DataDef r x bs $ concatMap notSoNiceDeclarations cs]
NiceRecDef r _ _ _ _ x dir bs ds -> [RecordDef r x dir bs ds]
NicePatternSyn r _ n as p -> [PatternSyn r n as p]
NiceGeneralize r _ i tac n e -> [Generalize r [TypeSig i tac n e]]
NiceUnquoteDecl r _ _ i _ _ x e -> inst i [UnquoteDecl r x e]
NiceUnquoteDef r _ _ _ _ x e -> [UnquoteDef r x e]
NiceUnquoteData r _ _ _ _ x xs e -> [UnquoteData r x xs e]
where
inst (InstanceDef r) ds = [InstanceB r ds]
inst NotInstanceDef ds = ds
| Has the ' NiceDeclaration ' a field of type ' IsAbstract ' ?
niceHasAbstract :: NiceDeclaration -> Maybe IsAbstract
niceHasAbstract = \case
Axiom{} -> Nothing
NiceField _ _ a _ _ _ _ -> Just a
PrimitiveFunction _ _ a _ _ -> Just a
NiceMutual{} -> Nothing
NiceLoneConstructor{} -> Nothing
NiceModule _ _ a _ _ _ _ -> Just a
NiceModuleMacro{} -> Nothing
NiceOpen{} -> Nothing
NiceImport{} -> Nothing
NicePragma{} -> Nothing
NiceRecSig{} -> Nothing
NiceDataSig{} -> Nothing
NiceFunClause _ _ a _ _ _ _ -> Just a
FunSig{} -> Nothing
FunDef _ _ a _ _ _ _ _ -> Just a
NiceDataDef _ _ a _ _ _ _ _ -> Just a
NiceRecDef _ _ a _ _ _ _ _ _ -> Just a
NicePatternSyn{} -> Nothing
NiceGeneralize{} -> Nothing
NiceUnquoteDecl _ _ a _ _ _ _ _ -> Just a
NiceUnquoteDef _ _ a _ _ _ _ -> Just a
NiceUnquoteData _ _ a _ _ _ _ _ -> Just a
|
c4f1c4c534e478e2344ee893005c99382336b06c2febc5f0448257b72666bb8b | clojure-lsp/clojure-lsp | pod_test.clj | (ns clojure-lsp.pod-test
(:require
[babashka.pods :as pods]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]))
(def pod-spec (if (= "native" (System/getenv "CLOJURE_LSP_TEST_ENV"))
["../clojure-lsp"]
(if (str/starts-with? (System/getProperty "os.name") "Windows")
["powershell" "-Command" "clojure" "-M:run"]
["clojure" "-M:run"])))
(pods/load-pod pod-spec)
(require '[clojure-lsp.api :as clojure-lsp])
#_{:clj-kondo/ignore [:unresolved-var]}
(deftest pod-test
(testing "analyze-project-only!"
(let [result (clojure-lsp/analyze-project-only!
{:project-root (io/file "integration-test/sample-test")})]
(is result)))
(testing "analyze-project-and-deps!"
(let [result (clojure-lsp/analyze-project-and-deps!
{:project-root (io/file "integration-test/sample-test")})]
(is result)))
(testing "clean-ns!"
(let [result (clojure-lsp/clean-ns!
{:project-root (io/file "integration-test/sample-test")
:namespace '[sample-test.api.format.a]
:dry? true})]
(is (= 1 (:result-code result)))
(is (seq (:edits result)))))
(testing "diagnostics"
(let [result (clojure-lsp/diagnostics
{:project-root (io/file "integration-test/sample-test")
:dry? true})]
(is (not= 0 (:result-code result)))
(is (seq (:diagnostics result)))))
(testing "format!"
(let [result (clojure-lsp/format!
{:project-root (io/file "integration-test/sample-test")
:namespace '[sample-test.api.format.a]
:dry? true})]
(is (= 1 (:result-code result)))
(is (seq (:edits result))))))
| null | https://raw.githubusercontent.com/clojure-lsp/clojure-lsp/7a10a24affb6bdb50ab34c61b4dbbc98aeb6ee3f/cli/pod-test/clojure_lsp/pod_test.clj | clojure | (ns clojure-lsp.pod-test
(:require
[babashka.pods :as pods]
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer [deftest is testing]]))
(def pod-spec (if (= "native" (System/getenv "CLOJURE_LSP_TEST_ENV"))
["../clojure-lsp"]
(if (str/starts-with? (System/getProperty "os.name") "Windows")
["powershell" "-Command" "clojure" "-M:run"]
["clojure" "-M:run"])))
(pods/load-pod pod-spec)
(require '[clojure-lsp.api :as clojure-lsp])
#_{:clj-kondo/ignore [:unresolved-var]}
(deftest pod-test
(testing "analyze-project-only!"
(let [result (clojure-lsp/analyze-project-only!
{:project-root (io/file "integration-test/sample-test")})]
(is result)))
(testing "analyze-project-and-deps!"
(let [result (clojure-lsp/analyze-project-and-deps!
{:project-root (io/file "integration-test/sample-test")})]
(is result)))
(testing "clean-ns!"
(let [result (clojure-lsp/clean-ns!
{:project-root (io/file "integration-test/sample-test")
:namespace '[sample-test.api.format.a]
:dry? true})]
(is (= 1 (:result-code result)))
(is (seq (:edits result)))))
(testing "diagnostics"
(let [result (clojure-lsp/diagnostics
{:project-root (io/file "integration-test/sample-test")
:dry? true})]
(is (not= 0 (:result-code result)))
(is (seq (:diagnostics result)))))
(testing "format!"
(let [result (clojure-lsp/format!
{:project-root (io/file "integration-test/sample-test")
:namespace '[sample-test.api.format.a]
:dry? true})]
(is (= 1 (:result-code result)))
(is (seq (:edits result))))))
|
|
970f64bbbd065d30ee6cf961b2ef0715fa8cfd08b164fca415b6b1f9baa8c664 | imitator-model-checker/imitator | AlgoBCCoverDistributedSubdomainStatic.mli | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Distribution mode : subdomain with static distribution . [ ACN15 ]
*
* File contributors : * Created : 2016/03/17
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Distribution mode: subdomain with static distribution. [ACN15]
*
* File contributors : Étienne André
* Created : 2016/03/17
*
************************************************************)
(************************************************************)
(* Modules *)
(************************************************************)
open AlgoGeneric
(************************************************************)
(* Class definition *)
(************************************************************)
class virtual algoBCCoverDistributedSubdomainStatic : HyperRectangle.hyper_rectangle -> NumConst.t -> (PVal.pval -> AlgoStateBased.algoStateBased) -> AlgoCartoGeneric.tiles_storage ->
object inherit AlgoBCCoverDistributedSubdomain.algoBCCoverDistributedSubdomain
(************************************************************)
(* Class variables *)
(************************************************************)
(************************************************************)
(* Class methods *)
(************************************************************)
method virtual algorithm_name : string
method initialize_variables : unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
Finalization method to process results communication to the coordinator
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method virtual finalize : Result.cartography_result -> unit
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
Generic algorithm for all collaborators ( including the coordinator )
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method run : unit -> Result.imitator_result
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
(* Method packaging the result output by the algorithm *)
(*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*)
method virtual compute_bc_result : Result.imitator_result
end | null | https://raw.githubusercontent.com/imitator-model-checker/imitator/105408ae2bd8c3e3291f286e4d127defd492a58b/src/AlgoBCCoverDistributedSubdomainStatic.mli | ocaml | **********************************************************
Modules
**********************************************************
**********************************************************
Class definition
**********************************************************
**********************************************************
Class variables
**********************************************************
**********************************************************
Class methods
**********************************************************
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
Method packaging the result output by the algorithm
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*- | * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13 , LIPN , CNRS , France
* Université de Lorraine , CNRS , , LORIA , Nancy , France
*
* Module description : Classical Behavioral Cartography with exhaustive coverage of integer points [ AF10 ] . Distribution mode : subdomain with static distribution . [ ACN15 ]
*
* File contributors : * Created : 2016/03/17
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*
* IMITATOR
*
* Université Paris 13, LIPN, CNRS, France
* Université de Lorraine, CNRS, Inria, LORIA, Nancy, France
*
* Module description: Classical Behavioral Cartography with exhaustive coverage of integer points [AF10]. Distribution mode: subdomain with static distribution. [ACN15]
*
* File contributors : Étienne André
* Created : 2016/03/17
*
************************************************************)
open AlgoGeneric
class virtual algoBCCoverDistributedSubdomainStatic : HyperRectangle.hyper_rectangle -> NumConst.t -> (PVal.pval -> AlgoStateBased.algoStateBased) -> AlgoCartoGeneric.tiles_storage ->
object inherit AlgoBCCoverDistributedSubdomain.algoBCCoverDistributedSubdomain
method virtual algorithm_name : string
method initialize_variables : unit
Finalization method to process results communication to the coordinator
method virtual finalize : Result.cartography_result -> unit
Generic algorithm for all collaborators ( including the coordinator )
method run : unit -> Result.imitator_result
method virtual compute_bc_result : Result.imitator_result
end |
0b8e3c2d6c016396560543b7fa80630dc1768cd96919e452385f5c3e9783990f | kelamg/HtDP2e-workthrough | ex166.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex166) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct work [employee rate hours])
; A (piece of) Work is a structure:
( make - work String Number Number )
; interpretation (make-work n r h) combines the name
with the pay rate r and the number of hours h
Low ( short for list of works ) is one of :
; – '()
; – (cons Work Low)
; interpretation an instance of Low represents the
; hours worked for a number of employees
(define-struct paycheck (employee amount))
;; A Paycheck is a structure:
( make - paycheck String Number )
interp . combines an employee 's name with their week 's wage
( short for list of paychecks ) is one of :
;; - '()
- ( cons )
;; interp. an instance of lop represents a number of employees
and the amounts paid to them for hours worked
(define LOW1 '())
(define LOW2 (cons (make-work "Robby" 11.95 39) '()))
(define LOW3 (cons (make-work "Matthew" 12.95 45)
(cons (make-work "Robby" 11.95 39) '())))
(define LOW4
(cons (make-work "Jerry" 10.80 50)
(cons (make-work "Nyssa" 13.50 40)
(cons (make-work "Justin" 12.50 60) '()))))
(define LOW5
(cons (make-work "Bruce" 12 101)
(cons (make-work "Hommer" 10.20 30) '())))
; Low -> List-of-numbers
computes the weekly wages for the given records
(check-expect (wage*.v2 LOW1) '())
(check-expect (wage*.v2 LOW2)
(cons (* 11.95 39) '()))
(check-expect (wage*.v2 LOW3)
(cons (* 12.95 45)
(cons (* 11.95 39) '())))
(check-expect (wage*.v2 LOW4)
(cons (* 10.80 50)
(cons (* 13.50 40)
(cons (* 12.50 60) '()))))
(check-expect (wage*.v2 LOW5)
(cons (* 12 101)
(cons (* 10.20 30) '())))
(define (wage*.v2 an-low)
(cond
[(empty? an-low) '()]
[(cons? an-low) (cons (wage.v2 (first an-low))
(wage*.v2 (rest an-low)))]))
; Work -> Number
; computes the wage for the given work record w
(define (wage.v2 w)
(* (work-rate w) (work-hours w)))
;; Low -> Lop
computes the weekly paychecks for the given record
(check-expect (wage*.v3 LOW1) '())
(check-expect (wage*.v3 LOW2)
(cons (make-paycheck "Robby" (* 11.95 39)) '()))
(check-expect (wage*.v3 LOW3)
(cons (make-paycheck "Matthew" (* 12.95 45))
(cons (make-paycheck "Robby" (* 11.95 39)) '())))
(check-expect (wage*.v3 LOW4)
(cons (make-paycheck "Jerry" (* 10.80 50))
(cons (make-paycheck "Nyssa" (* 13.50 40))
(cons (make-paycheck "Justin" (* 12.50 60)) '()))))
(check-expect (wage*.v3 LOW5)
(cons (make-paycheck "Bruce" (* 12 101))
(cons (make-paycheck "Hommer" (* 10.20 30)) '())))
(define (wage*.v3 low)
(cond
[(empty? low) '()]
[else
(cons (make-paycheck (work-employee (first low))
(wage.v3 (first low)))
(wage*.v3 (rest low)))]))
; Work -> Number
; computes the wage for the given work record w
(define (wage.v3 w)
(* (work-rate w) (work-hours w)))
(define-struct employee (name number))
;; An Employee is a structure:
( make - employee String Natural )
;; interp. (make-employee s n) is an employee with name s
;; and employee number n
(define-struct ework [employee rate hours])
; A (piece of) Work is a structure:
; (make-work Employee Number Number)
; interpretation (make-work n r h) combines the employee
with the pay rate r and the number of hours h
Low ( short for list of works ) is one of :
; – '()
; – (cons Work Low)
; interpretation an instance of Low represents the
; hours worked for a number of employees
(define-struct epaycheck (employee amount))
;; A Paycheck is a structure:
;; (make-paycheck Employee Number)
interp . combines an employee with his / her week 's wage
( short for list of paychecks ) is one of :
;; - '()
- ( cons )
;; interp. an instance of lop represents a number of employees
and the amounts paid to them for hours worked
(define E1 (make-employee "Robby" 40))
(define E2 (make-employee "Matthew" 12))
(define E3 (make-employee "Jerry" 5))
(define E4 (make-employee "Nyssa" 98))
(define E5 (make-employee "Justin" 55))
(define E6 (make-employee "Bruce" 73))
(define E7 (make-employee "Hommer" 26))
(define LOWE1 '())
(define LOWE2 (cons (make-ework E1 11.95 39) '()))
(define LOWE3 (cons (make-ework E2 12.95 45)
(cons (make-ework E1 11.95 39) '())))
(define LOWE4
(cons (make-ework E3 10.80 50)
(cons (make-ework E4 13.50 40)
(cons (make-ework E5 12.50 60) '()))))
(define LOWE5
(cons (make-ework E6 12 101)
(cons (make-ework E7 10.20 30) '())))
; Work -> Number
; computes the wage for the given work record w
(define (wage.v4 we)
(* (ework-rate we) (ework-hours we)))
;; Low -> Lop
computes the weekly paychecks for the given record
(check-expect (wage*.v4 LOWE1) '())
(check-expect (wage*.v4 LOWE2)
(cons (make-epaycheck E1 (* 11.95 39)) '()))
(check-expect (wage*.v4 LOWE3)
(cons (make-epaycheck E2 (* 12.95 45))
(cons (make-epaycheck E1 (* 11.95 39)) '())))
(check-expect (wage*.v4 LOWE4)
(cons (make-epaycheck E3 (* 10.80 50))
(cons (make-epaycheck E4 (* 13.50 40))
(cons (make-epaycheck E5 (* 12.50 60)) '()))))
(check-expect (wage*.v4 LOWE5)
(cons (make-epaycheck E6 (* 12 101))
(cons (make-epaycheck E7 (* 10.20 30)) '())))
(define (wage*.v4 lowe)
(cond
[(empty? lowe) '()]
[else
(cons (make-epaycheck
(ework-employee (first lowe))
(wage.v4 (first lowe)))
(wage*.v4 (rest lowe)))])) | null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Arbitrarily-Large-Data/ex166.rkt | racket | about the language level of this file in a form that our tools can easily process.
A (piece of) Work is a structure:
interpretation (make-work n r h) combines the name
– '()
– (cons Work Low)
interpretation an instance of Low represents the
hours worked for a number of employees
A Paycheck is a structure:
- '()
interp. an instance of lop represents a number of employees
Low -> List-of-numbers
Work -> Number
computes the wage for the given work record w
Low -> Lop
Work -> Number
computes the wage for the given work record w
An Employee is a structure:
interp. (make-employee s n) is an employee with name s
and employee number n
A (piece of) Work is a structure:
(make-work Employee Number Number)
interpretation (make-work n r h) combines the employee
– '()
– (cons Work Low)
interpretation an instance of Low represents the
hours worked for a number of employees
A Paycheck is a structure:
(make-paycheck Employee Number)
- '()
interp. an instance of lop represents a number of employees
Work -> Number
computes the wage for the given work record w
Low -> Lop | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex166) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define-struct work [employee rate hours])
( make - work String Number Number )
with the pay rate r and the number of hours h
Low ( short for list of works ) is one of :
(define-struct paycheck (employee amount))
( make - paycheck String Number )
interp . combines an employee 's name with their week 's wage
( short for list of paychecks ) is one of :
- ( cons )
and the amounts paid to them for hours worked
(define LOW1 '())
(define LOW2 (cons (make-work "Robby" 11.95 39) '()))
(define LOW3 (cons (make-work "Matthew" 12.95 45)
(cons (make-work "Robby" 11.95 39) '())))
(define LOW4
(cons (make-work "Jerry" 10.80 50)
(cons (make-work "Nyssa" 13.50 40)
(cons (make-work "Justin" 12.50 60) '()))))
(define LOW5
(cons (make-work "Bruce" 12 101)
(cons (make-work "Hommer" 10.20 30) '())))
computes the weekly wages for the given records
(check-expect (wage*.v2 LOW1) '())
(check-expect (wage*.v2 LOW2)
(cons (* 11.95 39) '()))
(check-expect (wage*.v2 LOW3)
(cons (* 12.95 45)
(cons (* 11.95 39) '())))
(check-expect (wage*.v2 LOW4)
(cons (* 10.80 50)
(cons (* 13.50 40)
(cons (* 12.50 60) '()))))
(check-expect (wage*.v2 LOW5)
(cons (* 12 101)
(cons (* 10.20 30) '())))
(define (wage*.v2 an-low)
(cond
[(empty? an-low) '()]
[(cons? an-low) (cons (wage.v2 (first an-low))
(wage*.v2 (rest an-low)))]))
(define (wage.v2 w)
(* (work-rate w) (work-hours w)))
computes the weekly paychecks for the given record
(check-expect (wage*.v3 LOW1) '())
(check-expect (wage*.v3 LOW2)
(cons (make-paycheck "Robby" (* 11.95 39)) '()))
(check-expect (wage*.v3 LOW3)
(cons (make-paycheck "Matthew" (* 12.95 45))
(cons (make-paycheck "Robby" (* 11.95 39)) '())))
(check-expect (wage*.v3 LOW4)
(cons (make-paycheck "Jerry" (* 10.80 50))
(cons (make-paycheck "Nyssa" (* 13.50 40))
(cons (make-paycheck "Justin" (* 12.50 60)) '()))))
(check-expect (wage*.v3 LOW5)
(cons (make-paycheck "Bruce" (* 12 101))
(cons (make-paycheck "Hommer" (* 10.20 30)) '())))
(define (wage*.v3 low)
(cond
[(empty? low) '()]
[else
(cons (make-paycheck (work-employee (first low))
(wage.v3 (first low)))
(wage*.v3 (rest low)))]))
(define (wage.v3 w)
(* (work-rate w) (work-hours w)))
(define-struct employee (name number))
( make - employee String Natural )
(define-struct ework [employee rate hours])
with the pay rate r and the number of hours h
Low ( short for list of works ) is one of :
(define-struct epaycheck (employee amount))
interp . combines an employee with his / her week 's wage
( short for list of paychecks ) is one of :
- ( cons )
and the amounts paid to them for hours worked
(define E1 (make-employee "Robby" 40))
(define E2 (make-employee "Matthew" 12))
(define E3 (make-employee "Jerry" 5))
(define E4 (make-employee "Nyssa" 98))
(define E5 (make-employee "Justin" 55))
(define E6 (make-employee "Bruce" 73))
(define E7 (make-employee "Hommer" 26))
(define LOWE1 '())
(define LOWE2 (cons (make-ework E1 11.95 39) '()))
(define LOWE3 (cons (make-ework E2 12.95 45)
(cons (make-ework E1 11.95 39) '())))
(define LOWE4
(cons (make-ework E3 10.80 50)
(cons (make-ework E4 13.50 40)
(cons (make-ework E5 12.50 60) '()))))
(define LOWE5
(cons (make-ework E6 12 101)
(cons (make-ework E7 10.20 30) '())))
(define (wage.v4 we)
(* (ework-rate we) (ework-hours we)))
computes the weekly paychecks for the given record
(check-expect (wage*.v4 LOWE1) '())
(check-expect (wage*.v4 LOWE2)
(cons (make-epaycheck E1 (* 11.95 39)) '()))
(check-expect (wage*.v4 LOWE3)
(cons (make-epaycheck E2 (* 12.95 45))
(cons (make-epaycheck E1 (* 11.95 39)) '())))
(check-expect (wage*.v4 LOWE4)
(cons (make-epaycheck E3 (* 10.80 50))
(cons (make-epaycheck E4 (* 13.50 40))
(cons (make-epaycheck E5 (* 12.50 60)) '()))))
(check-expect (wage*.v4 LOWE5)
(cons (make-epaycheck E6 (* 12 101))
(cons (make-epaycheck E7 (* 10.20 30)) '())))
(define (wage*.v4 lowe)
(cond
[(empty? lowe) '()]
[else
(cons (make-epaycheck
(ework-employee (first lowe))
(wage.v4 (first lowe)))
(wage*.v4 (rest lowe)))])) |
97ccc6e06424218b04b4d9bd24626258bed48c0482d273efd1c4195c873a9e58 | Decentralized-Pictures/T4L3NT | state.mli | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2021 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
(** {b PLEASE, DO NOT DIRECTLY USE THIS MODULE BY YOURSELF
IN YOUR OWN CODE. IT IS ONLY INTENDED TO BE USED THROUGH
[Tezos_time_measurement_ppx] PPX REWRITERS FOR TESTING.
AN UNWISE USE COULD SEVERELY IMPACT THE MEMORY USAGE OF
YOUR PROGRAM.} *)
(** Defines the type of an element inside the state. *)
module type Elt = sig
type t
end
(** Defines an interface to interact with a mutable state
that could aggregate values. *)
module type S = sig
(** The type of elements in the state. *)
type elt
(** [get_all_and_reset ()] evaluates in all the elements that
were aggregated inside the state and then resets the state
to its initial value.
Elements are returned in the order they were pushed in the
state (the resulting list starts by older elements). *)
val get_all_and_reset : unit -> elt list
(** [push elt] aggregates the given element [elt] in the state. *)
val push : elt -> unit
end
(** [State.S] default implementation relying on Ocaml [ref].
The state is initialized with the given [Elt.init] value. *)
module WithRef (E : Elt) : S with type elt := E.t
| null | https://raw.githubusercontent.com/Decentralized-Pictures/T4L3NT/6d4d3edb2d73575384282ad5a633518cba3d29e3/src/lib_time_measurement/runtime/state.mli | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* {b PLEASE, DO NOT DIRECTLY USE THIS MODULE BY YOURSELF
IN YOUR OWN CODE. IT IS ONLY INTENDED TO BE USED THROUGH
[Tezos_time_measurement_ppx] PPX REWRITERS FOR TESTING.
AN UNWISE USE COULD SEVERELY IMPACT THE MEMORY USAGE OF
YOUR PROGRAM.}
* Defines the type of an element inside the state.
* Defines an interface to interact with a mutable state
that could aggregate values.
* The type of elements in the state.
* [get_all_and_reset ()] evaluates in all the elements that
were aggregated inside the state and then resets the state
to its initial value.
Elements are returned in the order they were pushed in the
state (the resulting list starts by older elements).
* [push elt] aggregates the given element [elt] in the state.
* [State.S] default implementation relying on Ocaml [ref].
The state is initialized with the given [Elt.init] value. | Copyright ( c ) 2021 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
module type Elt = sig
type t
end
module type S = sig
type elt
val get_all_and_reset : unit -> elt list
val push : elt -> unit
end
module WithRef (E : Elt) : S with type elt := E.t
|
4d19a1426b80b4574d0be6a8750db4793985f433a747140942d8a7afeb0ec46d | byorgey/AoC | 25.hs | #!/usr/bin/env stack
-- stack --resolver lts-18.18 script
import Control.Arrow ((***), (>>>))
import Data.Array.Unboxed (UArray, (!))
import qualified Data.Array.Unboxed as U
import Data.Function (on)
import Data.List (findIndex, groupBy)
import Data.Maybe (fromJust)
main = interact $ readInput >>> solve >>> show >>> (++"\n")
infixr 0 >$>
(>$>) = flip ($)
type Grid = UArray (Int,Int) Char
readInput :: String -> Grid
readInput = lines >>> mkArray
where
mkArray ls = U.listArray ((0,0),(r-1,c-1)) (concat ls)
where
r = length ls
c = length (head ls)
type Output = Int
solve :: Grid -> Output
solve = iterate (step E >>> step S) >>>
(zip <*> tail) >>> findIndex (uncurry (==)) >>> fromJust >>> succ
------------------------------------------------------------
showGrid :: Grid -> String
showGrid = U.assocs >>> groupBy ((==) `on` (fst.fst)) >>> map (map snd) >>> unlines
printGrid :: Grid -> IO ()
printGrid = putStr . showGrid
data Dir = S | E deriving (Eq, Ord, Show)
dirChar :: Dir -> Char
dirChar S = 'v'
dirChar E = '>'
prev, next :: (Int,Int) -> Dir -> (Int,Int) -> (Int,Int)
prev (r,c) S (i,j) = ((i-1) `mod` r, j)
prev (r,c) E (i,j) = (i, (j-1) `mod` c)
next (r,c) S (i,j) = ((i+1) `mod` r, j)
next (r,c) E (i,j) = (i, (j+1) `mod` c)
step :: Dir -> Grid -> Grid
step dir g = U.array ((0,0),(r-1,c-1))
[ ((i,j), x)
| i <- [0..r-1], j <- [0..c-1]
, let x
| g!(i,j) == '.' && (g!(prev (r,c) dir (i,j)) == dirChar dir) = dirChar dir
| g!(i,j) == dirChar dir && g!(next (r,c) dir (i,j)) == '.' = '.'
| otherwise = g!(i,j)
]
where
(r,c) = g >$> U.bounds >>> snd >>> (succ *** succ)
| null | https://raw.githubusercontent.com/byorgey/AoC/d496593ec5c6487e180d1df4457ef8764ba30af2/2021/25/25.hs | haskell | stack --resolver lts-18.18 script
---------------------------------------------------------- | #!/usr/bin/env stack
import Control.Arrow ((***), (>>>))
import Data.Array.Unboxed (UArray, (!))
import qualified Data.Array.Unboxed as U
import Data.Function (on)
import Data.List (findIndex, groupBy)
import Data.Maybe (fromJust)
main = interact $ readInput >>> solve >>> show >>> (++"\n")
infixr 0 >$>
(>$>) = flip ($)
type Grid = UArray (Int,Int) Char
readInput :: String -> Grid
readInput = lines >>> mkArray
where
mkArray ls = U.listArray ((0,0),(r-1,c-1)) (concat ls)
where
r = length ls
c = length (head ls)
type Output = Int
solve :: Grid -> Output
solve = iterate (step E >>> step S) >>>
(zip <*> tail) >>> findIndex (uncurry (==)) >>> fromJust >>> succ
showGrid :: Grid -> String
showGrid = U.assocs >>> groupBy ((==) `on` (fst.fst)) >>> map (map snd) >>> unlines
printGrid :: Grid -> IO ()
printGrid = putStr . showGrid
data Dir = S | E deriving (Eq, Ord, Show)
dirChar :: Dir -> Char
dirChar S = 'v'
dirChar E = '>'
prev, next :: (Int,Int) -> Dir -> (Int,Int) -> (Int,Int)
prev (r,c) S (i,j) = ((i-1) `mod` r, j)
prev (r,c) E (i,j) = (i, (j-1) `mod` c)
next (r,c) S (i,j) = ((i+1) `mod` r, j)
next (r,c) E (i,j) = (i, (j+1) `mod` c)
step :: Dir -> Grid -> Grid
step dir g = U.array ((0,0),(r-1,c-1))
[ ((i,j), x)
| i <- [0..r-1], j <- [0..c-1]
, let x
| g!(i,j) == '.' && (g!(prev (r,c) dir (i,j)) == dirChar dir) = dirChar dir
| g!(i,j) == dirChar dir && g!(next (r,c) dir (i,j)) == '.' = '.'
| otherwise = g!(i,j)
]
where
(r,c) = g >$> U.bounds >>> snd >>> (succ *** succ)
|
c0b2280b7b6d3f6dc242860497be8dc504a71cf5ce44146a7becadc1d1d1da89 | racket/typed-racket | pr226-variation-2.rkt | #lang typed/racket/optional
Chaperoned struct predicates must be wrapped in a contract .
;; (Even though `struct-predicate-procedure?` will return
;; true for these values)
(module untyped racket
(struct s ())
(define s?? (chaperone-procedure s? (lambda (x) (x) x)))
;; provide enough names to trick #:struct
(provide s struct:s (rename-out [s?? s?])))
(require/typed 'untyped
[#:struct s ()])
(define (fail-if-called)
(error 'pr226 "Untyped code invoked a higher-order value passed as 'Any'"))
(require typed/rackunit)
(check-exn #rx"Untyped code invoked a higher-order value"
(lambda () (s? fail-if-called)))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/pr226-variation-2.rkt | racket | (Even though `struct-predicate-procedure?` will return
true for these values)
provide enough names to trick #:struct | #lang typed/racket/optional
Chaperoned struct predicates must be wrapped in a contract .
(module untyped racket
(struct s ())
(define s?? (chaperone-procedure s? (lambda (x) (x) x)))
(provide s struct:s (rename-out [s?? s?])))
(require/typed 'untyped
[#:struct s ()])
(define (fail-if-called)
(error 'pr226 "Untyped code invoked a higher-order value passed as 'Any'"))
(require typed/rackunit)
(check-exn #rx"Untyped code invoked a higher-order value"
(lambda () (s? fail-if-called)))
|
b7cdeb2a7e5abfff4d122ea57686f7b4e0bc193c6aa13b1b94f88b6d32ccc93a | FundingCircle/fc4-framework | model_test.clj | (ns fc4.dsl.model-test
(:require [clojure.test :refer [deftest]]
[fc4.dsl.model :as dm]
[fc4.test-utils :refer [check]]))
(deftest parse-file (check `dm/parse-file 100))
(deftest validate-parsed-file (check `dm/validate-parsed-file 100))
20 is a really low number of test cases , but it takes ~33 seconds on my laptop . So it might be
;; worth looking into speeding up this test.
(deftest build-model (check `dm/build-model 20))
| null | https://raw.githubusercontent.com/FundingCircle/fc4-framework/674af39e7edb2cbfd3e1941e6abe80fd87d93bed/test/fc4/dsl/model_test.clj | clojure | worth looking into speeding up this test. | (ns fc4.dsl.model-test
(:require [clojure.test :refer [deftest]]
[fc4.dsl.model :as dm]
[fc4.test-utils :refer [check]]))
(deftest parse-file (check `dm/parse-file 100))
(deftest validate-parsed-file (check `dm/validate-parsed-file 100))
20 is a really low number of test cases , but it takes ~33 seconds on my laptop . So it might be
(deftest build-model (check `dm/build-model 20))
|
7e747ee5ff0629bd55fa6689b06436b89aed770fcc6218de73cfd426c0a2ef4e | babashka/babashka | main.clj | (ns my.main
(:require [my.impl1 :as impl1] ;; my.impl is already loaded, so it will not be loaded again (normally)
;; but my.impl2 also loads my.impl
[my.impl2]))
;; top-level requires are also supported
(require '[my.impl3 :refer [foo]])
(defn -main [& args]
;; this function is defined non-top-level and may cause problems
(foo)
;; this should just return args
(impl1/impl-fn args))
| null | https://raw.githubusercontent.com/babashka/babashka/3dfc15f5a40efaec07cba991892c1207a352fab4/test-resources/babashka/uberscript/src/my/main.clj | clojure | my.impl is already loaded, so it will not be loaded again (normally)
but my.impl2 also loads my.impl
top-level requires are also supported
this function is defined non-top-level and may cause problems
this should just return args | (ns my.main
[my.impl2]))
(require '[my.impl3 :refer [foo]])
(defn -main [& args]
(foo)
(impl1/impl-fn args))
|
f6b2ab95182a21a29fdb6240497f3b41c62ca54ba62004e205bf976da0ee215a | Factual/s3-journal | s3_journal_test.clj | (ns s3-journal-test
(:require
[clojure.java.shell :as sh]
[byte-streams :as bs]
[clojure.test :refer :all]
[s3-journal :as s]
[s3-journal.s3 :as s3])
(:import
[com.amazonaws.services.s3.model
GetObjectRequest
S3Object]
[com.amazonaws.services.s3
AmazonS3Client]))
(defn sometimes-explode [f]
(fn [& args]
(assert (not= 1 (rand-int 3)) "rolled the dice, you lost")
(apply f args)))
(defn explode-in-streaks [f]
(fn [& args]
(assert
(if-not (not= 1 (rem (long (/ (System/currentTimeMillis) 1e4)) 10))
(do (Thread/sleep 1000) false)
true)
"things are down for a bit")
(apply f args)))
(defn get-test-object [^AmazonS3Client client bucket directory]
(let [test-objects (s3/complete-uploads client bucket directory)]
(apply concat
(map
(fn [object]
(->> object
(GetObjectRequest. bucket)
(.getObject client)
.getObjectContent
bs/to-reader
line-seq
(map #(Long/parseLong %))
doall))
(sort test-objects)))))
(defn clear-test-folder [^AmazonS3Client client bucket directory]
(doseq [u (s3/multipart-uploads client bucket directory)]
(s3/abort-multipart client u))
(doseq [o (s3/complete-uploads client bucket directory)]
(.deleteObject client bucket o)))
(defmacro with-random-errors [& body]
`(with-redefs [s3/init-multipart (sometimes-explode s3/init-multipart)
s3/upload-part (sometimes-explode s3/upload-part)
s3/end-multipart (sometimes-explode s3/end-multipart)
]
~@body))
(defmacro with-intermittent-errors [& body]
`(with-redefs [s3/init-multipart (explode-in-streaks s3/init-multipart)
s3/upload-part (explode-in-streaks s3/upload-part)
s3/end-multipart (explode-in-streaks s3/end-multipart)
]
~@body))
(defn run-stress-test [access-key secret-key bucket]
(with-redefs [s3/max-parts 4]
(let [s3-dir "stress-test"
directory "/tmp/journal-stress-test"
c (s3/client access-key secret-key)
_ (clear-test-folder c bucket (str "0/" s3-dir))
_ (sh/sh "rm" "-rf" directory)
j (s/journal
{:shards 1
:s3-access-key access-key
:s3-secret-key secret-key
:s3-bucket bucket
:s3-directory-format (str \' s3-dir \' "/yy/MM/dd/hh/mm")
:local-directory directory
:max-batch-size 1e5})
n 5e6]
(dotimes [i n]
(s/put! j (str (inc i))))
(prn (s/stats j))
(.close j)
(prn (s/stats j))
(=
(get-test-object c "journal-test" (str "0/" s3-dir))
(map inc (range n))))))
(deftest test-journalling
(let [{:keys [access-key secret-key bucket]} (read-string (slurp "test/credentials.edn"))]
(is
(and
(run-stress-test access-key secret-key bucket)
(with-random-errors (run-stress-test access-key secret-key bucket))
(with-intermittent-errors (run-stress-test access-key secret-key bucket))))))
| null | https://raw.githubusercontent.com/Factual/s3-journal/5a09abd47d9595b3ae8df35c665ad806a9dffd8e/test/s3_journal_test.clj | clojure | (ns s3-journal-test
(:require
[clojure.java.shell :as sh]
[byte-streams :as bs]
[clojure.test :refer :all]
[s3-journal :as s]
[s3-journal.s3 :as s3])
(:import
[com.amazonaws.services.s3.model
GetObjectRequest
S3Object]
[com.amazonaws.services.s3
AmazonS3Client]))
(defn sometimes-explode [f]
(fn [& args]
(assert (not= 1 (rand-int 3)) "rolled the dice, you lost")
(apply f args)))
(defn explode-in-streaks [f]
(fn [& args]
(assert
(if-not (not= 1 (rem (long (/ (System/currentTimeMillis) 1e4)) 10))
(do (Thread/sleep 1000) false)
true)
"things are down for a bit")
(apply f args)))
(defn get-test-object [^AmazonS3Client client bucket directory]
(let [test-objects (s3/complete-uploads client bucket directory)]
(apply concat
(map
(fn [object]
(->> object
(GetObjectRequest. bucket)
(.getObject client)
.getObjectContent
bs/to-reader
line-seq
(map #(Long/parseLong %))
doall))
(sort test-objects)))))
(defn clear-test-folder [^AmazonS3Client client bucket directory]
(doseq [u (s3/multipart-uploads client bucket directory)]
(s3/abort-multipart client u))
(doseq [o (s3/complete-uploads client bucket directory)]
(.deleteObject client bucket o)))
(defmacro with-random-errors [& body]
`(with-redefs [s3/init-multipart (sometimes-explode s3/init-multipart)
s3/upload-part (sometimes-explode s3/upload-part)
s3/end-multipart (sometimes-explode s3/end-multipart)
]
~@body))
(defmacro with-intermittent-errors [& body]
`(with-redefs [s3/init-multipart (explode-in-streaks s3/init-multipart)
s3/upload-part (explode-in-streaks s3/upload-part)
s3/end-multipart (explode-in-streaks s3/end-multipart)
]
~@body))
(defn run-stress-test [access-key secret-key bucket]
(with-redefs [s3/max-parts 4]
(let [s3-dir "stress-test"
directory "/tmp/journal-stress-test"
c (s3/client access-key secret-key)
_ (clear-test-folder c bucket (str "0/" s3-dir))
_ (sh/sh "rm" "-rf" directory)
j (s/journal
{:shards 1
:s3-access-key access-key
:s3-secret-key secret-key
:s3-bucket bucket
:s3-directory-format (str \' s3-dir \' "/yy/MM/dd/hh/mm")
:local-directory directory
:max-batch-size 1e5})
n 5e6]
(dotimes [i n]
(s/put! j (str (inc i))))
(prn (s/stats j))
(.close j)
(prn (s/stats j))
(=
(get-test-object c "journal-test" (str "0/" s3-dir))
(map inc (range n))))))
(deftest test-journalling
(let [{:keys [access-key secret-key bucket]} (read-string (slurp "test/credentials.edn"))]
(is
(and
(run-stress-test access-key secret-key bucket)
(with-random-errors (run-stress-test access-key secret-key bucket))
(with-intermittent-errors (run-stress-test access-key secret-key bucket))))))
|
|
990e2e8f233f4d4fcc6ed48c1d0f84da06d1d80bfa8d111c5d725a60e25c5e08 | jumarko/clojure-experiments | 02_inventory_management.clj | (ns advent-of-clojure.2018.02-inventory-management
""
(:require [clojure.test :refer [deftest testing is]]
[advent-of-clojure.2018.input :as io]))
Inventory management system
Year 1518 : Warehouse boxes
Puzzle 1 : Count checksum of candidate boxes
;;; Simply scan find number of boxes with an ID containing any of letters repeating twice;
then find number of boxes with an ID containing any of letters repeating three times ;
then multiply these two numbers together
(defn checksum [ids]
e.g. ' ( # { 1 } # { 1 3 2 } # { 1 2 } # { 1 3 } # { 1 2 } # { 1 2 } # { 3 } )
count-freqs (fn [desired-freq] (count (filter #(contains? % desired-freq) ids-freqs)))
twos-count (count-freqs 2)
threes-count (count-freqs 3)]
(* twos-count threes-count)))
(defn puzzle1 []
(io/with-input "02_input.txt" checksum))
(deftest puzzle1-test
(testing "Simple checksum"
(is (= 12 (checksum ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]))))
(testing "Real input"
(is (= 4920 (puzzle1)))))
Puzzle 2 :
;;; --------
(defn common-chars
"Returns a string representing all characters that are the same and at the same position.
Same characters at different positions don't count!"
[w1 w2]
(let [char-or-nil (map (fn [ch1 ch2]
(when (= ch1 ch2)
ch1))
w1
w2)]
(->> char-or-nil
(remove nil?)
(apply str))))
(defn matching-ids
"For given ID find another id that 'match it' - that means they differ in exactly one character."
[id other-ids]
(first (filter (fn [id2] (and (= (count id) (count id2))
(= (dec (count id)) (count (common-chars id id2)))))
other-ids
)))
(defn off-by-one-ids
"In given set of ides find all ids that differ in exactly one character.
See `common-chars`."
[ids]
(->> ids
(map (fn [id]
(let [other-ids (disj (set ids) id)]
(matching-ids id other-ids))))
(remove empty?)))
(defn common-chars-for-correct-ids
"Finds common characters for 'matching ids in given collection.
It's assumed that there are only two such IDs - otherwise `common=chars` call throws an exception."
[ids]
(->> ids
off-by-one-ids
(apply common-chars)))
(defn puzzle2 []
(io/with-input "02_input.txt" common-chars-for-correct-ids))
(deftest puzzle2-test
(testing "Simple test"
(is (= #{"fghij" "fguij"}
(set (off-by-one-ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"])))))
(testing "Simple test - check common letters"
(is (= "fgij"
(apply common-chars (off-by-one-ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"])))
(testing "Real input"
(is (= "fonbwmjquwtapeyzikghtvdxl" (time (puzzle2))))))))
Journal :
;;; ===============================================================================
(comment
;; let's start with frequencies
(map frequencies ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"])
( { \a 1 , \b 1 , \c 1 , \d 1 , \e 1 , \f 1 }
{ \b 3 , \a 2 , \c 1 }
{ \a 1 , \b 2 , \c 1 , \d 1 , \e 1 }
{ \a 1 , \b 1 , \c 3 , \d 1 }
{ \a 2 , \b 1 , \c 1 , \d 2 }
{ \a 1 , \b 1 , \c 1 , \d 1 , \e 2 }
{ \a 3 , \b 3 } )
filter only those with 2 or 3 frequency
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map frequencies)
(filter (fn [id-freqs]
(some (fn [[char freq]] (<= 2 freq 3))
id-freqs))))
({\b 3, \a 2, \c 1}
{\a 1, \b 2, \c 1, \d 1, \e 1}
{\a 1, \b 1, \c 3, \d 1}
{\a 2, \b 1, \c 1, \d 2}
{\a 1, \b 1, \c 1, \d 1, \e 2}
{\a 3, \b 3})
;; what if I use only vals and make them sets?
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
#_(map (comp frequencies vals distinct))
(map #(-> % frequencies vals set)))
( # { 1 } # { 1 3 2 } # { 1 2 } # { 1 3 } # { 1 2 } # { 1 2 } # { 3 } )
;; sum twos
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map #(-> % frequencies vals set))
(filter #(contains? % 2)))
and sum threes
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map #(-> % frequencies vals set))
(filter #(contains? % 3)))
;; let's put it together
(let [ids ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
ids-freqs (map #(-> % frequencies vals set) ids)
count-freqs (fn [desired-freq] (count (filter #(contains? % desired-freq) ids-freqs)))
twos-count (count-freqs 2)
threes-count (count-freqs 3)]
(* twos-count
threes-count))
Puzzle 2
;; first create a skeleton + simple implementation
(defn off-by-one-ids [ids]
)
(defn common-chars [w1 w2]
(apply str (filter (set w1) w2)))
(common-chars "fghij" "fguij")
;; continue to find candidates.
(let [ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"]]
(->> ids
(map (fn [id]
(first (filter (fn [id2] (and (= (count id) (count id2))
(= (dec (count id)) (count (common-chars id id2)))))
(disj (set ids) id)))))
(remove empty?)))
)
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/advent_of_code/advent_2018/02_inventory_management.clj | clojure | Simply scan find number of boxes with an ID containing any of letters repeating twice;
--------
===============================================================================
let's start with frequencies
what if I use only vals and make them sets?
sum twos
let's put it together
first create a skeleton + simple implementation
continue to find candidates. | (ns advent-of-clojure.2018.02-inventory-management
""
(:require [clojure.test :refer [deftest testing is]]
[advent-of-clojure.2018.input :as io]))
Inventory management system
Year 1518 : Warehouse boxes
Puzzle 1 : Count checksum of candidate boxes
then multiply these two numbers together
(defn checksum [ids]
e.g. ' ( # { 1 } # { 1 3 2 } # { 1 2 } # { 1 3 } # { 1 2 } # { 1 2 } # { 3 } )
count-freqs (fn [desired-freq] (count (filter #(contains? % desired-freq) ids-freqs)))
twos-count (count-freqs 2)
threes-count (count-freqs 3)]
(* twos-count threes-count)))
(defn puzzle1 []
(io/with-input "02_input.txt" checksum))
(deftest puzzle1-test
(testing "Simple checksum"
(is (= 12 (checksum ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]))))
(testing "Real input"
(is (= 4920 (puzzle1)))))
Puzzle 2 :
(defn common-chars
"Returns a string representing all characters that are the same and at the same position.
Same characters at different positions don't count!"
[w1 w2]
(let [char-or-nil (map (fn [ch1 ch2]
(when (= ch1 ch2)
ch1))
w1
w2)]
(->> char-or-nil
(remove nil?)
(apply str))))
(defn matching-ids
"For given ID find another id that 'match it' - that means they differ in exactly one character."
[id other-ids]
(first (filter (fn [id2] (and (= (count id) (count id2))
(= (dec (count id)) (count (common-chars id id2)))))
other-ids
)))
(defn off-by-one-ids
"In given set of ides find all ids that differ in exactly one character.
See `common-chars`."
[ids]
(->> ids
(map (fn [id]
(let [other-ids (disj (set ids) id)]
(matching-ids id other-ids))))
(remove empty?)))
(defn common-chars-for-correct-ids
"Finds common characters for 'matching ids in given collection.
It's assumed that there are only two such IDs - otherwise `common=chars` call throws an exception."
[ids]
(->> ids
off-by-one-ids
(apply common-chars)))
(defn puzzle2 []
(io/with-input "02_input.txt" common-chars-for-correct-ids))
(deftest puzzle2-test
(testing "Simple test"
(is (= #{"fghij" "fguij"}
(set (off-by-one-ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"])))))
(testing "Simple test - check common letters"
(is (= "fgij"
(apply common-chars (off-by-one-ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"])))
(testing "Real input"
(is (= "fonbwmjquwtapeyzikghtvdxl" (time (puzzle2))))))))
Journal :
(comment
(map frequencies ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"])
( { \a 1 , \b 1 , \c 1 , \d 1 , \e 1 , \f 1 }
{ \b 3 , \a 2 , \c 1 }
{ \a 1 , \b 2 , \c 1 , \d 1 , \e 1 }
{ \a 1 , \b 1 , \c 3 , \d 1 }
{ \a 2 , \b 1 , \c 1 , \d 2 }
{ \a 1 , \b 1 , \c 1 , \d 1 , \e 2 }
{ \a 3 , \b 3 } )
filter only those with 2 or 3 frequency
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map frequencies)
(filter (fn [id-freqs]
(some (fn [[char freq]] (<= 2 freq 3))
id-freqs))))
({\b 3, \a 2, \c 1}
{\a 1, \b 2, \c 1, \d 1, \e 1}
{\a 1, \b 1, \c 3, \d 1}
{\a 2, \b 1, \c 1, \d 2}
{\a 1, \b 1, \c 1, \d 1, \e 2}
{\a 3, \b 3})
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
#_(map (comp frequencies vals distinct))
(map #(-> % frequencies vals set)))
( # { 1 } # { 1 3 2 } # { 1 2 } # { 1 3 } # { 1 2 } # { 1 2 } # { 3 } )
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map #(-> % frequencies vals set))
(filter #(contains? % 2)))
and sum threes
(->> ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
(map #(-> % frequencies vals set))
(filter #(contains? % 3)))
(let [ids ["abcdef" "bababc" "abbcde" "abcccd" "aabcdd" "abcdee" "ababab"]
ids-freqs (map #(-> % frequencies vals set) ids)
count-freqs (fn [desired-freq] (count (filter #(contains? % desired-freq) ids-freqs)))
twos-count (count-freqs 2)
threes-count (count-freqs 3)]
(* twos-count
threes-count))
Puzzle 2
(defn off-by-one-ids [ids]
)
(defn common-chars [w1 w2]
(apply str (filter (set w1) w2)))
(common-chars "fghij" "fguij")
(let [ids ["abcde" "fghij" "klmno" "pqrst" "fguij" "axcye" "wvxyz"]]
(->> ids
(map (fn [id]
(first (filter (fn [id2] (and (= (count id) (count id2))
(= (dec (count id)) (count (common-chars id id2)))))
(disj (set ids) id)))))
(remove empty?)))
)
|
943a6b529ec00cdbc2f51d204985fcbbef6c1efa143706d96d57506599ea94af | erlang/otp | core_alias_SUITE.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2007 - 2021 . 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.
%%
%% %CopyrightEnd%
%%
-module(core_alias_SUITE).
-export([all/0, suite/0, groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2, end_per_group/2,
tuples/1, cons/1, catastrophic_runtime/1,
coverage/1]).
-include_lib("common_test/include/ct.hrl").
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
[{group,p}].
groups() ->
[{p,[parallel],
[tuples, cons, catastrophic_runtime, coverage]}].
init_per_suite(Config) ->
test_lib:recompile(?MODULE),
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
id(X) -> X.
tuples(Config) when is_list(Config) ->
Tuple = id({ok,id(value)}),
true = erts_debug:same(Tuple, simple_tuple(Tuple)),
true = erts_debug:same(Tuple, simple_tuple_in_map(#{hello => Tuple})),
true = erts_debug:same(Tuple, simple_tuple_case_repeated(Tuple, Tuple)),
true = erts_debug:same(Tuple, simple_tuple_fun_repeated(Tuple, Tuple)),
true = erts_debug:same(Tuple, simple_tuple_twice_head(Tuple, Tuple)),
{Tuple1, Tuple2} = id(simple_tuple_twice_body(Tuple)),
true = erts_debug:same(Tuple, Tuple1),
true = erts_debug:same(Tuple, Tuple2),
Nested = id({nested,Tuple}),
true = erts_debug:same(Tuple, nested_tuple_part(Nested)),
true = erts_debug:same(Nested, nested_tuple_whole(Nested)),
true = erts_debug:same(Nested, nested_tuple_with_alias(Nested)),
true = erts_debug:same(Tuple, tuple_rebinding_after(Tuple)),
Tuple = id(unaliased_tuple_rebinding_before(Tuple)),
false = erts_debug:same(Tuple, unaliased_tuple_rebinding_before(Tuple)),
Nested = id(unaliased_literal_tuple_head(Nested)),
false = erts_debug:same(Nested, unaliased_literal_tuple_head(Nested)),
Nested = id(unaliased_literal_tuple_body(Nested)),
false = erts_debug:same(Nested, unaliased_literal_tuple_body(Nested)),
Nested = id(unaliased_different_var_tuple(Nested, Tuple)),
false = erts_debug:same(Nested, unaliased_different_var_tuple(Nested, Tuple)).
simple_tuple({ok,X}) ->
{ok,X}.
simple_tuple_twice_head({ok,X}, {ok,X}) ->
{ok,X}.
simple_tuple_twice_body({ok,X}) ->
{{ok,X},{ok,X}}.
simple_tuple_in_map(#{hello := {ok,X}}) ->
{ok,X}.
simple_tuple_fun_repeated({ok,X}, Y) ->
io:format("~p~n", [X]),
(fun({ok,X}) -> {ok,X} end)(Y).
simple_tuple_case_repeated({ok,X}, Y) ->
io:format("~p~n", [X]),
case Y of {ok,X} -> {ok,X} end.
nested_tuple_part({nested,{ok,X}}) ->
{ok,X}.
nested_tuple_whole({nested,{ok,X}}) ->
{nested,{ok,X}}.
nested_tuple_with_alias({nested,{ok,_}=Y}) ->
{nested,Y}.
tuple_rebinding_after(Y) ->
(fun(X) -> {ok,X} end)(Y),
case Y of {ok,X} -> {ok,X} end.
unaliased_tuple_rebinding_before({ok,X}) ->
io:format("~p~n", [X]),
(fun(X) -> {ok,X} end)(value).
unaliased_literal_tuple_head({nested,{ok,value}=X}) ->
io:format("~p~n", [X]),
{nested,{ok,value}}.
unaliased_literal_tuple_body({nested,{ok,value}=X}) ->
Res = {nested,Y={ok,value}},
io:format("~p~n", [[X,Y]]),
Res.
unaliased_different_var_tuple({nested,{ok,value}=X}, Y) ->
io:format("~p~n", [X]),
{nested,Y}.
cons(Config) when is_list(Config) ->
Cons = id([ok|id(value)]),
true = erts_debug:same(Cons, simple_cons(Cons)),
true = erts_debug:same(Cons, simple_cons_in_map(#{hello => Cons})),
true = erts_debug:same(Cons, simple_cons_case_repeated(Cons, Cons)),
true = erts_debug:same(Cons, simple_cons_fun_repeated(Cons, Cons)),
true = erts_debug:same(Cons, simple_cons_twice_head(Cons, Cons)),
{Cons1,Cons2} = id(simple_cons_twice_body(Cons)),
true = erts_debug:same(Cons, Cons1),
true = erts_debug:same(Cons, Cons2),
Nested = id([nested,Cons]),
true = erts_debug:same(Cons, nested_cons_part(Nested)),
true = erts_debug:same(Nested, nested_cons_whole(Nested)),
true = erts_debug:same(Nested, nested_cons_with_alias(Nested)),
true = erts_debug:same(Cons, cons_rebinding_after(Cons)),
Unstripped = id([a,b]),
Stripped = id(cons_with_binary([<<>>|Unstripped])),
true = erts_debug:same(Unstripped, Stripped),
Cons = id(unaliased_cons_rebinding_before(Cons)),
false = erts_debug:same(Cons, unaliased_cons_rebinding_before(Cons)),
Nested = id(unaliased_literal_cons_head(Nested)),
false = erts_debug:same(Nested, unaliased_literal_cons_head(Nested)),
Nested = id(unaliased_literal_cons_body(Nested)),
false = erts_debug:same(Nested, unaliased_literal_cons_body(Nested)),
Nested = id(unaliased_different_var_cons(Nested, Cons)),
false = erts_debug:same(Nested, unaliased_different_var_cons(Nested, Cons)).
simple_cons([ok|X]) ->
[ok|X].
simple_cons_twice_head([ok|X], [ok|X]) ->
[ok|X].
simple_cons_twice_body([ok|X]) ->
{[ok|X],[ok|X]}.
simple_cons_in_map(#{hello := [ok|X]}) ->
[ok|X].
simple_cons_fun_repeated([ok|X], Y) ->
io:format("~p~n", [X]),
(fun([ok|X]) -> [ok|X] end)(Y).
simple_cons_case_repeated([ok|X], Y) ->
io:format("~p~n", [X]),
case Y of [ok|X] -> [ok|X] end.
nested_cons_part([nested,[ok|X]]) ->
[ok|X].
nested_cons_whole([nested,[ok|X]]) ->
[nested,[ok|X]].
nested_cons_with_alias([nested,[ok|_]=Y]) ->
[nested,Y].
cons_with_binary([<<>>,X|Y]) ->
cons_with_binary([X|Y]);
cons_with_binary(A) ->
A.
cons_rebinding_after(Y) ->
(fun(X) -> [ok|X] end)(Y),
case Y of [ok|X] -> [ok|X] end.
unaliased_cons_rebinding_before([ok|X]) ->
io:format("~p~n", [X]),
(fun(X) -> [ok|X] end)(value).
unaliased_literal_cons_head([nested,[ok|value]=X]) ->
io:format("~p~n", [X]),
[nested,[ok|value]].
unaliased_literal_cons_body([nested,[ok|value]=X]) ->
Res = [nested,Y=[ok|value]],
io:format("~p~n", [[X, Y]]),
Res.
unaliased_different_var_cons([nested,[ok|value]=X], Y) ->
io:format("~p~n", [X]),
[nested,Y].
catastrophic_runtime(Config) ->
ct:timetrap({minutes, 6}),
Depth = 16000,
PrivDir = proplists:get_value(priv_dir,Config),
Path = filename:join(PrivDir, "catastrophic_runtime.erl"),
Term = catastrophic_runtime_1(Depth),
Source = ["-module(catastrophic_runtime). t(Value) -> ", Term, "."],
ok = file:write_file(Path, Source),
{ok, catastrophic_runtime} = compile:file(Path, [return_error]),
file:delete(Path),
ok.
catastrophic_runtime_1(0) ->
<<"Value">>;
catastrophic_runtime_1(N) ->
Nested = catastrophic_runtime_1(N - 1),
Integer = integer_to_binary(N),
Eq = [<<"{{'.',[],[erlang,'=:=']},[],[Value, \"">>, Integer, <<"\"]}">>],
[<<"{{'.',[],[erlang,atom]},[],[">>, Nested, <<",">>, Eq, <<"]}">>].
coverage(_Config) ->
State = id({undefined,undefined}),
{State, "Can't detect character encoding due to lack of indata"} =
too_deep(State),
ok.
too_deep({_,undefined} = State) ->
{State, "Can't detect character encoding due to lack of indata"}.
| null | https://raw.githubusercontent.com/erlang/otp/93f444c27ec2a3a9001ea9d0930d8d19432628e5/lib/compiler/test/core_alias_SUITE.erl | erlang |
%CopyrightBegin%
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.
%CopyrightEnd%
| Copyright Ericsson AB 2007 - 2021 . 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(core_alias_SUITE).
-export([all/0, suite/0, groups/0,init_per_suite/1, end_per_suite/1,
init_per_group/2, end_per_group/2,
tuples/1, cons/1, catastrophic_runtime/1,
coverage/1]).
-include_lib("common_test/include/ct.hrl").
suite() -> [{ct_hooks,[ts_install_cth]}].
all() ->
[{group,p}].
groups() ->
[{p,[parallel],
[tuples, cons, catastrophic_runtime, coverage]}].
init_per_suite(Config) ->
test_lib:recompile(?MODULE),
Config.
end_per_suite(_Config) ->
ok.
init_per_group(_GroupName, Config) ->
Config.
end_per_group(_GroupName, Config) ->
Config.
id(X) -> X.
tuples(Config) when is_list(Config) ->
Tuple = id({ok,id(value)}),
true = erts_debug:same(Tuple, simple_tuple(Tuple)),
true = erts_debug:same(Tuple, simple_tuple_in_map(#{hello => Tuple})),
true = erts_debug:same(Tuple, simple_tuple_case_repeated(Tuple, Tuple)),
true = erts_debug:same(Tuple, simple_tuple_fun_repeated(Tuple, Tuple)),
true = erts_debug:same(Tuple, simple_tuple_twice_head(Tuple, Tuple)),
{Tuple1, Tuple2} = id(simple_tuple_twice_body(Tuple)),
true = erts_debug:same(Tuple, Tuple1),
true = erts_debug:same(Tuple, Tuple2),
Nested = id({nested,Tuple}),
true = erts_debug:same(Tuple, nested_tuple_part(Nested)),
true = erts_debug:same(Nested, nested_tuple_whole(Nested)),
true = erts_debug:same(Nested, nested_tuple_with_alias(Nested)),
true = erts_debug:same(Tuple, tuple_rebinding_after(Tuple)),
Tuple = id(unaliased_tuple_rebinding_before(Tuple)),
false = erts_debug:same(Tuple, unaliased_tuple_rebinding_before(Tuple)),
Nested = id(unaliased_literal_tuple_head(Nested)),
false = erts_debug:same(Nested, unaliased_literal_tuple_head(Nested)),
Nested = id(unaliased_literal_tuple_body(Nested)),
false = erts_debug:same(Nested, unaliased_literal_tuple_body(Nested)),
Nested = id(unaliased_different_var_tuple(Nested, Tuple)),
false = erts_debug:same(Nested, unaliased_different_var_tuple(Nested, Tuple)).
simple_tuple({ok,X}) ->
{ok,X}.
simple_tuple_twice_head({ok,X}, {ok,X}) ->
{ok,X}.
simple_tuple_twice_body({ok,X}) ->
{{ok,X},{ok,X}}.
simple_tuple_in_map(#{hello := {ok,X}}) ->
{ok,X}.
simple_tuple_fun_repeated({ok,X}, Y) ->
io:format("~p~n", [X]),
(fun({ok,X}) -> {ok,X} end)(Y).
simple_tuple_case_repeated({ok,X}, Y) ->
io:format("~p~n", [X]),
case Y of {ok,X} -> {ok,X} end.
nested_tuple_part({nested,{ok,X}}) ->
{ok,X}.
nested_tuple_whole({nested,{ok,X}}) ->
{nested,{ok,X}}.
nested_tuple_with_alias({nested,{ok,_}=Y}) ->
{nested,Y}.
tuple_rebinding_after(Y) ->
(fun(X) -> {ok,X} end)(Y),
case Y of {ok,X} -> {ok,X} end.
unaliased_tuple_rebinding_before({ok,X}) ->
io:format("~p~n", [X]),
(fun(X) -> {ok,X} end)(value).
unaliased_literal_tuple_head({nested,{ok,value}=X}) ->
io:format("~p~n", [X]),
{nested,{ok,value}}.
unaliased_literal_tuple_body({nested,{ok,value}=X}) ->
Res = {nested,Y={ok,value}},
io:format("~p~n", [[X,Y]]),
Res.
unaliased_different_var_tuple({nested,{ok,value}=X}, Y) ->
io:format("~p~n", [X]),
{nested,Y}.
cons(Config) when is_list(Config) ->
Cons = id([ok|id(value)]),
true = erts_debug:same(Cons, simple_cons(Cons)),
true = erts_debug:same(Cons, simple_cons_in_map(#{hello => Cons})),
true = erts_debug:same(Cons, simple_cons_case_repeated(Cons, Cons)),
true = erts_debug:same(Cons, simple_cons_fun_repeated(Cons, Cons)),
true = erts_debug:same(Cons, simple_cons_twice_head(Cons, Cons)),
{Cons1,Cons2} = id(simple_cons_twice_body(Cons)),
true = erts_debug:same(Cons, Cons1),
true = erts_debug:same(Cons, Cons2),
Nested = id([nested,Cons]),
true = erts_debug:same(Cons, nested_cons_part(Nested)),
true = erts_debug:same(Nested, nested_cons_whole(Nested)),
true = erts_debug:same(Nested, nested_cons_with_alias(Nested)),
true = erts_debug:same(Cons, cons_rebinding_after(Cons)),
Unstripped = id([a,b]),
Stripped = id(cons_with_binary([<<>>|Unstripped])),
true = erts_debug:same(Unstripped, Stripped),
Cons = id(unaliased_cons_rebinding_before(Cons)),
false = erts_debug:same(Cons, unaliased_cons_rebinding_before(Cons)),
Nested = id(unaliased_literal_cons_head(Nested)),
false = erts_debug:same(Nested, unaliased_literal_cons_head(Nested)),
Nested = id(unaliased_literal_cons_body(Nested)),
false = erts_debug:same(Nested, unaliased_literal_cons_body(Nested)),
Nested = id(unaliased_different_var_cons(Nested, Cons)),
false = erts_debug:same(Nested, unaliased_different_var_cons(Nested, Cons)).
simple_cons([ok|X]) ->
[ok|X].
simple_cons_twice_head([ok|X], [ok|X]) ->
[ok|X].
simple_cons_twice_body([ok|X]) ->
{[ok|X],[ok|X]}.
simple_cons_in_map(#{hello := [ok|X]}) ->
[ok|X].
simple_cons_fun_repeated([ok|X], Y) ->
io:format("~p~n", [X]),
(fun([ok|X]) -> [ok|X] end)(Y).
simple_cons_case_repeated([ok|X], Y) ->
io:format("~p~n", [X]),
case Y of [ok|X] -> [ok|X] end.
nested_cons_part([nested,[ok|X]]) ->
[ok|X].
nested_cons_whole([nested,[ok|X]]) ->
[nested,[ok|X]].
nested_cons_with_alias([nested,[ok|_]=Y]) ->
[nested,Y].
cons_with_binary([<<>>,X|Y]) ->
cons_with_binary([X|Y]);
cons_with_binary(A) ->
A.
cons_rebinding_after(Y) ->
(fun(X) -> [ok|X] end)(Y),
case Y of [ok|X] -> [ok|X] end.
unaliased_cons_rebinding_before([ok|X]) ->
io:format("~p~n", [X]),
(fun(X) -> [ok|X] end)(value).
unaliased_literal_cons_head([nested,[ok|value]=X]) ->
io:format("~p~n", [X]),
[nested,[ok|value]].
unaliased_literal_cons_body([nested,[ok|value]=X]) ->
Res = [nested,Y=[ok|value]],
io:format("~p~n", [[X, Y]]),
Res.
unaliased_different_var_cons([nested,[ok|value]=X], Y) ->
io:format("~p~n", [X]),
[nested,Y].
catastrophic_runtime(Config) ->
ct:timetrap({minutes, 6}),
Depth = 16000,
PrivDir = proplists:get_value(priv_dir,Config),
Path = filename:join(PrivDir, "catastrophic_runtime.erl"),
Term = catastrophic_runtime_1(Depth),
Source = ["-module(catastrophic_runtime). t(Value) -> ", Term, "."],
ok = file:write_file(Path, Source),
{ok, catastrophic_runtime} = compile:file(Path, [return_error]),
file:delete(Path),
ok.
catastrophic_runtime_1(0) ->
<<"Value">>;
catastrophic_runtime_1(N) ->
Nested = catastrophic_runtime_1(N - 1),
Integer = integer_to_binary(N),
Eq = [<<"{{'.',[],[erlang,'=:=']},[],[Value, \"">>, Integer, <<"\"]}">>],
[<<"{{'.',[],[erlang,atom]},[],[">>, Nested, <<",">>, Eq, <<"]}">>].
coverage(_Config) ->
State = id({undefined,undefined}),
{State, "Can't detect character encoding due to lack of indata"} =
too_deep(State),
ok.
too_deep({_,undefined} = State) ->
{State, "Can't detect character encoding due to lack of indata"}.
|
08882cdfa2db3d19497eb3945c9b1fedccb25ff7e646dd880b7dcf36da107618 | Emmanuel-PLF/facile | fcl_fdArray.mli | (***********************************************************************)
(* *)
FaCiLe
A Functional Constraint Library
(* *)
, , LOG , CENA
(* *)
Copyright 2004 CENA . All rights reserved . This file is distributed
(* under the terms of the GNU Lesser General Public License. *)
(***********************************************************************)
$ I d : , v 1.15 2003/02/03 15:50:48 brisset Exp $
(** Constraints over Arrays of Variables *)
val min : Fcl_var.Fd.t array -> Fcl_var.Fd.t
val max : Fcl_var.Fd.t array -> Fcl_var.Fd.t
* [ min vars ] ( resp . [ vars ] ) returns a variable constrained to be equal
to the variable that will be instantiated to the minimal ( resp . maximal )
value among all the variables in the array [ vars ] . Raises
[ Invalid_argument ] if [ vars ] is empty . Not reifiable .
to the variable that will be instantiated to the minimal (resp. maximal)
value among all the variables in the array [vars]. Raises
[Invalid_argument] if [vars] is empty. Not reifiable. *)
val min_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_cstr.t
val max_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_cstr.t
* [ vars mini ] ( resp . [ max_cstr vars maxi ] ) returns the constraint
[ fd2e ( min vars ) = ~ fd2e mini ] ( resp . [ fd2e ( max vars ) = ~ fd2e maxi ] ) .
Raises [ Invalid_argument ] if [ vars ] is empty . Not reifiable .
[fd2e (min vars) =~ fd2e mini] (resp. [fd2e (max vars) =~ fd2e maxi]).
Raises [Invalid_argument] if [vars] is empty. Not reifiable. *)
val get : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_var.Fd.t
(** [get vars index] returns a variable constrained to be equal to
[vars.(index)]. Variable [index] is constrained within the range of
the valid indices of the array [(0..Array.length vars - 1)]. Raises
[Invalid_argument] if [vars] is empty.
Not reifiable. *)
val get_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_var.Fd.t -> Fcl_cstr.t
* [ get_cstr vars index v ] returns the constraint
[ fd2e vars.(index ) = ~ fd2e v ] . Variable [ index ] is constrained within
the range of the valid indices of the array [ ( 0 .. Array.length vars - 1 ) ] .
Raises [ Invalid_argument ] if [ vars ] is empty . Not reifiable .
[fd2e vars.(index) =~ fd2e v]. Variable [index] is constrained within
the range of the valid indices of the array [(0..Array.length vars - 1)].
Raises [Invalid_argument] if [vars] is empty. Not reifiable. *)
| null | https://raw.githubusercontent.com/Emmanuel-PLF/facile/3b6902e479019c25b582042d9a02152fec145eb0/lib/fcl_fdArray.mli | ocaml | *********************************************************************
under the terms of the GNU Lesser General Public License.
*********************************************************************
* Constraints over Arrays of Variables
* [get vars index] returns a variable constrained to be equal to
[vars.(index)]. Variable [index] is constrained within the range of
the valid indices of the array [(0..Array.length vars - 1)]. Raises
[Invalid_argument] if [vars] is empty.
Not reifiable. | FaCiLe
A Functional Constraint Library
, , LOG , CENA
Copyright 2004 CENA . All rights reserved . This file is distributed
$ I d : , v 1.15 2003/02/03 15:50:48 brisset Exp $
val min : Fcl_var.Fd.t array -> Fcl_var.Fd.t
val max : Fcl_var.Fd.t array -> Fcl_var.Fd.t
* [ min vars ] ( resp . [ vars ] ) returns a variable constrained to be equal
to the variable that will be instantiated to the minimal ( resp . maximal )
value among all the variables in the array [ vars ] . Raises
[ Invalid_argument ] if [ vars ] is empty . Not reifiable .
to the variable that will be instantiated to the minimal (resp. maximal)
value among all the variables in the array [vars]. Raises
[Invalid_argument] if [vars] is empty. Not reifiable. *)
val min_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_cstr.t
val max_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_cstr.t
* [ vars mini ] ( resp . [ max_cstr vars maxi ] ) returns the constraint
[ fd2e ( min vars ) = ~ fd2e mini ] ( resp . [ fd2e ( max vars ) = ~ fd2e maxi ] ) .
Raises [ Invalid_argument ] if [ vars ] is empty . Not reifiable .
[fd2e (min vars) =~ fd2e mini] (resp. [fd2e (max vars) =~ fd2e maxi]).
Raises [Invalid_argument] if [vars] is empty. Not reifiable. *)
val get : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_var.Fd.t
val get_cstr : Fcl_var.Fd.t array -> Fcl_var.Fd.t -> Fcl_var.Fd.t -> Fcl_cstr.t
* [ get_cstr vars index v ] returns the constraint
[ fd2e vars.(index ) = ~ fd2e v ] . Variable [ index ] is constrained within
the range of the valid indices of the array [ ( 0 .. Array.length vars - 1 ) ] .
Raises [ Invalid_argument ] if [ vars ] is empty . Not reifiable .
[fd2e vars.(index) =~ fd2e v]. Variable [index] is constrained within
the range of the valid indices of the array [(0..Array.length vars - 1)].
Raises [Invalid_argument] if [vars] is empty. Not reifiable. *)
|
9f802fe58191d52e93762eb14d913049f0b597c0d2c1d58cac861e1f5ca2d552 | ocaml-ppx/ocamlformat | test_indent.ml | open Ocamlformat_lib
let read_file f = Stdio.In_channel.with_file f ~f:Stdio.In_channel.input_all
let partial_let = read_file "../passing/tests/partial.ml"
let normalize_eol = Eol_compat.normalize_eol ~line_endings:`Lf
module Partial_ast = struct
let tests_indent_range =
let test name ~input:source ~range ~expected =
let test_name = "Partial_ast.indent_range: " ^ name in
( test_name
, `Quick
, fun () ->
let range = Range.make ~range source in
let indent = Indent.Partial_ast.indent_range ~source ~range in
let output =
Test_translation_unit.reindent ~source ~range indent
in
let expected = normalize_eol expected in
Alcotest.(check string) test_name expected output )
in
[ test "empty" ~input:"" ~range:(1, 1) ~expected:""
; test "multiline let" ~range:(1, 5) ~input:{|let f =
let x =
y
in
2|}
~expected:{|let f =
let x =
y
in
2|}
; test "after in" ~range:(1, 12)
~input:
{|let f =
let x =
let y =
foooooooooooooooooooo
in
let x = fooooooooooooo in
let k =
fooooooo
in
foooooooooooooooooooooooooo
foooooooooooooooooooo foooooooooooooooo fooooooooo
in
|}
~expected:
{|let f =
let x =
let y =
foooooooooooooooooooo
in
let x = fooooooooooooo in
let k =
fooooooo
in
foooooooooooooooooooooooooo
foooooooooooooooooooo foooooooooooooooo fooooooooo
in|}
; test "partial let" ~range:(2, 14) ~input:partial_let
~expected:
{| let () =
ffff;
hhhhhh;
fff;
let (quot, _rem) =
let quot_rem n k =
let (d, m) = (n / k, n mod k) in
if d < 0 && m > 0 then (d+1, m-k)
else (d, m)
in
let quot n k = fst (quot_rem n k) in
let rem n k = snd (quot_rem n k) in
quot, rem|}
]
let tests = tests_indent_range
end
let tests = Partial_ast.tests
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/39c6197eb2a8f27d7fd64035f5fb6a52a598845c/test/unit/test_indent.ml | ocaml | open Ocamlformat_lib
let read_file f = Stdio.In_channel.with_file f ~f:Stdio.In_channel.input_all
let partial_let = read_file "../passing/tests/partial.ml"
let normalize_eol = Eol_compat.normalize_eol ~line_endings:`Lf
module Partial_ast = struct
let tests_indent_range =
let test name ~input:source ~range ~expected =
let test_name = "Partial_ast.indent_range: " ^ name in
( test_name
, `Quick
, fun () ->
let range = Range.make ~range source in
let indent = Indent.Partial_ast.indent_range ~source ~range in
let output =
Test_translation_unit.reindent ~source ~range indent
in
let expected = normalize_eol expected in
Alcotest.(check string) test_name expected output )
in
[ test "empty" ~input:"" ~range:(1, 1) ~expected:""
; test "multiline let" ~range:(1, 5) ~input:{|let f =
let x =
y
in
2|}
~expected:{|let f =
let x =
y
in
2|}
; test "after in" ~range:(1, 12)
~input:
{|let f =
let x =
let y =
foooooooooooooooooooo
in
let x = fooooooooooooo in
let k =
fooooooo
in
foooooooooooooooooooooooooo
foooooooooooooooooooo foooooooooooooooo fooooooooo
in
|}
~expected:
{|let f =
let x =
let y =
foooooooooooooooooooo
in
let x = fooooooooooooo in
let k =
fooooooo
in
foooooooooooooooooooooooooo
foooooooooooooooooooo foooooooooooooooo fooooooooo
in|}
; test "partial let" ~range:(2, 14) ~input:partial_let
~expected:
{| let () =
ffff;
hhhhhh;
fff;
let (quot, _rem) =
let quot_rem n k =
let (d, m) = (n / k, n mod k) in
if d < 0 && m > 0 then (d+1, m-k)
else (d, m)
in
let quot n k = fst (quot_rem n k) in
let rem n k = snd (quot_rem n k) in
quot, rem|}
]
let tests = tests_indent_range
end
let tests = Partial_ast.tests
|
|
22163754ea4e691e65ae928f01c984ef7c2cd52dfcd94c772f144246b8c630a4 | kafka4beam/kafka_protocol | kpro_schema_tests.erl | Copyright ( c ) 2018 - 2021 , Klarna Bank AB ( publ )
%%%
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(kpro_schema_tests).
-include_lib("eunit/include/eunit.hrl").
all_test() ->
lists:foreach(fun test_api/1, kpro_schema:all_apis()).
test_api(API) ->
?assertEqual(API, kpro_schema:api_key(kpro_schema:api_key(API))),
{MinV, MaxV} = kpro_schema:vsn_range(API),
lists:foreach(fun(V) ->
?assert(is_list(kpro_schema:req(API, V))),
?assert(is_list(kpro_schema:rsp(API, V)))
end, lists:seq(MinV, MaxV)).
error_code_test() ->
%% insure it's added (if we ever regenerate the schema module)
?assertEqual(invalid_record, kpro_schema:ec(87)),
%% unknown error code should not crash
?assertEqual(99999, kpro_schema:ec(99999)).
%%%_* Emacs ====================================================================
%%% Local Variables:
%%% allout-layout: t
erlang - indent - level : 2
%%% End:
| null | https://raw.githubusercontent.com/kafka4beam/kafka_protocol/f0100ada6c318377f55502b9d9cd6d7043f5b930/test/kpro_schema_tests.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.
insure it's added (if we ever regenerate the schema module)
unknown error code should not crash
_* Emacs ====================================================================
Local Variables:
allout-layout: t
End: | Copyright ( c ) 2018 - 2021 , Klarna Bank AB ( publ )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(kpro_schema_tests).
-include_lib("eunit/include/eunit.hrl").
all_test() ->
lists:foreach(fun test_api/1, kpro_schema:all_apis()).
test_api(API) ->
?assertEqual(API, kpro_schema:api_key(kpro_schema:api_key(API))),
{MinV, MaxV} = kpro_schema:vsn_range(API),
lists:foreach(fun(V) ->
?assert(is_list(kpro_schema:req(API, V))),
?assert(is_list(kpro_schema:rsp(API, V)))
end, lists:seq(MinV, MaxV)).
error_code_test() ->
?assertEqual(invalid_record, kpro_schema:ec(87)),
?assertEqual(99999, kpro_schema:ec(99999)).
erlang - indent - level : 2
|
aca8c78c8a1c3435ceea38d8c1a41e0614676a828e5f0b75b136c30aadd2dc0e | isovector/algebra-checkers | Suggestions.hs | {-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TemplateHaskellQuotes #-}
module AlgebraCheckers.Suggestions where
import AlgebraCheckers.Patterns
import AlgebraCheckers.Ppr
import AlgebraCheckers.Unification
import Control.Monad
import Data.Char
import Data.Data
import Data.Generics.Schemes (listify)
import Data.Group
import Data.List
import Data.Maybe
import Data.Semigroup
import Data.Traversable
import Language.Haskell.TH hiding (ppr)
import Language.Haskell.TH.Syntax
import Prelude hiding (exp)
import THInstanceReification
data Suggestion
= HomoSuggestion Name Name Int Type Type Exp
deriving (Eq, Ord, Show)
homoSuggestionEq :: Suggestion -> Suggestion -> Bool
homoSuggestionEq (HomoSuggestion _ fn1 ix1 _ _ _)
(HomoSuggestion _ fn2 ix2 _ _ _) = fn1 == fn2
&& ix1 == ix2
pprSuggestion :: Suggestion -> Doc
pprSuggestion (HomoSuggestion nm _ _ arg_ty res_ty (LamE [VarP var] exp)) =
ppr $ deModuleName $
VarE 'law `AppTypeE` ConT nm `AppE` (LamE [SigP (VarP var) arg_ty] $ SigE exp res_ty)
pprSuggestion (HomoSuggestion nm _ _ _ _ exp) =
ppr $ deModuleName $
VarE 'law `AppTypeE` ConT nm `AppE` exp
knownSuggestionHierarchies :: [[Name]]
knownSuggestionHierarchies =
[ [ ''Group, ''Monoid, ''Semigroup ]
]
suggest :: Data a => Module -> a -> Q [Suggestion]
suggest md a = do
let surface = getSurface md a
fmap (join . join) $
for surface $ \nm ->
for knownSuggestionHierarchies $ \hierarchy -> do
zs <- fmap join $ for hierarchy $ \tc_name -> do
VarI _ ty _ <- reify nm
possibleHomos tc_name nm ty
pure $ nubBy homoSuggestionEq zs
suggest' :: Data a => a -> Q [Suggestion]
suggest' a = do
md <- thisModule
suggest md a
possibleHomos :: Name -> Name -> Type -> Q [Suggestion]
possibleHomos tc_name fn ty = do
let (args, res) = unrollTyArr ty
hasInstance tc_name res >>= \case
False -> pure []
True -> do
names <- for args $ newName . goodTyName
fmap catMaybes $ for (zip3 names args [0..]) $ \(name, arg, ix) ->
hasInstance tc_name arg >>= \case
False -> pure Nothing
True -> do
exp <- lamE [varP name] $ appsE $ varE fn : fmap varE names
pure $ Just $ HomoSuggestion tc_name fn ix arg res exp
goodTyName :: Type -> String
goodTyName = fmap toLower . take 1 . dropWhile (not . isAlpha) . render . ppr . deModuleName
getSurface :: Data a => Module -> a -> [Name]
getSurface m = listify (sameModule m)
sameModule :: Module -> Name -> Bool
sameModule (Module (PkgName pkg) (ModName md)) n =
nameModule n == Just md && namePackage n == Just pkg
unrollTyArr :: Type -> ([Type], Type)
unrollTyArr ty =
let tys = unloopTyArrs ty
in (init tys, last tys)
where
unloopTyArrs :: Type -> [Type]
unloopTyArrs (ArrowT `AppT` a `AppT` b) = a : unloopTyArrs b
unloopTyArrs t = [t]
hasInstance :: Name -> Type -> Q Bool
hasInstance tc_name = isProperInstance tc_name . pure
| null | https://raw.githubusercontent.com/isovector/algebra-checkers/40ed33d23ff36a78cef133d02cd9e44e4f7101f9/src/AlgebraCheckers/Suggestions.hs | haskell | # LANGUAGE LambdaCase #
# LANGUAGE TemplateHaskellQuotes # |
module AlgebraCheckers.Suggestions where
import AlgebraCheckers.Patterns
import AlgebraCheckers.Ppr
import AlgebraCheckers.Unification
import Control.Monad
import Data.Char
import Data.Data
import Data.Generics.Schemes (listify)
import Data.Group
import Data.List
import Data.Maybe
import Data.Semigroup
import Data.Traversable
import Language.Haskell.TH hiding (ppr)
import Language.Haskell.TH.Syntax
import Prelude hiding (exp)
import THInstanceReification
data Suggestion
= HomoSuggestion Name Name Int Type Type Exp
deriving (Eq, Ord, Show)
homoSuggestionEq :: Suggestion -> Suggestion -> Bool
homoSuggestionEq (HomoSuggestion _ fn1 ix1 _ _ _)
(HomoSuggestion _ fn2 ix2 _ _ _) = fn1 == fn2
&& ix1 == ix2
pprSuggestion :: Suggestion -> Doc
pprSuggestion (HomoSuggestion nm _ _ arg_ty res_ty (LamE [VarP var] exp)) =
ppr $ deModuleName $
VarE 'law `AppTypeE` ConT nm `AppE` (LamE [SigP (VarP var) arg_ty] $ SigE exp res_ty)
pprSuggestion (HomoSuggestion nm _ _ _ _ exp) =
ppr $ deModuleName $
VarE 'law `AppTypeE` ConT nm `AppE` exp
knownSuggestionHierarchies :: [[Name]]
knownSuggestionHierarchies =
[ [ ''Group, ''Monoid, ''Semigroup ]
]
suggest :: Data a => Module -> a -> Q [Suggestion]
suggest md a = do
let surface = getSurface md a
fmap (join . join) $
for surface $ \nm ->
for knownSuggestionHierarchies $ \hierarchy -> do
zs <- fmap join $ for hierarchy $ \tc_name -> do
VarI _ ty _ <- reify nm
possibleHomos tc_name nm ty
pure $ nubBy homoSuggestionEq zs
suggest' :: Data a => a -> Q [Suggestion]
suggest' a = do
md <- thisModule
suggest md a
possibleHomos :: Name -> Name -> Type -> Q [Suggestion]
possibleHomos tc_name fn ty = do
let (args, res) = unrollTyArr ty
hasInstance tc_name res >>= \case
False -> pure []
True -> do
names <- for args $ newName . goodTyName
fmap catMaybes $ for (zip3 names args [0..]) $ \(name, arg, ix) ->
hasInstance tc_name arg >>= \case
False -> pure Nothing
True -> do
exp <- lamE [varP name] $ appsE $ varE fn : fmap varE names
pure $ Just $ HomoSuggestion tc_name fn ix arg res exp
goodTyName :: Type -> String
goodTyName = fmap toLower . take 1 . dropWhile (not . isAlpha) . render . ppr . deModuleName
getSurface :: Data a => Module -> a -> [Name]
getSurface m = listify (sameModule m)
sameModule :: Module -> Name -> Bool
sameModule (Module (PkgName pkg) (ModName md)) n =
nameModule n == Just md && namePackage n == Just pkg
unrollTyArr :: Type -> ([Type], Type)
unrollTyArr ty =
let tys = unloopTyArrs ty
in (init tys, last tys)
where
unloopTyArrs :: Type -> [Type]
unloopTyArrs (ArrowT `AppT` a `AppT` b) = a : unloopTyArrs b
unloopTyArrs t = [t]
hasInstance :: Name -> Type -> Q Bool
hasInstance tc_name = isProperInstance tc_name . pure
|
e1a9a650a835c87243117d9a1d4f2d40e80918aee8b7d71b1e0d2c3b0c4742fd | metametadata/clj-fakes | runner.cljs | (ns unit.runner
(:require [cljs.test]
[doo.runner :refer-macros [doo-tests]]
[unit.context]
[unit.args-matcher]
[unit.optional-fake]
[unit.fake]
[unit.recorded-fake]
[unit.unused-fakes-self-test]
[unit.unchecked-fakes-self-test]
[unit.was-called]
[unit.was-called-once]
[unit.was-matched-once]
[unit.was-not-called]
[unit.were-called-in-order]
[unit.reify-fake]
[unit.reify-nice-fake]
[unit.positions]
[unit.method-was-called]
[unit.method-was-called-once]
[unit.method-was-matched-once]
[unit.method-was-not-called]
[unit.methods-were-called-in-order]
[unit.patch]
[unit.original-val]
[unit.unpatch]
[unit.spy]
[unit.cyclically]
))
(doo-tests
'unit.context
'unit.args-matcher
'unit.optional-fake
'unit.fake
'unit.recorded-fake
'unit.unused-fakes-self-test
'unit.unchecked-fakes-self-test
'unit.was-called
'unit.was-called-once
'unit.was-matched-once
'unit.was-not-called
'unit.were-called-in-order
'unit.reify-fake
'unit.reify-nice-fake
'unit.positions
'unit.method-was-called
'unit.method-was-called-once
'unit.method-was-matched-once
'unit.method-was-not-called
'unit.methods-were-called-in-order
'unit.patch
'unit.original-val
'unit.unpatch
'unit.spy
'unit.cyclically
)
| null | https://raw.githubusercontent.com/metametadata/clj-fakes/d928ddfd11b150b1cd2df5621265c447bf42395a/test/unit/runner.cljs | clojure | (ns unit.runner
(:require [cljs.test]
[doo.runner :refer-macros [doo-tests]]
[unit.context]
[unit.args-matcher]
[unit.optional-fake]
[unit.fake]
[unit.recorded-fake]
[unit.unused-fakes-self-test]
[unit.unchecked-fakes-self-test]
[unit.was-called]
[unit.was-called-once]
[unit.was-matched-once]
[unit.was-not-called]
[unit.were-called-in-order]
[unit.reify-fake]
[unit.reify-nice-fake]
[unit.positions]
[unit.method-was-called]
[unit.method-was-called-once]
[unit.method-was-matched-once]
[unit.method-was-not-called]
[unit.methods-were-called-in-order]
[unit.patch]
[unit.original-val]
[unit.unpatch]
[unit.spy]
[unit.cyclically]
))
(doo-tests
'unit.context
'unit.args-matcher
'unit.optional-fake
'unit.fake
'unit.recorded-fake
'unit.unused-fakes-self-test
'unit.unchecked-fakes-self-test
'unit.was-called
'unit.was-called-once
'unit.was-matched-once
'unit.was-not-called
'unit.were-called-in-order
'unit.reify-fake
'unit.reify-nice-fake
'unit.positions
'unit.method-was-called
'unit.method-was-called-once
'unit.method-was-matched-once
'unit.method-was-not-called
'unit.methods-were-called-in-order
'unit.patch
'unit.original-val
'unit.unpatch
'unit.spy
'unit.cyclically
)
|
|
b737da42cc68767551b7e76ae369d14d13ed8e805129752dfcbd1f06a9a89c1f | amnh/poy5 | nonaddCS.mli | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
(* *)
(* 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
* This module implements sets of equally - weighted non - additive characters
in C. These sets are immutable but can share data through reference
counting on the C side . C is used mainly to ensure fast median - taking ;
medians are made with vectorizable bitwise operators .
This implementation can handle sets of size up to the word size in bits ,
i.e. , 32 characters on 32 - bit machines , 64 characters on 64 - bit machines .
Using n-1 characters ( 31 , 63 ) ensures complete interoperability with OCaml ;
using 32 or 64 allows you to use all the standard functions , but some of the
raw operations included will fail . However , these should only be used for
debugging in the first place .
They are implemented as custom blocks in C , allowing for serialization ,
deserialization , and comparison . The functions listed here mainly come from
the interfaces mentioned above ; any additional functions are explained here .
in C. These sets are immutable but can share data through reference
counting on the C side. C is used mainly to ensure fast median-taking;
medians are made with vectorizable bitwise operators.
This implementation can handle sets of size up to the word size in bits,
i.e., 32 characters on 32-bit machines, 64 characters on 64-bit machines.
Using n-1 characters (31, 63) ensures complete interoperability with OCaml;
using 32 or 64 allows you to use all the standard functions, but some of the
raw operations included will fail. However, these should only be used for
debugging in the first place.
They are implemented as custom blocks in C, allowing for serialization,
deserialization, and comparison. The functions listed here mainly come from
the interfaces mentioned above; any additional functions are explained here. *)
(** {2 Types} *)
* Abstract type that defines a set of NonAdditive characters
type ct
(** The Abstract type for union based non additive characters *)
type cu
(** The type of a set of nonadditive characters *)
type t = {
codes : int array;
data : ct;
}
(** The type of individual set elements *)
type e = int * int
(** {2 Accessing Codes and Querying Codes} *)
val mem : int list option -> t -> bool
val code : ct -> int
* { 2 Union operations }
val union : ct -> cu -> cu -> cu
val to_union : ct -> cu
val elt_code : e -> int
(** {2 Creation} *)
val make_new : int -> int -> ct
* Makes a new nonadditive character set of a given size and code . All
elements are initialized to zero , which is an inconsistent state . ( Please
see this module 's TeX file for details . )
elements are initialized to zero, which is an inconsistent state. (Please
see this module's TeX file for details.) *)
val set_elt : ct -> int -> e -> unit
* [ set ] sets element number [ loc ] to value [ val ] . [ val ] is
treated as bit - encoding its possible states .
treated as bit-encoding its possible states. *)
val set_elt_bit : ct -> int -> int -> unit
(** [set_elt_bit set loc bit] sets bit [bit] of element [loc], signifying that
element [loc] is / can be in state [bit]. *)
* { 2 Medians and distances }
val median : 'a -> t -> t -> t
* [ median _ child1 child2 ] determine the median of two non - additive characters
val median_3 : t -> t -> t -> t -> t
(** [median_3 parent node child1 child2] returns node_final *)
val distance : ct -> ct -> float
val distance_list : ct -> ct -> (int * float) list
val dist_2 : t -> t -> t -> int
(** [dist_2 a b c] returns the smallest distance from [a] to either [b] or [c],
computed element-wise *)
val reroot_median : ct -> ct -> ct
* [ reroot_median a b ] performs a special median for finding the root value
between two nodes for which the final states are known . This is done by
taking the union of the states , as described in 1993 .
between two nodes for which the final states are known. This is done by
taking the union of the states, as described in Goloboff 1993. *)
* { 2 State , listing , parsing }
val cardinal : ct -> int
val cardinal_union : cu -> int
(** number of elements in set *)
val poly_items : cu -> int -> int
val to_int : ct -> int -> int
(** [elt_to_list set eltnum] returns a list of states that element [eltnum]
might be in. ~Deprecated *)
val elt_to_list : ct -> int -> int list
(* this is the prefered method to inspect set bits. *)
val e_to_list : e -> int list
val to_list : ct -> (int * e * float) list
val of_list : (int * e * float) list -> t
val of_parser : Data.d -> (Parser.SC.static_state * int) array * 'a -> int -> t * 'a
val is_potentially_informative : int list option list -> bool
val max_possible_cost : int list option list -> float
val min_possible_cost : int list option list -> float
val to_simple_list : t -> (int * e) list
val to_string : t -> string
* [ to_formatter c parent d : Xml.xml list ] returns the formatter for
node c where parent is optional parent of c if available
node c where parent is optional parent of c if available *)
val to_formatter : Xml.xml Sexpr.t list ->
Xml.attributes -> t -> t option -> Data.d ->
Xml.xml Sexpr.t list
* { 2 Other standard functions }
val compare_codes : t -> t -> int
val compare_data : t -> t -> int
val empty : t
val add : e -> float -> t -> t
val del : int -> t -> t
val codes : t -> int list
val costs : t -> (int * float) list
val get_elt_withcode : int -> t -> e option
val pair_map : ('a -> 'b) -> 'a * 'a -> 'b * 'b
val substitute : t -> t -> t
val merge : t -> t -> t
val minus : t -> t -> t
val random : (unit -> bool) -> t -> t
val fold : (e -> 'a -> 'a) -> 'a -> t -> 'a
val filter : (int * e * float -> bool) -> t -> t
val f_codes : t -> All_sets.Integers.t -> t
val f_codes_comp : t -> All_sets.Integers.t -> t
val iter : (e -> int -> unit) -> t -> unit
val map : (e -> int -> e) -> t -> t
val is_empty : t -> bool
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/nonaddCS.mli | ocaml |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
* {2 Types}
* The Abstract type for union based non additive characters
* The type of a set of nonadditive characters
* The type of individual set elements
* {2 Accessing Codes and Querying Codes}
* {2 Creation}
* [set_elt_bit set loc bit] sets bit [bit] of element [loc], signifying that
element [loc] is / can be in state [bit].
* [median_3 parent node child1 child2] returns node_final
* [dist_2 a b c] returns the smallest distance from [a] to either [b] or [c],
computed element-wise
* number of elements in set
* [elt_to_list set eltnum] returns a list of states that element [eltnum]
might be in. ~Deprecated
this is the prefered method to inspect set bits. | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
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
* This module implements sets of equally - weighted non - additive characters
in C. These sets are immutable but can share data through reference
counting on the C side . C is used mainly to ensure fast median - taking ;
medians are made with vectorizable bitwise operators .
This implementation can handle sets of size up to the word size in bits ,
i.e. , 32 characters on 32 - bit machines , 64 characters on 64 - bit machines .
Using n-1 characters ( 31 , 63 ) ensures complete interoperability with OCaml ;
using 32 or 64 allows you to use all the standard functions , but some of the
raw operations included will fail . However , these should only be used for
debugging in the first place .
They are implemented as custom blocks in C , allowing for serialization ,
deserialization , and comparison . The functions listed here mainly come from
the interfaces mentioned above ; any additional functions are explained here .
in C. These sets are immutable but can share data through reference
counting on the C side. C is used mainly to ensure fast median-taking;
medians are made with vectorizable bitwise operators.
This implementation can handle sets of size up to the word size in bits,
i.e., 32 characters on 32-bit machines, 64 characters on 64-bit machines.
Using n-1 characters (31, 63) ensures complete interoperability with OCaml;
using 32 or 64 allows you to use all the standard functions, but some of the
raw operations included will fail. However, these should only be used for
debugging in the first place.
They are implemented as custom blocks in C, allowing for serialization,
deserialization, and comparison. The functions listed here mainly come from
the interfaces mentioned above; any additional functions are explained here. *)
* Abstract type that defines a set of NonAdditive characters
type ct
type cu
type t = {
codes : int array;
data : ct;
}
type e = int * int
val mem : int list option -> t -> bool
val code : ct -> int
* { 2 Union operations }
val union : ct -> cu -> cu -> cu
val to_union : ct -> cu
val elt_code : e -> int
val make_new : int -> int -> ct
* Makes a new nonadditive character set of a given size and code . All
elements are initialized to zero , which is an inconsistent state . ( Please
see this module 's TeX file for details . )
elements are initialized to zero, which is an inconsistent state. (Please
see this module's TeX file for details.) *)
val set_elt : ct -> int -> e -> unit
* [ set ] sets element number [ loc ] to value [ val ] . [ val ] is
treated as bit - encoding its possible states .
treated as bit-encoding its possible states. *)
val set_elt_bit : ct -> int -> int -> unit
* { 2 Medians and distances }
val median : 'a -> t -> t -> t
* [ median _ child1 child2 ] determine the median of two non - additive characters
val median_3 : t -> t -> t -> t -> t
val distance : ct -> ct -> float
val distance_list : ct -> ct -> (int * float) list
val dist_2 : t -> t -> t -> int
val reroot_median : ct -> ct -> ct
* [ reroot_median a b ] performs a special median for finding the root value
between two nodes for which the final states are known . This is done by
taking the union of the states , as described in 1993 .
between two nodes for which the final states are known. This is done by
taking the union of the states, as described in Goloboff 1993. *)
* { 2 State , listing , parsing }
val cardinal : ct -> int
val cardinal_union : cu -> int
val poly_items : cu -> int -> int
val to_int : ct -> int -> int
val elt_to_list : ct -> int -> int list
val e_to_list : e -> int list
val to_list : ct -> (int * e * float) list
val of_list : (int * e * float) list -> t
val of_parser : Data.d -> (Parser.SC.static_state * int) array * 'a -> int -> t * 'a
val is_potentially_informative : int list option list -> bool
val max_possible_cost : int list option list -> float
val min_possible_cost : int list option list -> float
val to_simple_list : t -> (int * e) list
val to_string : t -> string
* [ to_formatter c parent d : Xml.xml list ] returns the formatter for
node c where parent is optional parent of c if available
node c where parent is optional parent of c if available *)
val to_formatter : Xml.xml Sexpr.t list ->
Xml.attributes -> t -> t option -> Data.d ->
Xml.xml Sexpr.t list
* { 2 Other standard functions }
val compare_codes : t -> t -> int
val compare_data : t -> t -> int
val empty : t
val add : e -> float -> t -> t
val del : int -> t -> t
val codes : t -> int list
val costs : t -> (int * float) list
val get_elt_withcode : int -> t -> e option
val pair_map : ('a -> 'b) -> 'a * 'a -> 'b * 'b
val substitute : t -> t -> t
val merge : t -> t -> t
val minus : t -> t -> t
val random : (unit -> bool) -> t -> t
val fold : (e -> 'a -> 'a) -> 'a -> t -> 'a
val filter : (int * e * float -> bool) -> t -> t
val f_codes : t -> All_sets.Integers.t -> t
val f_codes_comp : t -> All_sets.Integers.t -> t
val iter : (e -> int -> unit) -> t -> unit
val map : (e -> int -> e) -> t -> t
val is_empty : t -> bool
|
173a0a5abfcdecb7609c496502149f8be26947cf1a25cef2ea6662ba1ac9309a | swarmpit/swarmpit | common.cljs | (ns swarmpit.component.common
(:refer-clojure :exclude [list])
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.chart :as chart]
[material.component.list.basic :as list]
[swarmpit.component.state :as state]
[swarmpit.component.toolbar :as toolbar]
[sablono.core :refer-macros [html]]
[clojure.contrib.humanize :as humanize]
[clojure.contrib.inflect :as inflect]
[goog.string.format]
[goog.string :as gstring]
[rum.core :as rum]))
(def swarmpit-home-page "")
(defn parse-version [version]
(clojure.string/replace
(:version version)
#"SNAPSHOT"
(->> (:revision version)
(take 7)
(apply str))))
(rum/defc title-logo < rum/static []
[:a {:target "_blank"
:href swarmpit-home-page}
[:img {:src "img/logo.svg"
:height "50"
:width "200"}]])
(rum/defc title-version < rum/static [version]
(when version
[:span.Swarmpit-title-version (str "v" (parse-version version))]))
(rum/defc title-login-version < rum/static [version]
(when version
[:span.Swarmpit-login-version "Version: " (parse-version version)]))
(defn list-empty [title]
(comp/typography
{:key "empty-text"} (str "There are no " title " configured.")))
(defn list-no-items-found []
(comp/typography
{:key "nothing-match-text"} "Nothing matches this filter."))
(rum/defc list-filters < rum/static [filterOpen? comp]
(comp/swipeable-drawer
{:anchor "right"
:open filterOpen?}
(comp/box
{:className "Swarmpit-filter"}
(comp/box
{:className "Swarmpit-filter-actions"}
(comp/button
{:onClick #(state/update-value [:filterOpen?] false state/form-state-cursor)
:startIcon (icon/close {})
:variant "text"
:color "default"} "Close"))
comp
(comp/box {:className "grow"})
(comp/button
{:onClick #(state/update-value [:filter] nil state/form-state-cursor)
:startIcon (comp/svg icon/trash-path)
:fullWidth true
:variant "contained"
:color "default"} "Clear"))))
(rum/defc list < rum/reactive
[title items filtered-items render-metadata onclick-handler toolbar-render-metadata]
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-toolbar
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/list-toobar title items filtered-items toolbar-render-metadata))
(comp/grid
{:item true
:xs 12}
(cond
(empty? items) (list-empty title)
(empty? filtered-items) (list-no-items-found)
:else
(comp/card
{:className "Swarmpit-card"}
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive-footer
render-metadata
filtered-items
onclick-handler))))))]])))
(rum/defc list-grid < rum/reactive
[title items filtered-items grid toolbar-render-metadata]
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-toolbar
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/list-toobar title items filtered-items toolbar-render-metadata))
(comp/grid
{:item true
:xs 12}
(cond
(empty? items) (list-empty title)
(empty? filtered-items) (list-no-items-found)
:else grid)))]])))
(defn show-password-adornment
([show-password]
(show-password-adornment show-password :showPassword))
([show-password password-key]
(comp/input-adornment
{:position "end"}
(comp/icon-button
{:aria-label "Toggle password visibility"
:onClick #(state/update-value [password-key] (not show-password) state/form-state-cursor)
:onMouseDown (fn [event]
(.preventDefault event))}
(if show-password
(icon/visibility)
(icon/visibility-off))))))
(defn tab-panel [{:keys [value index] :as props} & childs]
(comp/typography
{:component "div"
:role "tabpanel"
:hidden (not= value index)
:id (str "scrollable-auto-tabpanel-" index)
:aria-labelledby (str "scrollable-auto-tab-" index)}
(when (= value index)
(comp/box {} childs))))
(defn render-percentage
[val]
(if (some? val)
(str (gstring/format "%.2f" val) "%")
"-"))
(defn render-cores
[val]
(if (some? val)
(gstring/format "%.2f" val)
"-"))
(defn render-capacity
[val binary?]
(if (some? val)
(humanize/filesize val :binary binary?)
"-"))
(defn resource-used [usage value]
(cond
(< usage 75) {:name "used"
:value usage
:hover value
:color "#52B359"}
(> usage 90) {:name "used"
:value usage
:hover value
:color "#d32f2f"}
:else {:name "used"
:value usage
:hover value
:color "#ffa000"}))
(rum/defc resource-pie < rum/static
[{:keys [usage value limit type]} label id]
(let [usage (or usage (* (/ value limit) 100))
data [(resource-used usage value)
{:name "free"
:value (- 100 usage)
:hover (- limit value)
:color "#ccc"}]]
(if limit
(chart/pie
data
label
"Swarmpit-stat-graph"
id
{:formatter (fn [value name props]
(let [hover-value (.-hover (.-payload props))]
(case type
:disk (render-capacity hover-value false)
:memory (render-capacity hover-value true)
:cpu (str (render-cores hover-value) " vCPU")
hover-value)))})
(chart/pie
[{:value 100
:color "#ccc"}]
"Loading"
"Swarmpit-stat-skeleton"
id
nil))))
(rum/defc resource-pie-empty < rum/static
[id]
(chart/pie
[{:value 100
:color "#ccc"}]
"-"
"Swarmpit-stat-graph"
id
nil)) | null | https://raw.githubusercontent.com/swarmpit/swarmpit/38ffbe08e717d8620bf433c99f2e85a9e5984c32/src/cljs/swarmpit/component/common.cljs | clojure | (ns swarmpit.component.common
(:refer-clojure :exclude [list])
(:require [material.icon :as icon]
[material.components :as comp]
[material.component.chart :as chart]
[material.component.list.basic :as list]
[swarmpit.component.state :as state]
[swarmpit.component.toolbar :as toolbar]
[sablono.core :refer-macros [html]]
[clojure.contrib.humanize :as humanize]
[clojure.contrib.inflect :as inflect]
[goog.string.format]
[goog.string :as gstring]
[rum.core :as rum]))
(def swarmpit-home-page "")
(defn parse-version [version]
(clojure.string/replace
(:version version)
#"SNAPSHOT"
(->> (:revision version)
(take 7)
(apply str))))
(rum/defc title-logo < rum/static []
[:a {:target "_blank"
:href swarmpit-home-page}
[:img {:src "img/logo.svg"
:height "50"
:width "200"}]])
(rum/defc title-version < rum/static [version]
(when version
[:span.Swarmpit-title-version (str "v" (parse-version version))]))
(rum/defc title-login-version < rum/static [version]
(when version
[:span.Swarmpit-login-version "Version: " (parse-version version)]))
(defn list-empty [title]
(comp/typography
{:key "empty-text"} (str "There are no " title " configured.")))
(defn list-no-items-found []
(comp/typography
{:key "nothing-match-text"} "Nothing matches this filter."))
(rum/defc list-filters < rum/static [filterOpen? comp]
(comp/swipeable-drawer
{:anchor "right"
:open filterOpen?}
(comp/box
{:className "Swarmpit-filter"}
(comp/box
{:className "Swarmpit-filter-actions"}
(comp/button
{:onClick #(state/update-value [:filterOpen?] false state/form-state-cursor)
:startIcon (icon/close {})
:variant "text"
:color "default"} "Close"))
comp
(comp/box {:className "grow"})
(comp/button
{:onClick #(state/update-value [:filter] nil state/form-state-cursor)
:startIcon (comp/svg icon/trash-path)
:fullWidth true
:variant "contained"
:color "default"} "Clear"))))
(rum/defc list < rum/reactive
[title items filtered-items render-metadata onclick-handler toolbar-render-metadata]
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-toolbar
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/list-toobar title items filtered-items toolbar-render-metadata))
(comp/grid
{:item true
:xs 12}
(cond
(empty? items) (list-empty title)
(empty? filtered-items) (list-no-items-found)
:else
(comp/card
{:className "Swarmpit-card"}
(comp/card-content
{:className "Swarmpit-table-card-content"}
(list/responsive-footer
render-metadata
filtered-items
onclick-handler))))))]])))
(rum/defc list-grid < rum/reactive
[title items filtered-items grid toolbar-render-metadata]
(comp/mui
(html
[:div.Swarmpit-form
[:div.Swarmpit-form-toolbar
(comp/grid
{:container true
:spacing 2}
(comp/grid
{:item true
:xs 12}
(toolbar/list-toobar title items filtered-items toolbar-render-metadata))
(comp/grid
{:item true
:xs 12}
(cond
(empty? items) (list-empty title)
(empty? filtered-items) (list-no-items-found)
:else grid)))]])))
(defn show-password-adornment
([show-password]
(show-password-adornment show-password :showPassword))
([show-password password-key]
(comp/input-adornment
{:position "end"}
(comp/icon-button
{:aria-label "Toggle password visibility"
:onClick #(state/update-value [password-key] (not show-password) state/form-state-cursor)
:onMouseDown (fn [event]
(.preventDefault event))}
(if show-password
(icon/visibility)
(icon/visibility-off))))))
(defn tab-panel [{:keys [value index] :as props} & childs]
(comp/typography
{:component "div"
:role "tabpanel"
:hidden (not= value index)
:id (str "scrollable-auto-tabpanel-" index)
:aria-labelledby (str "scrollable-auto-tab-" index)}
(when (= value index)
(comp/box {} childs))))
(defn render-percentage
[val]
(if (some? val)
(str (gstring/format "%.2f" val) "%")
"-"))
(defn render-cores
[val]
(if (some? val)
(gstring/format "%.2f" val)
"-"))
(defn render-capacity
[val binary?]
(if (some? val)
(humanize/filesize val :binary binary?)
"-"))
(defn resource-used [usage value]
(cond
(< usage 75) {:name "used"
:value usage
:hover value
:color "#52B359"}
(> usage 90) {:name "used"
:value usage
:hover value
:color "#d32f2f"}
:else {:name "used"
:value usage
:hover value
:color "#ffa000"}))
(rum/defc resource-pie < rum/static
[{:keys [usage value limit type]} label id]
(let [usage (or usage (* (/ value limit) 100))
data [(resource-used usage value)
{:name "free"
:value (- 100 usage)
:hover (- limit value)
:color "#ccc"}]]
(if limit
(chart/pie
data
label
"Swarmpit-stat-graph"
id
{:formatter (fn [value name props]
(let [hover-value (.-hover (.-payload props))]
(case type
:disk (render-capacity hover-value false)
:memory (render-capacity hover-value true)
:cpu (str (render-cores hover-value) " vCPU")
hover-value)))})
(chart/pie
[{:value 100
:color "#ccc"}]
"Loading"
"Swarmpit-stat-skeleton"
id
nil))))
(rum/defc resource-pie-empty < rum/static
[id]
(chart/pie
[{:value 100
:color "#ccc"}]
"-"
"Swarmpit-stat-graph"
id
nil)) |
|
e2984ba6e19ab0f000a0ec3ac57d8d2af7a1e470fea1150aa68dc9b6ee5c4e0c | lemmih/lhc | Case2.hs | module Case2 where
x = case x of
x -> x
y :: ()
y = case y of
y -> y
z :: ()
z = case z of
() -> ()
| null | https://raw.githubusercontent.com/lemmih/lhc/53bfa57b9b7275b7737dcf9dd620533d0261be66/haskell-crux/tests/Case2.hs | haskell | module Case2 where
x = case x of
x -> x
y :: ()
y = case y of
y -> y
z :: ()
z = case z of
() -> ()
|
|
0c826a66d4344c58b25fbe67f488ff1763797f1a4ee131626767c34954a78d32 | jackfirth/rebellion | converter.rkt | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[converter? predicate/c]
[make-converter
(->* ((-> any/c any/c) (-> any/c any/c))
(#:name (or/c interned-symbol? #false))
converter?)]
[convert-forward (-> converter? any/c any/c)]
[convert-backward (-> converter? any/c any/c)]
[converter/c (-> contract? contract? contract?)]
[identity-converter converter?]
[number<->string (converter/c number? string?)]
[string<->symbol (converter/c string? symbol?)]
[string<->keyword (converter/c string? keyword?)]
[symbol<->keyword (converter/c symbol? keyword?)]
[converter-pipe (-> converter? ... converter?)]
[converter-flip
(->* (converter?) (#:name (or/c interned-symbol? #false)) converter?)]))
(require racket/bool
racket/contract/combinator
racket/keyword
racket/symbol
rebellion/base/symbol
(only-in rebellion/base/immutable-string
immutable-string?
number->immutable-string)
rebellion/collection/list
rebellion/private/contract-projection
rebellion/private/guarded-block
rebellion/private/impersonation
rebellion/private/static-name
rebellion/type/object)
(module+ test
(require (submod "..")
racket/contract/parametric
racket/contract/region
racket/function
rackunit))
;@------------------------------------------------------------------------------
;; Core API
(define-object-type converter (forward-function backward-function)
#:constructor-name constructor:converter)
(define (make-converter forward-function backward-function #:name [name #false])
(constructor:converter
#:forward-function (fix-arity forward-function)
#:backward-function (fix-arity backward-function)
#:name name))
(define (fix-arity conversion-function)
(if (equal? (procedure-arity conversion-function) 1)
conversion-function
(procedure-reduce-arity conversion-function 1)))
(define (convert-forward converter domain-value)
((converter-forward-function converter) domain-value))
(define (convert-backward converter range-value)
((converter-backward-function converter) range-value))
(define/name identity-converter
(make-converter values values #:name enclosing-variable-name))
;@------------------------------------------------------------------------------
;; Contracts
(define (converter-impersonate
converter
#:domain-input-guard [domain-input-guard #false]
#:domain-output-guard [domain-output-guard #false]
#:range-input-guard [range-input-guard #false]
#:range-output-guard [range-output-guard #false]
#:properties [properties (hash)]
#:forward-marks [forward-marks (hash)]
#:backward-marks [backward-marks (hash)]
#:chaperone?
[chaperone?
(nor domain-input-guard
domain-output-guard
range-input-guard
range-output-guard)])
(define forward-function (converter-forward-function converter))
(define backward-function (converter-backward-function converter))
(define impersonated-forward-function
(function-impersonate
forward-function
#:arguments-guard domain-input-guard
#:results-guard range-output-guard
#:application-marks forward-marks
#:chaperone? chaperone?))
(define impersonated-backward-function
(function-impersonate
backward-function
#:arguments-guard range-input-guard
#:results-guard domain-output-guard
#:application-marks backward-marks
#:chaperone? chaperone?))
(define impersonated-without-props
(make-converter impersonated-forward-function impersonated-backward-function
#:name (object-name converter)))
(object-impersonate impersonated-without-props descriptor:converter
#:properties properties))
(define/name (converter/c domain-contract* range-contract*)
(define domain-contract
(coerce-contract enclosing-function-name domain-contract*))
(define range-contract
(coerce-contract enclosing-function-name range-contract*))
(define contract-name
(build-compound-type-name
enclosing-function-name domain-contract range-contract))
(define domain-projection (contract-late-neg-projection domain-contract))
(define range-projection (contract-late-neg-projection range-contract))
(define chaperone?
(and (chaperone-contract? domain-contract)
(chaperone-contract? range-contract)))
(define (projection blame)
(define domain-input-blame
(blame-add-context blame "an input in the converter domain of"
#:swap? #true))
(define domain-output-blame
(blame-add-context blame "an output in the converter domain of"))
(define range-output-blame
(blame-add-context blame "an output in the converter range of"))
(define range-input-blame
(blame-add-context
blame "an input in the converter range of" #:swap? #true))
(define late-neg-domain-input-guard (domain-projection domain-input-blame))
(define late-neg-range-output-guard (range-projection range-output-blame))
(define late-neg-range-input-guard (range-projection range-input-blame))
(define late-neg-domain-output-guard
(domain-projection domain-output-blame))
(λ (original-converter missing-party)
(assert-satisfies original-converter converter? blame
#:missing-party missing-party)
(define props
(hash impersonator-prop:contracted the-contract
impersonator-prop:blame (cons blame missing-party)))
(define (domain-input-guard input)
(late-neg-domain-input-guard input missing-party))
(define (domain-output-guard output)
(late-neg-domain-output-guard output missing-party))
(define (range-input-guard input)
(late-neg-range-input-guard input missing-party))
(define (range-output-guard output)
(late-neg-range-output-guard output missing-party))
(converter-impersonate
original-converter
#:domain-input-guard domain-input-guard
#:domain-output-guard domain-output-guard
#:range-input-guard range-input-guard
#:range-output-guard range-output-guard
#:chaperone? chaperone?
#:properties props)))
(define the-contract
((if chaperone? make-chaperone-contract make-contract)
#:name contract-name
#:first-order converter?
#:late-neg-projection projection))
the-contract)
(module+ test
(test-case (name-string converter/c)
(test-case "should make chaperones for non-impersonator operand contracts"
(check-pred chaperone-contract? (converter/c any/c any/c))
(check-pred chaperone-contract? (converter/c string? string?))
(check-pred chaperone-contract?
(converter/c (-> any/c any/c) (-> any/c any/c)))
(check-pred (negate chaperone-contract?) (converter/c (new-∀/c) any/c))
(check-pred (negate chaperone-contract?) (converter/c any/c (new-∀/c))))
(define/name number<->symbol
(make-converter
(λ (x) (string->symbol (number->string x)))
(λ (sym) (string->number (symbol->string sym)))
#:name enclosing-variable-name))
(test-case "should only enforce converter? predicate in first order checks"
(check-exn
exn:fail:contract:blame?
(λ () (invariant-assertion (converter/c any/c any/c) 42)))
(check-not-exn
(λ () (invariant-assertion (converter/c any/c any/c) number<->symbol)))
(check-not-exn
(λ ()
(invariant-assertion (converter/c number? symbol?) number<->symbol)))
(check-not-exn
(λ ()
(invariant-assertion (converter/c string? string?) number<->symbol))))
(test-case "should enforce domain contract on inputs"
(define/contract contracted (converter/c number? any/c) number<->symbol)
(check-not-exn (λ () (convert-forward contracted 42)))
(check-exn
#rx"contracted: contract violation"
(λ () (convert-forward contracted "foo")))
(check-exn #rx"\"foo\"" (λ () (convert-forward contracted "foo")))
(check-exn #rx"number\\?" (λ () (convert-forward contracted "foo")))
(check-exn #rx"input" (λ () (convert-forward contracted "foo")))
(check-exn #rx"domain" (λ () (convert-forward contracted "foo")))
(check-exn #rx"expected" (λ () (convert-forward contracted "foo")))
(check-exn #rx"given" (λ () (convert-forward contracted "foo"))))
(test-case "should enforce domain contract on outputs"
(define/contract contracted (converter/c integer? any/c) number<->symbol)
(check-not-exn (λ () (convert-backward contracted '|42|)))
(check-exn
#rx"contracted: broke its own contract"
(λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"42\\.5" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"integer\\?" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"output" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"domain" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"promised" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"produced" (λ () (convert-backward contracted '|42.5|))))
(test-case "should enforce range contract on inputs"
(define/contract contracted (converter/c any/c symbol?) number<->symbol)
(check-not-exn (λ () (convert-backward contracted '|42|)))
(check-exn
#rx"contracted: contract violation"
(λ () (convert-backward contracted "foo")))
(check-exn #rx"\"foo\"" (λ () (convert-backward contracted "foo")))
(check-exn #rx"symbol\\?" (λ () (convert-backward contracted "foo")))
(check-exn #rx"input" (λ () (convert-backward contracted "foo")))
(check-exn #rx"range" (λ () (convert-backward contracted "foo")))
(check-exn #rx"expected" (λ () (convert-backward contracted "foo")))
(check-exn #rx"given" (λ () (convert-backward contracted "foo"))))
(test-case "should enforce range contract on outputs"
(define (short-symbol? v)
(and (symbol? v) (< (string-length (symbol->immutable-string v)) 4)))
(define/contract contracted (converter/c any/c short-symbol?)
number<->symbol)
(check-not-exn (λ () (convert-forward contracted 42)))
(check-exn
#rx"contracted: broke its own contract"
(λ () (convert-forward contracted 999999)))
(check-exn #rx"999999" (λ () (convert-forward contracted 999999)))
(check-exn
#rx"short\\-symbol\\?" (λ () (convert-forward contracted 999999)))
(check-exn #rx"output" (λ () (convert-forward contracted 999999)))
(check-exn #rx"range" (λ () (convert-forward contracted 999999)))
(check-exn #rx"promised" (λ () (convert-forward contracted 999999)))
(check-exn #rx"produced" (λ () (convert-forward contracted 999999))))
(test-case "should add contract system impersonator properties"
(define the-contract (converter/c number? symbol?))
(define/contract contracted the-contract number<->symbol)
(check-pred has-contract? contracted)
(check-equal? (value-contract contracted) the-contract)
(check-pred has-blame? contracted))))
;@------------------------------------------------------------------------------
;; Built-in converters and converter utilities
(define/guard (converter-pipe #:name [name 'piped] . converters)
(guard (nonempty-list? converters) else identity-converter)
(define forward-functions (map converter-forward-function converters))
(define backward-functions (map converter-backward-function converters))
(make-converter
(apply compose (reverse forward-functions))
(apply compose backward-functions)
#:name name))
(define (converter-flip converter #:name [name 'flipped])
(make-converter (converter-backward-function converter)
(converter-forward-function converter)
#:name name))
(define/name number<->string
(make-converter number->immutable-string string->number
#:name enclosing-variable-name))
(define/name string<->symbol
(make-converter string->symbol symbol->immutable-string
#:name enclosing-variable-name))
(define/name string<->keyword
(make-converter string->keyword keyword->immutable-string
#:name enclosing-variable-name))
(define (symbol->keyword sym)
(string->keyword (symbol->immutable-string sym)))
(define (keyword->symbol kw)
(string->symbol (keyword->immutable-string kw)))
(define/name symbol<->keyword
(make-converter symbol->keyword keyword->symbol
#:name enclosing-variable-name))
(module+ test
(test-case (name-string number<->string)
(check-equal? (convert-forward number<->string 42) "42")
(check-pred immutable-string? (convert-forward number<->string 42))
(check-equal? (convert-backward number<->string "-5.7") -5.7)
(check-equal? (convert-backward number<->string (make-string 3 #\1)) 111)
(check-exn
#rx"number<\\->string: contract violation"
(λ () (convert-forward number<->string "42")))
(check-exn
#rx"number<\\->string: contract violation"
(λ () (convert-backward number<->string 42))))
(define (mutable-foo)
(define s (make-string 3))
(string-set! s 0 #\f)
(string-set! s 1 #\o)
(string-set! s 2 #\o)
s)
(define (unreadable-foo) (string->unreadable-symbol "foo"))
(define (uninterned-foo) (string->uninterned-symbol "foo"))
(test-case (name-string string<->symbol)
(check-equal? (convert-forward string<->symbol "foo") 'foo)
(check-equal? (convert-forward string<->symbol (mutable-foo)) 'foo)
(check-equal? (convert-backward string<->symbol 'foo) "foo")
(check-pred immutable-string? (convert-backward string<->symbol 'foo))
(check-equal? (convert-backward string<->symbol (unreadable-foo)) "foo")
(check-pred
immutable-string? (convert-backward string<->symbol (unreadable-foo)))
(check-equal? (convert-backward string<->symbol (uninterned-foo)) "foo")
(check-pred
immutable-string? (convert-backward string<->symbol (uninterned-foo))))
(test-case (name-string string<->keyword)
(check-equal? (convert-forward string<->keyword "foo") '#:foo)
(check-equal? (convert-forward string<->keyword (mutable-foo)) '#:foo)
(check-equal? (convert-backward string<->keyword '#:foo) "foo")
(check-pred immutable-string? (convert-backward string<->keyword '#:foo)))
(test-case (name-string symbol<->keyword)
(check-equal? (convert-forward symbol<->keyword 'foo) '#:foo)
(check-equal? (convert-forward symbol<->keyword (unreadable-foo)) '#:foo)
(check-equal? (convert-forward symbol<->keyword (uninterned-foo)) '#:foo)
(check-equal? (convert-backward symbol<->keyword '#:foo) 'foo))
(test-case (name-string converter-flip)
(define keyword<->string (converter-flip string<->keyword))
(check-equal? (convert-forward keyword<->string '#:foo) "foo")
(check-equal? (convert-backward keyword<->string "foo") '#:foo)
(check-equal?
(converter-flip keyword<->string #:name (name string<->keyword))
string<->keyword))
(test-case (name-string converter-pipe)
(define number<->keyword (converter-pipe number<->string string<->keyword))
(check-equal? (convert-forward number<->keyword 42) '#:42)
(check-equal? (convert-backward number<->keyword '#:42) 42)))
| null | https://raw.githubusercontent.com/jackfirth/rebellion/64f8f82ac3343fe632388bfcbb9e537759ac1ac2/base/converter.rkt | racket | @------------------------------------------------------------------------------
Core API
@------------------------------------------------------------------------------
Contracts
@------------------------------------------------------------------------------
Built-in converters and converter utilities | #lang racket/base
(require racket/contract/base)
(provide
(contract-out
[converter? predicate/c]
[make-converter
(->* ((-> any/c any/c) (-> any/c any/c))
(#:name (or/c interned-symbol? #false))
converter?)]
[convert-forward (-> converter? any/c any/c)]
[convert-backward (-> converter? any/c any/c)]
[converter/c (-> contract? contract? contract?)]
[identity-converter converter?]
[number<->string (converter/c number? string?)]
[string<->symbol (converter/c string? symbol?)]
[string<->keyword (converter/c string? keyword?)]
[symbol<->keyword (converter/c symbol? keyword?)]
[converter-pipe (-> converter? ... converter?)]
[converter-flip
(->* (converter?) (#:name (or/c interned-symbol? #false)) converter?)]))
(require racket/bool
racket/contract/combinator
racket/keyword
racket/symbol
rebellion/base/symbol
(only-in rebellion/base/immutable-string
immutable-string?
number->immutable-string)
rebellion/collection/list
rebellion/private/contract-projection
rebellion/private/guarded-block
rebellion/private/impersonation
rebellion/private/static-name
rebellion/type/object)
(module+ test
(require (submod "..")
racket/contract/parametric
racket/contract/region
racket/function
rackunit))
(define-object-type converter (forward-function backward-function)
#:constructor-name constructor:converter)
(define (make-converter forward-function backward-function #:name [name #false])
(constructor:converter
#:forward-function (fix-arity forward-function)
#:backward-function (fix-arity backward-function)
#:name name))
(define (fix-arity conversion-function)
(if (equal? (procedure-arity conversion-function) 1)
conversion-function
(procedure-reduce-arity conversion-function 1)))
(define (convert-forward converter domain-value)
((converter-forward-function converter) domain-value))
(define (convert-backward converter range-value)
((converter-backward-function converter) range-value))
(define/name identity-converter
(make-converter values values #:name enclosing-variable-name))
(define (converter-impersonate
converter
#:domain-input-guard [domain-input-guard #false]
#:domain-output-guard [domain-output-guard #false]
#:range-input-guard [range-input-guard #false]
#:range-output-guard [range-output-guard #false]
#:properties [properties (hash)]
#:forward-marks [forward-marks (hash)]
#:backward-marks [backward-marks (hash)]
#:chaperone?
[chaperone?
(nor domain-input-guard
domain-output-guard
range-input-guard
range-output-guard)])
(define forward-function (converter-forward-function converter))
(define backward-function (converter-backward-function converter))
(define impersonated-forward-function
(function-impersonate
forward-function
#:arguments-guard domain-input-guard
#:results-guard range-output-guard
#:application-marks forward-marks
#:chaperone? chaperone?))
(define impersonated-backward-function
(function-impersonate
backward-function
#:arguments-guard range-input-guard
#:results-guard domain-output-guard
#:application-marks backward-marks
#:chaperone? chaperone?))
(define impersonated-without-props
(make-converter impersonated-forward-function impersonated-backward-function
#:name (object-name converter)))
(object-impersonate impersonated-without-props descriptor:converter
#:properties properties))
(define/name (converter/c domain-contract* range-contract*)
(define domain-contract
(coerce-contract enclosing-function-name domain-contract*))
(define range-contract
(coerce-contract enclosing-function-name range-contract*))
(define contract-name
(build-compound-type-name
enclosing-function-name domain-contract range-contract))
(define domain-projection (contract-late-neg-projection domain-contract))
(define range-projection (contract-late-neg-projection range-contract))
(define chaperone?
(and (chaperone-contract? domain-contract)
(chaperone-contract? range-contract)))
(define (projection blame)
(define domain-input-blame
(blame-add-context blame "an input in the converter domain of"
#:swap? #true))
(define domain-output-blame
(blame-add-context blame "an output in the converter domain of"))
(define range-output-blame
(blame-add-context blame "an output in the converter range of"))
(define range-input-blame
(blame-add-context
blame "an input in the converter range of" #:swap? #true))
(define late-neg-domain-input-guard (domain-projection domain-input-blame))
(define late-neg-range-output-guard (range-projection range-output-blame))
(define late-neg-range-input-guard (range-projection range-input-blame))
(define late-neg-domain-output-guard
(domain-projection domain-output-blame))
(λ (original-converter missing-party)
(assert-satisfies original-converter converter? blame
#:missing-party missing-party)
(define props
(hash impersonator-prop:contracted the-contract
impersonator-prop:blame (cons blame missing-party)))
(define (domain-input-guard input)
(late-neg-domain-input-guard input missing-party))
(define (domain-output-guard output)
(late-neg-domain-output-guard output missing-party))
(define (range-input-guard input)
(late-neg-range-input-guard input missing-party))
(define (range-output-guard output)
(late-neg-range-output-guard output missing-party))
(converter-impersonate
original-converter
#:domain-input-guard domain-input-guard
#:domain-output-guard domain-output-guard
#:range-input-guard range-input-guard
#:range-output-guard range-output-guard
#:chaperone? chaperone?
#:properties props)))
(define the-contract
((if chaperone? make-chaperone-contract make-contract)
#:name contract-name
#:first-order converter?
#:late-neg-projection projection))
the-contract)
(module+ test
(test-case (name-string converter/c)
(test-case "should make chaperones for non-impersonator operand contracts"
(check-pred chaperone-contract? (converter/c any/c any/c))
(check-pred chaperone-contract? (converter/c string? string?))
(check-pred chaperone-contract?
(converter/c (-> any/c any/c) (-> any/c any/c)))
(check-pred (negate chaperone-contract?) (converter/c (new-∀/c) any/c))
(check-pred (negate chaperone-contract?) (converter/c any/c (new-∀/c))))
(define/name number<->symbol
(make-converter
(λ (x) (string->symbol (number->string x)))
(λ (sym) (string->number (symbol->string sym)))
#:name enclosing-variable-name))
(test-case "should only enforce converter? predicate in first order checks"
(check-exn
exn:fail:contract:blame?
(λ () (invariant-assertion (converter/c any/c any/c) 42)))
(check-not-exn
(λ () (invariant-assertion (converter/c any/c any/c) number<->symbol)))
(check-not-exn
(λ ()
(invariant-assertion (converter/c number? symbol?) number<->symbol)))
(check-not-exn
(λ ()
(invariant-assertion (converter/c string? string?) number<->symbol))))
(test-case "should enforce domain contract on inputs"
(define/contract contracted (converter/c number? any/c) number<->symbol)
(check-not-exn (λ () (convert-forward contracted 42)))
(check-exn
#rx"contracted: contract violation"
(λ () (convert-forward contracted "foo")))
(check-exn #rx"\"foo\"" (λ () (convert-forward contracted "foo")))
(check-exn #rx"number\\?" (λ () (convert-forward contracted "foo")))
(check-exn #rx"input" (λ () (convert-forward contracted "foo")))
(check-exn #rx"domain" (λ () (convert-forward contracted "foo")))
(check-exn #rx"expected" (λ () (convert-forward contracted "foo")))
(check-exn #rx"given" (λ () (convert-forward contracted "foo"))))
(test-case "should enforce domain contract on outputs"
(define/contract contracted (converter/c integer? any/c) number<->symbol)
(check-not-exn (λ () (convert-backward contracted '|42|)))
(check-exn
#rx"contracted: broke its own contract"
(λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"42\\.5" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"integer\\?" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"output" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"domain" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"promised" (λ () (convert-backward contracted '|42.5|)))
(check-exn #rx"produced" (λ () (convert-backward contracted '|42.5|))))
(test-case "should enforce range contract on inputs"
(define/contract contracted (converter/c any/c symbol?) number<->symbol)
(check-not-exn (λ () (convert-backward contracted '|42|)))
(check-exn
#rx"contracted: contract violation"
(λ () (convert-backward contracted "foo")))
(check-exn #rx"\"foo\"" (λ () (convert-backward contracted "foo")))
(check-exn #rx"symbol\\?" (λ () (convert-backward contracted "foo")))
(check-exn #rx"input" (λ () (convert-backward contracted "foo")))
(check-exn #rx"range" (λ () (convert-backward contracted "foo")))
(check-exn #rx"expected" (λ () (convert-backward contracted "foo")))
(check-exn #rx"given" (λ () (convert-backward contracted "foo"))))
(test-case "should enforce range contract on outputs"
(define (short-symbol? v)
(and (symbol? v) (< (string-length (symbol->immutable-string v)) 4)))
(define/contract contracted (converter/c any/c short-symbol?)
number<->symbol)
(check-not-exn (λ () (convert-forward contracted 42)))
(check-exn
#rx"contracted: broke its own contract"
(λ () (convert-forward contracted 999999)))
(check-exn #rx"999999" (λ () (convert-forward contracted 999999)))
(check-exn
#rx"short\\-symbol\\?" (λ () (convert-forward contracted 999999)))
(check-exn #rx"output" (λ () (convert-forward contracted 999999)))
(check-exn #rx"range" (λ () (convert-forward contracted 999999)))
(check-exn #rx"promised" (λ () (convert-forward contracted 999999)))
(check-exn #rx"produced" (λ () (convert-forward contracted 999999))))
(test-case "should add contract system impersonator properties"
(define the-contract (converter/c number? symbol?))
(define/contract contracted the-contract number<->symbol)
(check-pred has-contract? contracted)
(check-equal? (value-contract contracted) the-contract)
(check-pred has-blame? contracted))))
(define/guard (converter-pipe #:name [name 'piped] . converters)
(guard (nonempty-list? converters) else identity-converter)
(define forward-functions (map converter-forward-function converters))
(define backward-functions (map converter-backward-function converters))
(make-converter
(apply compose (reverse forward-functions))
(apply compose backward-functions)
#:name name))
(define (converter-flip converter #:name [name 'flipped])
(make-converter (converter-backward-function converter)
(converter-forward-function converter)
#:name name))
(define/name number<->string
(make-converter number->immutable-string string->number
#:name enclosing-variable-name))
(define/name string<->symbol
(make-converter string->symbol symbol->immutable-string
#:name enclosing-variable-name))
(define/name string<->keyword
(make-converter string->keyword keyword->immutable-string
#:name enclosing-variable-name))
(define (symbol->keyword sym)
(string->keyword (symbol->immutable-string sym)))
(define (keyword->symbol kw)
(string->symbol (keyword->immutable-string kw)))
(define/name symbol<->keyword
(make-converter symbol->keyword keyword->symbol
#:name enclosing-variable-name))
(module+ test
(test-case (name-string number<->string)
(check-equal? (convert-forward number<->string 42) "42")
(check-pred immutable-string? (convert-forward number<->string 42))
(check-equal? (convert-backward number<->string "-5.7") -5.7)
(check-equal? (convert-backward number<->string (make-string 3 #\1)) 111)
(check-exn
#rx"number<\\->string: contract violation"
(λ () (convert-forward number<->string "42")))
(check-exn
#rx"number<\\->string: contract violation"
(λ () (convert-backward number<->string 42))))
(define (mutable-foo)
(define s (make-string 3))
(string-set! s 0 #\f)
(string-set! s 1 #\o)
(string-set! s 2 #\o)
s)
(define (unreadable-foo) (string->unreadable-symbol "foo"))
(define (uninterned-foo) (string->uninterned-symbol "foo"))
(test-case (name-string string<->symbol)
(check-equal? (convert-forward string<->symbol "foo") 'foo)
(check-equal? (convert-forward string<->symbol (mutable-foo)) 'foo)
(check-equal? (convert-backward string<->symbol 'foo) "foo")
(check-pred immutable-string? (convert-backward string<->symbol 'foo))
(check-equal? (convert-backward string<->symbol (unreadable-foo)) "foo")
(check-pred
immutable-string? (convert-backward string<->symbol (unreadable-foo)))
(check-equal? (convert-backward string<->symbol (uninterned-foo)) "foo")
(check-pred
immutable-string? (convert-backward string<->symbol (uninterned-foo))))
(test-case (name-string string<->keyword)
(check-equal? (convert-forward string<->keyword "foo") '#:foo)
(check-equal? (convert-forward string<->keyword (mutable-foo)) '#:foo)
(check-equal? (convert-backward string<->keyword '#:foo) "foo")
(check-pred immutable-string? (convert-backward string<->keyword '#:foo)))
(test-case (name-string symbol<->keyword)
(check-equal? (convert-forward symbol<->keyword 'foo) '#:foo)
(check-equal? (convert-forward symbol<->keyword (unreadable-foo)) '#:foo)
(check-equal? (convert-forward symbol<->keyword (uninterned-foo)) '#:foo)
(check-equal? (convert-backward symbol<->keyword '#:foo) 'foo))
(test-case (name-string converter-flip)
(define keyword<->string (converter-flip string<->keyword))
(check-equal? (convert-forward keyword<->string '#:foo) "foo")
(check-equal? (convert-backward keyword<->string "foo") '#:foo)
(check-equal?
(converter-flip keyword<->string #:name (name string<->keyword))
string<->keyword))
(test-case (name-string converter-pipe)
(define number<->keyword (converter-pipe number<->string string<->keyword))
(check-equal? (convert-forward number<->keyword 42) '#:42)
(check-equal? (convert-backward number<->keyword '#:42) 42)))
|
bcb762f093e487586b048796db2c3368dbeb0fe02338cebde0cb0f0afe08d52d | deadcode/Learning-CL--David-Touretzky | 8.36.lisp | (defun count-odd (x)
(cond ((null x) 0)
((oddp (first x))
(+ 1 (count-odd (rest x))))
(t (count-odd (rest x)))))
(let ((test1 '(count-odd '(4 5 6 7 8)))
(test2 '(count-odd '(0 2 4 6 8)))
(test3 '(count-odd '())))
(format t "~s = ~s~%" test1 (eval test1))
(format t "~s = ~s~%" test2 (eval test2))
(format t "~s = ~s~%" test3 (eval test3)))
(defun count-odd (x)
(cond ((null x) 0)
(t
(+ (cond ((oddp (first x)) 1)
(t 0))
(count-odd (rest x))))))
(let ((test1 '(count-odd '(4 5 6 7 8)))
(test2 '(count-odd '(0 2 4 6 8)))
(test3 '(count-odd '())))
(format t "~s = ~s~%" test1 (eval test1))
(format t "~s = ~s~%" test2 (eval test2))
(format t "~s = ~s~%" test3 (eval test3)))
| null | https://raw.githubusercontent.com/deadcode/Learning-CL--David-Touretzky/b4557c33f58e382f765369971e6a4747c27ca692/Chapter%208/8.36.lisp | lisp | (defun count-odd (x)
(cond ((null x) 0)
((oddp (first x))
(+ 1 (count-odd (rest x))))
(t (count-odd (rest x)))))
(let ((test1 '(count-odd '(4 5 6 7 8)))
(test2 '(count-odd '(0 2 4 6 8)))
(test3 '(count-odd '())))
(format t "~s = ~s~%" test1 (eval test1))
(format t "~s = ~s~%" test2 (eval test2))
(format t "~s = ~s~%" test3 (eval test3)))
(defun count-odd (x)
(cond ((null x) 0)
(t
(+ (cond ((oddp (first x)) 1)
(t 0))
(count-odd (rest x))))))
(let ((test1 '(count-odd '(4 5 6 7 8)))
(test2 '(count-odd '(0 2 4 6 8)))
(test3 '(count-odd '())))
(format t "~s = ~s~%" test1 (eval test1))
(format t "~s = ~s~%" test2 (eval test2))
(format t "~s = ~s~%" test3 (eval test3)))
|
|
b890755dda044ae6e4a9fb4e0e10803dd9921f07d1f9275d47e9e0ac87478cac | Limmen/erl_pengine | table_mngr.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2017 ,
%% @doc table_mngr server. Only purpose to maintain the ETS-table with
%% all the active slave-pengines and add fault-tolerance in case
%% the pengine_master dies. This process have very low-chance of crashing
%% due to its limited purpose.
%% @end
%%%-------------------------------------------------------------------
-module(table_mngr).
-author('Kim Hammar <>').
-behaviour(gen_server).
%% includes
-include("records.hrl").
%% API
-export([start_link/0, handover/0]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
%% macros
-define(SERVER, ?MODULE).
%% types
%% state
-type table_mngr_state() :: #table_mngr_state{}.
%%====================================================================
%% API functions
%%====================================================================
%% @doc
%% Starts the server
-spec start_link() -> {ok, pid()}.
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
%% @doc
%% handover store to pengine_master
-spec handover() -> ok.
handover() ->
gen_server:cast(?MODULE, {handover}).
%%====================================================================
%% gen_server callbacks
%%====================================================================
@private
%% @doc
%% Initializes the server
-spec init(list()) -> {ok, table_mngr_state()}.
init([]) ->
process_flag(trap_exit, true),
handover(),
{ok, #table_mngr_state{}}.
@private
%% @doc
%% Handling call messages
-spec handle_call(term(), term(), table_mngr_state()) -> {reply, ok, table_mngr_state()}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
@private
%% @doc
%% Handling cast messages
-spec handle_cast(term(), table_mngr_state()) -> {noreply, table_mngr_state()}.
handle_cast({handover}, State) ->
MasterPengine = whereis(pengine_master),
link(MasterPengine),
TableId = ets:new(pengines, [named_table, set, private]),
ets:setopts(TableId, {heir, self(), {table_handover}}),
ets:give_away(TableId, MasterPengine, {table_handover}),
{noreply, State#table_mngr_state{table_id=TableId}};
handle_cast(_Msg, State) ->
{noreply, State}.
@private
%% @doc
%% Handling all non call/cast messages
-spec handle_info(timeout | term(), table_mngr_state()) -> {noreply, table_mngr_state()}.
handle_info({'EXIT', _Pid, _Reason}, State) ->
{noreply, State};
handle_info({'ETS-TRANSFER', TableId, _Pid, Data}, State) ->
MasterPengine = wait_for_master(),
link(MasterPengine),
ets:give_away(TableId, MasterPengine, Data),
{noreply, State#table_mngr_state{table_id=TableId}};
handle_info(_Info, State) ->
{noreply, State}.
@private
%% @doc
%% Cleanup function
-spec terminate(normal | shutdown | {shutdown, term()}, table_mngr_state()) -> ok.
terminate(_Reason, _State) ->
ok.
@private
%% @doc
%% Convert process state when code is changed
-spec code_change(term | {down, term()}, table_mngr_state(), term()) -> {ok, table_mngr_state()}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%====================================================================
Internal functions
%%====================================================================
@private
%% @doc
%% Wait for master pengine to be restored
-spec wait_for_master() -> pid().
wait_for_master() ->
case whereis(pengine_master) of
undefined ->
timer:sleep(100),
wait_for_master();
Pid -> Pid
end.
| null | https://raw.githubusercontent.com/Limmen/erl_pengine/fde53184609036a1ebec5d8bd61766da1d8e3aab/src/table_mngr.erl | erlang | -------------------------------------------------------------------
@doc table_mngr server. Only purpose to maintain the ETS-table with
all the active slave-pengines and add fault-tolerance in case
the pengine_master dies. This process have very low-chance of crashing
due to its limited purpose.
@end
-------------------------------------------------------------------
includes
API
gen_server callbacks
macros
types
state
====================================================================
API functions
====================================================================
@doc
Starts the server
@doc
handover store to pengine_master
====================================================================
gen_server callbacks
====================================================================
@doc
Initializes the server
@doc
Handling call messages
@doc
Handling cast messages
@doc
Handling all non call/cast messages
@doc
Cleanup function
@doc
Convert process state when code is changed
====================================================================
====================================================================
@doc
Wait for master pengine to be restored | @author < >
( C ) 2017 ,
-module(table_mngr).
-author('Kim Hammar <>').
-behaviour(gen_server).
-include("records.hrl").
-export([start_link/0, handover/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-define(SERVER, ?MODULE).
-type table_mngr_state() :: #table_mngr_state{}.
-spec start_link() -> {ok, pid()}.
start_link() ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [], []).
-spec handover() -> ok.
handover() ->
gen_server:cast(?MODULE, {handover}).
@private
-spec init(list()) -> {ok, table_mngr_state()}.
init([]) ->
process_flag(trap_exit, true),
handover(),
{ok, #table_mngr_state{}}.
@private
-spec handle_call(term(), term(), table_mngr_state()) -> {reply, ok, table_mngr_state()}.
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
@private
-spec handle_cast(term(), table_mngr_state()) -> {noreply, table_mngr_state()}.
handle_cast({handover}, State) ->
MasterPengine = whereis(pengine_master),
link(MasterPengine),
TableId = ets:new(pengines, [named_table, set, private]),
ets:setopts(TableId, {heir, self(), {table_handover}}),
ets:give_away(TableId, MasterPengine, {table_handover}),
{noreply, State#table_mngr_state{table_id=TableId}};
handle_cast(_Msg, State) ->
{noreply, State}.
@private
-spec handle_info(timeout | term(), table_mngr_state()) -> {noreply, table_mngr_state()}.
handle_info({'EXIT', _Pid, _Reason}, State) ->
{noreply, State};
handle_info({'ETS-TRANSFER', TableId, _Pid, Data}, State) ->
MasterPengine = wait_for_master(),
link(MasterPengine),
ets:give_away(TableId, MasterPengine, Data),
{noreply, State#table_mngr_state{table_id=TableId}};
handle_info(_Info, State) ->
{noreply, State}.
@private
-spec terminate(normal | shutdown | {shutdown, term()}, table_mngr_state()) -> ok.
terminate(_Reason, _State) ->
ok.
@private
-spec code_change(term | {down, term()}, table_mngr_state(), term()) -> {ok, table_mngr_state()}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
@private
-spec wait_for_master() -> pid().
wait_for_master() ->
case whereis(pengine_master) of
undefined ->
timer:sleep(100),
wait_for_master();
Pid -> Pid
end.
|
8fa3d26458add58e8078c641a59993ec4ba6421447cc756d8386e312616eabbf | CloudI/CloudI | parse_trans_codegen.erl | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
%% --------------------------------------------------
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%% --------------------------------------------------
%% File : parse_trans_codegen.erl
@author :
%% @end
%%-------------------------------------------------------------------
@doc Parse transform for code generation pseduo functions
%%
< p> ... >
%%
%% @end
-module(parse_trans_codegen).
-export([parse_transform/2]).
-export([format_error/1]).
%% @spec (Forms, Options) -> NewForms
%%
%% @doc
Searches for calls to pseudo functions in the module ` codegen ' ,
and converts the corresponding erlang code to a data structure
%% representing the abstract form of that code.
%%
%% The purpose of these functions is to let the programmer write
%% the actual code that is to be generated, rather than manually
%% writing abstract forms, which is more error prone and cannot be
%% checked by the compiler until the generated module is compiled.
%%
%% Supported functions:
%%
%% <h2>gen_function/2</h2>
%%
Usage : ` codegen : , Fun ) '
%%
%% Substitutes the abstract code for a function with name `Name'
%% and the same behaviour as `Fun'.
%%
%% `Fun' can either be a anonymous `fun', which is then converted to
%% a named function, or it can be an `implicit fun', e.g.
%% `fun is_member/2'. In the latter case, the referenced function is fetched
%% and converted to an abstract form representation. It is also renamed
%% so that the generated function has the name `Name'.
%% <p/>
%% Another alternative is to wrap a fun inside a list comprehension, e.g.
%% <pre>
%% f(Name, L) ->
%% codegen:gen_function(
%% Name,
%% [ fun({'$var',X}) ->
%% {'$var', Y}
%% end || {X, Y} &lt;- L ]).
%% </pre>
%% <p/>
%% Calling the above with `f(foo, [{1,a},{2,b},{3,c}])' will result in
%% generated code corresponding to:
%% <pre>
%% foo(1) -> a;
%% foo(2) -> b;
%% foo(3) -> c.
%% </pre>
%%
%% <h2>gen_functions/1</h2>
%%
%% Takes a list of `{Name, Fun}' tuples and produces a list of abstract
%% data objects, just as if one had written
` [ codegen : gen_function(N1,F1),codegen : ) , ... ] ' .
%%
%% <h2>exprs/1</h2>
%%
Usage : ` codegen : exprs(Fun ) '
%%
` Fun ' is either an anonymous function , or an implicit fun with only one
%% function clause. This "function" takes the body of the fun and produces
%% a data type representing the abstract form of the list of expressions in
%% the body. The arguments of the function clause are ignored, but can be
%% used to ensure that all necessary variables are known to the compiler.
%%
%% <h2>gen_module/3</h2>
%%
%% Generates abstract forms for a complete module definition.
%%
Usage : ` codegen : gen_module(ModuleName , Exports , Functions ) '
%%
` ModuleName ' is either an atom or a < code>{'$var ' , V}</code > reference .
%%
%% `Exports' is a list of `{Function, Arity}' tuples.
%%
%% `Functions' is a list of `{Name, Fun}' tuples analogous to that for
%% `gen_functions/1'.
%%
%% <h2>Variable substitution</h2>
%%
%% It is possible to do some limited expansion (importing a value
bound at compile - time ) , using the construct < code>{'$var ' , V}</code > , where
%% `V' is a bound variable in the scope of the call to `gen_function/2'.
%%
%% Example:
%% <pre>
%% gen(Name, X) ->
: , ) - > lists : member({'$var',X } , L ) end ) .
%% </pre>
%%
After transformation , calling ` gen(contains_17 , 17 ) ' will yield the
%% abstract form corresponding to:
%% <pre>
%% contains_17(L) ->
%% lists:member(17, L).
%% </pre>
%%
%% <h2>Form substitution</h2>
%%
%% It is possible to inject abstract forms, using the construct
%% <code>{'$form', F}</code>, where `F' is bound to a parsed form in
%% the scope of the call to `gen_function/2'.
%%
%% Example:
%% <pre>
%% gen(Name, F) ->
: , fun(X ) - > X = : = { ' $ form',F } end ) .
%% </pre>
%%
%% After transformation, calling `gen(is_foo, {atom,0,foo})' will yield the
%% abstract form corresponding to:
%% <pre>
%% is_foo(X) ->
%% X =:= foo.
%% </pre>
%% @end
%%
parse_transform(Forms, Options) ->
Context = parse_trans:initial_context(Forms, Options),
{NewForms, _} =
parse_trans:do_depth_first(
fun xform_fun/4, _Acc = Forms, Forms, Context),
parse_trans:return(parse_trans:revert(NewForms), Context).
xform_fun(application, Form, _Ctxt, Acc) ->
MFA = erl_syntax_lib:analyze_application(Form),
L = erl_syntax:get_pos(Form),
case MFA of
{codegen, {gen_module, 3}} ->
[NameF, ExportsF, FunsF] =
erl_syntax:application_arguments(Form),
NewForms = gen_module(NameF, ExportsF, FunsF, L, Acc),
{NewForms, Acc};
{codegen, {gen_function, 2}} ->
[NameF, FunF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function(NameF, FunF, L, L, Acc),
{NewForm, Acc};
{codegen, {gen_function, 3}} ->
[NameF, FunF, LineF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function(
NameF, FunF, L, erl_syntax:integer_value(LineF), Acc),
{NewForm, Acc};
{codegen, {gen_function_alt, 3}} ->
[NameF, FunF, AltF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function_alt(NameF, FunF, AltF, L, L, Acc),
{NewForm, Acc};
{codegen, {gen_functions, 1}} ->
[List] = erl_syntax:application_arguments(Form),
Elems = erl_syntax:list_elements(List),
NewForms = lists:map(
fun(E) ->
[NameF, FunF] = erl_syntax:tuple_elements(E),
gen_function(NameF, FunF, L, L, Acc)
end, Elems),
{erl_syntax:list(NewForms), Acc};
{codegen, {exprs, 1}} ->
[FunF] = erl_syntax:application_arguments(Form),
[Clause] = erl_syntax:fun_expr_clauses(FunF),
[{clause,_,_,_,Body}] = parse_trans:revert([Clause]),
NewForm = substitute(erl_parse:abstract(Body)),
{NewForm, Acc};
_ ->
{Form, Acc}
end;
xform_fun(_, Form, _Ctxt, Acc) ->
{Form, Acc}.
gen_module(NameF, ExportsF, FunsF, L, Acc) ->
case erl_syntax:type(FunsF) of
list ->
try gen_module_(NameF, ExportsF, FunsF, L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L, ?MODULE, ErrStr}}
end;
_ ->
ErrStr = parse_trans:format_exception(
error, "Argument must be a list"),
{error, {L, ?MODULE, ErrStr}}
end.
gen_module_(NameF, ExportsF, FunsF, L0, Acc) ->
P = erl_syntax:get_pos(NameF),
ModF = case parse_trans:revert_form(NameF) of
{atom,_,_} = Am -> Am;
{tuple,_,[{atom,_,'$var'},
{var,_,V}]} ->
{var,P,V}
end,
cons(
{cons,P,
{tuple,P,
[{atom,P,attribute},
{integer,P,1},
{atom,P,module},
ModF]},
substitute(
abstract(
[{attribute,P,export,
lists:map(
fun(TupleF) ->
[F,A] = erl_syntax:tuple_elements(TupleF),
{erl_syntax:atom_value(F), erl_syntax:integer_value(A)}
end, erl_syntax:list_elements(ExportsF))}]))},
lists:map(
fun(FTupleF) ->
Pos = erl_syntax:get_pos(FTupleF),
[FName, FFunF] = erl_syntax:tuple_elements(FTupleF),
gen_function(FName, FFunF, L0, Pos, Acc)
end, erl_syntax:list_elements(FunsF))).
cons({cons,L,H,T}, L2) ->
{cons,L,H,cons(T, L2)};
cons({nil,L}, [H|T]) ->
Pos = erl_syntax:get_pos(H),
{cons,L,H,cons({nil,Pos}, T)};
cons({nil,L}, []) ->
{nil,L}.
gen_function(NameF, FunF, L0, L, Acc) ->
try gen_function_(NameF, FunF, [], L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L0, ?MODULE, ErrStr}}
end.
gen_function_alt(NameF, FunF, AltF, L0, L, Acc) ->
try gen_function_(NameF, FunF, AltF, L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L0, ?MODULE, ErrStr}}
end.
gen_function_(NameF, FunF, AltF, L, Acc) ->
case erl_syntax:type(FunF) of
T when T==implicit_fun; T==fun_expr ->
{Arity, Clauses} = gen_function_clauses(T, NameF, FunF, L, Acc),
{tuple, 1, [{atom, 1, function},
{integer, 1, L},
NameF,
{integer, 1, Arity},
substitute(abstract(Clauses))]};
list_comp ->
%% Extract the fun from the LC
[Template] = parse_trans:revert(
[erl_syntax:list_comp_template(FunF)]),
%% Process fun in the normal fashion (as above)
{Arity, Clauses} = gen_function_clauses(erl_syntax:type(Template),
NameF, Template, L, Acc),
Body = erl_syntax:list_comp_body(FunF),
%% Collect all variables from the LC generator(s)
%% We want to produce an abstract representation of something like:
{ function,1,Name , Arity ,
%% lists:flatten(
%% [(fun(V1,V2,...) ->
%% ...
end)(__V1,__V2 , ... ) || { _ _ , ... } < - L ] ) }
where the _ _ Vn vars are our renamed versions of the LC generator
%% vars. This allows us to instantiate the clauses at run-time.
Vars = lists:flatten(
[sets:to_list(erl_syntax_lib:variables(
erl_syntax:generator_pattern(G)))
|| G <- Body]),
Vars1 = [list_to_atom("__" ++ atom_to_list(V)) || V <- Vars],
VarMap = lists:zip(Vars, Vars1),
Body1 =
[erl_syntax:generator(
rename_vars(VarMap, gen_pattern(G)),
gen_body(G)) || G <- Body],
[RevLC] = parse_trans:revert(
[erl_syntax:list_comp(
{call, 1,
{'fun',1,
{clauses,
[{clause,1,[{var,1,V} || V <- Vars],[],
[substitute(
abstract(Clauses))]
}]}
}, [{var,1,V} || V <- Vars1]}, Body1)]),
AltC = case AltF of
[] -> {nil,1};
_ ->
{Arity, AltC1} = gen_function_clauses(
erl_syntax:type(AltF),
NameF, AltF, L, Acc),
substitute(abstract(AltC1))
end,
{tuple,1,[{atom,1,function},
{integer, 1, L},
NameF,
{integer, 1, Arity},
{call, 1, {remote, 1, {atom, 1, lists},
{atom,1,flatten}},
[{op, 1, '++', RevLC, AltC}]}]}
end.
gen_pattern(G) ->
erl_syntax:generator_pattern(G).
gen_body(G) ->
erl_syntax:generator_body(G).
rename_vars(Vars, Tree) ->
erl_syntax_lib:map(
fun(T) ->
case erl_syntax:type(T) of
variable ->
V = erl_syntax:variable_name(T),
{_,V1} = lists:keyfind(V,1,Vars),
erl_syntax:variable(V1);
_ ->
T
end
end, Tree).
gen_function_clauses(implicit_fun, _NameF, FunF, _L, Acc) ->
AQ = erl_syntax:implicit_fun_name(FunF),
Name = erl_syntax:atom_value(erl_syntax:arity_qualifier_body(AQ)),
Arity = erl_syntax:integer_value(
erl_syntax:arity_qualifier_argument(AQ)),
NewForm = find_function(Name, Arity, Acc),
ClauseForms = erl_syntax:function_clauses(NewForm),
{Arity, ClauseForms};
gen_function_clauses(fun_expr, _NameF, FunF, _L, _Acc) ->
ClauseForms = erl_syntax:fun_expr_clauses(FunF),
Arity = get_arity(ClauseForms),
{Arity, ClauseForms}.
find_function(Name, Arity, Forms) ->
[Form] = [F || {function,_,N,A,_} = F <- Forms,
N == Name,
A == Arity],
Form.
abstract(ClauseForms) ->
erl_parse:abstract(parse_trans:revert(ClauseForms)).
substitute({tuple,L0,
[{atom,_,tuple},
{integer,_,L},
{cons,_,
{tuple,_,[{atom,_,atom},{integer,_,_},{atom,_,'$var'}]},
{cons,_,
{tuple,_,[{atom,_,var},{integer,_,_},{atom,_,V}]},
{nil,_}}}]}) ->
{call, L0, {remote,L0,{atom,L0,erl_parse},
{atom,L0,abstract}},
[{var, L0, V}, {integer, L0, L}]};
substitute({tuple,L0,
[{atom,_,tuple},
{integer,_,_},
{cons,_,
{tuple,_,[{atom,_,atom},{integer,_,_},{atom,_,'$form'}]},
{cons,_,
{tuple,_,[{atom,_,var},{integer,_,_},{atom,_,F}]},
{nil,_}}}]}) ->
{var, L0, F};
substitute([]) ->
[];
substitute([H|T]) ->
[substitute(H) | substitute(T)];
substitute(T) when is_tuple(T) ->
list_to_tuple(substitute(tuple_to_list(T)));
substitute(X) ->
X.
get_arity(Clauses) ->
Ays = [length(erl_syntax:clause_patterns(C)) || C <- Clauses],
case lists:usort(Ays) of
[Ay] ->
Ay;
Other ->
erlang:error(ambiguous, Other)
end.
format_error(E) ->
case io_lib:deep_char_list(E) of
true ->
E;
_ ->
io_lib:write(E)
end.
| null | https://raw.githubusercontent.com/CloudI/CloudI/3e45031c7ee3e974ead2612ea7dd06c9edf973c9/src/external/cloudi_x_parse_trans/src/parse_trans_codegen.erl | erlang | --------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
--------------------------------------------------
File : parse_trans_codegen.erl
@end
-------------------------------------------------------------------
@end
@spec (Forms, Options) -> NewForms
@doc
representing the abstract form of that code.
The purpose of these functions is to let the programmer write
the actual code that is to be generated, rather than manually
writing abstract forms, which is more error prone and cannot be
checked by the compiler until the generated module is compiled.
Supported functions:
<h2>gen_function/2</h2>
Substitutes the abstract code for a function with name `Name'
and the same behaviour as `Fun'.
`Fun' can either be a anonymous `fun', which is then converted to
a named function, or it can be an `implicit fun', e.g.
`fun is_member/2'. In the latter case, the referenced function is fetched
and converted to an abstract form representation. It is also renamed
so that the generated function has the name `Name'.
<p/>
Another alternative is to wrap a fun inside a list comprehension, e.g.
<pre>
f(Name, L) ->
codegen:gen_function(
Name,
[ fun({'$var',X}) ->
{'$var', Y}
end || {X, Y} &lt;- L ]).
</pre>
<p/>
Calling the above with `f(foo, [{1,a},{2,b},{3,c}])' will result in
generated code corresponding to:
<pre>
foo(1) -> a;
foo(2) -> b;
foo(3) -> c.
</pre>
<h2>gen_functions/1</h2>
Takes a list of `{Name, Fun}' tuples and produces a list of abstract
data objects, just as if one had written
<h2>exprs/1</h2>
function clause. This "function" takes the body of the fun and produces
a data type representing the abstract form of the list of expressions in
the body. The arguments of the function clause are ignored, but can be
used to ensure that all necessary variables are known to the compiler.
<h2>gen_module/3</h2>
Generates abstract forms for a complete module definition.
`Exports' is a list of `{Function, Arity}' tuples.
`Functions' is a list of `{Name, Fun}' tuples analogous to that for
`gen_functions/1'.
<h2>Variable substitution</h2>
It is possible to do some limited expansion (importing a value
`V' is a bound variable in the scope of the call to `gen_function/2'.
Example:
<pre>
gen(Name, X) ->
</pre>
abstract form corresponding to:
<pre>
contains_17(L) ->
lists:member(17, L).
</pre>
<h2>Form substitution</h2>
It is possible to inject abstract forms, using the construct
<code>{'$form', F}</code>, where `F' is bound to a parsed form in
the scope of the call to `gen_function/2'.
Example:
<pre>
gen(Name, F) ->
</pre>
After transformation, calling `gen(is_foo, {atom,0,foo})' will yield the
abstract form corresponding to:
<pre>
is_foo(X) ->
X =:= foo.
</pre>
@end
Extract the fun from the LC
Process fun in the normal fashion (as above)
Collect all variables from the LC generator(s)
We want to produce an abstract representation of something like:
lists:flatten(
[(fun(V1,V2,...) ->
...
vars. This allows us to instantiate the clauses at run-time. | -*- erlang - indent - level : 4;indent - tabs - mode : nil -*-
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
@author :
@doc Parse transform for code generation pseduo functions
< p> ... >
-module(parse_trans_codegen).
-export([parse_transform/2]).
-export([format_error/1]).
Searches for calls to pseudo functions in the module ` codegen ' ,
and converts the corresponding erlang code to a data structure
Usage : ` codegen : , Fun ) '
` [ codegen : gen_function(N1,F1),codegen : ) , ... ] ' .
Usage : ` codegen : exprs(Fun ) '
` Fun ' is either an anonymous function , or an implicit fun with only one
Usage : ` codegen : gen_module(ModuleName , Exports , Functions ) '
` ModuleName ' is either an atom or a < code>{'$var ' , V}</code > reference .
bound at compile - time ) , using the construct < code>{'$var ' , V}</code > , where
: , ) - > lists : member({'$var',X } , L ) end ) .
After transformation , calling ` gen(contains_17 , 17 ) ' will yield the
: , fun(X ) - > X = : = { ' $ form',F } end ) .
parse_transform(Forms, Options) ->
Context = parse_trans:initial_context(Forms, Options),
{NewForms, _} =
parse_trans:do_depth_first(
fun xform_fun/4, _Acc = Forms, Forms, Context),
parse_trans:return(parse_trans:revert(NewForms), Context).
xform_fun(application, Form, _Ctxt, Acc) ->
MFA = erl_syntax_lib:analyze_application(Form),
L = erl_syntax:get_pos(Form),
case MFA of
{codegen, {gen_module, 3}} ->
[NameF, ExportsF, FunsF] =
erl_syntax:application_arguments(Form),
NewForms = gen_module(NameF, ExportsF, FunsF, L, Acc),
{NewForms, Acc};
{codegen, {gen_function, 2}} ->
[NameF, FunF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function(NameF, FunF, L, L, Acc),
{NewForm, Acc};
{codegen, {gen_function, 3}} ->
[NameF, FunF, LineF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function(
NameF, FunF, L, erl_syntax:integer_value(LineF), Acc),
{NewForm, Acc};
{codegen, {gen_function_alt, 3}} ->
[NameF, FunF, AltF] =
erl_syntax:application_arguments(Form),
NewForm = gen_function_alt(NameF, FunF, AltF, L, L, Acc),
{NewForm, Acc};
{codegen, {gen_functions, 1}} ->
[List] = erl_syntax:application_arguments(Form),
Elems = erl_syntax:list_elements(List),
NewForms = lists:map(
fun(E) ->
[NameF, FunF] = erl_syntax:tuple_elements(E),
gen_function(NameF, FunF, L, L, Acc)
end, Elems),
{erl_syntax:list(NewForms), Acc};
{codegen, {exprs, 1}} ->
[FunF] = erl_syntax:application_arguments(Form),
[Clause] = erl_syntax:fun_expr_clauses(FunF),
[{clause,_,_,_,Body}] = parse_trans:revert([Clause]),
NewForm = substitute(erl_parse:abstract(Body)),
{NewForm, Acc};
_ ->
{Form, Acc}
end;
xform_fun(_, Form, _Ctxt, Acc) ->
{Form, Acc}.
gen_module(NameF, ExportsF, FunsF, L, Acc) ->
case erl_syntax:type(FunsF) of
list ->
try gen_module_(NameF, ExportsF, FunsF, L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L, ?MODULE, ErrStr}}
end;
_ ->
ErrStr = parse_trans:format_exception(
error, "Argument must be a list"),
{error, {L, ?MODULE, ErrStr}}
end.
gen_module_(NameF, ExportsF, FunsF, L0, Acc) ->
P = erl_syntax:get_pos(NameF),
ModF = case parse_trans:revert_form(NameF) of
{atom,_,_} = Am -> Am;
{tuple,_,[{atom,_,'$var'},
{var,_,V}]} ->
{var,P,V}
end,
cons(
{cons,P,
{tuple,P,
[{atom,P,attribute},
{integer,P,1},
{atom,P,module},
ModF]},
substitute(
abstract(
[{attribute,P,export,
lists:map(
fun(TupleF) ->
[F,A] = erl_syntax:tuple_elements(TupleF),
{erl_syntax:atom_value(F), erl_syntax:integer_value(A)}
end, erl_syntax:list_elements(ExportsF))}]))},
lists:map(
fun(FTupleF) ->
Pos = erl_syntax:get_pos(FTupleF),
[FName, FFunF] = erl_syntax:tuple_elements(FTupleF),
gen_function(FName, FFunF, L0, Pos, Acc)
end, erl_syntax:list_elements(FunsF))).
cons({cons,L,H,T}, L2) ->
{cons,L,H,cons(T, L2)};
cons({nil,L}, [H|T]) ->
Pos = erl_syntax:get_pos(H),
{cons,L,H,cons({nil,Pos}, T)};
cons({nil,L}, []) ->
{nil,L}.
gen_function(NameF, FunF, L0, L, Acc) ->
try gen_function_(NameF, FunF, [], L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L0, ?MODULE, ErrStr}}
end.
gen_function_alt(NameF, FunF, AltF, L0, L, Acc) ->
try gen_function_(NameF, FunF, AltF, L, Acc)
catch
error:E ->
ErrStr = parse_trans:format_exception(error, E),
{error, {L0, ?MODULE, ErrStr}}
end.
gen_function_(NameF, FunF, AltF, L, Acc) ->
case erl_syntax:type(FunF) of
T when T==implicit_fun; T==fun_expr ->
{Arity, Clauses} = gen_function_clauses(T, NameF, FunF, L, Acc),
{tuple, 1, [{atom, 1, function},
{integer, 1, L},
NameF,
{integer, 1, Arity},
substitute(abstract(Clauses))]};
list_comp ->
[Template] = parse_trans:revert(
[erl_syntax:list_comp_template(FunF)]),
{Arity, Clauses} = gen_function_clauses(erl_syntax:type(Template),
NameF, Template, L, Acc),
Body = erl_syntax:list_comp_body(FunF),
{ function,1,Name , Arity ,
end)(__V1,__V2 , ... ) || { _ _ , ... } < - L ] ) }
where the _ _ Vn vars are our renamed versions of the LC generator
Vars = lists:flatten(
[sets:to_list(erl_syntax_lib:variables(
erl_syntax:generator_pattern(G)))
|| G <- Body]),
Vars1 = [list_to_atom("__" ++ atom_to_list(V)) || V <- Vars],
VarMap = lists:zip(Vars, Vars1),
Body1 =
[erl_syntax:generator(
rename_vars(VarMap, gen_pattern(G)),
gen_body(G)) || G <- Body],
[RevLC] = parse_trans:revert(
[erl_syntax:list_comp(
{call, 1,
{'fun',1,
{clauses,
[{clause,1,[{var,1,V} || V <- Vars],[],
[substitute(
abstract(Clauses))]
}]}
}, [{var,1,V} || V <- Vars1]}, Body1)]),
AltC = case AltF of
[] -> {nil,1};
_ ->
{Arity, AltC1} = gen_function_clauses(
erl_syntax:type(AltF),
NameF, AltF, L, Acc),
substitute(abstract(AltC1))
end,
{tuple,1,[{atom,1,function},
{integer, 1, L},
NameF,
{integer, 1, Arity},
{call, 1, {remote, 1, {atom, 1, lists},
{atom,1,flatten}},
[{op, 1, '++', RevLC, AltC}]}]}
end.
gen_pattern(G) ->
erl_syntax:generator_pattern(G).
gen_body(G) ->
erl_syntax:generator_body(G).
rename_vars(Vars, Tree) ->
erl_syntax_lib:map(
fun(T) ->
case erl_syntax:type(T) of
variable ->
V = erl_syntax:variable_name(T),
{_,V1} = lists:keyfind(V,1,Vars),
erl_syntax:variable(V1);
_ ->
T
end
end, Tree).
gen_function_clauses(implicit_fun, _NameF, FunF, _L, Acc) ->
AQ = erl_syntax:implicit_fun_name(FunF),
Name = erl_syntax:atom_value(erl_syntax:arity_qualifier_body(AQ)),
Arity = erl_syntax:integer_value(
erl_syntax:arity_qualifier_argument(AQ)),
NewForm = find_function(Name, Arity, Acc),
ClauseForms = erl_syntax:function_clauses(NewForm),
{Arity, ClauseForms};
gen_function_clauses(fun_expr, _NameF, FunF, _L, _Acc) ->
ClauseForms = erl_syntax:fun_expr_clauses(FunF),
Arity = get_arity(ClauseForms),
{Arity, ClauseForms}.
find_function(Name, Arity, Forms) ->
[Form] = [F || {function,_,N,A,_} = F <- Forms,
N == Name,
A == Arity],
Form.
abstract(ClauseForms) ->
erl_parse:abstract(parse_trans:revert(ClauseForms)).
substitute({tuple,L0,
[{atom,_,tuple},
{integer,_,L},
{cons,_,
{tuple,_,[{atom,_,atom},{integer,_,_},{atom,_,'$var'}]},
{cons,_,
{tuple,_,[{atom,_,var},{integer,_,_},{atom,_,V}]},
{nil,_}}}]}) ->
{call, L0, {remote,L0,{atom,L0,erl_parse},
{atom,L0,abstract}},
[{var, L0, V}, {integer, L0, L}]};
substitute({tuple,L0,
[{atom,_,tuple},
{integer,_,_},
{cons,_,
{tuple,_,[{atom,_,atom},{integer,_,_},{atom,_,'$form'}]},
{cons,_,
{tuple,_,[{atom,_,var},{integer,_,_},{atom,_,F}]},
{nil,_}}}]}) ->
{var, L0, F};
substitute([]) ->
[];
substitute([H|T]) ->
[substitute(H) | substitute(T)];
substitute(T) when is_tuple(T) ->
list_to_tuple(substitute(tuple_to_list(T)));
substitute(X) ->
X.
get_arity(Clauses) ->
Ays = [length(erl_syntax:clause_patterns(C)) || C <- Clauses],
case lists:usort(Ays) of
[Ay] ->
Ay;
Other ->
erlang:error(ambiguous, Other)
end.
format_error(E) ->
case io_lib:deep_char_list(E) of
true ->
E;
_ ->
io_lib:write(E)
end.
|
fd9ab06d0bd2d9fc2d0e1e169d219bd8bb632e16c6532d7b71b11dd66a34ceb4 | coq/coq | notationextern.mli | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
(** Declaration of uninterpretation functions (i.e. printing rules)
for notations *)
open Names
open Constrexpr
open Glob_term
open Notation_term
val interpretation_eq : interpretation -> interpretation -> bool
(** Equality on [interpretation]. *)
val notation_entry_level_eq : notation_entry_level -> notation_entry_level -> bool
(** Equality on [notation_entry_level]. *)
(** Binds a notation in a given scope to an interpretation *)
type 'a interp_rule_gen =
| NotationRule of Constrexpr.specific_notation
| AbbrevRule of 'a
type interp_rule = KerName.t interp_rule_gen
val remove_uninterpretation : interp_rule -> interpretation -> unit
val declare_uninterpretation : ?also_in_cases_pattern:bool -> interp_rule -> interpretation -> unit
type notation_applicative_status =
| AppBoundedNotation of int
| AppUnboundedNotation
| NotAppNotation
type notation_rule = interp_rule * interpretation * notation_applicative_status
(** Return printing key *)
type key
val glob_prim_constr_key : 'a Glob_term.glob_constr_g -> Names.GlobRef.t option
val glob_constr_keys : glob_constr -> key list
val cases_pattern_key : cases_pattern -> key
val notation_constr_key : Notation_term.notation_constr -> key * notation_applicative_status
(** Return the possible notations for a given term *)
val uninterp_notations : 'a glob_constr_g -> notation_rule list
val uninterp_cases_pattern_notations : 'a cases_pattern_g -> notation_rule list
val uninterp_ind_pattern_notations : inductive -> notation_rule list
(** State protection *)
val with_notation_uninterpretation_protection : ('a -> 'b) -> 'a -> 'b
(** Miscellaneous *)
type notation_use =
| OnlyPrinting
| OnlyParsing
| ParsingAndPrinting
| null | https://raw.githubusercontent.com/coq/coq/681cd76e5117c18ec2dc8545f8f63c381a00ec0e/interp/notationextern.mli | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
**********************************************************************
* Declaration of uninterpretation functions (i.e. printing rules)
for notations
* Equality on [interpretation].
* Equality on [notation_entry_level].
* Binds a notation in a given scope to an interpretation
* Return printing key
* Return the possible notations for a given term
* State protection
* Miscellaneous | v * Copyright INRIA , CNRS and contributors
< O _ _ _ , , * ( see version control and CREDITS file for authors & dates )
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
open Names
open Constrexpr
open Glob_term
open Notation_term
val interpretation_eq : interpretation -> interpretation -> bool
val notation_entry_level_eq : notation_entry_level -> notation_entry_level -> bool
type 'a interp_rule_gen =
| NotationRule of Constrexpr.specific_notation
| AbbrevRule of 'a
type interp_rule = KerName.t interp_rule_gen
val remove_uninterpretation : interp_rule -> interpretation -> unit
val declare_uninterpretation : ?also_in_cases_pattern:bool -> interp_rule -> interpretation -> unit
type notation_applicative_status =
| AppBoundedNotation of int
| AppUnboundedNotation
| NotAppNotation
type notation_rule = interp_rule * interpretation * notation_applicative_status
type key
val glob_prim_constr_key : 'a Glob_term.glob_constr_g -> Names.GlobRef.t option
val glob_constr_keys : glob_constr -> key list
val cases_pattern_key : cases_pattern -> key
val notation_constr_key : Notation_term.notation_constr -> key * notation_applicative_status
val uninterp_notations : 'a glob_constr_g -> notation_rule list
val uninterp_cases_pattern_notations : 'a cases_pattern_g -> notation_rule list
val uninterp_ind_pattern_notations : inductive -> notation_rule list
val with_notation_uninterpretation_protection : ('a -> 'b) -> 'a -> 'b
type notation_use =
| OnlyPrinting
| OnlyParsing
| ParsingAndPrinting
|
64c6a83d1f09c3ef895555677cf55043d21e2f44d1b1b1d46d086dc742409e6f | fujita-y/digamma | ctak.scm | CTAK -- A version of the TAK procedure that uses continuations .
(define (ctak x y z)
(call-with-current-continuation
(lambda (k) (ctak-aux k x y z))))
(define (ctak-aux k x y z)
(if (not (< y x))
(k z)
(call-with-current-continuation
(lambda (k)
(ctak-aux
k
(call-with-current-continuation
(lambda (k) (ctak-aux k (- x 1) y z)))
(call-with-current-continuation
(lambda (k) (ctak-aux k (- y 1) z x)))
(call-with-current-continuation
(lambda (k) (ctak-aux k (- z 1) x y))))))))
(define (compile)
(closure-compile ctak)
(closure-compile ctak-aux)
(closure-compile main))
(define (main . args)
(run-benchmark
"ctak"
ctak-iters
(lambda (result) (equal? result 7))
(lambda (x y z) (lambda () (ctak x y z)))
18
12
6))
| null | https://raw.githubusercontent.com/fujita-y/digamma/5a31f9fd67737fd857ada643d5548155a2ed0e76/bench/gambit-benchmarks/ctak.scm | scheme | CTAK -- A version of the TAK procedure that uses continuations .
(define (ctak x y z)
(call-with-current-continuation
(lambda (k) (ctak-aux k x y z))))
(define (ctak-aux k x y z)
(if (not (< y x))
(k z)
(call-with-current-continuation
(lambda (k)
(ctak-aux
k
(call-with-current-continuation
(lambda (k) (ctak-aux k (- x 1) y z)))
(call-with-current-continuation
(lambda (k) (ctak-aux k (- y 1) z x)))
(call-with-current-continuation
(lambda (k) (ctak-aux k (- z 1) x y))))))))
(define (compile)
(closure-compile ctak)
(closure-compile ctak-aux)
(closure-compile main))
(define (main . args)
(run-benchmark
"ctak"
ctak-iters
(lambda (result) (equal? result 7))
(lambda (x y z) (lambda () (ctak x y z)))
18
12
6))
|
|
49ffd1a54d2baa4f0e32e07d5ec372629cdfada58b2aeec8ffe916543c56591a | mk270/archipelago | node.mli |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2013
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2013 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
type structure =
| Graph
| Tree
type ('a, 'b) node
val create : ('b -> structure) -> 'a -> ('a, 'b) node
val remove_from : ('a, 'b) node -> ('a, 'b) node -> 'b -> unit
val insert_into : ('a, 'b) node -> ('a, 'b) node -> 'b -> unit
val contained : ('a, 'b) node -> 'a
val destinations_of : ('a, 'b) node -> 'b -> ('a, 'b) node list
val sources_of : ('a, 'b) node -> 'b -> ('a, 'b) node list
| null | https://raw.githubusercontent.com/mk270/archipelago/4241bdc994da6d846637bcc079051405ee905c9b/src/model/node.mli | ocaml |
Archipelago , a multi - user dungeon ( MUD ) server , by ( C ) 2009 - 2013
This programme is free software ; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation , either version 3 of said Licence , or
( at your option ) any later version .
Archipelago, a multi-user dungeon (MUD) server, by Martin Keegan
Copyright (C) 2009-2013 Martin Keegan
This programme is free software; you may redistribute and/or modify
it under the terms of the GNU Affero General Public Licence as published by
the Free Software Foundation, either version 3 of said Licence, or
(at your option) any later version.
*)
type structure =
| Graph
| Tree
type ('a, 'b) node
val create : ('b -> structure) -> 'a -> ('a, 'b) node
val remove_from : ('a, 'b) node -> ('a, 'b) node -> 'b -> unit
val insert_into : ('a, 'b) node -> ('a, 'b) node -> 'b -> unit
val contained : ('a, 'b) node -> 'a
val destinations_of : ('a, 'b) node -> 'b -> ('a, 'b) node list
val sources_of : ('a, 'b) node -> 'b -> ('a, 'b) node list
|
|
e083622b7d278abc225918bee269bbce5511e81bea28b5ef59fc21e813c6eb5b | creswick/cabal-dev | Main.hs | Copyright ( c ) 2011 Galois , Inc
module Main
( main )
where
import Data.Char ( isSpace, isLetter )
import Data.List ( intercalate, transpose )
import Data.Maybe ( listToMaybe )
import Data.Version ( showVersion )
import Control.Monad ( unless )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
import System.IO.Error ( catchIOError )
import System.SetEnv (setEnv)
import System.FilePath ((</>), searchPathSeparator)
import System.Console.GetOpt ( usageInfo, getOpt, ArgOrder(Permute) )
import Distribution.Simple.Utils ( cabalVersion, debug )
import Distribution.Text ( display )
import Control.Monad.Trans.State ( evalState, gets, modify )
import Distribution.Dev.Command ( CommandActions(..), CommandResult(..) )
import Distribution.Dev.Flags ( parseGlobalFlags, helpRequested, globalOpts
, GlobalFlag(Version), getOpt'', fromFlags
, getVerbosity, Config, getSandbox, getEnvVars
)
import qualified Distribution.Dev.AddSource as AddSource
import qualified Distribution.Dev.Ghci as Ghci
import qualified Distribution.Dev.InvokeCabal as InvokeCabal
import qualified Distribution.Dev.InstallDependencies as InstallDeps
import qualified Distribution.Dev.BuildOpts as BuildOpts
import qualified Distribution.Dev.GhcPkg as GhcPkg
import qualified Distribution.Dev.CabalInstall as CI
import Paths_cabal_dev ( version )
import qualified Data.Map as Map
cabalDevCommands :: [(String, CommandActions, String)]
cabalDevCommands = [ ( "add-source"
, AddSource.actions
, "Make a package available for cabal-install to " ++
"install (in a sandbox-local Hackage repository). " ++
"Note that this command does NOT install the " ++
"package in the sandbox, and does require the " ++
"package to have a working sdist."
)
, ( "install-deps"
, InstallDeps.actions
, "Install the packages that depend on the specified " ++
"packages, but not the packages themselves. " ++
"(Equivalent to install --only-dependencies for " ++
"cabal-install > 0.10)"
)
, ( "ghci"
, Ghci.actions
, "Start ghci with the sandbox's GHC package " ++
"repository available. This command does not " ++
"yet take into account the contents of the .cabal " ++
"file (e.g. source directories, available packages " ++
"LANGUAGE pragmas)."
)
, ( "buildopts"
, BuildOpts.actions
, "Extract the options that would be passed to the " ++
"compiler when building"
)
, ( "ghc-pkg"
, GhcPkg.actions
, "Invoke ghc-pkg including the appropriate " ++
"--package-conf argument to run on the sandbox's " ++
"package database."
)
]
cabalInstallCommands :: [(String, CommandActions)]
cabalInstallCommands = map cabal CI.allCommands
where
cabal s = (CI.commandToString s, InvokeCabal.actions s)
allCommands :: [(String, CommandActions)]
allCommands = [(s, a) | (s, a, _) <- cabalDevCommands] ++ cabalInstallCommands
printVersion :: IO ()
printVersion = do
putStr versionString
exitWith ExitSuccess
versionString :: String
versionString = unlines $
[ "cabal-dev " ++ showVersion version
, "built with Cabal " ++ display cabalVersion
]
printNumericVersion :: IO ()
printNumericVersion = do
putStrLn $ showVersion version
exitWith ExitSuccess
main :: IO ()
main = do
envConf <- getEnvVars
(globalFlags, args, errs) <- parseGlobalFlags `fmap` getArgs
unless (null errs) $ do
mapM_ putStrLn errs
putStr =<< globalUsage
exitWith (ExitFailure 1)
let cfg = fromFlags envConf globalFlags
add sandbox to PATH , so that custom preprocessors that are
-- installed into the sandbox are found
let binDir = getSandbox cfg </> "bin"
mPath <- maybeGetEnv "PATH"
let path = maybe binDir ((binDir ++ [searchPathSeparator]) ++) mPath
setEnv "PATH" path
case [f|(Version f) <- globalFlags] of
(True:_) -> printNumericVersion
(False:_) -> printVersion
[] -> return ()
debug (getVerbosity cfg) versionString
case args of
(name:args') ->
case nameCmd name of
Just cmdAct | helpRequested globalFlags ->
do putStrLn $ cmdDesc cmdAct
putStr =<< globalUsage
exitWith ExitSuccess
| otherwise -> runCmd cmdAct cfg args'
Nothing -> do putStrLn $ "Unknown command: " ++ show name
putStr =<< globalUsage
exitWith (ExitFailure 1)
_ | helpRequested globalFlags -> do
putStr =<< globalUsage
exitWith ExitSuccess
| otherwise -> do
putStrLn "Missing command name"
putStr =<< globalUsage
exitWith (ExitFailure 1)
globalUsage :: IO String
globalUsage = do
progName <- getProgName
let fmtCommands cmds =
fmtTable " " [ [[""], [n], wrap 60 d] | (n, _, d) <- cmds ]
let preamble =
unlines $
[ ""
, "Usage: " ++ progName ++ " <command>"
, ""
, "Where <command> is one of:"
] ++ fmtCommands cabalDevCommands ++
[ ""
, "or any cabal-install command (see cabal --help for documentation)."
, ""
, "Options to cabal-dev:"
]
return $ usageInfo preamble globalOpts
nameCmd :: String -> Maybe CommandActions
nameCmd s = listToMaybe [a | (n, a) <- allCommands, n == s]
runCmd :: CommandActions -> Config -> [String] -> IO ()
runCmd cmdAct cfg args =
do res <- run
case res of
CommandOk -> exitWith ExitSuccess
CommandError msg -> showError [msg]
where
showError msgs = do
putStr $ unlines $ "FAILED:":msgs ++ [replicate 50 '-', cmdDesc cmdAct]
putStr =<< globalUsage
exitWith (ExitFailure 1)
run = case cmdAct of
(CommandActions _ r o passFlags) ->
let (cmdFlags, cmdArgs, cmdErrs) =
if passFlags
then getOpt'' o args
else getOpt Permute o args
in if null cmdErrs
then r cfg cmdFlags cmdArgs
else showError cmdErrs
-- |Format a table
fmtTable :: String -- ^Column separator
-> [[[String]]] -- ^Table rows (each cell may have more than
one line )
-> [String] -- ^Lines of output
fmtTable colSep rows = map fmtLine $ fmtRow =<< rows
where
fmtRow cs = transpose $ map (pad [] (maximum $ map length cs)) cs
fmtLine l = intercalate colSep $ zipWith (pad ' ') widths l
widths = map (maximum . map length . concat) $ transpose rows
pad c w s = take w $ s ++ repeat c
-- |Wrap a String of text to lines shorter than the specified number.
--
-- This function has heuristics for human-readability, such as
-- avoiding splitting in the middle of words when possible.
wrap :: Int -- ^Maximum line length
-> String -- ^Text to wrap
-> [String] -- ^Wrapped lines
wrap _ "" = []
wrap w orig = snd $ evalState (go 0 orig) Map.empty
where
go loc s = do
precomputed <- gets $ Map.lookup loc
case precomputed of
Nothing -> bestAnswer loc =<< mapM (scoreSplit loc) (splits w s)
Just answer -> return answer
scoreSplit loc (offset, lineScore, line, s') =
case s' of
"" -> return (lineScore, [line])
_ -> do
(restScore, lines_) <- go (loc + offset) s'
return (lineScore + restScore, line:lines_)
bestAnswer _ [] = error "No splits found!"
bestAnswer loc answers = do
let answer = minimum answers
modify $ Map.insert loc answer
return answer
-- Find all the locations that make sense to split the next line, and
-- score them.
splits :: Int -> String -> [(Int, Int, String, String)]
splits w s = map (\k -> score k $ splitAt k s) [w - 1,w - 2..1]
where
score k ([], cs) = (k, w * w, [], cs)
score k (r, []) = (k, 0, r, [])
score k (r, cs@(c:_)) = let (sps, cs') = countDropSpaces 0 cs
spaceLeft = w - length r
in ( -- How much of the string was consumed?
k + sps
-- How much does it cost to split here?
, penalty (last r) c + spaceLeft * spaceLeft
-- The text of the line that results
-- from this split
, r
-- The text that has not yet been split
, cs'
)
countDropSpaces i (c:cs) | isSpace c = countDropSpaces (i + 1) cs
countDropSpaces i cs = (i, cs)
-- Characters that want to stick to non-whitespace characters to
-- their right
rbind = (`elem` "\"'([<")
-- How much should it cost to make a split between these
-- characters?
penalty b c
-- Don't penalize boundaries between space and non-space
| not (isSpace b) && isSpace c = 0
| isSpace b && not (isSpace c) = 2
| rbind b && not (isSpace c) = w `div` 2
Penalize splitting a word heavily
| isLetter b && isLetter c = w * 2
-- Prefer splitting after a letter if it's not
-- followed by a letter
| isLetter c = 3
-- Other kinds of splits are not as bad as splitting
-- between words, but are still pretty harmful.
| otherwise = w
-- Return the value of the environment variable with the given name
-- or Nothing if the variable is not defined.
-- Probably should be replaced with System.Environment.lookupEnv
when the base library is upgraded > = 4.6
maybeGetEnv :: String -> IO (Maybe String)
maybeGetEnv name = (Just `fmap` getEnv name) `catchIOError` const (return Nothing)
| null | https://raw.githubusercontent.com/creswick/cabal-dev/bb1fb44a00cf053ea142617a31b5e2f2c189866b/src/Main.hs | haskell | installed into the sandbox are found
|Format a table
^Column separator
^Table rows (each cell may have more than
^Lines of output
|Wrap a String of text to lines shorter than the specified number.
This function has heuristics for human-readability, such as
avoiding splitting in the middle of words when possible.
^Maximum line length
^Text to wrap
^Wrapped lines
Find all the locations that make sense to split the next line, and
score them.
How much of the string was consumed?
How much does it cost to split here?
The text of the line that results
from this split
The text that has not yet been split
Characters that want to stick to non-whitespace characters to
their right
How much should it cost to make a split between these
characters?
Don't penalize boundaries between space and non-space
Prefer splitting after a letter if it's not
followed by a letter
Other kinds of splits are not as bad as splitting
between words, but are still pretty harmful.
Return the value of the environment variable with the given name
or Nothing if the variable is not defined.
Probably should be replaced with System.Environment.lookupEnv | Copyright ( c ) 2011 Galois , Inc
module Main
( main )
where
import Data.Char ( isSpace, isLetter )
import Data.List ( intercalate, transpose )
import Data.Maybe ( listToMaybe )
import Data.Version ( showVersion )
import Control.Monad ( unless )
import System.Exit ( exitWith, ExitCode(..) )
import System.Environment ( getArgs, getProgName, getEnv )
import System.IO.Error ( catchIOError )
import System.SetEnv (setEnv)
import System.FilePath ((</>), searchPathSeparator)
import System.Console.GetOpt ( usageInfo, getOpt, ArgOrder(Permute) )
import Distribution.Simple.Utils ( cabalVersion, debug )
import Distribution.Text ( display )
import Control.Monad.Trans.State ( evalState, gets, modify )
import Distribution.Dev.Command ( CommandActions(..), CommandResult(..) )
import Distribution.Dev.Flags ( parseGlobalFlags, helpRequested, globalOpts
, GlobalFlag(Version), getOpt'', fromFlags
, getVerbosity, Config, getSandbox, getEnvVars
)
import qualified Distribution.Dev.AddSource as AddSource
import qualified Distribution.Dev.Ghci as Ghci
import qualified Distribution.Dev.InvokeCabal as InvokeCabal
import qualified Distribution.Dev.InstallDependencies as InstallDeps
import qualified Distribution.Dev.BuildOpts as BuildOpts
import qualified Distribution.Dev.GhcPkg as GhcPkg
import qualified Distribution.Dev.CabalInstall as CI
import Paths_cabal_dev ( version )
import qualified Data.Map as Map
cabalDevCommands :: [(String, CommandActions, String)]
cabalDevCommands = [ ( "add-source"
, AddSource.actions
, "Make a package available for cabal-install to " ++
"install (in a sandbox-local Hackage repository). " ++
"Note that this command does NOT install the " ++
"package in the sandbox, and does require the " ++
"package to have a working sdist."
)
, ( "install-deps"
, InstallDeps.actions
, "Install the packages that depend on the specified " ++
"packages, but not the packages themselves. " ++
"(Equivalent to install --only-dependencies for " ++
"cabal-install > 0.10)"
)
, ( "ghci"
, Ghci.actions
, "Start ghci with the sandbox's GHC package " ++
"repository available. This command does not " ++
"yet take into account the contents of the .cabal " ++
"file (e.g. source directories, available packages " ++
"LANGUAGE pragmas)."
)
, ( "buildopts"
, BuildOpts.actions
, "Extract the options that would be passed to the " ++
"compiler when building"
)
, ( "ghc-pkg"
, GhcPkg.actions
, "Invoke ghc-pkg including the appropriate " ++
"--package-conf argument to run on the sandbox's " ++
"package database."
)
]
cabalInstallCommands :: [(String, CommandActions)]
cabalInstallCommands = map cabal CI.allCommands
where
cabal s = (CI.commandToString s, InvokeCabal.actions s)
allCommands :: [(String, CommandActions)]
allCommands = [(s, a) | (s, a, _) <- cabalDevCommands] ++ cabalInstallCommands
printVersion :: IO ()
printVersion = do
putStr versionString
exitWith ExitSuccess
versionString :: String
versionString = unlines $
[ "cabal-dev " ++ showVersion version
, "built with Cabal " ++ display cabalVersion
]
printNumericVersion :: IO ()
printNumericVersion = do
putStrLn $ showVersion version
exitWith ExitSuccess
main :: IO ()
main = do
envConf <- getEnvVars
(globalFlags, args, errs) <- parseGlobalFlags `fmap` getArgs
unless (null errs) $ do
mapM_ putStrLn errs
putStr =<< globalUsage
exitWith (ExitFailure 1)
let cfg = fromFlags envConf globalFlags
add sandbox to PATH , so that custom preprocessors that are
let binDir = getSandbox cfg </> "bin"
mPath <- maybeGetEnv "PATH"
let path = maybe binDir ((binDir ++ [searchPathSeparator]) ++) mPath
setEnv "PATH" path
case [f|(Version f) <- globalFlags] of
(True:_) -> printNumericVersion
(False:_) -> printVersion
[] -> return ()
debug (getVerbosity cfg) versionString
case args of
(name:args') ->
case nameCmd name of
Just cmdAct | helpRequested globalFlags ->
do putStrLn $ cmdDesc cmdAct
putStr =<< globalUsage
exitWith ExitSuccess
| otherwise -> runCmd cmdAct cfg args'
Nothing -> do putStrLn $ "Unknown command: " ++ show name
putStr =<< globalUsage
exitWith (ExitFailure 1)
_ | helpRequested globalFlags -> do
putStr =<< globalUsage
exitWith ExitSuccess
| otherwise -> do
putStrLn "Missing command name"
putStr =<< globalUsage
exitWith (ExitFailure 1)
globalUsage :: IO String
globalUsage = do
progName <- getProgName
let fmtCommands cmds =
fmtTable " " [ [[""], [n], wrap 60 d] | (n, _, d) <- cmds ]
let preamble =
unlines $
[ ""
, "Usage: " ++ progName ++ " <command>"
, ""
, "Where <command> is one of:"
] ++ fmtCommands cabalDevCommands ++
[ ""
, "or any cabal-install command (see cabal --help for documentation)."
, ""
, "Options to cabal-dev:"
]
return $ usageInfo preamble globalOpts
nameCmd :: String -> Maybe CommandActions
nameCmd s = listToMaybe [a | (n, a) <- allCommands, n == s]
runCmd :: CommandActions -> Config -> [String] -> IO ()
runCmd cmdAct cfg args =
do res <- run
case res of
CommandOk -> exitWith ExitSuccess
CommandError msg -> showError [msg]
where
showError msgs = do
putStr $ unlines $ "FAILED:":msgs ++ [replicate 50 '-', cmdDesc cmdAct]
putStr =<< globalUsage
exitWith (ExitFailure 1)
run = case cmdAct of
(CommandActions _ r o passFlags) ->
let (cmdFlags, cmdArgs, cmdErrs) =
if passFlags
then getOpt'' o args
else getOpt Permute o args
in if null cmdErrs
then r cfg cmdFlags cmdArgs
else showError cmdErrs
one line )
fmtTable colSep rows = map fmtLine $ fmtRow =<< rows
where
fmtRow cs = transpose $ map (pad [] (maximum $ map length cs)) cs
fmtLine l = intercalate colSep $ zipWith (pad ' ') widths l
widths = map (maximum . map length . concat) $ transpose rows
pad c w s = take w $ s ++ repeat c
wrap _ "" = []
wrap w orig = snd $ evalState (go 0 orig) Map.empty
where
go loc s = do
precomputed <- gets $ Map.lookup loc
case precomputed of
Nothing -> bestAnswer loc =<< mapM (scoreSplit loc) (splits w s)
Just answer -> return answer
scoreSplit loc (offset, lineScore, line, s') =
case s' of
"" -> return (lineScore, [line])
_ -> do
(restScore, lines_) <- go (loc + offset) s'
return (lineScore + restScore, line:lines_)
bestAnswer _ [] = error "No splits found!"
bestAnswer loc answers = do
let answer = minimum answers
modify $ Map.insert loc answer
return answer
splits :: Int -> String -> [(Int, Int, String, String)]
splits w s = map (\k -> score k $ splitAt k s) [w - 1,w - 2..1]
where
score k ([], cs) = (k, w * w, [], cs)
score k (r, []) = (k, 0, r, [])
score k (r, cs@(c:_)) = let (sps, cs') = countDropSpaces 0 cs
spaceLeft = w - length r
k + sps
, penalty (last r) c + spaceLeft * spaceLeft
, r
, cs'
)
countDropSpaces i (c:cs) | isSpace c = countDropSpaces (i + 1) cs
countDropSpaces i cs = (i, cs)
rbind = (`elem` "\"'([<")
penalty b c
| not (isSpace b) && isSpace c = 0
| isSpace b && not (isSpace c) = 2
| rbind b && not (isSpace c) = w `div` 2
Penalize splitting a word heavily
| isLetter b && isLetter c = w * 2
| isLetter c = 3
| otherwise = w
when the base library is upgraded > = 4.6
maybeGetEnv :: String -> IO (Maybe String)
maybeGetEnv name = (Just `fmap` getEnv name) `catchIOError` const (return Nothing)
|
3952b0e31504f486a59db8d2fae79d13a5b4d3bd15c04707defc79acd87cd995 | chaoxu/mgccl-haskell | pe1.hs | result = sum [n| n<-[1..999],n `mod` 3 == 0 || n `mod` 5==0]
| null | https://raw.githubusercontent.com/chaoxu/mgccl-haskell/bb03e39ae43f410bd2a673ac2b438929ab8ef7a1/pe/pe1.hs | haskell | result = sum [n| n<-[1..999],n `mod` 3 == 0 || n `mod` 5==0]
|
|
ee841ba9a3275facf51e34d8954e50b366051ea8874da8c70b14973d3d6be204 | PeterDWhite/Osker | Test3.hs | Copyright ( c ) , 2003
Copyright ( c ) OHSU , 2003
module Main where
--Haskell imports
import Monad
-- Test imports
import TestSupport
Braid imports
import qualified BraidExternal as B
import qualified BraidInternal as BI
The hub of the level 1 braid
-- This is not a lifted thread.
-- Argument is the maximum number of loops
hubl1 :: Int -> B.Braid Gs Ls ()
hubl1 loops =
do { tid <- B.myThreadId
; B.putStrLn ( ">>> hubl1, my tid = " ++ show tid )
; tid2 <- B.fork "Gs1" (gs1 loops)
; B.putStrLn ( ">>> Gs1 forked, tid = " ++ show tid2 )
; hubloop loops 0 1000000
; B.putStrLn ("... hubl1' is done" )
}
main :: IO ()
main = startup 3 "hubl1" hubl1
| null | https://raw.githubusercontent.com/PeterDWhite/Osker/301e1185f7c08c62c2929171cc0469a159ea802f/Braid/Test3.hs | haskell | Haskell imports
Test imports
This is not a lifted thread.
Argument is the maximum number of loops | Copyright ( c ) , 2003
Copyright ( c ) OHSU , 2003
module Main where
import Monad
import TestSupport
Braid imports
import qualified BraidExternal as B
import qualified BraidInternal as BI
The hub of the level 1 braid
hubl1 :: Int -> B.Braid Gs Ls ()
hubl1 loops =
do { tid <- B.myThreadId
; B.putStrLn ( ">>> hubl1, my tid = " ++ show tid )
; tid2 <- B.fork "Gs1" (gs1 loops)
; B.putStrLn ( ">>> Gs1 forked, tid = " ++ show tid2 )
; hubloop loops 0 1000000
; B.putStrLn ("... hubl1' is done" )
}
main :: IO ()
main = startup 3 "hubl1" hubl1
|
16c2128e46288c19552de809139150d742792a96d22ea98016cc1bd05badda39 | well-typed/large-records | R090.hs | #if PROFILE_CORESIZE
{-# OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #-}
#endif
#if PROFILE_TIMING
{-# OPTIONS_GHC -ddump-to-file -ddump-timings #-}
#endif
module Experiment.HListBaseline.Sized.R090 where
import Bench.Types
import Bench.HList
import Common.HListOfSize.HL090
hlist :: HList Fields
hlist =
-- 00 .. 09
MkT 00
:* MkT 01
:* MkT 02
:* MkT 03
:* MkT 04
:* MkT 05
:* MkT 06
:* MkT 07
:* MkT 08
:* MkT 09
10 .. 19
:* MkT 10
:* MkT 11
:* MkT 12
:* MkT 13
:* MkT 14
:* MkT 15
:* MkT 16
:* MkT 17
:* MkT 18
:* MkT 19
20 .. 29
:* MkT 20
:* MkT 21
:* MkT 22
:* MkT 23
:* MkT 24
:* MkT 25
:* MkT 26
:* MkT 27
:* MkT 28
:* MkT 29
30 .. 39
:* MkT 30
:* MkT 31
:* MkT 32
:* MkT 33
:* MkT 34
:* MkT 35
:* MkT 36
:* MkT 37
:* MkT 38
:* MkT 39
40 .. 49
:* MkT 40
:* MkT 41
:* MkT 42
:* MkT 43
:* MkT 44
:* MkT 45
:* MkT 46
:* MkT 47
:* MkT 48
:* MkT 49
50 .. 59
:* MkT 50
:* MkT 51
:* MkT 52
:* MkT 53
:* MkT 54
:* MkT 55
:* MkT 56
:* MkT 57
:* MkT 58
:* MkT 59
60 .. 69
:* MkT 60
:* MkT 61
:* MkT 62
:* MkT 63
:* MkT 64
:* MkT 65
:* MkT 66
:* MkT 67
:* MkT 68
:* MkT 69
70 .. 79
:* MkT 70
:* MkT 71
:* MkT 72
:* MkT 73
:* MkT 74
:* MkT 75
:* MkT 76
:* MkT 77
:* MkT 78
:* MkT 79
80 .. 89
:* MkT 80
:* MkT 81
:* MkT 82
:* MkT 83
:* MkT 84
:* MkT 85
:* MkT 86
:* MkT 87
:* MkT 88
:* MkT 89
:* Nil | null | https://raw.githubusercontent.com/well-typed/large-records/551f265845fbe56346988a6b484dca40ef380609/large-records-benchmarks/bench/typelet/Experiment/HListBaseline/Sized/R090.hs | haskell | # OPTIONS_GHC -ddump-to-file -ddump-ds-preopt -ddump-ds -ddump-simpl #
# OPTIONS_GHC -ddump-to-file -ddump-timings #
00 .. 09 | #if PROFILE_CORESIZE
#endif
#if PROFILE_TIMING
#endif
module Experiment.HListBaseline.Sized.R090 where
import Bench.Types
import Bench.HList
import Common.HListOfSize.HL090
hlist :: HList Fields
hlist =
MkT 00
:* MkT 01
:* MkT 02
:* MkT 03
:* MkT 04
:* MkT 05
:* MkT 06
:* MkT 07
:* MkT 08
:* MkT 09
10 .. 19
:* MkT 10
:* MkT 11
:* MkT 12
:* MkT 13
:* MkT 14
:* MkT 15
:* MkT 16
:* MkT 17
:* MkT 18
:* MkT 19
20 .. 29
:* MkT 20
:* MkT 21
:* MkT 22
:* MkT 23
:* MkT 24
:* MkT 25
:* MkT 26
:* MkT 27
:* MkT 28
:* MkT 29
30 .. 39
:* MkT 30
:* MkT 31
:* MkT 32
:* MkT 33
:* MkT 34
:* MkT 35
:* MkT 36
:* MkT 37
:* MkT 38
:* MkT 39
40 .. 49
:* MkT 40
:* MkT 41
:* MkT 42
:* MkT 43
:* MkT 44
:* MkT 45
:* MkT 46
:* MkT 47
:* MkT 48
:* MkT 49
50 .. 59
:* MkT 50
:* MkT 51
:* MkT 52
:* MkT 53
:* MkT 54
:* MkT 55
:* MkT 56
:* MkT 57
:* MkT 58
:* MkT 59
60 .. 69
:* MkT 60
:* MkT 61
:* MkT 62
:* MkT 63
:* MkT 64
:* MkT 65
:* MkT 66
:* MkT 67
:* MkT 68
:* MkT 69
70 .. 79
:* MkT 70
:* MkT 71
:* MkT 72
:* MkT 73
:* MkT 74
:* MkT 75
:* MkT 76
:* MkT 77
:* MkT 78
:* MkT 79
80 .. 89
:* MkT 80
:* MkT 81
:* MkT 82
:* MkT 83
:* MkT 84
:* MkT 85
:* MkT 86
:* MkT 87
:* MkT 88
:* MkT 89
:* Nil |
b2de174892853f04040e5ae50c56dfc639b3fdf0989fc88c75c7b0ba480a7e49 | zeniuseducation/poly-euler | p144.clj | (ns alfa.special.p144
(:require
[clojure.set :refer [union difference intersection subset?]]
[clojure.core.reducers :as r]
[clojure.string :refer [split-lines]]
[alfa.common :refer :all]
[clojure.string :as cs]))
(defn atan [l] (Math/atan l))
(defn tan [l] (Math/tan l))
(def PI Math/PI)
(declare f= reflection-grad impact-point grad next-grad next-impact)
(defn sol144
([p1 p2]
(sol144 p1 p2 0))
([[x1 y1 :as p1] [x2 y2 :as p2] res]
(if (and (<= (- y2 0.01) 10 (+ y2 00.1)) (f= x2 0))
res
(recur p2 (next-impact p1 p2) (+ res 1)))))
(defn next-impact
[p1 p2]
(let [m1 (reflection-grad p1 p2)
m2 (grad p2)]
(impact-point (next-grad m1 m2) p2)))
(defn impact-point
[m [x y]]
(let [c (- y (* m x))
bb (* 2 m c)
aa (+ (* m m) 4)
cc (- (* c c) 100)
det (sqrt (- (* bb bb) (* 4 aa cc)))
x1 (/ (+ (- bb) det) (* 2 aa))
x2 (/ (- (- bb) det) (* 2 aa))
y1 (+ (* m x1) c)
y2 (+ (* m x2) c)]
(if (and (f= x1 x) (f= y1 y))
[x2 y2]
[x1 y1])))
(defn f=
([x i] (f= x i 0.01))
([x i lim] (<= (- i lim) x (+ i lim))))
(defn grad [[x y]] (/ (* -4 x) y))
(defn reflection-grad
[[x1 y1] [x2 y2]]
(/ (- y2 y1) (- x2 x1)))
(defn next-grad
[m1 m2]
(let [am1 (atan m1)
am2 (atan m2)
diff (- am1 am2)]
(tan (+ (- PI (* 2 diff)) am1)))) | null | https://raw.githubusercontent.com/zeniuseducation/poly-euler/734fdcf1ddd096a8730600b684bf7398d071d499/Alfa/src/alfa/special/p144.clj | clojure | (ns alfa.special.p144
(:require
[clojure.set :refer [union difference intersection subset?]]
[clojure.core.reducers :as r]
[clojure.string :refer [split-lines]]
[alfa.common :refer :all]
[clojure.string :as cs]))
(defn atan [l] (Math/atan l))
(defn tan [l] (Math/tan l))
(def PI Math/PI)
(declare f= reflection-grad impact-point grad next-grad next-impact)
(defn sol144
([p1 p2]
(sol144 p1 p2 0))
([[x1 y1 :as p1] [x2 y2 :as p2] res]
(if (and (<= (- y2 0.01) 10 (+ y2 00.1)) (f= x2 0))
res
(recur p2 (next-impact p1 p2) (+ res 1)))))
(defn next-impact
[p1 p2]
(let [m1 (reflection-grad p1 p2)
m2 (grad p2)]
(impact-point (next-grad m1 m2) p2)))
(defn impact-point
[m [x y]]
(let [c (- y (* m x))
bb (* 2 m c)
aa (+ (* m m) 4)
cc (- (* c c) 100)
det (sqrt (- (* bb bb) (* 4 aa cc)))
x1 (/ (+ (- bb) det) (* 2 aa))
x2 (/ (- (- bb) det) (* 2 aa))
y1 (+ (* m x1) c)
y2 (+ (* m x2) c)]
(if (and (f= x1 x) (f= y1 y))
[x2 y2]
[x1 y1])))
(defn f=
([x i] (f= x i 0.01))
([x i lim] (<= (- i lim) x (+ i lim))))
(defn grad [[x y]] (/ (* -4 x) y))
(defn reflection-grad
[[x1 y1] [x2 y2]]
(/ (- y2 y1) (- x2 x1)))
(defn next-grad
[m1 m2]
(let [am1 (atan m1)
am2 (atan m2)
diff (- am1 am2)]
(tan (+ (- PI (* 2 diff)) am1)))) |
|
2a6e7f957ab703ac9e793a014b1ac112baa6a1a80119baaabeb5b42ec078d1f5 | typeclasses/dsv | LookupErrorUtf8.hs | # LANGUAGE NoImplicitPrelude #
# LANGUAGE DerivingStrategies , DeriveAnyClass #
module DSV.LookupErrorUtf8
( LookupErrorUtf8 (..)
) where
import DSV.IO
import DSV.Prelude
-- | The general concept of what can go wrong when you look up the position of a particular element in a list.
data LookupErrorUtf8
= LookupErrorUtf8_Missing -- ^ There is /no/ matching element.
| LookupErrorUtf8_Duplicate -- ^ There are /more than one/ matching elements.
^ Found one matching element , but it is not a valid UTF-8 string .
deriving stock (Eq, Show)
deriving anyclass Exception
| null | https://raw.githubusercontent.com/typeclasses/dsv/ae4eb823e27e4c569c4f9b097441985cf865fbab/dsv/library/DSV/LookupErrorUtf8.hs | haskell | | The general concept of what can go wrong when you look up the position of a particular element in a list.
^ There is /no/ matching element.
^ There are /more than one/ matching elements. | # LANGUAGE NoImplicitPrelude #
# LANGUAGE DerivingStrategies , DeriveAnyClass #
module DSV.LookupErrorUtf8
( LookupErrorUtf8 (..)
) where
import DSV.IO
import DSV.Prelude
data LookupErrorUtf8
^ Found one matching element , but it is not a valid UTF-8 string .
deriving stock (Eq, Show)
deriving anyclass Exception
|
f9f6b92cfa1d724049d9611f93f93a4613679723e10d861d8472eb6e83220ffd | weyrick/roadsend-php | re-extensions.scm | ; ***** BEGIN LICENSE BLOCK *****
Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , 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 ; either version 2.1
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 Lesser General Public License for more details .
;;
You should have received a copy of the GNU Lesser General Public License
;; along with this program; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
;; ***** END LICENSE BLOCK *****
(module re-extension-lib
(include "../phpoo-extension.sch")
(library profiler)
; exports
(export
(init-re-extension-lib)
(re_get_loaded_libs)
(re_copy thing)
(re_register_extension php-ext-name ext-lib-name version depends-on)
))
;
; NOTE: the goal is to keep these to a minimum. this should only, only functions
; that hook into roadsend specific functionality
;
(define (init-re-extension-lib) 1)
get a list of PHP libs loaded from pcc.conf
(defbuiltin (re_get_loaded_libs)
(list->php-hash *user-libs*))
;explicitly copy
(defbuiltin (re_copy thing)
(copy-php-data thing))
;a way for pcc PHP extensions to register
(defbuiltin (re_register_extension php-ext-name ext-lib-name version (depends-on #f))
"PCC only function to register a PHP extension.
Used for Roadsend PHP extensions written in PHP and compiled to libraries, e.g. PDO"
(register-extension (mkstr php-ext-name)
(mkstr version)
(mkstr ext-lib-name)
required-extensions: (if (php-hash? depends-on)
(php-hash->list depends-on)
'())))
| null | https://raw.githubusercontent.com/weyrick/roadsend-php/d6301a897b1a02d7a85bdb915bea91d0991eb158/runtime/ext/standard/re-extensions.scm | scheme | ***** BEGIN LICENSE BLOCK *****
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
either version 2.1
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
along with this program; if not, write to the Free Software
***** END LICENSE BLOCK *****
exports
NOTE: the goal is to keep these to a minimum. this should only, only functions
that hook into roadsend specific functionality
explicitly copy
a way for pcc PHP extensions to register | Roadsend PHP Compiler Runtime Libraries
Copyright ( C ) 2007 Roadsend , Inc.
of the License , or ( at your option ) any later version .
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public License
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , MA 02110 - 1301 , USA
(module re-extension-lib
(include "../phpoo-extension.sch")
(library profiler)
(export
(init-re-extension-lib)
(re_get_loaded_libs)
(re_copy thing)
(re_register_extension php-ext-name ext-lib-name version depends-on)
))
(define (init-re-extension-lib) 1)
get a list of PHP libs loaded from pcc.conf
(defbuiltin (re_get_loaded_libs)
(list->php-hash *user-libs*))
(defbuiltin (re_copy thing)
(copy-php-data thing))
(defbuiltin (re_register_extension php-ext-name ext-lib-name version (depends-on #f))
"PCC only function to register a PHP extension.
Used for Roadsend PHP extensions written in PHP and compiled to libraries, e.g. PDO"
(register-extension (mkstr php-ext-name)
(mkstr version)
(mkstr ext-lib-name)
required-extensions: (if (php-hash? depends-on)
(php-hash->list depends-on)
'())))
|
40d7ac6eb771c8a94071054ccab9aee69cc6c603862a96e6e80165298ca7d328 | NorfairKing/cursor | Delete.hs | # LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Cursor.Tree.Delete
( treeCursorDeleteSubTreeAndSelectPrevious,
treeCursorDeleteSubTreeAndSelectNext,
treeCursorDeleteSubTreeAndSelectAbove,
treeCursorRemoveSubTree,
treeCursorDeleteSubTree,
treeCursorDeleteElemAndSelectPrevious,
treeCursorDeleteElemAndSelectNext,
treeCursorDeleteElemAndSelectAbove,
treeCursorRemoveElem,
treeCursorDeleteElem,
)
where
import Control.Applicative
import Cursor.Tree.Base
import Cursor.Tree.Types
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Tree
treeCursorDeleteSubTreeAndSelectPrevious ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteSubTreeAndSelectPrevious g TreeCursor {..} =
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveLefts ta of
[] -> Nothing
tree : xs -> Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveLefts = xs}
treeCursorDeleteSubTreeAndSelectNext ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteSubTreeAndSelectNext g TreeCursor {..} =
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs -> Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveRights = xs}
treeCursorDeleteSubTreeAndSelectAbove ::
(b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteSubTreeAndSelectAbove g TreeCursor {..} =
case treeAbove of
Nothing -> Deleted
Just TreeAbove {..} ->
Updated $
TreeCursor
{ treeAbove = treeAboveAbove,
treeCurrent = g treeAboveNode,
treeBelow = openForest $ reverse treeAboveLefts ++ treeAboveRights
}
treeCursorRemoveSubTree :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorRemoveSubTree g tc =
joinDeletes
(treeCursorDeleteSubTreeAndSelectPrevious g tc)
(treeCursorDeleteSubTreeAndSelectNext g tc)
<|> treeCursorDeleteSubTreeAndSelectAbove g tc
treeCursorDeleteSubTree :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteSubTree g tc =
joinDeletes
(treeCursorDeleteSubTreeAndSelectNext g tc)
(treeCursorDeleteSubTreeAndSelectPrevious g tc)
<|> treeCursorDeleteSubTreeAndSelectAbove g tc
treeCursorDeleteElemAndSelectPrevious ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectPrevious g TreeCursor {..} =
case treeAbove of
Nothing ->
case treeBelow of
EmptyCForest -> Just Deleted
_ -> Nothing
Just ta ->
case treeAboveLefts ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $
Just
ta
{ treeAboveLefts = xs,
treeAboveRights = unpackCForest treeBelow ++ treeAboveRights ta
}
treeCursorDeleteElemAndSelectNext ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectNext g TreeCursor {..} =
case treeBelow of
EmptyCForest ->
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveRights = xs}
ClosedForest ts ->
case treeAbove of
Nothing ->
case ts of
(Node e ts_ :| xs) ->
let t = CNode e $ closedForest $ ts_ ++ xs
in Just . Updated $ makeTreeCursorWithAbove g t treeAbove
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $
Just
ta
{ treeAboveLefts = map makeCTree (reverse $ NE.toList ts) ++ treeAboveLefts ta,
treeAboveRights = xs
}
OpenForest (CNode e ts :| xs) ->
let t =
CNode e $
case ts of
EmptyCForest -> openForest xs
OpenForest ts_ -> openForest $ NE.toList ts_ ++ xs
ClosedForest ts_ -> closedForest $ NE.toList ts_ ++ map rebuildCTree xs
in Just . Updated $ makeTreeCursorWithAbove g t treeAbove
treeCursorDeleteElemAndSelectAbove ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectAbove g TreeCursor {..} =
case treeAbove of
Nothing ->
case treeBelow of
EmptyCForest -> Just Deleted
_ -> Nothing
Just TreeAbove {..} ->
Just $
Updated $
TreeCursor
{ treeAbove = treeAboveAbove,
treeCurrent = g treeAboveNode,
treeBelow =
openForest $ reverse treeAboveLefts ++ unpackCForest treeBelow ++ treeAboveRights
}
treeCursorRemoveElem :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorRemoveElem g tc =
joinDeletes3
(treeCursorDeleteElemAndSelectPrevious g tc)
(treeCursorDeleteElemAndSelectNext g tc)
(treeCursorDeleteElemAndSelectAbove g tc)
treeCursorDeleteElem :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteElem g tc =
joinDeletes3
(treeCursorDeleteElemAndSelectNext g tc)
(treeCursorDeleteElemAndSelectPrevious g tc)
(treeCursorDeleteElemAndSelectAbove g tc)
| null | https://raw.githubusercontent.com/NorfairKing/cursor/ff27e78281430c298a25a7805c9c61ca1e69f4c5/cursor/src/Cursor/Tree/Delete.hs | haskell | # LANGUAGE RecordWildCards #
# LANGUAGE TypeFamilies #
module Cursor.Tree.Delete
( treeCursorDeleteSubTreeAndSelectPrevious,
treeCursorDeleteSubTreeAndSelectNext,
treeCursorDeleteSubTreeAndSelectAbove,
treeCursorRemoveSubTree,
treeCursorDeleteSubTree,
treeCursorDeleteElemAndSelectPrevious,
treeCursorDeleteElemAndSelectNext,
treeCursorDeleteElemAndSelectAbove,
treeCursorRemoveElem,
treeCursorDeleteElem,
)
where
import Control.Applicative
import Cursor.Tree.Base
import Cursor.Tree.Types
import Cursor.Types
import Data.List.NonEmpty (NonEmpty (..))
import qualified Data.List.NonEmpty as NE
import Data.Tree
treeCursorDeleteSubTreeAndSelectPrevious ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteSubTreeAndSelectPrevious g TreeCursor {..} =
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveLefts ta of
[] -> Nothing
tree : xs -> Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveLefts = xs}
treeCursorDeleteSubTreeAndSelectNext ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteSubTreeAndSelectNext g TreeCursor {..} =
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs -> Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveRights = xs}
treeCursorDeleteSubTreeAndSelectAbove ::
(b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteSubTreeAndSelectAbove g TreeCursor {..} =
case treeAbove of
Nothing -> Deleted
Just TreeAbove {..} ->
Updated $
TreeCursor
{ treeAbove = treeAboveAbove,
treeCurrent = g treeAboveNode,
treeBelow = openForest $ reverse treeAboveLefts ++ treeAboveRights
}
treeCursorRemoveSubTree :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorRemoveSubTree g tc =
joinDeletes
(treeCursorDeleteSubTreeAndSelectPrevious g tc)
(treeCursorDeleteSubTreeAndSelectNext g tc)
<|> treeCursorDeleteSubTreeAndSelectAbove g tc
treeCursorDeleteSubTree :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteSubTree g tc =
joinDeletes
(treeCursorDeleteSubTreeAndSelectNext g tc)
(treeCursorDeleteSubTreeAndSelectPrevious g tc)
<|> treeCursorDeleteSubTreeAndSelectAbove g tc
treeCursorDeleteElemAndSelectPrevious ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectPrevious g TreeCursor {..} =
case treeAbove of
Nothing ->
case treeBelow of
EmptyCForest -> Just Deleted
_ -> Nothing
Just ta ->
case treeAboveLefts ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $
Just
ta
{ treeAboveLefts = xs,
treeAboveRights = unpackCForest treeBelow ++ treeAboveRights ta
}
treeCursorDeleteElemAndSelectNext ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectNext g TreeCursor {..} =
case treeBelow of
EmptyCForest ->
case treeAbove of
Nothing -> Just Deleted
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $ Just ta {treeAboveRights = xs}
ClosedForest ts ->
case treeAbove of
Nothing ->
case ts of
(Node e ts_ :| xs) ->
let t = CNode e $ closedForest $ ts_ ++ xs
in Just . Updated $ makeTreeCursorWithAbove g t treeAbove
Just ta ->
case treeAboveRights ta of
[] -> Nothing
tree : xs ->
Just . Updated . makeTreeCursorWithAbove g tree $
Just
ta
{ treeAboveLefts = map makeCTree (reverse $ NE.toList ts) ++ treeAboveLefts ta,
treeAboveRights = xs
}
OpenForest (CNode e ts :| xs) ->
let t =
CNode e $
case ts of
EmptyCForest -> openForest xs
OpenForest ts_ -> openForest $ NE.toList ts_ ++ xs
ClosedForest ts_ -> closedForest $ NE.toList ts_ ++ map rebuildCTree xs
in Just . Updated $ makeTreeCursorWithAbove g t treeAbove
treeCursorDeleteElemAndSelectAbove ::
(b -> a) -> TreeCursor a b -> Maybe (DeleteOrUpdate (TreeCursor a b))
treeCursorDeleteElemAndSelectAbove g TreeCursor {..} =
case treeAbove of
Nothing ->
case treeBelow of
EmptyCForest -> Just Deleted
_ -> Nothing
Just TreeAbove {..} ->
Just $
Updated $
TreeCursor
{ treeAbove = treeAboveAbove,
treeCurrent = g treeAboveNode,
treeBelow =
openForest $ reverse treeAboveLefts ++ unpackCForest treeBelow ++ treeAboveRights
}
treeCursorRemoveElem :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorRemoveElem g tc =
joinDeletes3
(treeCursorDeleteElemAndSelectPrevious g tc)
(treeCursorDeleteElemAndSelectNext g tc)
(treeCursorDeleteElemAndSelectAbove g tc)
treeCursorDeleteElem :: (b -> a) -> TreeCursor a b -> DeleteOrUpdate (TreeCursor a b)
treeCursorDeleteElem g tc =
joinDeletes3
(treeCursorDeleteElemAndSelectNext g tc)
(treeCursorDeleteElemAndSelectPrevious g tc)
(treeCursorDeleteElemAndSelectAbove g tc)
|
|
0a2dbd6d7673dd7885cddc7d79fe8087ab041a2d6295169f9c8e98bace857e04 | Eduap-com/WordMat | sprdet.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module sprdet)
;; THIS IS THE NEW DETERMINANT PACKAGE
(declare-top (special x *ptr* *ptc* *blk* $ratmx ml* *detsign* rzl*))
(defun sprdet (ax n)
(declare (fixnum n))
(setq ax (get-array-pointer ax))
(prog ((j 0) rodr codr bl det (dm 0) (r 0) (i 0))
(declare (fixnum i j dm r))
(setq det 1)
(setq *ptr* (make-array (1+ n)))
(setq *ptc* (make-array (1+ n)))
(setq bl (tmlattice ax '*ptr* '*ptc* n)) ;tmlattice isn't defined anywhere -- are_muc
(when (null bl) (return 0))
(setq rodr (apply #'append bl))
(setq codr (mapcar #'cadr rodr))
(setq rodr (mapcar #'car rodr))
(setq det (* (prmusign rodr) (prmusign codr)))
(setq bl (mapcar #'length bl))
loop1 (when (null bl) (return det))
(setq i (car bl))
(setq dm i)
(setq *blk* (make-array (list (1+ dm) (1+ dm))))
(cond ((= dm 1)
(setq det (gptimes det (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (1+ r))))))
(go next))
((= dm 2)
(setq det (gptimes det
(gpdifference
(gptimes (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (1+ r))))
(car (aref ax (aref *ptr* (+ 2 r)) (aref *ptc* (+ 2 r)))))
(gptimes (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (+ 2 r))))
(car (aref ax (aref *ptr* (+ 2 r)) (aref *ptc* (1+ r))))))))
(go next)))
loop2 (when (= i 0) (go cmp))
(setq j dm)
loop3 (when (= j 0) (decf i) (go loop2))
(setf (aref *blk* i j) (car (aref ax (aref *ptr* (+ r i)) (aref *ptc*(+ r j)))))
(decf j) (go loop3)
cmp
(setq det (gptimes det (tdbu '*blk* dm)))
next
(incf r dm)
(setq bl (cdr bl))
(go loop1)))
(defun minorl (x n l nz)
(declare (fixnum n))
(prog (ans s rzl* (col 1) (n2 (truncate n 2)) d dl z a elm rule)
(declare (fixnum n2 col ))
(decf n2)
(setq dl l l nil nz (cons nil nz))
l1 (when (null nz) (return ans))
l3 (setq z (car nz))
(cond ((null l) (if dl (push dl ans) (return nil))
(setq nz (cdr nz) col (1+ col) l dl dl nil)
(go l1)))
(setq a (caar l) )
l2 (cond ((null z)
(cond (rule (rplaca (car l) (list a rule))
(setq rule nil) (setq l (cdr l)))
((null (cdr l))
(rplaca (car l) (list a 0))
(setq l (cdr l)))
(t (rplaca l (cadr l))
(rplacd l (cddr l))))
(go l3)))
(setq elm (car z) z (cdr z))
(setq s (signnp elm a))
(cond (s (setq d (delete elm (copy-list a) :test #'equal))
(cond ((membercar d dl)
(go on))
(t
(when (or (< col n2) (not (singp x d col n)))
(push (cons d 1) dl)
(go on))))))
(go l2)
on (setq rule (cons (list d s elm (1- col)) rule))
(go l2)))
(declare-top (special j))
(defun singp (x ml col n)
(declare (fixnum col n))
(prog (i (j col) l)
(declare (fixnum j))
(setq l ml)
(if (null ml)
(go loop)
(setq i (car ml)
ml (cdr ml)))
(cond ((member i rzl* :test #'equal) (return t))
((zrow x i col n) (return (setq rzl*(cons i rzl*)))))
loop (cond ((> j n) (return nil))
((every #'(lambda (i) (equal (aref x i j) 0)) l)
(return t)))
(incf j)
(go loop)))
(declare-top (unspecial j))
(defun tdbu (x n)
(declare (fixnum n))
(prog (a ml* nl nml dd)
(setq *detsign* 1)
(setq x (get-array-pointer x))
(detpivot x n)
(setq x (get-array-pointer 'x*))
(setq nl (nzl x n))
(when (member nil nl :test #'eq) (return 0))
(setq a (minorl x n (list (cons (nreverse(index* n)) 1)) nl))
(setq nl nil)
(when (null a) (return 0))
(tb2 x (car a) n)
tag2
(setq ml* (cons (cons nil nil) (car a)))
(setq a (cdr a))
(when (null a) (return (if (= *detsign* 1)
(cadadr ml*)
(gpctimes -1 (cadadr ml*)))))
(setq nml (car a))
tag1 (when (null nml) (go tag2))
(setq dd (car nml))
(setq nml (cdr nml))
(nbn dd)
(go tag1)))
(defun nbn (rule)
(declare (special x))
(prog (ans r a)
(setq ans 0 r (cadar rule))
(when (equal r 0) (return 0))
(rplaca rule (caar rule))
loop (when (null r) (return (rplacd rule (cons ans (cdr rule)))))
(setq a (car r) r(cdr r))
(setq ans (gpplus ans (gptimes (if (= (cadr a) 1)
(aref x (caddr a) (cadddr a))
(gpctimes (cadr a) (aref x (caddr a) (cadddr a))))
(getminor (car a)))))
(go loop)))
(defun getminor (index)
(cond ((null (setq index (assoc index ml* :test #'equal))) 0)
(t (rplacd (cdr index) (1- (cddr index)))
(when (= (cddr index) 0)
(setf index (delete index ml* :test #'equal)))
(cadr index))))
(defun tb2 (x l n)
(declare (fixnum n ))
(prog ((n-1 (1- n)) b a)
(declare (fixnum n-1))
loop (when (null l) (return nil))
(setq a (car l) l (cdr l) b (car a))
(rplacd a (cons (gpdifference (gptimes (aref x (car b) n-1) (aref x (cadr b) n))
(gptimes (aref x (car b) n) (aref x (cadr b) n-1)))
(cdr a)))
(go loop)))
(defun zrow (x i col n)
(declare (fixnum i col n))
(prog ((j col))
(declare (fixnum j))
loop (cond ((> j n)
(return t))
((equal (aref x i j) 0)
(incf j)
(go loop)))))
(defun nzl (a n)
(declare (fixnum n))
(prog ((i 0) (j (- n 2)) d l)
(declare (fixnum i j))
loop0 (when (= j 0) (return l))
(setq i n)
loop1 (when (= i 0)
(push d l)
(setq d nil)
(decf j)
(go loop0))
(when (not (equal (aref a i j) 0))
(push i d))
(decf i)
(go loop1)))
(defun signnp (e l)
(prog (i)
(setq i 1)
loop (cond ((null l) (return nil))
((equal e (car l)) (return i)))
(setq l (cdr l) i (- i))
(go loop)))
(defun membercar (e l)
(prog()
loop (cond ((null l)
(return nil))
((equal e (caar l))
(return (rplacd (car l) (1+ (cdar l))))))
(setq l (cdr l))
(go loop)))
(declare-top (unspecial x ml* rzl*))
(defun atranspose (a n)
(prog (i j d)
(setq i 0)
loop1 (setq i (1+ i) j i)
(when (> i n) (return nil))
loop2 (incf j)
(when (> j n) (go loop1))
(setq d (aref a i j))
(setf (aref a i j) (aref a j i))
(setf (aref a j i) d)
(go loop2)))
(defun mxcomp (l1 l2)
(prog()
loop (cond ((null l1) (return t))
((car> (car l1) (car l2)) (return t))
((car> (car l2) (car l1)) (return nil)))
(setq l1 (cdr l1) l2 (cdr l2))
(go loop)))
(defun prmusign (l)
(prog ((b 0) a d)
(declare (fixnum b))
loop (when (null l) (return (if (even b) 1 -1)))
(setq a (car l) l (cdr l) d l)
loop1 (cond ((null d) (go loop))
((> a (car d)) (incf b)))
(setq d (cdr d))
(go loop1)))
(defun detpivot (x n)
(prog (r0 c0)
(setq c0 (colrow0 x n nil)
r0 (colrow0 x n t))
(setq c0 (nreverse (bbsort c0 #'car>)))
(setq r0 (nreverse (bbsort r0 #'car>)))
(when (not (mxcomp c0 r0))
(atranspose x n)
(setq c0 r0))
(setq *detsign* (prmusign (mapcar #'car c0)))
(newmat 'x* x n c0)))
(defun newmat(x y n l)
(prog (i j jl)
(setf (symbol-value x) (make-array (list (1+ n) (1+ n))))
(setq x (get-array-pointer x))
(setq j 0)
loop (setq i 0 j (1+ j))
(when (null l) (return nil))
(setq jl (cdar l) l (cdr l))
tag (incf i)
(when (> i n) (go loop))
(setf (aref x i j) (aref y i jl))
(go tag)))
(defun car> (a b)
(> (car a) (car b)))
;; ind=t for row ortherwise col
(defun colrow0 (a n ind)
(declare (fixnum n))
(prog ((i 0) (j n) l (c 0))
(declare (fixnum i c j))
loop0 (cond ((= j 0) (return l)))
(setq i n)
loop1 (when (= i 0)
(push (cons c j) l)
(setq c 0)
(decf j)
(go loop0))
(when (equal (if ind (aref a j i) (aref a i j)) 0)
(incf c))
(decf i)
(go loop1)))
(defun gpdifference (a b)
(if $ratmx
(pdifference a b)
(simplus(list '(mplus) a (list '(mtimes) -1 b)) 1 nil)))
(defun gpctimes(a b)
(if $ratmx
(pctimes a b)
(simptimes(list '(mtimes) a b) 1 nil)))
(defun gptimes(a b)
(if $ratmx
(ptimes a b)
(simptimes (list '(mtimes) a b) 1 nil)))
(defun gpplus(a b)
(if $ratmx
(pplus a b)
(simplus(list '(mplus) a b) 1 nil)))
| null | https://raw.githubusercontent.com/Eduap-com/WordMat/83c9336770067f54431cc42c7147dc6ed640a339/Windows/ExternalPrograms/maxima-5.45.1/share/maxima/5.45.1/src/sprdet.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
THIS IS THE NEW DETERMINANT PACKAGE
tmlattice isn't defined anywhere -- are_muc
ind=t for row ortherwise col |
(in-package :maxima)
(macsyma-module sprdet)
(declare-top (special x *ptr* *ptc* *blk* $ratmx ml* *detsign* rzl*))
(defun sprdet (ax n)
(declare (fixnum n))
(setq ax (get-array-pointer ax))
(prog ((j 0) rodr codr bl det (dm 0) (r 0) (i 0))
(declare (fixnum i j dm r))
(setq det 1)
(setq *ptr* (make-array (1+ n)))
(setq *ptc* (make-array (1+ n)))
(when (null bl) (return 0))
(setq rodr (apply #'append bl))
(setq codr (mapcar #'cadr rodr))
(setq rodr (mapcar #'car rodr))
(setq det (* (prmusign rodr) (prmusign codr)))
(setq bl (mapcar #'length bl))
loop1 (when (null bl) (return det))
(setq i (car bl))
(setq dm i)
(setq *blk* (make-array (list (1+ dm) (1+ dm))))
(cond ((= dm 1)
(setq det (gptimes det (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (1+ r))))))
(go next))
((= dm 2)
(setq det (gptimes det
(gpdifference
(gptimes (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (1+ r))))
(car (aref ax (aref *ptr* (+ 2 r)) (aref *ptc* (+ 2 r)))))
(gptimes (car (aref ax (aref *ptr* (1+ r)) (aref *ptc* (+ 2 r))))
(car (aref ax (aref *ptr* (+ 2 r)) (aref *ptc* (1+ r))))))))
(go next)))
loop2 (when (= i 0) (go cmp))
(setq j dm)
loop3 (when (= j 0) (decf i) (go loop2))
(setf (aref *blk* i j) (car (aref ax (aref *ptr* (+ r i)) (aref *ptc*(+ r j)))))
(decf j) (go loop3)
cmp
(setq det (gptimes det (tdbu '*blk* dm)))
next
(incf r dm)
(setq bl (cdr bl))
(go loop1)))
(defun minorl (x n l nz)
(declare (fixnum n))
(prog (ans s rzl* (col 1) (n2 (truncate n 2)) d dl z a elm rule)
(declare (fixnum n2 col ))
(decf n2)
(setq dl l l nil nz (cons nil nz))
l1 (when (null nz) (return ans))
l3 (setq z (car nz))
(cond ((null l) (if dl (push dl ans) (return nil))
(setq nz (cdr nz) col (1+ col) l dl dl nil)
(go l1)))
(setq a (caar l) )
l2 (cond ((null z)
(cond (rule (rplaca (car l) (list a rule))
(setq rule nil) (setq l (cdr l)))
((null (cdr l))
(rplaca (car l) (list a 0))
(setq l (cdr l)))
(t (rplaca l (cadr l))
(rplacd l (cddr l))))
(go l3)))
(setq elm (car z) z (cdr z))
(setq s (signnp elm a))
(cond (s (setq d (delete elm (copy-list a) :test #'equal))
(cond ((membercar d dl)
(go on))
(t
(when (or (< col n2) (not (singp x d col n)))
(push (cons d 1) dl)
(go on))))))
(go l2)
on (setq rule (cons (list d s elm (1- col)) rule))
(go l2)))
(declare-top (special j))
(defun singp (x ml col n)
(declare (fixnum col n))
(prog (i (j col) l)
(declare (fixnum j))
(setq l ml)
(if (null ml)
(go loop)
(setq i (car ml)
ml (cdr ml)))
(cond ((member i rzl* :test #'equal) (return t))
((zrow x i col n) (return (setq rzl*(cons i rzl*)))))
loop (cond ((> j n) (return nil))
((every #'(lambda (i) (equal (aref x i j) 0)) l)
(return t)))
(incf j)
(go loop)))
(declare-top (unspecial j))
(defun tdbu (x n)
(declare (fixnum n))
(prog (a ml* nl nml dd)
(setq *detsign* 1)
(setq x (get-array-pointer x))
(detpivot x n)
(setq x (get-array-pointer 'x*))
(setq nl (nzl x n))
(when (member nil nl :test #'eq) (return 0))
(setq a (minorl x n (list (cons (nreverse(index* n)) 1)) nl))
(setq nl nil)
(when (null a) (return 0))
(tb2 x (car a) n)
tag2
(setq ml* (cons (cons nil nil) (car a)))
(setq a (cdr a))
(when (null a) (return (if (= *detsign* 1)
(cadadr ml*)
(gpctimes -1 (cadadr ml*)))))
(setq nml (car a))
tag1 (when (null nml) (go tag2))
(setq dd (car nml))
(setq nml (cdr nml))
(nbn dd)
(go tag1)))
(defun nbn (rule)
(declare (special x))
(prog (ans r a)
(setq ans 0 r (cadar rule))
(when (equal r 0) (return 0))
(rplaca rule (caar rule))
loop (when (null r) (return (rplacd rule (cons ans (cdr rule)))))
(setq a (car r) r(cdr r))
(setq ans (gpplus ans (gptimes (if (= (cadr a) 1)
(aref x (caddr a) (cadddr a))
(gpctimes (cadr a) (aref x (caddr a) (cadddr a))))
(getminor (car a)))))
(go loop)))
(defun getminor (index)
(cond ((null (setq index (assoc index ml* :test #'equal))) 0)
(t (rplacd (cdr index) (1- (cddr index)))
(when (= (cddr index) 0)
(setf index (delete index ml* :test #'equal)))
(cadr index))))
(defun tb2 (x l n)
(declare (fixnum n ))
(prog ((n-1 (1- n)) b a)
(declare (fixnum n-1))
loop (when (null l) (return nil))
(setq a (car l) l (cdr l) b (car a))
(rplacd a (cons (gpdifference (gptimes (aref x (car b) n-1) (aref x (cadr b) n))
(gptimes (aref x (car b) n) (aref x (cadr b) n-1)))
(cdr a)))
(go loop)))
(defun zrow (x i col n)
(declare (fixnum i col n))
(prog ((j col))
(declare (fixnum j))
loop (cond ((> j n)
(return t))
((equal (aref x i j) 0)
(incf j)
(go loop)))))
(defun nzl (a n)
(declare (fixnum n))
(prog ((i 0) (j (- n 2)) d l)
(declare (fixnum i j))
loop0 (when (= j 0) (return l))
(setq i n)
loop1 (when (= i 0)
(push d l)
(setq d nil)
(decf j)
(go loop0))
(when (not (equal (aref a i j) 0))
(push i d))
(decf i)
(go loop1)))
(defun signnp (e l)
(prog (i)
(setq i 1)
loop (cond ((null l) (return nil))
((equal e (car l)) (return i)))
(setq l (cdr l) i (- i))
(go loop)))
(defun membercar (e l)
(prog()
loop (cond ((null l)
(return nil))
((equal e (caar l))
(return (rplacd (car l) (1+ (cdar l))))))
(setq l (cdr l))
(go loop)))
(declare-top (unspecial x ml* rzl*))
(defun atranspose (a n)
(prog (i j d)
(setq i 0)
loop1 (setq i (1+ i) j i)
(when (> i n) (return nil))
loop2 (incf j)
(when (> j n) (go loop1))
(setq d (aref a i j))
(setf (aref a i j) (aref a j i))
(setf (aref a j i) d)
(go loop2)))
(defun mxcomp (l1 l2)
(prog()
loop (cond ((null l1) (return t))
((car> (car l1) (car l2)) (return t))
((car> (car l2) (car l1)) (return nil)))
(setq l1 (cdr l1) l2 (cdr l2))
(go loop)))
(defun prmusign (l)
(prog ((b 0) a d)
(declare (fixnum b))
loop (when (null l) (return (if (even b) 1 -1)))
(setq a (car l) l (cdr l) d l)
loop1 (cond ((null d) (go loop))
((> a (car d)) (incf b)))
(setq d (cdr d))
(go loop1)))
(defun detpivot (x n)
(prog (r0 c0)
(setq c0 (colrow0 x n nil)
r0 (colrow0 x n t))
(setq c0 (nreverse (bbsort c0 #'car>)))
(setq r0 (nreverse (bbsort r0 #'car>)))
(when (not (mxcomp c0 r0))
(atranspose x n)
(setq c0 r0))
(setq *detsign* (prmusign (mapcar #'car c0)))
(newmat 'x* x n c0)))
(defun newmat(x y n l)
(prog (i j jl)
(setf (symbol-value x) (make-array (list (1+ n) (1+ n))))
(setq x (get-array-pointer x))
(setq j 0)
loop (setq i 0 j (1+ j))
(when (null l) (return nil))
(setq jl (cdar l) l (cdr l))
tag (incf i)
(when (> i n) (go loop))
(setf (aref x i j) (aref y i jl))
(go tag)))
(defun car> (a b)
(> (car a) (car b)))
(defun colrow0 (a n ind)
(declare (fixnum n))
(prog ((i 0) (j n) l (c 0))
(declare (fixnum i c j))
loop0 (cond ((= j 0) (return l)))
(setq i n)
loop1 (when (= i 0)
(push (cons c j) l)
(setq c 0)
(decf j)
(go loop0))
(when (equal (if ind (aref a j i) (aref a i j)) 0)
(incf c))
(decf i)
(go loop1)))
(defun gpdifference (a b)
(if $ratmx
(pdifference a b)
(simplus(list '(mplus) a (list '(mtimes) -1 b)) 1 nil)))
(defun gpctimes(a b)
(if $ratmx
(pctimes a b)
(simptimes(list '(mtimes) a b) 1 nil)))
(defun gptimes(a b)
(if $ratmx
(ptimes a b)
(simptimes (list '(mtimes) a b) 1 nil)))
(defun gpplus(a b)
(if $ratmx
(pplus a b)
(simplus(list '(mplus) a b) 1 nil)))
|
bdb73f5efb22bf1cb4c8963cb9f5d559011e1c2d1d65954fdf0c010f8dc6ff8c | prg-titech/baccaml | mtj-call.ml | let print_array arr = print_string " [ " ; ( fun a - > print_int a ;
print_string " ; " ) ; print_string " ] " in
let debug stack pc sp = print_array stack ; print_newline ( ) ; print_string
" pc : " ; print_int pc ; print_newline ( ) ; print_string " sp : " ; print_int sp ;
print_newline ( ) ; in
print_string "; ") arr; print_string "]" in
let debug stack pc sp = print_array stack; print_newline (); print_string
"pc: "; print_int pc; print_newline (); print_string "sp: "; print_int sp;
print_newline (); in *)
;;
let rec interp bytecode pc stack sp =
(* debug stack pc sp; *)
let instr = bytecode.(pc) in
if instr = 0
then (
(* Add *)
let v2 = stack.(sp) in
let v1 = stack.(sp - 1) in
stack.(sp - 1) <- v1 + v2;
interp bytecode (pc + 1) stack (sp - 1))
else if instr = 1
then (
(* Sub *)
let v2 = stack.(sp) in
let v1 = stack.(sp - 1) in
stack.(sp - 1) <- v1 - v2;
interp bytecode (pc + 1) stack (sp - 1)
else if instr = 3 then ( * LT
- 1) in stack.(sp - 1) <- (if v1 < v2 then 1 else 0); interp bytecode (pc
+ 1) stack (sp - 1) *))
else if instr = 4
then (
CONST
let n = bytecode.(pc + 1) in
stack.(sp - 1) <- n;
interp bytecode (pc + 2) stack sp)
else if instr = 10
then (
(* CALL *)
let addr = bytecode.(pc + 1) in
stack.(sp + 1) <- pc + 2;
interp bytecode addr stack (sp + 1))
else if instr = 11
then (
RET
let n = bytecode.(pc + 1) in
let v = stack.(sp) in
let raddr = stack.(sp - 1) in
stack.(sp - n - 1) <- v;
interp bytecode raddr stack (sp - n - 1))
else if instr = 12
then (
(* JUMP_IF_ZERO *)
let addr = bytecode.(pc + 1) in
let v = stack.(sp) in
if v = 0
then interp bytecode addr stack (sp - 1)
else interp bytecode (pc + 2) stack (sp - 1))
else if instr = 20
then (
(* POP1 *)
let v = stack.(sp) in
let _ = stack.(sp - 1) in
stack.(sp - 1) <- v;
interp bytecode (pc + 1) stack (sp - 1))
else if instr = 21
then (
(* PUSH *)
let n = bytecode.(pc + 1) in
stack.(sp + 1) <- n;
interp bytecode (pc + 2) stack (sp + 1))
else if instr = 22
then (
DUP
let n = bytecode.(pc + 1) in
let v = stack.(sp - n) in
stack.(sp + 1) <- v;
interp bytecode (pc + 2) stack (sp + 1))
else if instr = 30
then (* HALT *)
stack.(sp)
else -1
in
let code = Array.make 10 0 in let stack = Array.make 10 0 in code.(0 ) < - 21 ;
code.(1 ) < - 2 ; code.(2 ) < - 21 ; code.(3 ) < - 3 ; code.(4 ) < - 22 ; code.(5 ) < - 1 ;
code.(6 ) < - 0 ; code.(7 ) < - 30 ; print_int ( interp code 0 stack 0 ) ; ( * return 5
code.(1) <- 2; code.(2) <- 21; code.(3) <- 3; code.(4) <- 22; code.(5) <- 1;
code.(6) <- 0; code.(7) <- 30; print_int (interp code 0 stack 0); (* return 5
*) print_newline (); *)
RET
let = Array.make 20 ( -1 ) in let = Array.make 20 ( -1 ) in
stack2.(0 ) < - 4 ; stack2.(1 ) < - 5 ; stack2.(2 ) < - 2 ; stack2.(3 ) < - 6 ; code2.(0 )
< - 11 ; code2.(1 ) < - 1 ; ) < - 0 ; code2.(3 ) < - 30 ; print_int ( interp
code2 0 stack2 3 ) ; ( * return 10
stack2.(0) <- 4; stack2.(1) <- 5; stack2.(2) <- 2; stack2.(3) <- 6; code2.(0)
<- 11; code2.(1) <- 1; code2.(2) <- 0; code2.(3) <- 30; print_int (interp
code2 0 stack2 3); (* return 10 *) print_newline (); *)
CALL and RET
let code3 = Array.make 100 (-1) in
let stack3 = Array.make 100 (-1) in
stack3.(0) <- 4;
stack3.(1) <- 5;
code3.(0) <- 22;
code3.(1) <- 2;
code3.(2) <- 22;
code3.(3) <- 2;
code3.(4) <- 0;
code3.(5) <- 11;
code3.(6) <- 2;
code3.(7) <- 10;
code3.(8) <- 0;
code3.(9) <- 30;
print_int (interp code3 7 stack3 1);
return 9
LT true
let = Array.make 100 ( -1 ) in let stack4 = Array.make 20 ( -1 ) in
stack4.(0 ) < - 2 ; stack4.(1 ) < - 3 ; code4.(0 ) < - 3 ; code4.(1 ) < - 30 ; print_int
( 0 stack4 1 ) ( * return 1
stack4.(0) <- 2; stack4.(1) <- 3; code4.(0) <- 3; code4.(1) <- 30; print_int
(interp code4 0 stack4 1) (* return 1*); print_newline ();
LT false
(-1) in stack5.(0) <- 3; stack5.(1) <- 2; code5.(0) <- 3; code5.(1) <- 30;
print_int (interp code5 0 stack5 1) (* return 0 *) *)
| null | https://raw.githubusercontent.com/prg-titech/baccaml/a3b95e996a995b5004ca897a4b6419edfee590aa/etc/mtj-call.ml | ocaml | debug stack pc sp;
Add
Sub
CALL
JUMP_IF_ZERO
POP1
PUSH
HALT
return 5
return 10
return 1
return 0 | let print_array arr = print_string " [ " ; ( fun a - > print_int a ;
print_string " ; " ) ; print_string " ] " in
let debug stack pc sp = print_array stack ; print_newline ( ) ; print_string
" pc : " ; print_int pc ; print_newline ( ) ; print_string " sp : " ; print_int sp ;
print_newline ( ) ; in
print_string "; ") arr; print_string "]" in
let debug stack pc sp = print_array stack; print_newline (); print_string
"pc: "; print_int pc; print_newline (); print_string "sp: "; print_int sp;
print_newline (); in *)
;;
let rec interp bytecode pc stack sp =
let instr = bytecode.(pc) in
if instr = 0
then (
let v2 = stack.(sp) in
let v1 = stack.(sp - 1) in
stack.(sp - 1) <- v1 + v2;
interp bytecode (pc + 1) stack (sp - 1))
else if instr = 1
then (
let v2 = stack.(sp) in
let v1 = stack.(sp - 1) in
stack.(sp - 1) <- v1 - v2;
interp bytecode (pc + 1) stack (sp - 1)
else if instr = 3 then ( * LT
- 1) in stack.(sp - 1) <- (if v1 < v2 then 1 else 0); interp bytecode (pc
+ 1) stack (sp - 1) *))
else if instr = 4
then (
CONST
let n = bytecode.(pc + 1) in
stack.(sp - 1) <- n;
interp bytecode (pc + 2) stack sp)
else if instr = 10
then (
let addr = bytecode.(pc + 1) in
stack.(sp + 1) <- pc + 2;
interp bytecode addr stack (sp + 1))
else if instr = 11
then (
RET
let n = bytecode.(pc + 1) in
let v = stack.(sp) in
let raddr = stack.(sp - 1) in
stack.(sp - n - 1) <- v;
interp bytecode raddr stack (sp - n - 1))
else if instr = 12
then (
let addr = bytecode.(pc + 1) in
let v = stack.(sp) in
if v = 0
then interp bytecode addr stack (sp - 1)
else interp bytecode (pc + 2) stack (sp - 1))
else if instr = 20
then (
let v = stack.(sp) in
let _ = stack.(sp - 1) in
stack.(sp - 1) <- v;
interp bytecode (pc + 1) stack (sp - 1))
else if instr = 21
then (
let n = bytecode.(pc + 1) in
stack.(sp + 1) <- n;
interp bytecode (pc + 2) stack (sp + 1))
else if instr = 22
then (
DUP
let n = bytecode.(pc + 1) in
let v = stack.(sp - n) in
stack.(sp + 1) <- v;
interp bytecode (pc + 2) stack (sp + 1))
else if instr = 30
stack.(sp)
else -1
in
let code = Array.make 10 0 in let stack = Array.make 10 0 in code.(0 ) < - 21 ;
code.(1 ) < - 2 ; code.(2 ) < - 21 ; code.(3 ) < - 3 ; code.(4 ) < - 22 ; code.(5 ) < - 1 ;
code.(6 ) < - 0 ; code.(7 ) < - 30 ; print_int ( interp code 0 stack 0 ) ; ( * return 5
code.(1) <- 2; code.(2) <- 21; code.(3) <- 3; code.(4) <- 22; code.(5) <- 1;
RET
let = Array.make 20 ( -1 ) in let = Array.make 20 ( -1 ) in
stack2.(0 ) < - 4 ; stack2.(1 ) < - 5 ; stack2.(2 ) < - 2 ; stack2.(3 ) < - 6 ; code2.(0 )
< - 11 ; code2.(1 ) < - 1 ; ) < - 0 ; code2.(3 ) < - 30 ; print_int ( interp
code2 0 stack2 3 ) ; ( * return 10
stack2.(0) <- 4; stack2.(1) <- 5; stack2.(2) <- 2; stack2.(3) <- 6; code2.(0)
<- 11; code2.(1) <- 1; code2.(2) <- 0; code2.(3) <- 30; print_int (interp
CALL and RET
let code3 = Array.make 100 (-1) in
let stack3 = Array.make 100 (-1) in
stack3.(0) <- 4;
stack3.(1) <- 5;
code3.(0) <- 22;
code3.(1) <- 2;
code3.(2) <- 22;
code3.(3) <- 2;
code3.(4) <- 0;
code3.(5) <- 11;
code3.(6) <- 2;
code3.(7) <- 10;
code3.(8) <- 0;
code3.(9) <- 30;
print_int (interp code3 7 stack3 1);
return 9
LT true
let = Array.make 100 ( -1 ) in let stack4 = Array.make 20 ( -1 ) in
stack4.(0 ) < - 2 ; stack4.(1 ) < - 3 ; code4.(0 ) < - 3 ; code4.(1 ) < - 30 ; print_int
( 0 stack4 1 ) ( * return 1
stack4.(0) <- 2; stack4.(1) <- 3; code4.(0) <- 3; code4.(1) <- 30; print_int
LT false
(-1) in stack5.(0) <- 3; stack5.(1) <- 2; code5.(0) <- 3; code5.(1) <- 30;
|
c3bcd1a4a5992130a693ee57e2ab608c4eabaa20d62defb0abf2efc6198dce4f | earl-ducaine/cl-garnet | motif-scrolling-window.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*-
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
The Garnet User Interface Development Environment . ; ;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;; This code was written as part of the Garnet project at ;;
Carnegie Mellon University , and has been placed in the public ; ;
domain . If you are using this code or any part of Garnet , ; ;
;; please contact to be put on the mailing list. ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
$ Id$
;;; Motif-Scrolling-Window-With-Bars
contains two optional scroll bars
;;
;; Customizable slots
;; :left, :top, :width, :height, Default=0,0,150,150 - left, top,
;; width and height of outer window (size of visible
;; portion smaller by :min-scroll-bar-width)
;; :position-by-hand, default=NIL - if T, the user is asked for the outer
;; window's position.
;; :border-width, default=2 - of outer window
;; :parent-window, default=NIL - window this scrolling-window is
inside of , or NIL
;; :double-buffered-p, default=NIL
;; :title, default="Motif Scrolling Window"
;; :icon-title, default=(same as title)
;; :total-width, default=200 - total size of the scrollable area inside
;; :total-height, default=200)
;; :X-Offset, default=0 - offset in the scrollable area; DO NOT SET
;; THESE OR PUT FORMULAS IN THEM, use the exported functions
;; :Y-Offset, default=0
;; :visible, default=T - whether the entire window is visible (mapped)
;;
;; :h-scroll-bar-p, default=T - Is there a horizontal scroll bar?
;; :v-scroll-bar-p, default=T - Is there a vertical scroll bar?
: Foreground - Color ( default = Motif - gray ) - the color of the
;; scrollbars and the background of the window
;;
Scroll Bar slots
;; :h-scroll-on-top-p, default=NIL - whether horiz bar is on top or bottom
;; :v-scroll-on-left-p, default=T - whether vert bar is on left or right
;; :h-scr-incr, default=10 - in pixels
: h - page - incr - default jumps one page
;; :v-scr-incr, default=10 - in pixels
: v - page - incr - default jumps one page
;;
;; Read-Only slots
;; :Inner-Window - these are created by the update method
;; :inner-aggregate - add your objects to this aggregate (but have to
update first )
;; :outer-window - call Opal:Update on this window (or on gadget itself)
;; :clip-window
;;
;; NOTE: Create the window, then call Update on it. Do not add it
;; to an aggregate or a window. If you want the scrolling window in
;; another window, specify the :parent-window slot instead:
;; (create-instance NIL garnet-gadgets:scrolling-window(-with-bars)
;; (...)(:parent-window other-window) )
;;
Designed and written by
Based on an idea from at the University of Leeds
;;
;; *** KNOWN BUG *** When the user changes the size or position of the outer
;; window with the window manager, the fields of the scrolling
;; window gadget are not updated. Circular constraints won't work
;; because the user will usually override the values for the slots
;; when the window is created. I think the fix will have to wait
;; for eager evaluation --BAM
;;; Change log:
12/13/93 - Added : omit - title - bar - p and made : parent
;; reference a formula
7/26/93 # + garnet - debug around demo functions
12/15/92 - Added type and parameter declarations
10/02/91 Meltsner - Checked if there was zero width or height
;; inner window in formula for :percent-visible
3/14/91 - created
(in-package "GARNET-GADGETS")
(eval-when (:execute :load-toplevel :compile-toplevel)
(export '(Motif-Scrolling-Window-With-Bars
Motif-Scrolling-Window-With-Bars-Go
Motif-Scrolling-Window-With-Bars-Stop)))
* * Scrolling - window - parts must be loaded first * *
;; Must return the outer-window
(defun Motif-Scrolling-Window-With-Bars-Creator (window-gadget)
(let* ((outer-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :left)))
(:top (o-formula (gvl :scroll-win-gadget :top)))
(:position-by-hand (o-formula (gvl :scroll-win-gadget
:position-by-hand)))
(:width (o-formula (gvl :scroll-win-gadget :width)))
(:height (o-formula (gvl :scroll-win-gadget :height)))
(:title (o-formula (gvl :scroll-win-gadget :title)))
(:icon-title (o-formula (gvl :scroll-win-gadget :icon-title)))
(:visible (o-formula (gvl :scroll-win-gadget :visible)))
(:border-width (o-formula (gvl :scroll-win-gadget
:border-width)))
(:parent (o-formula (gvl :scroll-win-gadget :parent-window)))
(:omit-title-bar-p (g-value window-gadget :omit-title-bar-p))
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(outer-agg (create-instance NIL opal:aggregate))
(clip-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :clip-win-left)))
(:top (o-formula (gvl :scroll-win-gadget :clip-win-top)))
(:width (o-formula (gvl :scroll-win-gadget :inner-width)))
(:height (o-formula (gvl :scroll-win-gadget :inner-height)))
(:border-width 0)
(:parent outer-window)
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(clip-agg (create-instance NIL opal:aggregate))
(inner-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :X-Offset)))
(:top (o-formula (gvl :scroll-win-gadget :Y-Offset)))
(:width (o-formula
(let ((w (or (gvl :scroll-win-gadget :total-width)
0))
(innerw (gvl :scroll-win-gadget
:clip-window :width)))
(max min-win-size w innerw))))
(:height (o-formula
(let ((h (or (gvl :scroll-win-gadget :total-height)
0))
(innerh (gvl :scroll-win-gadget
:clip-window :height)))
(max h innerh min-win-size))))
(:border-width 0) ; no border
(:double-buffered-p
(o-formula (gvl :scroll-win-gadget :double-buffered-p)))
(:parent clip-window)
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(inner-agg2 (create-instance NIL opal:aggregate))
(inner-agg (create-instance NIL opal:aggregate)))
(s-value outer-window :aggregate outer-agg)
(s-value clip-window :aggregate clip-agg) ; is an aggregate needed?
(s-value inner-window :aggregate inner-agg2)
(opal:add-component inner-agg2 inner-agg)
(s-value window-gadget :inner-window inner-window)
(s-value window-gadget :clip-window clip-window)
(s-value window-gadget :outer-window outer-window)
(s-value window-gadget :inner-aggregate inner-agg)
(opal:add-component outer-agg window-gadget)
outer-window
))
(create-instance 'Motif-Scrolling-Window-With-Bars opal:aggregadget
:declare ((:parameters :left :top :width :height :position-by-hand
:border-width :parent-window :double-buffered-p
:title :icon-title :total-width :total-height
:x-offset :y-offset :h-scroll-bar-p :v-scroll-bar-p
:h-scroll-on-left-p :v-scroll-on-top-p
:min-scroll-bar-width :scr-trill-p :page-trill-p
:h-scr-incr :h-page-incr :v-scr-incr :v-page-incr
:int-feedback-p :indicator-text-p :indicator-font
:foreground-color :visible)
(:type (kr-boolean :position-by-hand :double-buffered-p
:h-scroll-bar-p :v-scroll-bar-p :h-scroll-on-left-p
:v-scroll-on-top-p :scr-trill-p :page-trill-p
:int-feedback-p :indicator-text-p)
((integer 0) :border-width :total-width :total-height
:min-scroll-bar-width)
(integer :x-offset :y-offset :h-scr-incr :h-page-incr
:v-scr-incr :v-page-incr)
((or (is-a-p inter:interactor-window) null) :parent-window)
((or null string) :title :icon-title)
((or (is-a-p opal:font) (is-a-p opal:font-from-file))
:indicator-font)
((is-a-p opal:color) :foreground-color))
(:maybe-constant :left :top :width :height :border-width
:title :total-width :total-height :foreground-color
:h-scroll-bar-p :v-scroll-bar-p :visible
:h-scroll-on-top-p :v-scroll-on-left-p
:h-scr-incr :h-page-incr :v-scr-incr :v-page-incr
:icon-title :parent-window))
; Customizable slots
(:left 0) (:top 0)
(:position-by-hand NIL)
(:width 150)(:height 150) ; INNER width and height of outermost window
(:border-width 2)
(:parent-window NIL)
(:double-buffered-p NIL)
(:title "Motif Scrolling Window")
(:icon-title (o-formula (gvl :title)))
(:total-width 200) ; of the full area that graphics will be in
(:total-height 200) ; of the full area that graphics will be in
(:X-Offset 0) ; can be set explicitly, and is set by scroll bars
(:Y-Offset 0) ; can be set explicitly, and is set by scroll bars
(:h-scroll-bar-p T) ; Is there a horizontal scroll bar?
(:v-scroll-bar-p T) ; Is there a vertical scroll bar?
(:visible T)
(:foreground-color Opal:Motif-gray)
;scroll bar slots
(:h-scroll-on-top-p NIL) ; whether scroll bar is on left or right
(:v-scroll-on-left-p T) ; whether scroll bar is on top or bottom
(:h-scr-incr 10) ; in pixels
(:h-page-incr (o-formula (- (gvl :outer-window :width) 10)))
(:v-scr-incr 10) ; in pixels
(:v-page-incr (o-formula (- (gvl :outer-window :height) 10)))
; read-only slots
(:Inner-Window NIL) ; these are created by the update method
(:inner-aggregate NIL) ; add your objects to this aggregate
(:outer-window NIL) ; call Opal:Update on this window (or on gadget itself)
(:clip-window NIL)
; internal slots
make the next two depend on the outer window in
; case it is changed by the user using the window manager.
(:outer-win-inner-height (o-formula (gvl :outer-window :height) 50))
(:outer-win-inner-width (o-formula (gvl :outer-window :width) 50))
(:inner-width (o-formula (- (gvl :outer-win-inner-width)
(if (gvl :v-scroll-bar-p)
(gvl :v-scroll :width)
0))))
(:inner-height (o-formula (- (gvl :outer-win-inner-height)
(if (gvl :h-scroll-bar-p)
(gvl :h-scroll :height)
0))))
(:clip-win-left (o-formula (if (and (gvl :v-scroll-bar-p)
(gvl :v-scroll-on-left-p))
(gvl :v-scroll :width)
0)))
(:clip-win-top (o-formula (if (and (gvl :h-scroll-bar-p)
(gvl :h-scroll-on-top-p))
(gvl :h-scroll :height)
0)))
(:destroy-me 'Scrolling-Window-With-Bars-Destroy)
(:update 'Scrolling-Window-Update)
(:creator-func 'Motif-Scrolling-Window-With-Bars-Creator)
(:parts
`((:v-scroll ,garnet-gadgets:motif-v-scroll-bar
(:left ,(o-formula (if (gvl :parent :v-scroll-on-left-p)
0
; else at right
(- (gvl :parent :outer-win-inner-width)
(gvl :width)
-1))))
(:top ,(o-formula (if (and (gvl :parent :h-scroll-bar-p)
(gvl :parent :h-scroll-on-top-p))
(gvl :parent :h-scroll :height)
0)))
(:val-1 0)
(:height ,(o-formula (gvl :parent :inner-height)))
(:val-2 ,(o-formula (Max 1 (- (gvl :parent :total-height)
(gvl :parent :inner-height))) 0))
(:scr-incr ,(o-formula (gvl :parent :v-scr-incr)))
(:page-incr ,(o-formula (gvl :parent :v-page-incr)))
(:active-p ,(o-formula
(and (gvl :window)
(or (/= 0 (gvl :parent :y-offset))
(>= (gvl :parent :total-height)
(gvl :parent :inner-height))))))
(:visible ,(o-formula (gvl :parent :v-scroll-bar-p)))
(:foreground-color ,(o-formula (gvl :parent :foreground-color)))
(:percent-visible ,(o-formula
(if (zerop (gvl :parent :total-height))
1
(min (/ (gvl :parent :inner-height)
(gvl :parent :total-height))
1))))
(:selection-function
,#'(lambda (gadget new-val)
(s-value (g-value gadget :parent) :y-offset
(- new-val)))))
(:h-scroll ,garnet-gadgets:motif-h-scroll-bar
(:left ,(o-formula (if (and (gvl :parent :v-scroll-bar-p)
(gvl :parent :v-scroll-on-left-p))
(gvl :parent :v-scroll :width)
0)))
(:val-1 0)
(:top ,(o-formula (if (gvl :parent :h-scroll-on-top-p)
0
(- (gvl :parent :outer-win-inner-height)
(gvl :height)
-1))))
(:width ,(o-formula (gvl :parent :inner-width)))
(:val-2 ,(o-formula (Max 1 (- (gvl :parent :total-width)
(gvl :parent :inner-width))) 0))
(:scr-incr ,(o-formula (gvl :parent :h-scr-incr)))
(:page-incr ,(o-formula (gvl :parent :h-page-incr)))
(:active-p ,(o-formula
(and (gvl :window)
(or (/= 0 (gvl :parent :x-offset))
(>= (gvl :parent :total-width)
(gvl :parent :inner-width))))))
(:visible ,(o-formula (gvl :parent :h-scroll-bar-p)))
(:foreground-color ,(o-formula (gvl :parent :foreground-color)))
(:percent-visible ,(o-formula
(if (zerop (gvl :parent :inner-width))
1
(min (/ (gvl :parent :inner-width)
(gvl :parent :total-width))
1))))
(:selection-function
,#'(lambda (gadget new-val)
(s-value (g-value gadget :parent) :x-offset
(- new-val))))))))
;;; Demo programs
;;
#+garnet-test
(defparameter Motif-Scrolling-Window-With-Bars-Obj NIL)
#+garnet-test
(defun Motif-Scrolling-Window-With-Bars-Go (&key dont-enter-main-event-loop
double-buffered-p)
(setq Motif-Scrolling-Window-With-Bars-Obj
(Internal-Scrolling-Window-Go Motif-Scrolling-Window-With-Bars
dont-enter-main-event-loop
double-buffered-p)))
#+garnet-test
(defun Motif-Scrolling-Window-With-Bars-Stop ()
(opal:destroy Motif-Scrolling-Window-With-Bars-Obj))
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/gadgets/motif-scrolling-window.lisp | lisp | Syntax : Common - Lisp ; Package : GARNET - GADGETS ; Base : 10 -*-
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
This code was written as part of the Garnet project at ;;
;
;
please contact to be put on the mailing list. ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
Motif-Scrolling-Window-With-Bars
Customizable slots
:left, :top, :width, :height, Default=0,0,150,150 - left, top,
width and height of outer window (size of visible
portion smaller by :min-scroll-bar-width)
:position-by-hand, default=NIL - if T, the user is asked for the outer
window's position.
:border-width, default=2 - of outer window
:parent-window, default=NIL - window this scrolling-window is
:double-buffered-p, default=NIL
:title, default="Motif Scrolling Window"
:icon-title, default=(same as title)
:total-width, default=200 - total size of the scrollable area inside
:total-height, default=200)
:X-Offset, default=0 - offset in the scrollable area; DO NOT SET
THESE OR PUT FORMULAS IN THEM, use the exported functions
:Y-Offset, default=0
:visible, default=T - whether the entire window is visible (mapped)
:h-scroll-bar-p, default=T - Is there a horizontal scroll bar?
:v-scroll-bar-p, default=T - Is there a vertical scroll bar?
scrollbars and the background of the window
:h-scroll-on-top-p, default=NIL - whether horiz bar is on top or bottom
:v-scroll-on-left-p, default=T - whether vert bar is on left or right
:h-scr-incr, default=10 - in pixels
:v-scr-incr, default=10 - in pixels
Read-Only slots
:Inner-Window - these are created by the update method
:inner-aggregate - add your objects to this aggregate (but have to
:outer-window - call Opal:Update on this window (or on gadget itself)
:clip-window
NOTE: Create the window, then call Update on it. Do not add it
to an aggregate or a window. If you want the scrolling window in
another window, specify the :parent-window slot instead:
(create-instance NIL garnet-gadgets:scrolling-window(-with-bars)
(...)(:parent-window other-window) )
*** KNOWN BUG *** When the user changes the size or position of the outer
window with the window manager, the fields of the scrolling
window gadget are not updated. Circular constraints won't work
because the user will usually override the values for the slots
when the window is created. I think the fix will have to wait
for eager evaluation --BAM
Change log:
reference a formula
inner window in formula for :percent-visible
Must return the outer-window
no border
is an aggregate needed?
Customizable slots
INNER width and height of outermost window
of the full area that graphics will be in
of the full area that graphics will be in
can be set explicitly, and is set by scroll bars
can be set explicitly, and is set by scroll bars
Is there a horizontal scroll bar?
Is there a vertical scroll bar?
scroll bar slots
whether scroll bar is on left or right
whether scroll bar is on top or bottom
in pixels
in pixels
read-only slots
these are created by the update method
add your objects to this aggregate
call Opal:Update on this window (or on gadget itself)
internal slots
case it is changed by the user using the window manager.
else at right
Demo programs
|
$ Id$
contains two optional scroll bars
inside of , or NIL
: Foreground - Color ( default = Motif - gray ) - the color of the
Scroll Bar slots
: h - page - incr - default jumps one page
: v - page - incr - default jumps one page
update first )
Designed and written by
Based on an idea from at the University of Leeds
12/13/93 - Added : omit - title - bar - p and made : parent
7/26/93 # + garnet - debug around demo functions
12/15/92 - Added type and parameter declarations
10/02/91 Meltsner - Checked if there was zero width or height
3/14/91 - created
(in-package "GARNET-GADGETS")
(eval-when (:execute :load-toplevel :compile-toplevel)
(export '(Motif-Scrolling-Window-With-Bars
Motif-Scrolling-Window-With-Bars-Go
Motif-Scrolling-Window-With-Bars-Stop)))
* * Scrolling - window - parts must be loaded first * *
(defun Motif-Scrolling-Window-With-Bars-Creator (window-gadget)
(let* ((outer-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :left)))
(:top (o-formula (gvl :scroll-win-gadget :top)))
(:position-by-hand (o-formula (gvl :scroll-win-gadget
:position-by-hand)))
(:width (o-formula (gvl :scroll-win-gadget :width)))
(:height (o-formula (gvl :scroll-win-gadget :height)))
(:title (o-formula (gvl :scroll-win-gadget :title)))
(:icon-title (o-formula (gvl :scroll-win-gadget :icon-title)))
(:visible (o-formula (gvl :scroll-win-gadget :visible)))
(:border-width (o-formula (gvl :scroll-win-gadget
:border-width)))
(:parent (o-formula (gvl :scroll-win-gadget :parent-window)))
(:omit-title-bar-p (g-value window-gadget :omit-title-bar-p))
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(outer-agg (create-instance NIL opal:aggregate))
(clip-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :clip-win-left)))
(:top (o-formula (gvl :scroll-win-gadget :clip-win-top)))
(:width (o-formula (gvl :scroll-win-gadget :inner-width)))
(:height (o-formula (gvl :scroll-win-gadget :inner-height)))
(:border-width 0)
(:parent outer-window)
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(clip-agg (create-instance NIL opal:aggregate))
(inner-window (create-instance NIL inter:interactor-window
(:scroll-win-gadget window-gadget)
(:left (o-formula (gvl :scroll-win-gadget :X-Offset)))
(:top (o-formula (gvl :scroll-win-gadget :Y-Offset)))
(:width (o-formula
(let ((w (or (gvl :scroll-win-gadget :total-width)
0))
(innerw (gvl :scroll-win-gadget
:clip-window :width)))
(max min-win-size w innerw))))
(:height (o-formula
(let ((h (or (gvl :scroll-win-gadget :total-height)
0))
(innerh (gvl :scroll-win-gadget
:clip-window :height)))
(max h innerh min-win-size))))
(:double-buffered-p
(o-formula (gvl :scroll-win-gadget :double-buffered-p)))
(:parent clip-window)
(:background-color (o-formula (gvl :scroll-win-gadget
:foreground-color)))))
(inner-agg2 (create-instance NIL opal:aggregate))
(inner-agg (create-instance NIL opal:aggregate)))
(s-value outer-window :aggregate outer-agg)
(s-value inner-window :aggregate inner-agg2)
(opal:add-component inner-agg2 inner-agg)
(s-value window-gadget :inner-window inner-window)
(s-value window-gadget :clip-window clip-window)
(s-value window-gadget :outer-window outer-window)
(s-value window-gadget :inner-aggregate inner-agg)
(opal:add-component outer-agg window-gadget)
outer-window
))
(create-instance 'Motif-Scrolling-Window-With-Bars opal:aggregadget
:declare ((:parameters :left :top :width :height :position-by-hand
:border-width :parent-window :double-buffered-p
:title :icon-title :total-width :total-height
:x-offset :y-offset :h-scroll-bar-p :v-scroll-bar-p
:h-scroll-on-left-p :v-scroll-on-top-p
:min-scroll-bar-width :scr-trill-p :page-trill-p
:h-scr-incr :h-page-incr :v-scr-incr :v-page-incr
:int-feedback-p :indicator-text-p :indicator-font
:foreground-color :visible)
(:type (kr-boolean :position-by-hand :double-buffered-p
:h-scroll-bar-p :v-scroll-bar-p :h-scroll-on-left-p
:v-scroll-on-top-p :scr-trill-p :page-trill-p
:int-feedback-p :indicator-text-p)
((integer 0) :border-width :total-width :total-height
:min-scroll-bar-width)
(integer :x-offset :y-offset :h-scr-incr :h-page-incr
:v-scr-incr :v-page-incr)
((or (is-a-p inter:interactor-window) null) :parent-window)
((or null string) :title :icon-title)
((or (is-a-p opal:font) (is-a-p opal:font-from-file))
:indicator-font)
((is-a-p opal:color) :foreground-color))
(:maybe-constant :left :top :width :height :border-width
:title :total-width :total-height :foreground-color
:h-scroll-bar-p :v-scroll-bar-p :visible
:h-scroll-on-top-p :v-scroll-on-left-p
:h-scr-incr :h-page-incr :v-scr-incr :v-page-incr
:icon-title :parent-window))
(:left 0) (:top 0)
(:position-by-hand NIL)
(:border-width 2)
(:parent-window NIL)
(:double-buffered-p NIL)
(:title "Motif Scrolling Window")
(:icon-title (o-formula (gvl :title)))
(:visible T)
(:foreground-color Opal:Motif-gray)
(:h-page-incr (o-formula (- (gvl :outer-window :width) 10)))
(:v-page-incr (o-formula (- (gvl :outer-window :height) 10)))
(:clip-window NIL)
make the next two depend on the outer window in
(:outer-win-inner-height (o-formula (gvl :outer-window :height) 50))
(:outer-win-inner-width (o-formula (gvl :outer-window :width) 50))
(:inner-width (o-formula (- (gvl :outer-win-inner-width)
(if (gvl :v-scroll-bar-p)
(gvl :v-scroll :width)
0))))
(:inner-height (o-formula (- (gvl :outer-win-inner-height)
(if (gvl :h-scroll-bar-p)
(gvl :h-scroll :height)
0))))
(:clip-win-left (o-formula (if (and (gvl :v-scroll-bar-p)
(gvl :v-scroll-on-left-p))
(gvl :v-scroll :width)
0)))
(:clip-win-top (o-formula (if (and (gvl :h-scroll-bar-p)
(gvl :h-scroll-on-top-p))
(gvl :h-scroll :height)
0)))
(:destroy-me 'Scrolling-Window-With-Bars-Destroy)
(:update 'Scrolling-Window-Update)
(:creator-func 'Motif-Scrolling-Window-With-Bars-Creator)
(:parts
`((:v-scroll ,garnet-gadgets:motif-v-scroll-bar
(:left ,(o-formula (if (gvl :parent :v-scroll-on-left-p)
0
(- (gvl :parent :outer-win-inner-width)
(gvl :width)
-1))))
(:top ,(o-formula (if (and (gvl :parent :h-scroll-bar-p)
(gvl :parent :h-scroll-on-top-p))
(gvl :parent :h-scroll :height)
0)))
(:val-1 0)
(:height ,(o-formula (gvl :parent :inner-height)))
(:val-2 ,(o-formula (Max 1 (- (gvl :parent :total-height)
(gvl :parent :inner-height))) 0))
(:scr-incr ,(o-formula (gvl :parent :v-scr-incr)))
(:page-incr ,(o-formula (gvl :parent :v-page-incr)))
(:active-p ,(o-formula
(and (gvl :window)
(or (/= 0 (gvl :parent :y-offset))
(>= (gvl :parent :total-height)
(gvl :parent :inner-height))))))
(:visible ,(o-formula (gvl :parent :v-scroll-bar-p)))
(:foreground-color ,(o-formula (gvl :parent :foreground-color)))
(:percent-visible ,(o-formula
(if (zerop (gvl :parent :total-height))
1
(min (/ (gvl :parent :inner-height)
(gvl :parent :total-height))
1))))
(:selection-function
,#'(lambda (gadget new-val)
(s-value (g-value gadget :parent) :y-offset
(- new-val)))))
(:h-scroll ,garnet-gadgets:motif-h-scroll-bar
(:left ,(o-formula (if (and (gvl :parent :v-scroll-bar-p)
(gvl :parent :v-scroll-on-left-p))
(gvl :parent :v-scroll :width)
0)))
(:val-1 0)
(:top ,(o-formula (if (gvl :parent :h-scroll-on-top-p)
0
(- (gvl :parent :outer-win-inner-height)
(gvl :height)
-1))))
(:width ,(o-formula (gvl :parent :inner-width)))
(:val-2 ,(o-formula (Max 1 (- (gvl :parent :total-width)
(gvl :parent :inner-width))) 0))
(:scr-incr ,(o-formula (gvl :parent :h-scr-incr)))
(:page-incr ,(o-formula (gvl :parent :h-page-incr)))
(:active-p ,(o-formula
(and (gvl :window)
(or (/= 0 (gvl :parent :x-offset))
(>= (gvl :parent :total-width)
(gvl :parent :inner-width))))))
(:visible ,(o-formula (gvl :parent :h-scroll-bar-p)))
(:foreground-color ,(o-formula (gvl :parent :foreground-color)))
(:percent-visible ,(o-formula
(if (zerop (gvl :parent :inner-width))
1
(min (/ (gvl :parent :inner-width)
(gvl :parent :total-width))
1))))
(:selection-function
,#'(lambda (gadget new-val)
(s-value (g-value gadget :parent) :x-offset
(- new-val))))))))
#+garnet-test
(defparameter Motif-Scrolling-Window-With-Bars-Obj NIL)
#+garnet-test
(defun Motif-Scrolling-Window-With-Bars-Go (&key dont-enter-main-event-loop
double-buffered-p)
(setq Motif-Scrolling-Window-With-Bars-Obj
(Internal-Scrolling-Window-Go Motif-Scrolling-Window-With-Bars
dont-enter-main-event-loop
double-buffered-p)))
#+garnet-test
(defun Motif-Scrolling-Window-With-Bars-Stop ()
(opal:destroy Motif-Scrolling-Window-With-Bars-Obj))
|
f1c5d46d5191abf63c504899b8bdc0a0aa9fd02caef545bf9e473baddb9ebf86 | mfikes/fifth-postulate | ns361.cljs | (ns fifth-postulate.ns361)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns361.cljs | clojure | (ns fifth-postulate.ns361)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
|
|
71768bef7433ef4d7a97f37f5555d11a0a42b6abc45df555926369067fe00950 | facundoolano/clojure-gettext | core.clj | (ns gettext.core
(:require [carica.core :refer [config]]
[clojure.test :refer [function?]]))
; Load text source from project.clj
(if (config :gettext-source)
(require [(symbol (namespace (config :gettext-source)))]))
(def ^:dynamic *text-source* (eval (config :gettext-source)))
(defn gettext
"Look up the given key in the current text source dictionary.
If not found return the key itself."
[text-key & replacements]
(let [text-value (get *text-source* text-key text-key)
text-value (if (function? text-value) (text-value nil) text-value)]
(apply format text-value replacements)))
(defn pgettext
[ctx text-key & replacements]
(let [text-value (get *text-source* text-key text-key)
text-value (if (function? text-value) (text-value ctx) text-value)]
(apply format text-value replacements)))
; handy aliases
(def _ gettext)
(def p_ pgettext)
| null | https://raw.githubusercontent.com/facundoolano/clojure-gettext/56356a71b1e4765d4f72c2ac74b3316a59cf99a1/src/gettext/core.clj | clojure | Load text source from project.clj
handy aliases | (ns gettext.core
(:require [carica.core :refer [config]]
[clojure.test :refer [function?]]))
(if (config :gettext-source)
(require [(symbol (namespace (config :gettext-source)))]))
(def ^:dynamic *text-source* (eval (config :gettext-source)))
(defn gettext
"Look up the given key in the current text source dictionary.
If not found return the key itself."
[text-key & replacements]
(let [text-value (get *text-source* text-key text-key)
text-value (if (function? text-value) (text-value nil) text-value)]
(apply format text-value replacements)))
(defn pgettext
[ctx text-key & replacements]
(let [text-value (get *text-source* text-key text-key)
text-value (if (function? text-value) (text-value ctx) text-value)]
(apply format text-value replacements)))
(def _ gettext)
(def p_ pgettext)
|
97e4c1b8f61f2fd81475fd36667fcfba8913baf75c64fbb210adb469113b3da1 | bazqux/bazqux-urweb | QueryParser.hs | module Lib.QueryParser where
import Lib.ElasticSearch
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Aeson as JSON
-- data Primitive = Term T.Text | Phrase T.Text | Range T.Text T.Text
-- data Syntax t = T t | And [Syntax t] | Or [Syntax t] | Not (Syntax t)
data QueryBase = Primitive Primitive | Field T.Text ( Syntax Primitive )
-- data Query = Syntax QueryBase
data Q
= Term T.Text
| Phrase T.Text
| Range T.Text T.Text
ошибка , если уже внутри Field
| And [Q]
| Or [Q]
| Not Q
test x = BL.putStrLn $ JSON.encode $ toEs "_all" x
toEs field q = case q of
Term t
| T.all (`elem` "*?") t ->
obj "match_all" $ obj' []
| Just _ <- T.find (`elem` "*?") t ->
obj "wildcard" $ obj stdField $ JSON.String t
| otherwise ->
wrap $ \ f ->
obj " match " $ obj f $ JSON.String t
obj "match" $ obj f $ obj'
[ ("query", JSON.String t)
, ("operator", JSON.String "AND") ]
поскольку analyzer
-- надо указывать AND
Phrase p ->
wrap $ \ f ->
obj "match_prase" $ obj f $ JSON.String p
Range a b ->
obj "range" $ obj field $ obj'
[ ("gte", JSON.String a)
, ("lte", JSON.String b) ]
Field f q
| field /= "_all" -> error "Field inside field?"
| otherwise -> toEs f q
And qs -> esMust $ map (toEs field) qs
Or qs -> esShould $ map (toEs field) qs
Not q -> esMustNot [toEs field q]
where wrap f
| stdField /= field =
esShould [f field, f stdField]
| otherwise =
f field
stdField
| field `elem` ["subject", "author", "tags", "text"] =
T.append "std_" field
| field == "_all" =
"std_all"
| otherwise = field
| null | https://raw.githubusercontent.com/bazqux/bazqux-urweb/bf2d5a65b5b286348c131e91b6e57df9e8045c3f/crawler/Lib/QueryParser.hs | haskell | data Primitive = Term T.Text | Phrase T.Text | Range T.Text T.Text
data Syntax t = T t | And [Syntax t] | Or [Syntax t] | Not (Syntax t)
data Query = Syntax QueryBase
надо указывать AND | module Lib.QueryParser where
import Lib.ElasticSearch
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Char8 as B
import qualified Data.Text as T
import qualified Data.Aeson as JSON
data QueryBase = Primitive Primitive | Field T.Text ( Syntax Primitive )
data Q
= Term T.Text
| Phrase T.Text
| Range T.Text T.Text
ошибка , если уже внутри Field
| And [Q]
| Or [Q]
| Not Q
test x = BL.putStrLn $ JSON.encode $ toEs "_all" x
toEs field q = case q of
Term t
| T.all (`elem` "*?") t ->
obj "match_all" $ obj' []
| Just _ <- T.find (`elem` "*?") t ->
obj "wildcard" $ obj stdField $ JSON.String t
| otherwise ->
wrap $ \ f ->
obj " match " $ obj f $ JSON.String t
obj "match" $ obj f $ obj'
[ ("query", JSON.String t)
, ("operator", JSON.String "AND") ]
поскольку analyzer
Phrase p ->
wrap $ \ f ->
obj "match_prase" $ obj f $ JSON.String p
Range a b ->
obj "range" $ obj field $ obj'
[ ("gte", JSON.String a)
, ("lte", JSON.String b) ]
Field f q
| field /= "_all" -> error "Field inside field?"
| otherwise -> toEs f q
And qs -> esMust $ map (toEs field) qs
Or qs -> esShould $ map (toEs field) qs
Not q -> esMustNot [toEs field q]
where wrap f
| stdField /= field =
esShould [f field, f stdField]
| otherwise =
f field
stdField
| field `elem` ["subject", "author", "tags", "text"] =
T.append "std_" field
| field == "_all" =
"std_all"
| otherwise = field
|
28bfd82a38db8052b05cf7a92df459d76c1072b863bf4e6e36494e9804f1c540 | mjambon/dune-deps | Disambiguate.ml |
Disambiguate path - like names .
Disambiguate path-like names.
*)
open Printf
(* This splits the string wherever there's a slash or a backslash.
It ignores leading and trailing slashes, which should be fine for our
application.
*)
let parse_path =
let re = Str.regexp "[/\\]+" in
fun s ->
Str.split re s
Ensure each path has at least one component .
Reverse it so that the file name comes first .
Ensure each path has at least one component.
Reverse it so that the file name comes first.
*)
let normalize_path s =
match parse_path s |> List.rev with
| [] -> [""]
| l -> l
let deduplicate l =
let tbl = Hashtbl.create 100 in
Compat.List.filter_map (fun x ->
if Hashtbl.mem tbl x then
None
else (
Hashtbl.add tbl x ();
Some x
)
) l
Algorithm :
Store all the paths in a table , each path keyed by the file name .
Any cluster of more than 1 is removed and its elements are re - added
using a longer key .
This is repeated until there are no more clusters of more than 1 .
Algorithm:
Store all the paths in a table, each path keyed by the file name.
Any cluster of more than 1 is removed and its elements are re-added
using a longer key.
This is repeated until there are no more clusters of more than 1.
*)
(*
This table stores clusters of paths, where the key is the name
that we want to be unique in the end.
*)
type clus = (string list, (string list * string list ) list) Hashtbl.t
(* name full path rest of the path *)
let add (clus : clus) k v =
let values =
try Hashtbl.find clus k
with Not_found -> []
in
Hashtbl.replace clus k (v :: values)
let make_clusters kv_list =
let clus = Hashtbl.create (2 * List.length kv_list) in
List.iter (fun (k, v) -> add clus k v) kv_list;
clus
let extend_name name (full_path, rest) =
match rest with
| [] ->
(* don't extend because we can't, for this particular path *)
(name, (full_path, rest))
| dir :: parents ->
(name @ [dir], (full_path, parents))
(* Separate unique names (singletons) from other clusters (others). *)
let remove_singletons (clus : clus) =
Hashtbl.fold (fun k vl (singletons, clusters) ->
match vl with
| [v] ->
((k, v) :: singletons), clusters
| vl ->
let additional_clusters = List.map (fun v -> extend_name k v) vl in
singletons, (additional_clusters @ clusters)
) clus ([], [])
let extend_paths full_paths =
let rec loop acc clusters =
match clusters with
| [] -> acc
| clusters ->
let clus = make_clusters clusters in
let singletons, clusters = remove_singletons clus in
loop (singletons @ acc) clusters
in
let init full_path =
match full_path with
| name :: parents -> ([name], (full_path, parents))
| [] -> ([], (full_path, []))
in
let clusters =
List.map init full_paths
in
loop [] clusters
let format_name = function
| [] -> ""
| [name] -> name
| name :: rev_path ->
sprintf "%s<%s>" name (String.concat "/" (List.rev rev_path))
let create paths =
let unique_paths =
List.map normalize_path paths
|> deduplicate
in
let res = extend_paths unique_paths in
let lookup_tbl = Hashtbl.create 100 in
List.iter (fun (name, (full_path, _discarded_path)) ->
Hashtbl.add lookup_tbl full_path name
) res;
let simplify s =
let path = normalize_path s in
match Compat.Hashtbl.find_opt lookup_tbl path with
| None -> None
| Some name -> Some (format_name name)
in
simplify
let map paths =
let simplify = create paths in
List.map (fun path ->
match simplify path with
| Some name -> name
| None -> assert false
) paths
| null | https://raw.githubusercontent.com/mjambon/dune-deps/48897a338bcbf91b57fccbed883497f050870b92/src/lib/Disambiguate.ml | ocaml | This splits the string wherever there's a slash or a backslash.
It ignores leading and trailing slashes, which should be fine for our
application.
This table stores clusters of paths, where the key is the name
that we want to be unique in the end.
name full path rest of the path
don't extend because we can't, for this particular path
Separate unique names (singletons) from other clusters (others). |
Disambiguate path - like names .
Disambiguate path-like names.
*)
open Printf
let parse_path =
let re = Str.regexp "[/\\]+" in
fun s ->
Str.split re s
Ensure each path has at least one component .
Reverse it so that the file name comes first .
Ensure each path has at least one component.
Reverse it so that the file name comes first.
*)
let normalize_path s =
match parse_path s |> List.rev with
| [] -> [""]
| l -> l
let deduplicate l =
let tbl = Hashtbl.create 100 in
Compat.List.filter_map (fun x ->
if Hashtbl.mem tbl x then
None
else (
Hashtbl.add tbl x ();
Some x
)
) l
Algorithm :
Store all the paths in a table , each path keyed by the file name .
Any cluster of more than 1 is removed and its elements are re - added
using a longer key .
This is repeated until there are no more clusters of more than 1 .
Algorithm:
Store all the paths in a table, each path keyed by the file name.
Any cluster of more than 1 is removed and its elements are re-added
using a longer key.
This is repeated until there are no more clusters of more than 1.
*)
type clus = (string list, (string list * string list ) list) Hashtbl.t
let add (clus : clus) k v =
let values =
try Hashtbl.find clus k
with Not_found -> []
in
Hashtbl.replace clus k (v :: values)
let make_clusters kv_list =
let clus = Hashtbl.create (2 * List.length kv_list) in
List.iter (fun (k, v) -> add clus k v) kv_list;
clus
let extend_name name (full_path, rest) =
match rest with
| [] ->
(name, (full_path, rest))
| dir :: parents ->
(name @ [dir], (full_path, parents))
let remove_singletons (clus : clus) =
Hashtbl.fold (fun k vl (singletons, clusters) ->
match vl with
| [v] ->
((k, v) :: singletons), clusters
| vl ->
let additional_clusters = List.map (fun v -> extend_name k v) vl in
singletons, (additional_clusters @ clusters)
) clus ([], [])
let extend_paths full_paths =
let rec loop acc clusters =
match clusters with
| [] -> acc
| clusters ->
let clus = make_clusters clusters in
let singletons, clusters = remove_singletons clus in
loop (singletons @ acc) clusters
in
let init full_path =
match full_path with
| name :: parents -> ([name], (full_path, parents))
| [] -> ([], (full_path, []))
in
let clusters =
List.map init full_paths
in
loop [] clusters
let format_name = function
| [] -> ""
| [name] -> name
| name :: rev_path ->
sprintf "%s<%s>" name (String.concat "/" (List.rev rev_path))
let create paths =
let unique_paths =
List.map normalize_path paths
|> deduplicate
in
let res = extend_paths unique_paths in
let lookup_tbl = Hashtbl.create 100 in
List.iter (fun (name, (full_path, _discarded_path)) ->
Hashtbl.add lookup_tbl full_path name
) res;
let simplify s =
let path = normalize_path s in
match Compat.Hashtbl.find_opt lookup_tbl path with
| None -> None
| Some name -> Some (format_name name)
in
simplify
let map paths =
let simplify = create paths in
List.map (fun path ->
match simplify path with
| Some name -> name
| None -> assert false
) paths
|
658b473ec1f9382bca37da2fc4b983e3025d6102830a949728dcaa0fdc43600c | reflectionalist/S9fES | string-find-last.scm | Scheme 9 from Empty Space , Function Library
By , 2009,2010
; Placed in the Public Domain
;
( string - find - last ) = = > string | # f
( string - ci - find - last ) = = > string | # f
( string - find - last - word ) = = > string | # f
( string - ci - find - last - word ) = = > string | # f
;
; (load-from-library "string-find-last.scm")
;
Find the last occurrence of a small string STRING1 in a large
; string STRING2. Return the last substring of STRING2 beginning
with STRING1 . When STRING2 does not contain STRING1 , return # F.
; STRING-CI-FIND-LAST performs the same function, but ignores case.
;
; STRING-FIND-LAST-WORD (STRING-CI-FIND-LAST-WORD) differs from
; STRING-FIND-LAST (STRING-CI-FIND-LAST) in that is matches only
; full words, where a full word is a subsequence of characters that
is delimited on both sides by one of the following :
;
; - the beginning of the string;
; - the end of the string;
; - a non-alphabetic character.
;
; Example: (string-find-last "a" "aaaaa") ==> "a"
; (string-ci-find-last "A" "ab ac") ==> "ac"
; (string-find-last "ax" "ab ac") ==> #f
; (string-find-last-word "a" "ab a c") ==> "a c"
; (string-find-last-word "a" "ab ac") ==> #f
(load-from-library "string-last-position.scm")
(define (make-str-pos pos)
(lambda (u s)
(let ((i (pos u s)))
(and i (substring s i (string-length s))))))
(define string-find-last (make-str-pos string-last-position))
(define string-ci-find-last (make-str-pos string-ci-last-position))
(define string-find-last-word (make-str-pos string-last-word-position))
(define string-ci-find-last-word (make-str-pos string-ci-last-word-position))
| null | https://raw.githubusercontent.com/reflectionalist/S9fES/0ade11593cf35f112e197026886fc819042058dd/lib/string-find-last.scm | scheme | Placed in the Public Domain
(load-from-library "string-find-last.scm")
string STRING2. Return the last substring of STRING2 beginning
STRING-CI-FIND-LAST performs the same function, but ignores case.
STRING-FIND-LAST-WORD (STRING-CI-FIND-LAST-WORD) differs from
STRING-FIND-LAST (STRING-CI-FIND-LAST) in that is matches only
full words, where a full word is a subsequence of characters that
- the beginning of the string;
- the end of the string;
- a non-alphabetic character.
Example: (string-find-last "a" "aaaaa") ==> "a"
(string-ci-find-last "A" "ab ac") ==> "ac"
(string-find-last "ax" "ab ac") ==> #f
(string-find-last-word "a" "ab a c") ==> "a c"
(string-find-last-word "a" "ab ac") ==> #f | Scheme 9 from Empty Space , Function Library
By , 2009,2010
( string - find - last ) = = > string | # f
( string - ci - find - last ) = = > string | # f
( string - find - last - word ) = = > string | # f
( string - ci - find - last - word ) = = > string | # f
Find the last occurrence of a small string STRING1 in a large
with STRING1 . When STRING2 does not contain STRING1 , return # F.
is delimited on both sides by one of the following :
(load-from-library "string-last-position.scm")
(define (make-str-pos pos)
(lambda (u s)
(let ((i (pos u s)))
(and i (substring s i (string-length s))))))
(define string-find-last (make-str-pos string-last-position))
(define string-ci-find-last (make-str-pos string-ci-last-position))
(define string-find-last-word (make-str-pos string-last-word-position))
(define string-ci-find-last-word (make-str-pos string-ci-last-word-position))
|
8c32e039344d462cc4d211e0d76c99d832155903c66eb53d6011c8962956f8d9 | nasa/pvslib | nasalib.lisp | (defparameter *nasalib-version* "7.1.0 (08/20/20)")
| null | https://raw.githubusercontent.com/nasa/pvslib/2be465b36f4d884c33cbd49a37939c4664db74eb/RELEASE/nasalib.lisp | lisp | (defparameter *nasalib-version* "7.1.0 (08/20/20)")
|
|
659842d161f0c4fbbb944883babc175c74b7a4f65507af45f78d0d01f75ffa92 | nathanmarz/cascalog | def.clj | Copyright ( c ) . All rights reserved . The use and
;; distribution terms for this software are covered by the Eclipse Public
;; License 1.0 (-1.0.php) which can
;; be found in the file epl-v10.html at the root of this distribution. By
;; using this software in any fashion, you are agreeing to be bound by the
;; terms of this license. You must not remove this notice, or any other,
;; from this software.
;;
;; File: def.clj
;;
;; def.clj provides variants of def that make including doc strings and
;; making private definitions more succinct.
;;
scgilardi ( gmail )
17 May 2008
(ns
#^{:author "Stephen C. Gilardi",
:doc "def.clj provides variants of def that make including doc strings and
making private definitions more succinct."}
cascalog.math.contrib.def)
(defmacro defvar
"Defines a var with an optional intializer and doc string"
([name]
(list `def name))
([name init]
(list `def name init))
([name init doc]
(list `def (with-meta name (assoc (meta name) :doc doc)) init)))
name - with - attributes by :
(defn name-with-attributes
"To be used in macro definitions.
Handles optional docstrings and attribute maps for a name to be defined
in a list of macro arguments. If the first macro argument is a string,
it is added as a docstring to name and removed from the macro argument
list. If afterwards the first macro argument is a map, its entries are
added to the name's metadata map and the map is removed from the
macro argument list. The return value is a vector containing the name
with its extended metadata map and the list of unprocessed macro
arguments."
[name macro-args]
(let [[docstring macro-args] (if (string? (first macro-args))
[(first macro-args) (next macro-args)]
[nil macro-args])
[attr macro-args] (if (map? (first macro-args))
[(first macro-args) (next macro-args)]
[{} macro-args])
attr (if docstring
(assoc attr :doc docstring)
attr)
attr (if (meta name)
(conj (meta name) attr)
attr)]
[(with-meta name attr) macro-args]))
| null | https://raw.githubusercontent.com/nathanmarz/cascalog/deaad977aa98985f68f3d1cc3e081d345184c0c8/cascalog-math/src/cascalog/math/contrib/def.clj | clojure | distribution terms for this software are covered by the Eclipse Public
License 1.0 (-1.0.php) which can
be found in the file epl-v10.html at the root of this distribution. By
using this software in any fashion, you are agreeing to be bound by the
terms of this license. You must not remove this notice, or any other,
from this software.
File: def.clj
def.clj provides variants of def that make including doc strings and
making private definitions more succinct.
| Copyright ( c ) . All rights reserved . The use and
scgilardi ( gmail )
17 May 2008
(ns
#^{:author "Stephen C. Gilardi",
:doc "def.clj provides variants of def that make including doc strings and
making private definitions more succinct."}
cascalog.math.contrib.def)
(defmacro defvar
"Defines a var with an optional intializer and doc string"
([name]
(list `def name))
([name init]
(list `def name init))
([name init doc]
(list `def (with-meta name (assoc (meta name) :doc doc)) init)))
name - with - attributes by :
(defn name-with-attributes
"To be used in macro definitions.
Handles optional docstrings and attribute maps for a name to be defined
in a list of macro arguments. If the first macro argument is a string,
it is added as a docstring to name and removed from the macro argument
list. If afterwards the first macro argument is a map, its entries are
added to the name's metadata map and the map is removed from the
macro argument list. The return value is a vector containing the name
with its extended metadata map and the list of unprocessed macro
arguments."
[name macro-args]
(let [[docstring macro-args] (if (string? (first macro-args))
[(first macro-args) (next macro-args)]
[nil macro-args])
[attr macro-args] (if (map? (first macro-args))
[(first macro-args) (next macro-args)]
[{} macro-args])
attr (if docstring
(assoc attr :doc docstring)
attr)
attr (if (meta name)
(conj (meta name) attr)
attr)]
[(with-meta name attr) macro-args]))
|
577e0325def2aac7ae63aee569926bb1410c9f3f0474cf3bedea524dc68d5c37 | UBTECH-Walker/WalkerSimulationFor2020WAIC | _package_joint_test.lisp | (cl:in-package cruiser_msgs-msg)
(cl:export '(HEADER-VAL
HEADER
POSITION-VAL
POSITION
SPEED-VAL
SPEED
)) | null | https://raw.githubusercontent.com/UBTECH-Walker/WalkerSimulationFor2020WAIC/7cdb21dabb8423994ba3f6021bc7934290d5faa9/walker_WAIC_18.04_v1.2_20200616/walker_install/share/common-lisp/ros/cruiser_msgs/msg/_package_joint_test.lisp | lisp | (cl:in-package cruiser_msgs-msg)
(cl:export '(HEADER-VAL
HEADER
POSITION-VAL
POSITION
SPEED-VAL
SPEED
)) |
|
ff96ca16219a6d45fdcb1b3bac9d5dec8da1d70267e09ac3febe9d15a9514a38 | jjmeyer0/gt | grammaru.mli | module Grammaru :
sig
type highlights = string * (string * string list) list
type symbolu = string
type elementu =
Esymbolu of symbolu
| Eoptionu of elementu list list
| Erepetitionu of elementu list list * string * string
type productionu =
Productionu of string * string * elementu list *
elementu list list option
type lexclassu = string * (string * bool)
type grammaru =
Grammaru of string list option * string * string option *
productionu list * lexclassu list * highlights
val get_nonterminal_strings : grammaru -> string list
val get_start_symbol : grammaru -> string
val is_newlnsens : string option -> bool
val su2se : unit Trie.trie -> symbolu -> symbolu * bool
val esu2ese :
unit Trie.trie -> elementu list -> Grammare.Grammare.element list
val esuopt2eseopt :
unit Trie.trie ->
elementu list list option -> Grammare.Grammare.element list list option
val pul2pel :
unit Trie.trie ->
productionu list -> Grammare.Grammare.productione list
val gu2ge : grammaru -> Grammare.Grammare.grammare
end
| null | https://raw.githubusercontent.com/jjmeyer0/gt/c0c7febc2e3fd532d44617f663b224cc0b9c7cf2/src/grammaru.mli | ocaml | module Grammaru :
sig
type highlights = string * (string * string list) list
type symbolu = string
type elementu =
Esymbolu of symbolu
| Eoptionu of elementu list list
| Erepetitionu of elementu list list * string * string
type productionu =
Productionu of string * string * elementu list *
elementu list list option
type lexclassu = string * (string * bool)
type grammaru =
Grammaru of string list option * string * string option *
productionu list * lexclassu list * highlights
val get_nonterminal_strings : grammaru -> string list
val get_start_symbol : grammaru -> string
val is_newlnsens : string option -> bool
val su2se : unit Trie.trie -> symbolu -> symbolu * bool
val esu2ese :
unit Trie.trie -> elementu list -> Grammare.Grammare.element list
val esuopt2eseopt :
unit Trie.trie ->
elementu list list option -> Grammare.Grammare.element list list option
val pul2pel :
unit Trie.trie ->
productionu list -> Grammare.Grammare.productione list
val gu2ge : grammaru -> Grammare.Grammare.grammare
end
|
|
54370e31c5966e85f3ca223b88ed02b9046e0b8a4a32af8e4ba535234c108b5d | bondy-io/bondy | bondy_bridge_relay_server.erl | %% =============================================================================
%% bondy_bridge_relay_server.erl -
%%
Copyright ( c ) 2016 - 2022 Leapsight . 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.
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc EARLY DRAFT implementation of the server-side connection between and
%% client node ({@link bondy_bridge_relay_client}) and a remote/core node
%% (this module).
%%
< pre><code class="mermaid " >
%% stateDiagram-v2
% % { init:{'state':{'nodeSpacing ' : 50 , ' rankSpacing ' : 200}}}%%
%% [*] --> connected
%% connected --> active: session_opened
%% connected --> [*]: auth_timeout
active -- > active : rcv(data|ping ) | snd(data|pong )
%% active --> idle: ping_idle_timeout
%% active --> [*]: error
idle -- > idle : ) | rcv(ping|pong )
%% idle --> active: snd(data)
%% idle --> active: rcv(data)
%% idle --> [*]: error
%% idle --> [*]: ping_timeout
%% idle --> [*]: idle_timeout
%% </code></pre>
%%
%% == Configuration Options ==
%% <ul>
%% <li>auth_timeout - once the connection is established how long to wait for
the client to send the HELLO message.</li >
%% </ul>
%% @end
%% -----------------------------------------------------------------------------
-module(bondy_bridge_relay_server).
-behaviour(gen_statem).
-behaviour(ranch_protocol).
-include_lib("kernel/include/logger.hrl").
-include_lib("wamp/include/wamp.hrl").
-include_lib("bondy_plum_db.hrl").
-include("bondy.hrl").
-include("bondy_bridge_relay.hrl").
-record(state, {
ranch_ref :: atom(),
transport :: module(),
opts :: key_value:t(),
socket :: gen_tcp:socket() | ssl:sslsocket(),
auth_timeout :: pos_integer(),
ping_retry :: optional(bondy_retry:t()),
ping_payload :: optional(binary()),
ping_idle_timeout :: optional(non_neg_integer()),
idle_timeout :: pos_integer(),
hibernate = idle :: never | idle | always,
sessions = #{} :: #{id() => bondy_session:t()},
sessions_by_realm = #{} :: #{uri() => bondy_session_id:t()},
%% The context for the session currently being established
auth_context :: optional(bondy_auth:context()),
registrations = #{} :: reg_indx(),
start_ts :: pos_integer()
}).
% -type t() :: #state{}.
-type reg_indx() :: #{
SessionId :: bondy_session_id:t() => proxy_map()
}.
%% A mapping between a client entry id and the local (server) proxy id
-type proxy_map() :: #{OrigEntryId :: id() => ProxyEntryId :: id()}.
%% API.
-export([start_link/3]).
-export([start_link/4]).
%% GEN_STATEM CALLBACKS
-export([callback_mode/0]).
-export([init/1]).
-export([terminate/3]).
-export([code_change/4]).
%% STATE FUNCTIONS
-export([active/3]).
-export([idle/3]).
%% =============================================================================
%% API
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
start_link(RanchRef, Transport, Opts) ->
gen_statem:start_link(?MODULE, {RanchRef, Transport, Opts}, []).
%% -----------------------------------------------------------------------------
%% @doc
This will be deprecated with Ranch 2.0
%% @end
%% -----------------------------------------------------------------------------
start_link(RanchRef, _, Transport, Opts) ->
start_link(RanchRef, Transport, Opts).
%% =============================================================================
%% GEN_STATEM CALLBACKS
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
callback_mode() ->
[state_functions, state_enter].
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
init({RanchRef, Transport, Opts}) ->
AuthTimeout = key_value:get(auth_timeout, Opts, 5000),
IdleTimeout = key_value:get(idle_timeout, Opts, infinity),
%% Shall we hibernate when we are idle?
Hibernate = key_value:get(hibernate, Opts, idle),
State0 = #state{
ranch_ref = RanchRef,
transport = Transport,
opts = Opts,
auth_timeout = AuthTimeout,
idle_timeout = IdleTimeout,
hibernate = Hibernate,
start_ts = erlang:system_time(millisecond)
},
%% Setup ping
PingOpts = maps:from_list(key_value:get(ping, Opts, [])),
State = maybe_enable_ping(PingOpts, State0),
%% We setup the auth_timeout timer. This is the period we allow between
opening a connection and authenticating at least one session . Having
%% passed that time we will close the connection.
Actions = [auth_timeout(State)],
{ok, active, State, Actions}.
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
terminate({shutdown, Info}, StateName, #state{socket = undefined} = State) ->
ok = remove_all_registry_entries(State),
?LOG_INFO(Info#{
state_name => StateName
}),
ok;
terminate(Reason, StateName, #state{socket = undefined} = State) ->
ok = remove_all_registry_entries(State),
?LOG_INFO(#{
description => "Closing connection",
reason => Reason,
state_name => StateName
}),
ok;
terminate(Reason, StateName, #state{} = State) ->
Transport = State#state.transport,
Socket = State#state.socket,
catch Transport:close(Socket),
terminate(Reason, StateName, State#state{socket = undefined}).
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
%% =============================================================================
%% STATE FUNCTIONS
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
active(enter, active, State) ->
Ref = State#state.ranch_ref,
Transport = State#state.transport,
%% Setup and configure socket
TLSOpts = bondy_config:get([Ref, tls_opts], []),
{ok, Socket} = ranch:handshake(Ref, TLSOpts),
SocketOpts = [
binary,
{packet, 4},
{active, once}
| bondy_config:get([Ref, socket_opts], [])
],
%% If Transport == ssl, upgrades a gen_tcp, or equivalent socket to an SSL
socket by performing the TLS server - side handshake , returning a TLS
%% socket.
ok = Transport:setopts(Socket, SocketOpts),
{ok, Peername} = bondy_utils:peername(Transport, Socket),
PeernameBin = inet_utils:peername_to_binary(Peername),
ok = logger:set_process_metadata(#{
transport => Transport,
peername => PeernameBin,
socket => Socket
}),
ok = on_connect(State),
Actions = [auth_timeout(State)],
{keep_state, State#state{socket = Socket}, Actions};
active(enter, idle, State) ->
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
active(
internal, {hello, Uri, Details}, #state{auth_context = undefined} = State0
) ->
TODO validate Details
?LOG_DEBUG(#{
description => "Got hello",
details => Details
}),
try
Realm = bondy_realm:fetch(Uri),
bondy_realm:allow_connections(Realm)
orelse throw(connections_not_allowed),
%% We send the challenge
State = challenge(Realm, Details, State0),
%% We wait for response and timeout using auth_timeout again
Actions = [auth_timeout(State)],
{keep_state, State, Actions}
catch
error:{not_found, Uri} ->
Abort = {
abort,
undefined,
no_such_realm,
#{
message => <<"Realm does not exist.">>,
realm => Uri
}
},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:connections_not_allowed = Reason ->
Abort = {abort, undefined, Reason, #{
message => <<"The Realm does not allow user connections ('allow_connections' setting is off). This might be a temporary measure taken by the administrator or the realm is meant to be used only as a Same Sign-on (SSO) realm.">>,
realm => Uri
}},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:{no_authmethod, ReqMethods} ->
Abort = {abort, undefined, no_authmethod, #{
message => <<"The requested authentication methods are not available for this user on this realm.">>,
realm => Uri,
authmethods => ReqMethods
}},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:{authentication_failed, Reason} ->
Abort = {abort, undefined, authentication_failed, #{
message => <<"Authentication failed.">>,
realm => Uri,
reason => Reason
}},
ok = send_message(Abort, State0),
{stop, normal, State0}
end;
active(internal, {hello, _, _}, #state{} = State) ->
%% Assumption: no concurrent session establishment on this transport
%% Session already being established, invalid message
Abort = {abort, undefined, protocol_violation, #{
message => <<"You've sent the HELLO message twice">>
}},
ok = send_message(Abort, State),
{stop, normal, State};
active(internal, {authenticate, Signature, Extra}, State0) ->
TODO validate Details
?LOG_DEBUG(#{
description => "Got authenticate",
signature => Signature,
extra => Extra
}),
try
State = authenticate(<<"cryptosign">>, Signature, Extra, State0),
%% We cancel the auth timeout as soon as the connection has at least
one authenticate session
Actions = [
{{timeout, auth_timeout}, cancel},
ping_idle_timeout(State)
],
{keep_state, State, Actions}
catch
throw:{authentication_failed, Reason} ->
AuthCtxt = State0#state.auth_context,
RealmUri = bondy_auth:realm_uri(AuthCtxt),
SessionId = bondy_auth:realm_uri(AuthCtxt),
Abort = {abort, SessionId, authentication_failed, #{
message => <<"Authentication failed.">>,
realm_uri => RealmUri,
reason => Reason
}},
ok = send_message(Abort, State0),
{stop, normal, State0}
end;
active(internal, {aae_sync, SessionId, Opts}, State) ->
RealmUri = session_realm(SessionId, State),
ok = full_sync(SessionId, RealmUri, Opts, State),
Finish = {aae_sync, SessionId, finished},
ok = gen_statem:cast(self(), {forward_message, Finish}),
Actions = [ping_idle_timeout(State)],
{keep_state_and_data, Actions};
active(internal, {session_message, SessionId, Msg}, State) ->
?LOG_DEBUG(#{
description => "Got session message from client",
session_id => SessionId,
message => Msg
}),
try
handle_in(Msg, SessionId, State)
catch
throw:Reason:Stacktrace ->
?LOG_ERROR(#{
description => "Unhandled error",
session_id => SessionId,
message => Msg,
class => throw,
reason => Reason,
stacktrace => Stacktrace
}),
Actions = [ping_idle_timeout(State)],
{keep_state_and_data, Actions};
Class:Reason:Stacktrace ->
?LOG_ERROR(#{
description => "Error while handling session message",
session_id => SessionId,
message => Msg,
class => Class,
reason => Reason,
stacktrace => Stacktrace
}),
Abort = {abort, SessionId, server_error, #{
reason => Reason
}},
ok = send_message(Abort, State),
{stop, Reason, State}
end;
active({timeout, auth_timeout}, auth_timeout, _) ->
?LOG_INFO(#{
description => "Closing connection due to authentication timeout.",
reason => auth_timeout
}),
{stop, normal};
active({timeout, ping_idle_timeout}, ping_idle_timeout, State) ->
%% We have had no activity, transition to idle and start sending pings
{next_state, idle, State};
active(EventType, EventContent, State) ->
handle_event(EventType, EventContent, active, State).
%% -----------------------------------------------------------------------------
%% @doc
%% @end
%% -----------------------------------------------------------------------------
idle(enter, active, State) ->
%% We use an event timeout meaning any event received will cancel it
IdleTimeout = State#state.idle_timeout,
PingTimeout = State#state.idle_timeout,
Adjusted = IdleTimeout - PingTimeout,
Time = case Adjusted > 0 of
true -> Adjusted;
false -> IdleTimeout
end,
Actions = [
{state_timeout, Time, idle_timeout}
],
maybe_send_ping(State, Actions);
idle({timeout, ping_idle_timeout}, ping_idle_timeout, State) ->
maybe_send_ping(State);
idle({timeout, ping_timeout}, ping_timeout, State0) ->
%% No ping response in time
State = ping_fail(State0),
%% Try to send another one or stop if retry limit reached
maybe_send_ping(State);
idle(state_timeout, idle_timeout, _State) ->
Info = #{
description => "Shutting down connection due to inactivity.",
reason => idle_timeout
},
{stop, {shutdown, Info}};
idle(internal, {pong, Bin}, #state{ping_payload = Bin} = State0) ->
%% We got a response to our ping
State = ping_succeed(State0),
Actions = [
{{timeout, ping_timeout}, cancel},
ping_idle_timeout(State),
maybe_hibernate(idle, State)
],
{keep_state, State, Actions};
idle(internal, Msg, State) ->
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel},
{next_event, internal, Msg}
],
%% idle_timeout is a state timeout so it will be cancelled as we are
%% transitioning to active
{next_state, active, State, Actions};
idle(EventType, EventContent, State) ->
handle_event(EventType, EventContent, idle, State).
%% =============================================================================
%% PRIVATE: COMMON EVENT HANDLING
%% =============================================================================
%% -----------------------------------------------------------------------------
%% @doc Handle events common to all states
%% @end
%% -----------------------------------------------------------------------------
TODO forward_message or forward ?
handle_event({call, From}, Request, _, _) ->
?LOG_INFO(#{
description => "Received unknown request",
type => call,
event => Request
}),
%% We should not reset timers, nor change state here as this is an invalid
%% message
Actions = [
{reply, From, {error, badcall}}
],
{keep_state_and_data, Actions};
handle_event(cast, {forward_message, Msg}, _, State) ->
%% This is a cast we do to ourselves
ok = send_message(Msg, State),
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel}
],
{next_state, active, State, Actions};
handle_event(internal, {ping, Data}, _, State) ->
%% The client is sending us a ping
ok = send_message({pong, Data}, State),
%% We keep all timers
keep_state_and_data;
handle_event(info, {?BONDY_REQ, Pid, RealmUri, M}, _, State) ->
A local : send ( ) , we need to forward to client
?LOG_DEBUG(#{
description => "Received WAMP request we need to FWD to client",
message => M
}),
handle_out(M, RealmUri, Pid, State);
handle_event(info, {Tag, Socket, Data}, _, #state{socket = Socket} = State)
when ?SOCKET_DATA(Tag) ->
ok = set_socket_active(State),
try binary_to_term(Data) of
Msg ->
?LOG_DEBUG(#{
description => "Received message from client",
reason => Msg
}),
%% The message can be a ping|pong and in the case of idle state we
%% should not reset timers here, we'll do that in the handling
%% of next_event
Actions = [
{next_event, internal, Msg}
],
{keep_state, State, Actions}
catch
Class:Reason ->
Info = #{
description => "Received invalid data from client.",
data => Data,
class => Class,
reason => Reason
},
{stop, {shutdown, Info}}
end;
handle_event(info, {Tag, _Socket}, _, _) when ?CLOSED_TAG(Tag) ->
?LOG_INFO(#{
description => "Connection closed by client."
}),
{stop, normal};
handle_event(info, {Tag, _, Reason}, _, _) when ?SOCKET_ERROR(Tag) ->
?LOG_INFO(#{
description => "Connection closed due to error.",
reason => Reason
}),
{stop, Reason};
handle_event(EventType, EventContent, StateName, _) ->
?LOG_INFO(#{
description => "Received unknown message.",
type => EventType,
event => EventContent,
state_name => StateName
}),
keep_state_and_data.
%% =============================================================================
%% PRIVATE
%% =============================================================================
@private
challenge(Realm, Details, State0) ->
{ok, Peer} = bondy_utils:peername(
State0#state.transport, State0#state.socket
),
SessionId = bondy_session_id:new(),
Authid = maps:get(authid, Details),
Authroles0 = maps:get(authroles, Details, []),
case bondy_auth:init(SessionId, Realm, Authid, Authroles0, Peer) of
{ok, AuthCtxt} ->
TODO take it from conf
ReqMethods = [<<"cryptosign">>],
case bondy_auth:available_methods(ReqMethods, AuthCtxt) of
[] ->
throw({no_authmethod, ReqMethods});
[Method|_] ->
Uri = bondy_realm:uri(Realm),
FinalAuthid = bondy_auth:user_id(AuthCtxt),
Authrole = bondy_auth:role(AuthCtxt),
Authroles = bondy_auth:roles(AuthCtxt),
Authprovider = bondy_auth:provider(AuthCtxt),
SecEnabled = bondy_realm:is_security_enabled(Realm),
Properties = #{
type => bridge_relay,
peer => Peer,
security_enabled => SecEnabled,
is_anonymous => FinalAuthid == anonymous,
agent => bondy_router:agent(),
roles => maps:get(roles, Details, undefined),
authid => maybe_gen_authid(FinalAuthid),
authprovider => Authprovider,
authmethod => Method,
authrole => Authrole,
authroles => Authroles
},
%% We create a new session object but we do not open it
%% yet, as we need to send the callenge and verify the
%% response
Session = bondy_session:new(Uri, Properties),
Sessions0 = State0#state.sessions,
Sessions = maps:put(SessionId, Session, Sessions0),
SessionsByUri0 = State0#state.sessions_by_realm,
SessionsByUri = maps:put(Uri, SessionId, SessionsByUri0),
State = State0#state{
auth_context = AuthCtxt,
sessions = Sessions,
sessions_by_realm = SessionsByUri
},
send_challenge(Details, Method, State)
end;
{error, Reason0} ->
throw({authentication_failed, Reason0})
end.
@private
send_challenge(Details, Method, State0) ->
AuthCtxt0 = State0#state.auth_context,
{Reply, State} =
case bondy_auth:challenge(Method, Details, AuthCtxt0) of
{false, _} ->
%% We got no challenge? This cannot happen with cryptosign
exit(invalid_authmethod);
{true, ChallengeExtra, AuthCtxt1} ->
M = {challenge, Method, ChallengeExtra},
{M, State0#state{auth_context = AuthCtxt1}};
{error, Reason} ->
%% At the moment we only support a single session/realm
%% so we crash
throw({authentication_failed, Reason})
end,
ok = send_message(Reply, State),
State.
@private
authenticate(AuthMethod, Signature, Extra, State0) ->
AuthCtxt0 = State0#state.auth_context,
case bondy_auth:authenticate(AuthMethod, Signature, Extra, AuthCtxt0) of
{ok, AuthExtra0, _} ->
SessionId = bondy_auth:session_id(AuthCtxt0),
Session = session(SessionId, State0),
ok = bondy_session_manager:open(Session),
AuthExtra = AuthExtra0#{node => bondy_config:nodestring()},
M = {welcome, SessionId, #{authextra => AuthExtra}},
State = State0#state{auth_context = undefined},
ok = send_message(M, State),
State;
{error, Reason} ->
%% At the moment we only support a single session/realm
%% so we crash
throw({authentication_failed, Reason})
end.
@private
set_socket_active(State) ->
(State#state.transport):setopts(State#state.socket, [{active, once}]).
@private
send_message(Message, State) ->
?LOG_DEBUG(#{description => "sending message", message => Message}),
Data = term_to_binary(Message),
(State#state.transport):send(State#state.socket, Data).
@private
on_connect(_State) ->
?LOG_INFO(#{
description => "Established connection with client router."
}),
ok.
%% -----------------------------------------------------------------------------
@private
%% @doc Handles inbound session messages
%% @end
%% -----------------------------------------------------------------------------
handle_in({registration_created, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_added, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_removed, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_deleted, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_created, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_added, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_removed, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_deleted, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({forward, _, #publish{} = M, _Opts}, SessionId, State) ->
RealmUri = session_realm(SessionId, State),
ReqId = M#publish.request_id,
TopicUri = M#publish.topic_uri,
Args = M#publish.args,
KWArg = M#publish.kwargs,
Opts0 = M#publish.options,
Opts = Opts0#{exclude_me => true},
Ref = session_ref(SessionId, State),
%% We do a re-publish so that bondy_broker disseminates the event using its
%% normal optimizations
Job = fun() ->
Ctxt = bondy_context:local_context(RealmUri, Ref),
bondy_broker:publish(ReqId, Opts, TopicUri, Args, KWArg, Ctxt)
end,
case bondy_router_worker:cast(Job) of
ok ->
ok;
{error, overload} ->
TODO return proper return ... but we should move this to router
error(overload)
end,
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
handle_in({forward, To, Msg, Opts}, SessionId, State) ->
%% using cast here in theory breaks the CALL order guarantee!!!
%% We either need to implement Partisan 4 plus:
%% a) causality or
b ) a pool of relays ( selecting one by hashing { CallerID , CalleeId } ) and
%% do it sync
RealmUri = session_realm(SessionId, State),
Fwd = fun() ->
bondy_router:forward(Msg, To, Opts#{realm_uri => RealmUri})
end,
case bondy_router_worker:cast(Fwd) of
ok ->
ok;
{error, overload} ->
TODO return proper return ... but we should move this to router
error(overload)
end,
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
handle_in(Other, SessionId, State) ->
?LOG_INFO(#{
description => "Unhandled message",
session_id => SessionId,
message => Other
}),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions}.
%% -----------------------------------------------------------------------------
@private
%% @doc
%% @end
%% -----------------------------------------------------------------------------
handle_out(#goodbye{} = M, RealmUri, _From, State) ->
Details = M#goodbye.details,
ReasonUri = M#goodbye.reason_uri,
SessionId = session_id(RealmUri, State),
ControlMsg = {goodbye, SessionId, ReasonUri, Details},
ok = send_message(ControlMsg, State),
{stop, normal};
handle_out(M, RealmUri, _From, State) ->
SessionId = session_id(RealmUri, State),
ok = send_message({session_message, SessionId, M}, State),
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel}
],
{next_state, active, State, Actions}.
@private
add_registry_entry(SessionId, ExtEntry, State) ->
Ref = session_ref(SessionId, State),
ProxyEntry = bondy_registry_entry:proxy(Ref, ExtEntry),
Id = bondy_registry_entry:id(ProxyEntry),
OriginId = bondy_registry_entry:origin_id(ProxyEntry),
case bondy_registry:add(ProxyEntry) of
{ok, _} ->
Index0 = State#state.registrations,
Index = key_value:put([SessionId, OriginId], Id, Index0),
State#state{registrations = Index};
{error, already_exists} ->
ok
end.
@private
remove_registry_entry(SessionId, ExtEntry, State) ->
Index0 = State#state.registrations,
OriginId = maps:get(entry_id, ExtEntry),
Type = maps:get(type, ExtEntry),
try key_value:get([SessionId, OriginId], Index0) of
ProxyId ->
TODO get from session once we have real sessions
RealmUri = session_realm(SessionId, State),
Node = bondy_config:node(),
Ctxt = #{
realm_uri => RealmUri,
node => Node,
session_id => SessionId
},
ok = bondy_registry:remove(Type, ProxyId, Ctxt),
Index = key_value:remove([SessionId, OriginId], Index0),
State#state{registrations = Index}
catch
error:badkey ->
State
end.
remove_all_registry_entries(State) ->
maps:foreach(
fun(_, Session) ->
RealmUri = bondy_session:realm_uri(Session),
Ref = bondy_session:ref(Session),
bondy_router:flush(RealmUri, Ref)
end,
State#state.sessions
).
@private
full_sync(SessionId, RealmUri, Opts, State) ->
Realm = bondy_realm:fetch(RealmUri),
If the realm has a prototype we sync the prototype first
case bondy_realm:prototype_uri(Realm) of
undefined ->
ok;
ProtoUri ->
full_sync(SessionId, ProtoUri, Opts, State)
end,
%% We do not automatically sync the SSO Realms, if the client node wants it,
%% that should be requested explicitly
TODO However , we should sync a projection of the SSO Realm , the realm
%% definition itself but with users, groups, sources and grants that affect
%% the Realm's users, and avoiding bringing the password
%% SO WE NEED REPLICATION FILTERS AT PLUM_DB LEVEL
%% This means that only non SSO Users can login.
ALSO we are currently copying the CRA passwords which we should n't
%% Finally we sync the realm
ok = do_full_sync(SessionId, RealmUri, Opts, State).
%% -----------------------------------------------------------------------------
@private
%% @doc A temporary POC of full sync, not elegant at all.
%% This should be resolved at the plum_db layer and not here, but we are
%% interested in having a POC ASAP.
%% @end
%% -----------------------------------------------------------------------------
do_full_sync(SessionId, RealmUri, _Opts, _State0) ->
%% TODO we should spawn an exchange statem for this
Me = self(),
Prefixes = [
%% TODO We should NOT sync the priv keys!!
%% We might need to split the realm from the priv keys to enable a
AAE hash comparison .
{?PLUM_DB_REALM_TAB, RealmUri},
{?PLUM_DB_GROUP_TAB, RealmUri},
%% TODO we should not sync passwords! We might need to split the
%% password from the user object and allow admin to enable sync or not
( e.g. )
{?PLUM_DB_USER_TAB, RealmUri},
{?PLUM_DB_SOURCE_TAB, RealmUri},
{?PLUM_DB_USER_GRANT_TAB, RealmUri},
{?PLUM_DB_GROUP_GRANT_TAB, RealmUri}
% ,
% {?PLUM_DB_REGISTRATION_TAB, RealmUri},
{ ? , RealmUri } ,
% {?PLUM_DB_TICKET_TAB, RealmUri}
],
_ = lists:foreach(
fun(Prefix) ->
lists:foreach(
fun(Obj0) ->
Obj = prepare_object(Obj0),
Msg = {aae_data, SessionId, Obj},
gen_statem:cast(Me, {forward_message, Msg})
end,
pdb_objects(Prefix)
)
end,
Prefixes
),
ok.
@private
prepare_object(Obj) ->
case bondy_realm:is_type(Obj) of
true ->
%% A temporary hack to prevent keys being synced with an client
%% router. We will use this until be implement partial replication
and decide on Key management strategies .
bondy_realm:strip_private_keys(Obj);
false ->
Obj
end.
pdb_objects(FullPrefix) ->
It = plum_db:iterator(FullPrefix, []),
try
pdb_objects(It, [])
catch
{break, Result} -> Result
after
ok = plum_db:iterator_close(It)
end.
@private
pdb_objects(It, Acc0) ->
case plum_db:iterator_done(It) of
true ->
Acc0;
false ->
Acc = [plum_db:iterator_element(It) | Acc0],
pdb_objects(plum_db:iterate(It), Acc)
end.
@private
session(SessionId, #state{sessions = Map}) ->
maps:get(SessionId, Map).
@private
session_realm(SessionId, #state{sessions = Map}) ->
bondy_session:realm_uri(maps:get(SessionId, Map)).
@private
session_ref(SessionId, #state{sessions = Map}) ->
bondy_session:ref(maps:get(SessionId, Map)).
@private
session_id(RealmUri, #state{sessions_by_realm = Map}) ->
maps:get(RealmUri, Map).
@private
maybe_gen_authid(anonymous) ->
bondy_utils:uuid();
maybe_gen_authid(UserId) ->
UserId.
%% =============================================================================
%% PRIVATE: KEEP ALIVE PING
%% =============================================================================
@private
maybe_enable_ping(#{enabled := true} = PingOpts, State) ->
IdleTimeout = maps:get(idle_timeout, PingOpts),
Timeout = maps:get(timeout, PingOpts),
Attempts = maps:get(max_attempts, PingOpts),
Retry = bondy_retry:init(
ping_timeout,
#{
deadline => 0, % disable, use max_retries only
interval => Timeout,
max_retries => Attempts,
backoff_enabled => false
}
),
State#state{
ping_idle_timeout = IdleTimeout,
ping_payload = bondy_utils:generate_fragment(16),
ping_retry = Retry
};
maybe_enable_ping(#{enabled := false}, State) ->
State.
@private
ping_succeed(#state{ping_retry = undefined} = State) ->
%% ping disabled
State;
ping_succeed(#state{} = State) ->
{_, Retry} = bondy_retry:succeed(State#state.ping_retry),
State#state{ping_retry = Retry}.
@private
ping_fail(#state{ping_retry = undefined} = State) ->
%% ping disabled
State;
ping_fail(#state{} = State) ->
{_, Retry} = bondy_retry:fail(State#state.ping_retry),
State#state{ping_retry = Retry}.
@private
maybe_send_ping(State) ->
maybe_send_ping(State, []).
@private
maybe_send_ping(#state{ping_retry = undefined} = State, Actions0) ->
%% ping disabled
Actions = [
maybe_hibernate(idle, State) | Actions0
],
{keep_state_and_data, Actions};
maybe_send_ping(#state{} = State, Actions0) ->
case bondy_retry:get(State#state.ping_retry) of
Time when is_integer(Time) ->
%% We send a ping
Bin = State#state.ping_payload,
ok = send_message({ping, Bin}, State),
%% We set the timeout
Actions = [
ping_timeout(Time),
maybe_hibernate(idle, State)
| Actions0
],
{keep_state, State, Actions};
Limit when Limit == deadline orelse Limit == max_retries ->
Info = #{
description => "Client router has not responded to our ping on time. Shutting down.",
reason => ping_timeout
},
{stop, {shutdown, Info}, State}
end.
@private
ping_idle_timeout(State) ->
%% We use an generic timeout meaning we only reset the timer manually by
%% setting it again.
Time = State#state.ping_idle_timeout,
{{timeout, ping_idle_timeout}, Time, ping_idle_timeout}.
@private
ping_timeout(Time) ->
%% We use an generic timeout meaning we only reset the timer manually by
%% setting it again.
{{timeout, ping_timeout}, Time, ping_timeout}.
@private
auth_timeout(State) ->
%% We use an generic timeout meaning we only reset the timer manually by
%% setting it again.
Time = State#state.auth_timeout,
{{timeout, auth_timeout}, Time, auth_timeout}.
@private
maybe_hibernate(_, #state{hibernate = never}) ->
{hibernate, false};
maybe_hibernate(_, #state{hibernate = always}) ->
{hibernate, true};
maybe_hibernate(StateName, #state{hibernate = idle}) ->
{hibernate, StateName == idle}. | null | https://raw.githubusercontent.com/bondy-io/bondy/570cea3c79714e6db0d1ce64169eb43e2c94c54d/apps/bondy/src/bondy_bridge_relay_server.erl | erlang | =============================================================================
bondy_bridge_relay_server.erl -
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=============================================================================
-----------------------------------------------------------------------------
@doc EARLY DRAFT implementation of the server-side connection between and
client node ({@link bondy_bridge_relay_client}) and a remote/core node
(this module).
stateDiagram-v2
% { init:{'state':{'nodeSpacing ' : 50 , ' rankSpacing ' : 200}}}%%
[*] --> connected
connected --> active: session_opened
connected --> [*]: auth_timeout
active --> idle: ping_idle_timeout
active --> [*]: error
idle --> active: snd(data)
idle --> active: rcv(data)
idle --> [*]: error
idle --> [*]: ping_timeout
idle --> [*]: idle_timeout
</code></pre>
== Configuration Options ==
<ul>
<li>auth_timeout - once the connection is established how long to wait for
</ul>
@end
-----------------------------------------------------------------------------
The context for the session currently being established
-type t() :: #state{}.
A mapping between a client entry id and the local (server) proxy id
API.
GEN_STATEM CALLBACKS
STATE FUNCTIONS
=============================================================================
API
=============================================================================
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
=============================================================================
GEN_STATEM CALLBACKS
=============================================================================
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
Shall we hibernate when we are idle?
Setup ping
We setup the auth_timeout timer. This is the period we allow between
passed that time we will close the connection.
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
=============================================================================
STATE FUNCTIONS
=============================================================================
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
Setup and configure socket
If Transport == ssl, upgrades a gen_tcp, or equivalent socket to an SSL
socket.
We send the challenge
We wait for response and timeout using auth_timeout again
Assumption: no concurrent session establishment on this transport
Session already being established, invalid message
We cancel the auth timeout as soon as the connection has at least
We have had no activity, transition to idle and start sending pings
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
We use an event timeout meaning any event received will cancel it
No ping response in time
Try to send another one or stop if retry limit reached
We got a response to our ping
idle_timeout is a state timeout so it will be cancelled as we are
transitioning to active
=============================================================================
PRIVATE: COMMON EVENT HANDLING
=============================================================================
-----------------------------------------------------------------------------
@doc Handle events common to all states
@end
-----------------------------------------------------------------------------
We should not reset timers, nor change state here as this is an invalid
message
This is a cast we do to ourselves
The client is sending us a ping
We keep all timers
The message can be a ping|pong and in the case of idle state we
should not reset timers here, we'll do that in the handling
of next_event
=============================================================================
PRIVATE
=============================================================================
We create a new session object but we do not open it
yet, as we need to send the callenge and verify the
response
We got no challenge? This cannot happen with cryptosign
At the moment we only support a single session/realm
so we crash
At the moment we only support a single session/realm
so we crash
-----------------------------------------------------------------------------
@doc Handles inbound session messages
@end
-----------------------------------------------------------------------------
We do a re-publish so that bondy_broker disseminates the event using its
normal optimizations
using cast here in theory breaks the CALL order guarantee!!!
We either need to implement Partisan 4 plus:
a) causality or
do it sync
-----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
We do not automatically sync the SSO Realms, if the client node wants it,
that should be requested explicitly
definition itself but with users, groups, sources and grants that affect
the Realm's users, and avoiding bringing the password
SO WE NEED REPLICATION FILTERS AT PLUM_DB LEVEL
This means that only non SSO Users can login.
Finally we sync the realm
-----------------------------------------------------------------------------
@doc A temporary POC of full sync, not elegant at all.
This should be resolved at the plum_db layer and not here, but we are
interested in having a POC ASAP.
@end
-----------------------------------------------------------------------------
TODO we should spawn an exchange statem for this
TODO We should NOT sync the priv keys!!
We might need to split the realm from the priv keys to enable a
TODO we should not sync passwords! We might need to split the
password from the user object and allow admin to enable sync or not
,
{?PLUM_DB_REGISTRATION_TAB, RealmUri},
{?PLUM_DB_TICKET_TAB, RealmUri}
A temporary hack to prevent keys being synced with an client
router. We will use this until be implement partial replication
=============================================================================
PRIVATE: KEEP ALIVE PING
=============================================================================
disable, use max_retries only
ping disabled
ping disabled
ping disabled
We send a ping
We set the timeout
We use an generic timeout meaning we only reset the timer manually by
setting it again.
We use an generic timeout meaning we only reset the timer manually by
setting it again.
We use an generic timeout meaning we only reset the timer manually by
setting it again. | Copyright ( c ) 2016 - 2022 Leapsight . All rights reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
< pre><code class="mermaid " >
active -- > active : rcv(data|ping ) | snd(data|pong )
idle -- > idle : ) | rcv(ping|pong )
the client to send the HELLO message.</li >
-module(bondy_bridge_relay_server).
-behaviour(gen_statem).
-behaviour(ranch_protocol).
-include_lib("kernel/include/logger.hrl").
-include_lib("wamp/include/wamp.hrl").
-include_lib("bondy_plum_db.hrl").
-include("bondy.hrl").
-include("bondy_bridge_relay.hrl").
-record(state, {
ranch_ref :: atom(),
transport :: module(),
opts :: key_value:t(),
socket :: gen_tcp:socket() | ssl:sslsocket(),
auth_timeout :: pos_integer(),
ping_retry :: optional(bondy_retry:t()),
ping_payload :: optional(binary()),
ping_idle_timeout :: optional(non_neg_integer()),
idle_timeout :: pos_integer(),
hibernate = idle :: never | idle | always,
sessions = #{} :: #{id() => bondy_session:t()},
sessions_by_realm = #{} :: #{uri() => bondy_session_id:t()},
auth_context :: optional(bondy_auth:context()),
registrations = #{} :: reg_indx(),
start_ts :: pos_integer()
}).
-type reg_indx() :: #{
SessionId :: bondy_session_id:t() => proxy_map()
}.
-type proxy_map() :: #{OrigEntryId :: id() => ProxyEntryId :: id()}.
-export([start_link/3]).
-export([start_link/4]).
-export([callback_mode/0]).
-export([init/1]).
-export([terminate/3]).
-export([code_change/4]).
-export([active/3]).
-export([idle/3]).
start_link(RanchRef, Transport, Opts) ->
gen_statem:start_link(?MODULE, {RanchRef, Transport, Opts}, []).
This will be deprecated with Ranch 2.0
start_link(RanchRef, _, Transport, Opts) ->
start_link(RanchRef, Transport, Opts).
callback_mode() ->
[state_functions, state_enter].
init({RanchRef, Transport, Opts}) ->
AuthTimeout = key_value:get(auth_timeout, Opts, 5000),
IdleTimeout = key_value:get(idle_timeout, Opts, infinity),
Hibernate = key_value:get(hibernate, Opts, idle),
State0 = #state{
ranch_ref = RanchRef,
transport = Transport,
opts = Opts,
auth_timeout = AuthTimeout,
idle_timeout = IdleTimeout,
hibernate = Hibernate,
start_ts = erlang:system_time(millisecond)
},
PingOpts = maps:from_list(key_value:get(ping, Opts, [])),
State = maybe_enable_ping(PingOpts, State0),
opening a connection and authenticating at least one session . Having
Actions = [auth_timeout(State)],
{ok, active, State, Actions}.
terminate({shutdown, Info}, StateName, #state{socket = undefined} = State) ->
ok = remove_all_registry_entries(State),
?LOG_INFO(Info#{
state_name => StateName
}),
ok;
terminate(Reason, StateName, #state{socket = undefined} = State) ->
ok = remove_all_registry_entries(State),
?LOG_INFO(#{
description => "Closing connection",
reason => Reason,
state_name => StateName
}),
ok;
terminate(Reason, StateName, #state{} = State) ->
Transport = State#state.transport,
Socket = State#state.socket,
catch Transport:close(Socket),
terminate(Reason, StateName, State#state{socket = undefined}).
code_change(_OldVsn, StateName, StateData, _Extra) ->
{ok, StateName, StateData}.
active(enter, active, State) ->
Ref = State#state.ranch_ref,
Transport = State#state.transport,
TLSOpts = bondy_config:get([Ref, tls_opts], []),
{ok, Socket} = ranch:handshake(Ref, TLSOpts),
SocketOpts = [
binary,
{packet, 4},
{active, once}
| bondy_config:get([Ref, socket_opts], [])
],
socket by performing the TLS server - side handshake , returning a TLS
ok = Transport:setopts(Socket, SocketOpts),
{ok, Peername} = bondy_utils:peername(Transport, Socket),
PeernameBin = inet_utils:peername_to_binary(Peername),
ok = logger:set_process_metadata(#{
transport => Transport,
peername => PeernameBin,
socket => Socket
}),
ok = on_connect(State),
Actions = [auth_timeout(State)],
{keep_state, State#state{socket = Socket}, Actions};
active(enter, idle, State) ->
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
active(
internal, {hello, Uri, Details}, #state{auth_context = undefined} = State0
) ->
TODO validate Details
?LOG_DEBUG(#{
description => "Got hello",
details => Details
}),
try
Realm = bondy_realm:fetch(Uri),
bondy_realm:allow_connections(Realm)
orelse throw(connections_not_allowed),
State = challenge(Realm, Details, State0),
Actions = [auth_timeout(State)],
{keep_state, State, Actions}
catch
error:{not_found, Uri} ->
Abort = {
abort,
undefined,
no_such_realm,
#{
message => <<"Realm does not exist.">>,
realm => Uri
}
},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:connections_not_allowed = Reason ->
Abort = {abort, undefined, Reason, #{
message => <<"The Realm does not allow user connections ('allow_connections' setting is off). This might be a temporary measure taken by the administrator or the realm is meant to be used only as a Same Sign-on (SSO) realm.">>,
realm => Uri
}},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:{no_authmethod, ReqMethods} ->
Abort = {abort, undefined, no_authmethod, #{
message => <<"The requested authentication methods are not available for this user on this realm.">>,
realm => Uri,
authmethods => ReqMethods
}},
ok = send_message(Abort, State0),
{stop, normal, State0};
throw:{authentication_failed, Reason} ->
Abort = {abort, undefined, authentication_failed, #{
message => <<"Authentication failed.">>,
realm => Uri,
reason => Reason
}},
ok = send_message(Abort, State0),
{stop, normal, State0}
end;
active(internal, {hello, _, _}, #state{} = State) ->
Abort = {abort, undefined, protocol_violation, #{
message => <<"You've sent the HELLO message twice">>
}},
ok = send_message(Abort, State),
{stop, normal, State};
active(internal, {authenticate, Signature, Extra}, State0) ->
TODO validate Details
?LOG_DEBUG(#{
description => "Got authenticate",
signature => Signature,
extra => Extra
}),
try
State = authenticate(<<"cryptosign">>, Signature, Extra, State0),
one authenticate session
Actions = [
{{timeout, auth_timeout}, cancel},
ping_idle_timeout(State)
],
{keep_state, State, Actions}
catch
throw:{authentication_failed, Reason} ->
AuthCtxt = State0#state.auth_context,
RealmUri = bondy_auth:realm_uri(AuthCtxt),
SessionId = bondy_auth:realm_uri(AuthCtxt),
Abort = {abort, SessionId, authentication_failed, #{
message => <<"Authentication failed.">>,
realm_uri => RealmUri,
reason => Reason
}},
ok = send_message(Abort, State0),
{stop, normal, State0}
end;
active(internal, {aae_sync, SessionId, Opts}, State) ->
RealmUri = session_realm(SessionId, State),
ok = full_sync(SessionId, RealmUri, Opts, State),
Finish = {aae_sync, SessionId, finished},
ok = gen_statem:cast(self(), {forward_message, Finish}),
Actions = [ping_idle_timeout(State)],
{keep_state_and_data, Actions};
active(internal, {session_message, SessionId, Msg}, State) ->
?LOG_DEBUG(#{
description => "Got session message from client",
session_id => SessionId,
message => Msg
}),
try
handle_in(Msg, SessionId, State)
catch
throw:Reason:Stacktrace ->
?LOG_ERROR(#{
description => "Unhandled error",
session_id => SessionId,
message => Msg,
class => throw,
reason => Reason,
stacktrace => Stacktrace
}),
Actions = [ping_idle_timeout(State)],
{keep_state_and_data, Actions};
Class:Reason:Stacktrace ->
?LOG_ERROR(#{
description => "Error while handling session message",
session_id => SessionId,
message => Msg,
class => Class,
reason => Reason,
stacktrace => Stacktrace
}),
Abort = {abort, SessionId, server_error, #{
reason => Reason
}},
ok = send_message(Abort, State),
{stop, Reason, State}
end;
active({timeout, auth_timeout}, auth_timeout, _) ->
?LOG_INFO(#{
description => "Closing connection due to authentication timeout.",
reason => auth_timeout
}),
{stop, normal};
active({timeout, ping_idle_timeout}, ping_idle_timeout, State) ->
{next_state, idle, State};
active(EventType, EventContent, State) ->
handle_event(EventType, EventContent, active, State).
idle(enter, active, State) ->
IdleTimeout = State#state.idle_timeout,
PingTimeout = State#state.idle_timeout,
Adjusted = IdleTimeout - PingTimeout,
Time = case Adjusted > 0 of
true -> Adjusted;
false -> IdleTimeout
end,
Actions = [
{state_timeout, Time, idle_timeout}
],
maybe_send_ping(State, Actions);
idle({timeout, ping_idle_timeout}, ping_idle_timeout, State) ->
maybe_send_ping(State);
idle({timeout, ping_timeout}, ping_timeout, State0) ->
State = ping_fail(State0),
maybe_send_ping(State);
idle(state_timeout, idle_timeout, _State) ->
Info = #{
description => "Shutting down connection due to inactivity.",
reason => idle_timeout
},
{stop, {shutdown, Info}};
idle(internal, {pong, Bin}, #state{ping_payload = Bin} = State0) ->
State = ping_succeed(State0),
Actions = [
{{timeout, ping_timeout}, cancel},
ping_idle_timeout(State),
maybe_hibernate(idle, State)
],
{keep_state, State, Actions};
idle(internal, Msg, State) ->
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel},
{next_event, internal, Msg}
],
{next_state, active, State, Actions};
idle(EventType, EventContent, State) ->
handle_event(EventType, EventContent, idle, State).
TODO forward_message or forward ?
handle_event({call, From}, Request, _, _) ->
?LOG_INFO(#{
description => "Received unknown request",
type => call,
event => Request
}),
Actions = [
{reply, From, {error, badcall}}
],
{keep_state_and_data, Actions};
handle_event(cast, {forward_message, Msg}, _, State) ->
ok = send_message(Msg, State),
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel}
],
{next_state, active, State, Actions};
handle_event(internal, {ping, Data}, _, State) ->
ok = send_message({pong, Data}, State),
keep_state_and_data;
handle_event(info, {?BONDY_REQ, Pid, RealmUri, M}, _, State) ->
A local : send ( ) , we need to forward to client
?LOG_DEBUG(#{
description => "Received WAMP request we need to FWD to client",
message => M
}),
handle_out(M, RealmUri, Pid, State);
handle_event(info, {Tag, Socket, Data}, _, #state{socket = Socket} = State)
when ?SOCKET_DATA(Tag) ->
ok = set_socket_active(State),
try binary_to_term(Data) of
Msg ->
?LOG_DEBUG(#{
description => "Received message from client",
reason => Msg
}),
Actions = [
{next_event, internal, Msg}
],
{keep_state, State, Actions}
catch
Class:Reason ->
Info = #{
description => "Received invalid data from client.",
data => Data,
class => Class,
reason => Reason
},
{stop, {shutdown, Info}}
end;
handle_event(info, {Tag, _Socket}, _, _) when ?CLOSED_TAG(Tag) ->
?LOG_INFO(#{
description => "Connection closed by client."
}),
{stop, normal};
handle_event(info, {Tag, _, Reason}, _, _) when ?SOCKET_ERROR(Tag) ->
?LOG_INFO(#{
description => "Connection closed due to error.",
reason => Reason
}),
{stop, Reason};
handle_event(EventType, EventContent, StateName, _) ->
?LOG_INFO(#{
description => "Received unknown message.",
type => EventType,
event => EventContent,
state_name => StateName
}),
keep_state_and_data.
@private
challenge(Realm, Details, State0) ->
{ok, Peer} = bondy_utils:peername(
State0#state.transport, State0#state.socket
),
SessionId = bondy_session_id:new(),
Authid = maps:get(authid, Details),
Authroles0 = maps:get(authroles, Details, []),
case bondy_auth:init(SessionId, Realm, Authid, Authroles0, Peer) of
{ok, AuthCtxt} ->
TODO take it from conf
ReqMethods = [<<"cryptosign">>],
case bondy_auth:available_methods(ReqMethods, AuthCtxt) of
[] ->
throw({no_authmethod, ReqMethods});
[Method|_] ->
Uri = bondy_realm:uri(Realm),
FinalAuthid = bondy_auth:user_id(AuthCtxt),
Authrole = bondy_auth:role(AuthCtxt),
Authroles = bondy_auth:roles(AuthCtxt),
Authprovider = bondy_auth:provider(AuthCtxt),
SecEnabled = bondy_realm:is_security_enabled(Realm),
Properties = #{
type => bridge_relay,
peer => Peer,
security_enabled => SecEnabled,
is_anonymous => FinalAuthid == anonymous,
agent => bondy_router:agent(),
roles => maps:get(roles, Details, undefined),
authid => maybe_gen_authid(FinalAuthid),
authprovider => Authprovider,
authmethod => Method,
authrole => Authrole,
authroles => Authroles
},
Session = bondy_session:new(Uri, Properties),
Sessions0 = State0#state.sessions,
Sessions = maps:put(SessionId, Session, Sessions0),
SessionsByUri0 = State0#state.sessions_by_realm,
SessionsByUri = maps:put(Uri, SessionId, SessionsByUri0),
State = State0#state{
auth_context = AuthCtxt,
sessions = Sessions,
sessions_by_realm = SessionsByUri
},
send_challenge(Details, Method, State)
end;
{error, Reason0} ->
throw({authentication_failed, Reason0})
end.
@private
send_challenge(Details, Method, State0) ->
AuthCtxt0 = State0#state.auth_context,
{Reply, State} =
case bondy_auth:challenge(Method, Details, AuthCtxt0) of
{false, _} ->
exit(invalid_authmethod);
{true, ChallengeExtra, AuthCtxt1} ->
M = {challenge, Method, ChallengeExtra},
{M, State0#state{auth_context = AuthCtxt1}};
{error, Reason} ->
throw({authentication_failed, Reason})
end,
ok = send_message(Reply, State),
State.
@private
authenticate(AuthMethod, Signature, Extra, State0) ->
AuthCtxt0 = State0#state.auth_context,
case bondy_auth:authenticate(AuthMethod, Signature, Extra, AuthCtxt0) of
{ok, AuthExtra0, _} ->
SessionId = bondy_auth:session_id(AuthCtxt0),
Session = session(SessionId, State0),
ok = bondy_session_manager:open(Session),
AuthExtra = AuthExtra0#{node => bondy_config:nodestring()},
M = {welcome, SessionId, #{authextra => AuthExtra}},
State = State0#state{auth_context = undefined},
ok = send_message(M, State),
State;
{error, Reason} ->
throw({authentication_failed, Reason})
end.
@private
set_socket_active(State) ->
(State#state.transport):setopts(State#state.socket, [{active, once}]).
@private
send_message(Message, State) ->
?LOG_DEBUG(#{description => "sending message", message => Message}),
Data = term_to_binary(Message),
(State#state.transport):send(State#state.socket, Data).
@private
on_connect(_State) ->
?LOG_INFO(#{
description => "Established connection with client router."
}),
ok.
@private
handle_in({registration_created, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_added, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_removed, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({registration_deleted, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_created, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_added, Entry}, SessionId, State0) ->
State = add_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_removed, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({subscription_deleted, Entry}, SessionId, State0) ->
State = remove_registry_entry(SessionId, Entry, State0),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state, State, Actions};
handle_in({forward, _, #publish{} = M, _Opts}, SessionId, State) ->
RealmUri = session_realm(SessionId, State),
ReqId = M#publish.request_id,
TopicUri = M#publish.topic_uri,
Args = M#publish.args,
KWArg = M#publish.kwargs,
Opts0 = M#publish.options,
Opts = Opts0#{exclude_me => true},
Ref = session_ref(SessionId, State),
Job = fun() ->
Ctxt = bondy_context:local_context(RealmUri, Ref),
bondy_broker:publish(ReqId, Opts, TopicUri, Args, KWArg, Ctxt)
end,
case bondy_router_worker:cast(Job) of
ok ->
ok;
{error, overload} ->
TODO return proper return ... but we should move this to router
error(overload)
end,
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
handle_in({forward, To, Msg, Opts}, SessionId, State) ->
b ) a pool of relays ( selecting one by hashing { CallerID , CalleeId } ) and
RealmUri = session_realm(SessionId, State),
Fwd = fun() ->
bondy_router:forward(Msg, To, Opts#{realm_uri => RealmUri})
end,
case bondy_router_worker:cast(Fwd) of
ok ->
ok;
{error, overload} ->
TODO return proper return ... but we should move this to router
error(overload)
end,
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions};
handle_in(Other, SessionId, State) ->
?LOG_INFO(#{
description => "Unhandled message",
session_id => SessionId,
message => Other
}),
Actions = [
ping_idle_timeout(State),
maybe_hibernate(active, State)
],
{keep_state_and_data, Actions}.
@private
handle_out(#goodbye{} = M, RealmUri, _From, State) ->
Details = M#goodbye.details,
ReasonUri = M#goodbye.reason_uri,
SessionId = session_id(RealmUri, State),
ControlMsg = {goodbye, SessionId, ReasonUri, Details},
ok = send_message(ControlMsg, State),
{stop, normal};
handle_out(M, RealmUri, _From, State) ->
SessionId = session_id(RealmUri, State),
ok = send_message({session_message, SessionId, M}, State),
Actions = [
{{timeout, ping_timeout}, cancel},
{{timeout, ping_idle_timeout}, cancel}
],
{next_state, active, State, Actions}.
@private
add_registry_entry(SessionId, ExtEntry, State) ->
Ref = session_ref(SessionId, State),
ProxyEntry = bondy_registry_entry:proxy(Ref, ExtEntry),
Id = bondy_registry_entry:id(ProxyEntry),
OriginId = bondy_registry_entry:origin_id(ProxyEntry),
case bondy_registry:add(ProxyEntry) of
{ok, _} ->
Index0 = State#state.registrations,
Index = key_value:put([SessionId, OriginId], Id, Index0),
State#state{registrations = Index};
{error, already_exists} ->
ok
end.
@private
remove_registry_entry(SessionId, ExtEntry, State) ->
Index0 = State#state.registrations,
OriginId = maps:get(entry_id, ExtEntry),
Type = maps:get(type, ExtEntry),
try key_value:get([SessionId, OriginId], Index0) of
ProxyId ->
TODO get from session once we have real sessions
RealmUri = session_realm(SessionId, State),
Node = bondy_config:node(),
Ctxt = #{
realm_uri => RealmUri,
node => Node,
session_id => SessionId
},
ok = bondy_registry:remove(Type, ProxyId, Ctxt),
Index = key_value:remove([SessionId, OriginId], Index0),
State#state{registrations = Index}
catch
error:badkey ->
State
end.
remove_all_registry_entries(State) ->
maps:foreach(
fun(_, Session) ->
RealmUri = bondy_session:realm_uri(Session),
Ref = bondy_session:ref(Session),
bondy_router:flush(RealmUri, Ref)
end,
State#state.sessions
).
@private
full_sync(SessionId, RealmUri, Opts, State) ->
Realm = bondy_realm:fetch(RealmUri),
If the realm has a prototype we sync the prototype first
case bondy_realm:prototype_uri(Realm) of
undefined ->
ok;
ProtoUri ->
full_sync(SessionId, ProtoUri, Opts, State)
end,
TODO However , we should sync a projection of the SSO Realm , the realm
ALSO we are currently copying the CRA passwords which we should n't
ok = do_full_sync(SessionId, RealmUri, Opts, State).
@private
do_full_sync(SessionId, RealmUri, _Opts, _State0) ->
Me = self(),
Prefixes = [
AAE hash comparison .
{?PLUM_DB_REALM_TAB, RealmUri},
{?PLUM_DB_GROUP_TAB, RealmUri},
( e.g. )
{?PLUM_DB_USER_TAB, RealmUri},
{?PLUM_DB_SOURCE_TAB, RealmUri},
{?PLUM_DB_USER_GRANT_TAB, RealmUri},
{?PLUM_DB_GROUP_GRANT_TAB, RealmUri}
{ ? , RealmUri } ,
],
_ = lists:foreach(
fun(Prefix) ->
lists:foreach(
fun(Obj0) ->
Obj = prepare_object(Obj0),
Msg = {aae_data, SessionId, Obj},
gen_statem:cast(Me, {forward_message, Msg})
end,
pdb_objects(Prefix)
)
end,
Prefixes
),
ok.
@private
prepare_object(Obj) ->
case bondy_realm:is_type(Obj) of
true ->
and decide on Key management strategies .
bondy_realm:strip_private_keys(Obj);
false ->
Obj
end.
pdb_objects(FullPrefix) ->
It = plum_db:iterator(FullPrefix, []),
try
pdb_objects(It, [])
catch
{break, Result} -> Result
after
ok = plum_db:iterator_close(It)
end.
@private
pdb_objects(It, Acc0) ->
case plum_db:iterator_done(It) of
true ->
Acc0;
false ->
Acc = [plum_db:iterator_element(It) | Acc0],
pdb_objects(plum_db:iterate(It), Acc)
end.
@private
session(SessionId, #state{sessions = Map}) ->
maps:get(SessionId, Map).
@private
session_realm(SessionId, #state{sessions = Map}) ->
bondy_session:realm_uri(maps:get(SessionId, Map)).
@private
session_ref(SessionId, #state{sessions = Map}) ->
bondy_session:ref(maps:get(SessionId, Map)).
@private
session_id(RealmUri, #state{sessions_by_realm = Map}) ->
maps:get(RealmUri, Map).
@private
maybe_gen_authid(anonymous) ->
bondy_utils:uuid();
maybe_gen_authid(UserId) ->
UserId.
@private
maybe_enable_ping(#{enabled := true} = PingOpts, State) ->
IdleTimeout = maps:get(idle_timeout, PingOpts),
Timeout = maps:get(timeout, PingOpts),
Attempts = maps:get(max_attempts, PingOpts),
Retry = bondy_retry:init(
ping_timeout,
#{
interval => Timeout,
max_retries => Attempts,
backoff_enabled => false
}
),
State#state{
ping_idle_timeout = IdleTimeout,
ping_payload = bondy_utils:generate_fragment(16),
ping_retry = Retry
};
maybe_enable_ping(#{enabled := false}, State) ->
State.
@private
ping_succeed(#state{ping_retry = undefined} = State) ->
State;
ping_succeed(#state{} = State) ->
{_, Retry} = bondy_retry:succeed(State#state.ping_retry),
State#state{ping_retry = Retry}.
@private
ping_fail(#state{ping_retry = undefined} = State) ->
State;
ping_fail(#state{} = State) ->
{_, Retry} = bondy_retry:fail(State#state.ping_retry),
State#state{ping_retry = Retry}.
@private
maybe_send_ping(State) ->
maybe_send_ping(State, []).
@private
maybe_send_ping(#state{ping_retry = undefined} = State, Actions0) ->
Actions = [
maybe_hibernate(idle, State) | Actions0
],
{keep_state_and_data, Actions};
maybe_send_ping(#state{} = State, Actions0) ->
case bondy_retry:get(State#state.ping_retry) of
Time when is_integer(Time) ->
Bin = State#state.ping_payload,
ok = send_message({ping, Bin}, State),
Actions = [
ping_timeout(Time),
maybe_hibernate(idle, State)
| Actions0
],
{keep_state, State, Actions};
Limit when Limit == deadline orelse Limit == max_retries ->
Info = #{
description => "Client router has not responded to our ping on time. Shutting down.",
reason => ping_timeout
},
{stop, {shutdown, Info}, State}
end.
@private
ping_idle_timeout(State) ->
Time = State#state.ping_idle_timeout,
{{timeout, ping_idle_timeout}, Time, ping_idle_timeout}.
@private
ping_timeout(Time) ->
{{timeout, ping_timeout}, Time, ping_timeout}.
@private
auth_timeout(State) ->
Time = State#state.auth_timeout,
{{timeout, auth_timeout}, Time, auth_timeout}.
@private
maybe_hibernate(_, #state{hibernate = never}) ->
{hibernate, false};
maybe_hibernate(_, #state{hibernate = always}) ->
{hibernate, true};
maybe_hibernate(StateName, #state{hibernate = idle}) ->
{hibernate, StateName == idle}. |
99c02ea2cd8be4ab766abfc526d9c894ac516ace804672287545f3cb54781b71 | quoll/life | core.cljc | (ns life.core
(:require [clojure.core.matrix :refer [emap reshape array rotate add]]
[life.matrix :refer [nbool takeof and* or* =x power-limit]]
[clojure.core.matrix.operators :as m]
#?(:clj [life.display :refer :all])
#?(:clj [life.pic :refer :all])))
(def init #{1 2 3 4 7})
(def r (emap (nbool init) (reshape (array (range 9)) [3 3])))
(def R (rotate (rotate (takeof [5 7] r) 1 -2) 0 -1))
(def RR (rotate (rotate (takeof [15 35] R) 1 20) 0 10))
(defn life [o]
(apply or*
(map and*
[1 o]
(map (=x (apply add (for [y [1 0 -1] x [1 0 -1]] (rotate (rotate o 1 x) 0 y))))
[3 4]))))
#?(:clj
(defn draw-life [o]
(if (draw (image o))
(Thread/sleep 125)
(System/exit 0))
(life o)))
#?(:clj
(defn -main [& args]
(open-window)
(power-limit draw-life RR)
(inform-exitable)))
| null | https://raw.githubusercontent.com/quoll/life/f6647351990c076bc3e699989ba32293ea009314/src/life/core.cljc | clojure | (ns life.core
(:require [clojure.core.matrix :refer [emap reshape array rotate add]]
[life.matrix :refer [nbool takeof and* or* =x power-limit]]
[clojure.core.matrix.operators :as m]
#?(:clj [life.display :refer :all])
#?(:clj [life.pic :refer :all])))
(def init #{1 2 3 4 7})
(def r (emap (nbool init) (reshape (array (range 9)) [3 3])))
(def R (rotate (rotate (takeof [5 7] r) 1 -2) 0 -1))
(def RR (rotate (rotate (takeof [15 35] R) 1 20) 0 10))
(defn life [o]
(apply or*
(map and*
[1 o]
(map (=x (apply add (for [y [1 0 -1] x [1 0 -1]] (rotate (rotate o 1 x) 0 y))))
[3 4]))))
#?(:clj
(defn draw-life [o]
(if (draw (image o))
(Thread/sleep 125)
(System/exit 0))
(life o)))
#?(:clj
(defn -main [& args]
(open-window)
(power-limit draw-life RR)
(inform-exitable)))
|
|
e0167a95497b8d2f489194b3e1ec6c067275b72f00885e6b15ed948ea44eeb5c | kupl/LearnML | patch.ml | let rec fold (f : 'b -> 'a -> 'a) (l : 'b list) (a : int) =
match l with [] -> a | hd :: tl -> f hd (fold f tl a)
let rec max (lst : int list) : int =
fold
(fun (__s7 : int) (__s8 : int) -> if __s8 >= __s7 then __s8 else __s7)
lst min_int
| null | https://raw.githubusercontent.com/kupl/LearnML/c98ef2b95ef67e657b8158a2c504330e9cfb7700/result/cafe2/max/sub17/patch.ml | ocaml | let rec fold (f : 'b -> 'a -> 'a) (l : 'b list) (a : int) =
match l with [] -> a | hd :: tl -> f hd (fold f tl a)
let rec max (lst : int list) : int =
fold
(fun (__s7 : int) (__s8 : int) -> if __s8 >= __s7 then __s8 else __s7)
lst min_int
|
|
a95c7dd474931aa0356c4fe807528c02b2a2f76e72ea18cf50663b746fc2d41c | shop-planner/shop3 | basic-example.lisp | (in-package :shop-user)
; This extremely simple example shows some of the most essential
features of SHOP2 .
(defdomain basic-example (
(:operator (!pickup ?a) () () ((have ?a)))
(:operator (!drop ?a) ((have ?a)) ((have ?a)) ())
(:method (swap ?x ?y)
((have ?x))
((!drop ?x) (!pickup ?y))
((have ?y))
((!drop ?y) (!pickup ?x)))))
(defproblem problem1 basic-example
((have banjo)) ((swap banjo kiwi)))
(find-plans 'problem1 :verbose :plans)
| null | https://raw.githubusercontent.com/shop-planner/shop3/ba429cf91a575e88f28b7f0e89065de7b4d666a6/shop3/examples/toy/basic-example.lisp | lisp | This extremely simple example shows some of the most essential | (in-package :shop-user)
features of SHOP2 .
(defdomain basic-example (
(:operator (!pickup ?a) () () ((have ?a)))
(:operator (!drop ?a) ((have ?a)) ((have ?a)) ())
(:method (swap ?x ?y)
((have ?x))
((!drop ?x) (!pickup ?y))
((have ?y))
((!drop ?y) (!pickup ?x)))))
(defproblem problem1 basic-example
((have banjo)) ((swap banjo kiwi)))
(find-plans 'problem1 :verbose :plans)
|
0cde820decebe9d74dd9d4ad67a80e0765ce99d17836a907d4d207846507424d | vouillon/osm | table.ml | OSM tools
* Copyright ( C ) 2013
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2013 Jérôme Vouillon
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
let map_incr = 1024 * 1024 * 2
type ('a, 'b) t =
{ ch : Unix.file_descr;
mutable ar : ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t }
let int64 = Bigarray.int64
let int32 = Bigarray.int32
let int = Bigarray.int
let float = Bigarray.float64
let make ?len nm kind =
let flags = [Unix.O_RDWR; Unix.O_CREAT; Unix.O_TRUNC] in
let ch = Unix.openfile nm flags 0o600 in
let l = match len with None -> map_incr | Some l -> l in
{ ch = ch;
ar = Bigarray.array1_of_genarray
(Unix.map_file ch kind Bigarray.c_layout true [|l|]) }
let extend a l =
let l' = ref (Bigarray.Array1.dim a.ar) in
if !l' < l then begin
Format.printf "RESIZE@.";
while !l' < l do l' := !l' + map_incr done;
let kind = Bigarray.Array1.kind a.ar in
let layout = Bigarray.Array1.layout a.ar in
a.ar <- Bigarray.array1_of_genarray
(Unix.map_file a.ch kind layout true [|!l'|])
end
(****)
module A = Bigarray.Array1
type ta = (int, Bigarray.int_elt, Bigarray.c_layout) A.t
type tb = (int, Bigarray.int_elt, Bigarray.c_layout) A.t
let merge a1 b1 i1 l1 a2 b2 i2 l2 (a : ta) (b : tb) i l =
assert (l1 - i1 + l2 - i2 = l - i);
let rec loop i1 v1 i2 v2 i =
(* assert (l1 - i1 + l2 - i2 = l - i);*)
if compare v1 v2 <= 0 then begin
a.{i} <- v1; b.{i} <- b1.{i1};
let i1 = i1 + 1 in
if i1 < l1 then
loop i1 a1.{i1} i2 v2 (i + 1)
else begin
assert (l - i - 1 = l2 - i2);
A.blit (A.sub a2 i2 (l2 - i2)) (A.sub a (i + 1) (l2 - i2));
A.blit (A.sub b2 i2 (l2 - i2)) (A.sub b (i + 1) (l2 - i2))
end
end else begin
a.{i} <- v2; b.{i} <- b2.{i2};
let i2 = i2 + 1 in
if i2 < l2 then
loop i1 v1 i2 a2.{i2} (i + 1)
else begin
assert (l - i - 1 = l1 - i1);
A.blit (A.sub a1 i1 (l1 - i1)) (A.sub a (i + 1) (l1 - i1));
A.blit (A.sub b1 i1 (l1 - i1)) (A.sub b (i + 1) (l1 - i1))
end
end
in
assert (i1 < l1); assert (i2 < l2);
loop i1 a1.{i1} i2 a2.{i2} i
(*
; for j = i to l - 1 do
Format.printf "%Ld " a.{j}
done;
Format.printf "@."
*)
let isort (a1 : ta) (b1 : tb) i1 l1 a2 (b2 : tb) i2 l2 =
assert (l1 - i1 = l2 - i2);
let len = l1 - i1 in
(*
for i = 0 to len - 1 do
Format.printf "%Ld " a1.{i1 + i}
done;
Format.printf "@.";
*)
for i = 0 to len - 1 do
let v = a1.{i1 + i} in
let w = b1.{i1 + i} in
let j = ref (i2 + i) in
while !j > i2 && compare a2.{!j - 1} v > 0 do
a2.{!j} <- a2.{!j - 1};
b2.{!j} <- b2.{!j - 1};
decr j;
done;
a2.{!j} <- v;
b2.{!j} <- w
done
(*
;for i = 0 to len - 1 do
Format.printf "%Ld " a2.{i2 + i}
done;
Format.printf "@."
*)
let cuttoff = 15
let rec sort_rec a1 b1 i1 l1 a2 b2 i2 l2 =
let len = l1 - i1 in
assert (len = l2 - i2);
if len <= cuttoff then
isort a1 b1 i1 l1 a2 b2 i2 l2
else begin
let len = len / 2 in
assert (i1 + 2 * len <= l1);
sort_rec a1 b1 (i1 + len) l1 a2 b2 (i2 + len) l2;
sort_rec a1 b1 i1 (i1 + len) a1 b1 (i1 + len) (i1 + 2 * len);
merge a2 b2 (i2 + len) l2 a1 b1 (i1 + len) (i1 + 2 * len) a2 b2 i2 l2
end
let sort a1 b1 =
let len = A.dim a1 in
assert (A.dim b1 = len);
if len <= cuttoff then
isort a1 b1 0 len a1 b1 0 len
else begin
let len1 = len / 2 in
let len2 = len - len1 in
let a2 = A.create (A.kind a1) (A.layout a1) len2 in
let b2 = A.create (A.kind b1) (A.layout b1) len2 in
sort_rec a1 b1 len1 len a2 b2 0 len2;
sort_rec a1 b1 0 len1 a1 b1 len1 (2 * len1);
merge a2 b2 0 len2 a1 b1 len1 (2 * len1) a1 b1 0 len
end
external sort : ta -> tb -> unit = "sort_bigarrays"
let hash ( a : ta ) =
let len = A.dim a in
let len ' = 2 * len in
let tbl = A.create Bigarray.int Bigarray.c_layout len ' in
A.fill tbl ( -1 ) ;
for i = 0 to len - 1 do
let v = a.{i } in
let h0 = ( ( ( v 1357571L ) ) mod len ' ) in
let h = ref h0 in
let s = ref 1 in
while tbl.{!h } < > -1 do h : = ( ! h + ! s ) mod len ' ; s : = ! s + 1 done ;
( *
if i mod 10000 = 0 then Format.printf " ( % d)@. " i ;
if ! h > h0 then " % d % d % Ld@. " i ( ! h - h0 ) v ;
let hash (a : ta) =
let len = A.dim a in
let len' = 2 * len in
let tbl = A.create Bigarray.int Bigarray.c_layout len' in
A.fill tbl (-1);
for i = 0 to len - 1 do
let v = a.{i} in
let h0 = ((Int64.to_int (Int64.mul v 1357571L)) mod len') in
let h = ref h0 in
let s = ref 1 in
while tbl.{!h} <> -1 do h := (!h + !s) mod len'; s := !s + 1 done;
(*
if i mod 10000 = 0 then Format.printf "(%d)@." i;
if !h > h0 then Format.printf "%d %d %Ld@." i (!h - h0) v;
*)
tbl.{!h} <- i
done;
tbl
let hash_map (tbl : tb) (a : ta) (b : ta) (c : tb) =
let len = A.dim b in
let len' = A.dim tbl in
assert (A.dim c = len);
for i = 0 to len - 1 do
let v = b.{i} in
let h0 = ((Int64.to_int (Int64.mul v 1357571L)) mod len') in
let h = ref h0 in
let s = ref 1 in
while a.{tbl.{!h}} <> v do h := (!h + !s) mod len'; s := !s + 1 done;
c.{i} <- tbl.{!h}
done
*)
| null | https://raw.githubusercontent.com/vouillon/osm/5b06ed6fc6c508b8187209628cf02129a119b50a/database/table.ml | ocaml | **
assert (l1 - i1 + l2 - i2 = l - i);
; for j = i to l - 1 do
Format.printf "%Ld " a.{j}
done;
Format.printf "@."
for i = 0 to len - 1 do
Format.printf "%Ld " a1.{i1 + i}
done;
Format.printf "@.";
;for i = 0 to len - 1 do
Format.printf "%Ld " a2.{i2 + i}
done;
Format.printf "@."
if i mod 10000 = 0 then Format.printf "(%d)@." i;
if !h > h0 then Format.printf "%d %d %Ld@." i (!h - h0) v;
| OSM tools
* Copyright ( C ) 2013
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
* Copyright (C) 2013 Jérôme Vouillon
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
let map_incr = 1024 * 1024 * 2
type ('a, 'b) t =
{ ch : Unix.file_descr;
mutable ar : ('a, 'b, Bigarray.c_layout) Bigarray.Array1.t }
let int64 = Bigarray.int64
let int32 = Bigarray.int32
let int = Bigarray.int
let float = Bigarray.float64
let make ?len nm kind =
let flags = [Unix.O_RDWR; Unix.O_CREAT; Unix.O_TRUNC] in
let ch = Unix.openfile nm flags 0o600 in
let l = match len with None -> map_incr | Some l -> l in
{ ch = ch;
ar = Bigarray.array1_of_genarray
(Unix.map_file ch kind Bigarray.c_layout true [|l|]) }
let extend a l =
let l' = ref (Bigarray.Array1.dim a.ar) in
if !l' < l then begin
Format.printf "RESIZE@.";
while !l' < l do l' := !l' + map_incr done;
let kind = Bigarray.Array1.kind a.ar in
let layout = Bigarray.Array1.layout a.ar in
a.ar <- Bigarray.array1_of_genarray
(Unix.map_file a.ch kind layout true [|!l'|])
end
module A = Bigarray.Array1
type ta = (int, Bigarray.int_elt, Bigarray.c_layout) A.t
type tb = (int, Bigarray.int_elt, Bigarray.c_layout) A.t
let merge a1 b1 i1 l1 a2 b2 i2 l2 (a : ta) (b : tb) i l =
assert (l1 - i1 + l2 - i2 = l - i);
let rec loop i1 v1 i2 v2 i =
if compare v1 v2 <= 0 then begin
a.{i} <- v1; b.{i} <- b1.{i1};
let i1 = i1 + 1 in
if i1 < l1 then
loop i1 a1.{i1} i2 v2 (i + 1)
else begin
assert (l - i - 1 = l2 - i2);
A.blit (A.sub a2 i2 (l2 - i2)) (A.sub a (i + 1) (l2 - i2));
A.blit (A.sub b2 i2 (l2 - i2)) (A.sub b (i + 1) (l2 - i2))
end
end else begin
a.{i} <- v2; b.{i} <- b2.{i2};
let i2 = i2 + 1 in
if i2 < l2 then
loop i1 v1 i2 a2.{i2} (i + 1)
else begin
assert (l - i - 1 = l1 - i1);
A.blit (A.sub a1 i1 (l1 - i1)) (A.sub a (i + 1) (l1 - i1));
A.blit (A.sub b1 i1 (l1 - i1)) (A.sub b (i + 1) (l1 - i1))
end
end
in
assert (i1 < l1); assert (i2 < l2);
loop i1 a1.{i1} i2 a2.{i2} i
let isort (a1 : ta) (b1 : tb) i1 l1 a2 (b2 : tb) i2 l2 =
assert (l1 - i1 = l2 - i2);
let len = l1 - i1 in
for i = 0 to len - 1 do
let v = a1.{i1 + i} in
let w = b1.{i1 + i} in
let j = ref (i2 + i) in
while !j > i2 && compare a2.{!j - 1} v > 0 do
a2.{!j} <- a2.{!j - 1};
b2.{!j} <- b2.{!j - 1};
decr j;
done;
a2.{!j} <- v;
b2.{!j} <- w
done
let cuttoff = 15
let rec sort_rec a1 b1 i1 l1 a2 b2 i2 l2 =
let len = l1 - i1 in
assert (len = l2 - i2);
if len <= cuttoff then
isort a1 b1 i1 l1 a2 b2 i2 l2
else begin
let len = len / 2 in
assert (i1 + 2 * len <= l1);
sort_rec a1 b1 (i1 + len) l1 a2 b2 (i2 + len) l2;
sort_rec a1 b1 i1 (i1 + len) a1 b1 (i1 + len) (i1 + 2 * len);
merge a2 b2 (i2 + len) l2 a1 b1 (i1 + len) (i1 + 2 * len) a2 b2 i2 l2
end
let sort a1 b1 =
let len = A.dim a1 in
assert (A.dim b1 = len);
if len <= cuttoff then
isort a1 b1 0 len a1 b1 0 len
else begin
let len1 = len / 2 in
let len2 = len - len1 in
let a2 = A.create (A.kind a1) (A.layout a1) len2 in
let b2 = A.create (A.kind b1) (A.layout b1) len2 in
sort_rec a1 b1 len1 len a2 b2 0 len2;
sort_rec a1 b1 0 len1 a1 b1 len1 (2 * len1);
merge a2 b2 0 len2 a1 b1 len1 (2 * len1) a1 b1 0 len
end
external sort : ta -> tb -> unit = "sort_bigarrays"
let hash ( a : ta ) =
let len = A.dim a in
let len ' = 2 * len in
let tbl = A.create Bigarray.int Bigarray.c_layout len ' in
A.fill tbl ( -1 ) ;
for i = 0 to len - 1 do
let v = a.{i } in
let h0 = ( ( ( v 1357571L ) ) mod len ' ) in
let h = ref h0 in
let s = ref 1 in
while tbl.{!h } < > -1 do h : = ( ! h + ! s ) mod len ' ; s : = ! s + 1 done ;
( *
if i mod 10000 = 0 then Format.printf " ( % d)@. " i ;
if ! h > h0 then " % d % d % Ld@. " i ( ! h - h0 ) v ;
let hash (a : ta) =
let len = A.dim a in
let len' = 2 * len in
let tbl = A.create Bigarray.int Bigarray.c_layout len' in
A.fill tbl (-1);
for i = 0 to len - 1 do
let v = a.{i} in
let h0 = ((Int64.to_int (Int64.mul v 1357571L)) mod len') in
let h = ref h0 in
let s = ref 1 in
while tbl.{!h} <> -1 do h := (!h + !s) mod len'; s := !s + 1 done;
tbl.{!h} <- i
done;
tbl
let hash_map (tbl : tb) (a : ta) (b : ta) (c : tb) =
let len = A.dim b in
let len' = A.dim tbl in
assert (A.dim c = len);
for i = 0 to len - 1 do
let v = b.{i} in
let h0 = ((Int64.to_int (Int64.mul v 1357571L)) mod len') in
let h = ref h0 in
let s = ref 1 in
while a.{tbl.{!h}} <> v do h := (!h + !s) mod len'; s := !s + 1 done;
c.{i} <- tbl.{!h}
done
*)
|
4423bc9fc78a96fe44a07b197a2961b1817827005d461c2c5267766c0f03abf2 | webnf/webnf | base.cljs | (ns webnf.mui.base
(:require
[om.core :as om]))
(defn state-setter [owner key]
(fn [e]
(om/set-state! owner key (.. e -target -value))))
| null | https://raw.githubusercontent.com/webnf/webnf/6a2ccaa755e6e40528eb13a5c36bae16ba4947e7/cljs/src/webnf/mui/base.cljs | clojure | (ns webnf.mui.base
(:require
[om.core :as om]))
(defn state-setter [owner key]
(fn [e]
(om/set-state! owner key (.. e -target -value))))
|
|
670323529ac8c36bb50a1295a04cf06cc333e622b96b55152188cb28af77de4a | UU-ComputerScience/uhc | mod1.hs | -- import single export
module Main
where
import Imp1.Exp1
i2 = i1
main = i2
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/regress/20/mod1.hs | haskell | import single export |
module Main
where
import Imp1.Exp1
i2 = i1
main = i2
|
211c3f98fc2cea06c46364da885694688039043f4cb2c9ca16a58047351ba528 | techascent/tvm-clj | node.clj | (ns tvm-clj.impl.node
(:require [tvm-clj.impl.base :refer [make-tvm-jna-fn
device-type->int
device-id->int
ptr-ptr
check-call
->long-ptr
datatype->dl-datatype
int-ptr
long-ptr
global-function
tvm-value->jvm]
:as jna-base]
[tvm-clj.impl.typenames :as typenames]
[tvm-clj.impl.protocols :as bindings-proto]
[tech.v3.jna :refer [checknil] :as jna]
[tech.v3.resource :as resource]
;;Force generation of global functions
[tvm-clj.impl.fns.node :as node-fns]
[tvm-clj.impl.fns.runtime :as runtime]
[tech.v3.datatype :as dtype]
[tech.v3.datatype.protocols :as dtype-proto]
[clojure.tools.logging :as log])
(:import [com.sun.jna Native NativeLibrary Pointer Function Platform]
[com.sun.jna.ptr PointerByReference IntByReference LongByReference]
[java.util Map List RandomAccess]
[java.io Writer]
[tech.v3.datatype ObjectReader ObjectWriter]
[clojure.lang MapEntry IFn IObj]))
(set! *warn-on-reflection* true)
(defmulti get-extended-node-value
"Override this to enable type-specific lookups into nodes."
(fn [node-handle item-key]
(bindings-proto/node-type-name node-handle)))
(defmethod get-extended-node-value :default
[& args]
nil)
(defn get-node-fields
[node]
(resource/stack-resource-context
(let [field-fn (node-fns/NodeListAttrNames node)]
(vec (for [idx (range (field-fn -1))]
(field-fn idx))))))
(defn get-node-field
[node field-name]
(node-fns/NodeGetAttr node field-name))
(make-tvm-jna-fn TVMObjectGetTypeIndex
"Get the type index of a node."
Integer
[node-hdl checknil]
[out_index int-ptr])
(defn get-node-type-index
[^Pointer handle]
(let [node-type-data (IntByReference.)]
(check-call
(TVMObjectGetTypeIndex handle node-type-data))
(.getValue node-type-data)))
(make-tvm-jna-fn TVMObjectTypeKey2Index
"Convert a type name to a type index."
Integer
[type_key jna/string->ptr]
[out_index int-ptr])
(defn- node-type-name->index
"Convert a node type name to an index."
[^String type-name]
(let [int-data (IntByReference.)]
(check-call (TVMObjectTypeKey2Index type-name int-data))
(.getValue int-data)))
(defonce node-type-index->name*
(delay
(->> typenames/typenames
(map (fn [tname]
(try
[
(long (node-type-name->index tname))
tname
]
(catch Exception e
(log/warnf "Failed to find type index for name %s" tname)))))
(remove nil?)
(into {}))))
(declare construct-node-handle)
(deftype NodeHandle [^Pointer handle fields metadata]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this]
(let [retval [(Pointer/nativeValue handle)
(if (:rvalue-reference? metadata)
:object-rvalue-ref-arg
:node-handle)]]
retval))
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
dtype-proto/PElemwiseDatatype
(elemwise-datatype [item] (-> (.getOrDefault item :dtype "object")
(keyword)))
dtype-proto/PShape
(shape [item] (:shape item))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
Long/hashCode))
(toString [this] (node-fns/AsRepr this))
Map
(containsKey [item k] (boolean (contains? fields k)))
(entrySet [this]
(->> (.iterator this)
iterator-seq
set))
(get [this obj-key]
(if (contains? fields obj-key)
(get-node-field this (if (string? obj-key)
obj-key
(name obj-key)))
(throw (Exception. (format "Failed to get node value: %s" obj-key)))))
(getOrDefault [item obj-key obj-default-value]
(if (contains? fields obj-key)
(.get item obj-key)
obj-default-value))
(isEmpty [this] (= 0 (.size this)))
(keySet [this] fields)
(size [this] (count fields))
(values [this] (map #(.get this %) fields))
Iterable
(iterator [this]
(.iterator ^Iterable (map #(MapEntry. % (.get this %)) fields)))
IObj
(meta [this] metadata)
(withMeta [this newmeta]
(NodeHandle. handle fields newmeta))
IFn
(invoke [this arg]
(if (and (keyword? arg)
(contains? fields arg))
(.get this arg)
(get-extended-node-value this arg)))
(applyTo [this arglist]
(if (= 1 (count arglist))
(.invoke this (first arglist))
(throw (Exception. "Too many arguments to () operator")))))
(defn is-node-handle?
[item]
(bindings-proto/is-node-handle? item))
(make-tvm-jna-fn TVMObjectFree
"Free a tvm node."
Integer
[handle checknil])
(deftype ArrayHandle [handle num-items]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this] [(Pointer/nativeValue handle) :node-handle])
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
Long/hashCode))
(toString [this] (node-fns/AsRepr this))
ObjectReader
(lsize [this] num-items)
(readObject [this idx]
(node-fns/ArrayGetItem this idx)))
(defn get-map-items
[handle]
(->> (node-fns/MapItems handle)
(partition 2)
(map (fn [[k v]]
(MapEntry. k v)))))
(deftype MapHandle [handle]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this] [(Pointer/nativeValue handle) :node-handle])
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Map
(containsKey [item k] (not= 0 (node-fns/MapCount item (bindings-proto/->node k))))
(entrySet [this]
(->> (.iterator this)
iterator-seq
set))
(get [this obj-key]
(let [key-node (bindings-proto/->node obj-key)]
(when (.containsKey this key-node)
(node-fns/MapGetItem this key-node))))
(getOrDefault [item obj-key obj-default-value]
(if (.containsKey item obj-key)
(.get item obj-key)
obj-default-value))
(isEmpty [this] (= 0 (.size this)))
(keySet [this] (->> (map first (get-map-items this))
set))
(size [this] (int (node-fns/MapSize this)))
(values [this] (map second this))
Iterable
(iterator [this]
(.iterator ^Iterable (get-map-items this)))
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
long
(Long/hashCode)))
(toString [this] (node-fns/AsRepr this))
IFn
(invoke [this arg] (.get this arg))
(applyTo [this arglist]
(if (= 1 (count arglist))
(.invoke this (first arglist))
(throw (Exception. "Too many arguments to () operator")))))
(defmethod print-method NodeHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmethod print-method ArrayHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmethod print-method MapHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmulti construct-node
(fn [ptr]
(-> (NodeHandle. ptr #{} nil)
(bindings-proto/node-type-name))))
(defmethod construct-node :default
[ptr]
(NodeHandle. ptr (try (->> (NodeHandle. ptr #{} nil)
(get-node-fields)
(map keyword)
set)
(catch Exception e
(log/warnf e "Failed to get node fields")
#{}
))
nil))
(defmethod construct-node "Array"
[ptr]
(let [init-handle (NodeHandle. ptr #{} nil)
node-size (long (node-fns/ArraySize init-handle))]
(ArrayHandle. ptr node-size)))
(defmethod construct-node "Map"
[ptr]
(MapHandle. ptr))
(defn tvm-array
"Called when something like a shape needs to be passed into a tvm function. Most users will not need to call this
explicitly; it is done for you."
[& args]
(->> (map bindings-proto/->node args)
(apply node-fns/Array)))
(defn tvm-map
"Create tvm map of values. Works like hash-map."
[& args]
(when-not (= 0 (rem (count args)
2))
(throw (ex-info "Map fn call must have even arg count"
{:args args})))
(->> (map bindings-proto/->node args)
(apply node-fns/Map)))
(defmethod tvm-value->jvm :node-handle
[long-val val-type-kwd]
(let [tptr (Pointer. long-val)
tidx (get-node-type-index tptr)
tname (get @node-type-index->name* tidx)]
(condp = tname
"runtime.String"
(try
(runtime/GetFFIString (NodeHandle. tptr #{} nil))
(finally (do #_(println (format "freeing string 0x%016X" long-val))
(TVMObjectFree tptr))))
"IntImm"
(try (get-node-field (NodeHandle. tptr #{} nil) "value")
(finally (TVMObjectFree tptr)))
"FloatImm"
(try (get-node-field (NodeHandle. tptr #{} nil) "value")
(finally (TVMObjectFree tptr)))
(-> (construct-node (Pointer. long-val))
(resource/track {:track-type :auto
:dispose-fn #(do
#_(println (format "Freeing object 0x%016X" long-val))
(TVMObjectFree (Pointer. long-val)))})))))
(defmethod tvm-value->jvm :object-rvalue-ref-arg
[long-val val-type-kwd]
(let [tptr (Pointer. long-val)
tidx (get-node-type-index tptr)
tname (get @node-type-index->name* tidx)]
;;Like a regular node except we do not free these nodes
;;We do not free rvalue nodes coming from other places.
(condp = tname
"runtime.String"
(runtime/GetFFIString (NodeHandle. tptr #{} nil))
(let [
ndata
(-> (NodeHandle. (Pointer. long-val) #{} nil)
(vary-meta assoc :rvalue-reference? true))]
ndata))))
(extend-protocol bindings-proto/PJVMTypeToTVMValue
Object
(->tvm-value [value]
(cond
(sequential? value)
(bindings-proto/->tvm-value (apply tvm-array value))
(map? value)
(bindings-proto/->tvm-value (apply tvm-map (->> (seq value)
(apply concat))))
(fn? value)
(let [data
(resource/track
(jna-base/clj-fn->tvm-fn value)
{:track-type :stack})]
(bindings-proto/->tvm-value data))
(nil? value)
[(long 0) :null])))
(defn ->dtype
^String [dtype-or-name]
(cond
(keyword? dtype-or-name)
(name dtype-or-name)
(string? dtype-or-name)
dtype-or-name
;;punt if it is already a node
(instance? NodeHandle dtype-or-name)
dtype-or-name
:else
(throw (ex-info (format "Invalid datatype detected: %s" dtype-or-name)
{:dtype dtype-or-name}))))
(defonce ^:private _const-fnptr* (delay (jna-base/name->global-function "node._const")))
(defn const
"Convert an item to a const (immediate) value"
[numeric-value & [dtype]]
(let [dtype (->dtype (or dtype (dtype/datatype numeric-value)))
[long-val _ntype] (jna-base/raw-call-function @_const-fnptr* numeric-value dtype)]
(construct-node (Pointer. long-val))))
(defonce str-fn* (delay (jna-base/name->global-function "runtime.String")))
(extend-protocol bindings-proto/PConvertToNode
Boolean
(->node [item] (const item "uint1x1"))
Byte
(->node [item] (const item "int8"))
Short
(->node [item] (const item "int16"))
Integer
(->node [item] (const item "int32"))
Long
(->node [item] (const item "int64"))
Float
(->node [item] (const item "float32"))
Double
(->node [item] (const item "float64"))
RandomAccess
(->node [item] (apply tvm-array (map bindings-proto/->node item)))
Map
(->node [item] (apply tvm-map (apply concat item)))
String
(->node [item]
(let [[long-val _ntype] (jna-base/raw-call-function @str-fn* item)]
(NodeHandle. (Pointer. (long long-val)) #{} nil)))
Object
(->node [item]
(cond
(instance? Iterable item)
(apply tvm-array (map bindings-proto/->node item))
:else
(throw (Exception. (format "Object type %s is not convertible to node"
(type item)))))))
| null | https://raw.githubusercontent.com/techascent/tvm-clj/1088845bd613b4ba14b00381ffe3cdbd3d8b639e/src/tvm_clj/impl/node.clj | clojure | Force generation of global functions
it is done for you."
Like a regular node except we do not free these nodes
We do not free rvalue nodes coming from other places.
punt if it is already a node | (ns tvm-clj.impl.node
(:require [tvm-clj.impl.base :refer [make-tvm-jna-fn
device-type->int
device-id->int
ptr-ptr
check-call
->long-ptr
datatype->dl-datatype
int-ptr
long-ptr
global-function
tvm-value->jvm]
:as jna-base]
[tvm-clj.impl.typenames :as typenames]
[tvm-clj.impl.protocols :as bindings-proto]
[tech.v3.jna :refer [checknil] :as jna]
[tech.v3.resource :as resource]
[tvm-clj.impl.fns.node :as node-fns]
[tvm-clj.impl.fns.runtime :as runtime]
[tech.v3.datatype :as dtype]
[tech.v3.datatype.protocols :as dtype-proto]
[clojure.tools.logging :as log])
(:import [com.sun.jna Native NativeLibrary Pointer Function Platform]
[com.sun.jna.ptr PointerByReference IntByReference LongByReference]
[java.util Map List RandomAccess]
[java.io Writer]
[tech.v3.datatype ObjectReader ObjectWriter]
[clojure.lang MapEntry IFn IObj]))
(set! *warn-on-reflection* true)
(defmulti get-extended-node-value
"Override this to enable type-specific lookups into nodes."
(fn [node-handle item-key]
(bindings-proto/node-type-name node-handle)))
(defmethod get-extended-node-value :default
[& args]
nil)
(defn get-node-fields
[node]
(resource/stack-resource-context
(let [field-fn (node-fns/NodeListAttrNames node)]
(vec (for [idx (range (field-fn -1))]
(field-fn idx))))))
(defn get-node-field
[node field-name]
(node-fns/NodeGetAttr node field-name))
(make-tvm-jna-fn TVMObjectGetTypeIndex
"Get the type index of a node."
Integer
[node-hdl checknil]
[out_index int-ptr])
(defn get-node-type-index
[^Pointer handle]
(let [node-type-data (IntByReference.)]
(check-call
(TVMObjectGetTypeIndex handle node-type-data))
(.getValue node-type-data)))
(make-tvm-jna-fn TVMObjectTypeKey2Index
"Convert a type name to a type index."
Integer
[type_key jna/string->ptr]
[out_index int-ptr])
(defn- node-type-name->index
"Convert a node type name to an index."
[^String type-name]
(let [int-data (IntByReference.)]
(check-call (TVMObjectTypeKey2Index type-name int-data))
(.getValue int-data)))
(defonce node-type-index->name*
(delay
(->> typenames/typenames
(map (fn [tname]
(try
[
(long (node-type-name->index tname))
tname
]
(catch Exception e
(log/warnf "Failed to find type index for name %s" tname)))))
(remove nil?)
(into {}))))
(declare construct-node-handle)
(deftype NodeHandle [^Pointer handle fields metadata]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this]
(let [retval [(Pointer/nativeValue handle)
(if (:rvalue-reference? metadata)
:object-rvalue-ref-arg
:node-handle)]]
retval))
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
dtype-proto/PElemwiseDatatype
(elemwise-datatype [item] (-> (.getOrDefault item :dtype "object")
(keyword)))
dtype-proto/PShape
(shape [item] (:shape item))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
Long/hashCode))
(toString [this] (node-fns/AsRepr this))
Map
(containsKey [item k] (boolean (contains? fields k)))
(entrySet [this]
(->> (.iterator this)
iterator-seq
set))
(get [this obj-key]
(if (contains? fields obj-key)
(get-node-field this (if (string? obj-key)
obj-key
(name obj-key)))
(throw (Exception. (format "Failed to get node value: %s" obj-key)))))
(getOrDefault [item obj-key obj-default-value]
(if (contains? fields obj-key)
(.get item obj-key)
obj-default-value))
(isEmpty [this] (= 0 (.size this)))
(keySet [this] fields)
(size [this] (count fields))
(values [this] (map #(.get this %) fields))
Iterable
(iterator [this]
(.iterator ^Iterable (map #(MapEntry. % (.get this %)) fields)))
IObj
(meta [this] metadata)
(withMeta [this newmeta]
(NodeHandle. handle fields newmeta))
IFn
(invoke [this arg]
(if (and (keyword? arg)
(contains? fields arg))
(.get this arg)
(get-extended-node-value this arg)))
(applyTo [this arglist]
(if (= 1 (count arglist))
(.invoke this (first arglist))
(throw (Exception. "Too many arguments to () operator")))))
(defn is-node-handle?
[item]
(bindings-proto/is-node-handle? item))
(make-tvm-jna-fn TVMObjectFree
"Free a tvm node."
Integer
[handle checknil])
(deftype ArrayHandle [handle num-items]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this] [(Pointer/nativeValue handle) :node-handle])
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
Long/hashCode))
(toString [this] (node-fns/AsRepr this))
ObjectReader
(lsize [this] num-items)
(readObject [this idx]
(node-fns/ArrayGetItem this idx)))
(defn get-map-items
[handle]
(->> (node-fns/MapItems handle)
(partition 2)
(map (fn [[k v]]
(MapEntry. k v)))))
(deftype MapHandle [handle]
bindings-proto/PJVMTypeToTVMValue
(->tvm-value [this] [(Pointer/nativeValue handle) :node-handle])
bindings-proto/PToTVM
(->tvm [this] this)
bindings-proto/PConvertToNode
(->node [this] this)
bindings-proto/PTVMNode
(is-node-handle? [this] true)
(node-type-index [this] (get-node-type-index handle))
(node-type-name [this] (get @node-type-index->name*
(bindings-proto/node-type-index this)
"UnknownTypeName"))
jna/PToPtr
(is-jna-ptr-convertible? [item] true)
(->ptr-backing-store [item] handle)
Map
(containsKey [item k] (not= 0 (node-fns/MapCount item (bindings-proto/->node k))))
(entrySet [this]
(->> (.iterator this)
iterator-seq
set))
(get [this obj-key]
(let [key-node (bindings-proto/->node obj-key)]
(when (.containsKey this key-node)
(node-fns/MapGetItem this key-node))))
(getOrDefault [item obj-key obj-default-value]
(if (.containsKey item obj-key)
(.get item obj-key)
obj-default-value))
(isEmpty [this] (= 0 (.size this)))
(keySet [this] (->> (map first (get-map-items this))
set))
(size [this] (int (node-fns/MapSize this)))
(values [this] (map second this))
Iterable
(iterator [this]
(.iterator ^Iterable (get-map-items this)))
Object
(equals [a b]
(if (nil? b)
false
(= (.hashCode a) (.hashCode b))))
(hashCode [this]
(-> (runtime/ObjectPtrHash this)
long
(Long/hashCode)))
(toString [this] (node-fns/AsRepr this))
IFn
(invoke [this arg] (.get this arg))
(applyTo [this arglist]
(if (= 1 (count arglist))
(.invoke this (first arglist))
(throw (Exception. "Too many arguments to () operator")))))
(defmethod print-method NodeHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmethod print-method ArrayHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmethod print-method MapHandle
[hdl w]
(.write ^Writer w (str hdl)))
(defmulti construct-node
(fn [ptr]
(-> (NodeHandle. ptr #{} nil)
(bindings-proto/node-type-name))))
(defmethod construct-node :default
[ptr]
(NodeHandle. ptr (try (->> (NodeHandle. ptr #{} nil)
(get-node-fields)
(map keyword)
set)
(catch Exception e
(log/warnf e "Failed to get node fields")
#{}
))
nil))
(defmethod construct-node "Array"
[ptr]
(let [init-handle (NodeHandle. ptr #{} nil)
node-size (long (node-fns/ArraySize init-handle))]
(ArrayHandle. ptr node-size)))
(defmethod construct-node "Map"
[ptr]
(MapHandle. ptr))
(defn tvm-array
"Called when something like a shape needs to be passed into a tvm function. Most users will not need to call this
[& args]
(->> (map bindings-proto/->node args)
(apply node-fns/Array)))
(defn tvm-map
"Create tvm map of values. Works like hash-map."
[& args]
(when-not (= 0 (rem (count args)
2))
(throw (ex-info "Map fn call must have even arg count"
{:args args})))
(->> (map bindings-proto/->node args)
(apply node-fns/Map)))
(defmethod tvm-value->jvm :node-handle
[long-val val-type-kwd]
(let [tptr (Pointer. long-val)
tidx (get-node-type-index tptr)
tname (get @node-type-index->name* tidx)]
(condp = tname
"runtime.String"
(try
(runtime/GetFFIString (NodeHandle. tptr #{} nil))
(finally (do #_(println (format "freeing string 0x%016X" long-val))
(TVMObjectFree tptr))))
"IntImm"
(try (get-node-field (NodeHandle. tptr #{} nil) "value")
(finally (TVMObjectFree tptr)))
"FloatImm"
(try (get-node-field (NodeHandle. tptr #{} nil) "value")
(finally (TVMObjectFree tptr)))
(-> (construct-node (Pointer. long-val))
(resource/track {:track-type :auto
:dispose-fn #(do
#_(println (format "Freeing object 0x%016X" long-val))
(TVMObjectFree (Pointer. long-val)))})))))
(defmethod tvm-value->jvm :object-rvalue-ref-arg
[long-val val-type-kwd]
(let [tptr (Pointer. long-val)
tidx (get-node-type-index tptr)
tname (get @node-type-index->name* tidx)]
(condp = tname
"runtime.String"
(runtime/GetFFIString (NodeHandle. tptr #{} nil))
(let [
ndata
(-> (NodeHandle. (Pointer. long-val) #{} nil)
(vary-meta assoc :rvalue-reference? true))]
ndata))))
(extend-protocol bindings-proto/PJVMTypeToTVMValue
Object
(->tvm-value [value]
(cond
(sequential? value)
(bindings-proto/->tvm-value (apply tvm-array value))
(map? value)
(bindings-proto/->tvm-value (apply tvm-map (->> (seq value)
(apply concat))))
(fn? value)
(let [data
(resource/track
(jna-base/clj-fn->tvm-fn value)
{:track-type :stack})]
(bindings-proto/->tvm-value data))
(nil? value)
[(long 0) :null])))
(defn ->dtype
^String [dtype-or-name]
(cond
(keyword? dtype-or-name)
(name dtype-or-name)
(string? dtype-or-name)
dtype-or-name
(instance? NodeHandle dtype-or-name)
dtype-or-name
:else
(throw (ex-info (format "Invalid datatype detected: %s" dtype-or-name)
{:dtype dtype-or-name}))))
(defonce ^:private _const-fnptr* (delay (jna-base/name->global-function "node._const")))
(defn const
"Convert an item to a const (immediate) value"
[numeric-value & [dtype]]
(let [dtype (->dtype (or dtype (dtype/datatype numeric-value)))
[long-val _ntype] (jna-base/raw-call-function @_const-fnptr* numeric-value dtype)]
(construct-node (Pointer. long-val))))
(defonce str-fn* (delay (jna-base/name->global-function "runtime.String")))
(extend-protocol bindings-proto/PConvertToNode
Boolean
(->node [item] (const item "uint1x1"))
Byte
(->node [item] (const item "int8"))
Short
(->node [item] (const item "int16"))
Integer
(->node [item] (const item "int32"))
Long
(->node [item] (const item "int64"))
Float
(->node [item] (const item "float32"))
Double
(->node [item] (const item "float64"))
RandomAccess
(->node [item] (apply tvm-array (map bindings-proto/->node item)))
Map
(->node [item] (apply tvm-map (apply concat item)))
String
(->node [item]
(let [[long-val _ntype] (jna-base/raw-call-function @str-fn* item)]
(NodeHandle. (Pointer. (long long-val)) #{} nil)))
Object
(->node [item]
(cond
(instance? Iterable item)
(apply tvm-array (map bindings-proto/->node item))
:else
(throw (Exception. (format "Object type %s is not convertible to node"
(type item)))))))
|
fc3b0a1a13733421249d07d8c04125902c6d53c164bc96fb21ef7e733a1880ac | aaltodsg/instans | datetime.lisp | -*- Mode : Lisp ; Syntax : COMMON - LISP ; Base : 10 ; Package : INSTANS -*-
;;;
Author : ( )
;;;
(in-package #:instans)
(define-class datetime ()
((time :initarg :time :accessor datetime-time)
(usec :initarg :usec :accessor datetime-usec)
(year :initform nil :initarg :year)
(month :initform nil :initarg :month)
(day :initform nil :initarg :day)
(hours :initform nil :initarg :hours)
(minutes :initform nil :initarg :minutes)
(seconds :initform nil :initarg :seconds)
(tz :initform nil :initarg :tz)
(tz-str :initform nil :initarg :tz-str)))
(defmethod print-object ((this datetime) stream)
(format stream "#<~S ~S>" (type-of this) (datetime-canonic-string this)))
(defun datetime-fill-slots (x)
(multiple-value-bind (seconds minutes hours day month year day-of-week dst tz)
(decode-universal-time (+ (datetime-time x) sb-impl::unix-to-universal-time))
(declare (ignore day-of-week))
(when dst (incf tz))
(setf (slot-value x 'year) year)
(setf (slot-value x 'month) month)
(setf (slot-value x 'day) day)
(setf (slot-value x 'hours) hours)
(setf (slot-value x 'minutes) minutes)
(setf (slot-value x 'seconds) seconds)
(setf (slot-value x 'tz) tz)))
(defmacro define-datetime-lazy-getter (slot-name)
(let ((getter-name (fmt-intern "~A-~A" 'datetime slot-name)))
`(defun ,getter-name (x)
(unless (slot-value x 'year)
(datetime-fill-slots x))
(slot-value x ',slot-name))))
(define-datetime-lazy-getter year)
(define-datetime-lazy-getter month)
(define-datetime-lazy-getter day)
(define-datetime-lazy-getter hours)
(define-datetime-lazy-getter minutes)
(define-datetime-lazy-getter seconds)
(define-datetime-lazy-getter tz)
(defun datetime-tz-string (dt)
(or (slot-value dt 'tz-str)
(let* ((tz (datetime-tz dt))
(tz-str (cond ((or (null tz) (zerop tz)) "")
(t
(multiple-value-bind (tz-h tz-m) (floor (abs tz) 1)
(concatenate 'string (if (< tz 0) "-" "+") (format nil "~2,'0D:~2,'0D" tz-h (* 60 tz-m))))))))
(setf (slot-value dt 'tz-str) tz-str)
tz-str)))
(defun datetime-compare (dt1 dt2)
(let ((ut1 (datetime-time dt1))
(ut2 (datetime-time dt2)))
(cond ((< ut1 ut2) -1)
((> ut1 ut2) 1)
(t
(signum (- (datetime-usec dt1) (datetime-usec dt2)))))))
(defun datetime= (dt1 dt2)
(= (datetime-compare dt1 dt2) 0))
(defun datetime< (dt1 dt2)
(< (datetime-compare dt1 dt2) 0))
(defun datetime<= (dt1 dt2)
(<= (datetime-compare dt1 dt2) 0))
(defun datetime> (dt1 dt2)
(> (datetime-compare dt1 dt2) 0))
(defun datetime>= (dt1 dt2)
(>= (datetime-compare dt1 dt2) 0))
(defun datetime-plain ()
(make-instance 'datetime :time 0 :usec 0))
(defun datetime-now ()
(multiple-value-bind (time-t suseconds-t)
(sb-unix::get-time-of-day)
(make-instance 'datetime :time time-t :usec suseconds-t)))
(defun datetime-from-string (str)
(let (year month day hours minutes seconds usec tz-string tz)
(catch 'parse-error
(let ((strlen (length str))
(error-msg nil)
(current-position 0))
(labels ((looking-at (ch) (and (< current-position strlen) (char= (char str current-position) ch)))
(eat-int (&optional length delim)
(loop with result = 0
with start = current-position
with max = (if (null length) strlen (min strlen (+ start length)))
while (and (< current-position max)
(let ((ch (char str current-position)))
(if (digit-char-p ch)
(progn
(setf result (+ (* 10 result) (+ (- (char-code ch) (char-code #\0)))))
(incf current-position))
nil)))
finally (return (progn
(cond ((null length)
(when (= current-position start) (parse-error "Could not parse an int in ~S starting at index ~D" str start)))
(t
(when (not (= current-position (+ start length))) (parse-error "Could not parse an int of length ~D in ~S starting at index ~D" length str start))))
(when delim (if (looking-at delim) (incf current-position) (parse-error "Missing delimiter '~A' in ~S at ~D" delim str current-position)))
result))))
(parse-error (fmt &rest args)
(setf error-msg (apply #'format nil fmt args))
(throw 'parse-error (values nil error-msg))))
(let* ((year-sign (if (looking-at #\-) (progn (incf current-position) -1) 1))
(cp current-position))
(setf year (eat-int nil #\-))
(when (zerop year) (parse-error "No year zero allowed in ~S" str))
(when (and (> (- current-position cp) 4) (char= (char str cp) #\0))
(parse-error "Leading '0' not allowed in year in ~S" str))
(setf year (* year-sign year)))
(setf month (eat-int 2 #\-))
(setf day (eat-int 2 #\T))
(setf hours (eat-int 2 #\:))
(setf minutes (eat-int 2 #\:))
(setf seconds (eat-int 2))
(cond ((looking-at #\.)
(incf current-position)
(let ((cp current-position))
(setf usec (eat-int))
(loop for i from 1 to (- 6 (- current-position cp))
do (setf usec (* 10 usec)))))
(t
(setf usec 0)))
( setf tz - string ( subseq str current - position ) )
(cond ((< current-position strlen)
(let (tz-sign tz-hours tz-minutes)
(cond ((looking-at #\Z)
(incf current-position)
(setf tz 0)
(setf tz-string "Z"))
((or (looking-at #\+) (looking-at #\-))
(setf tz-sign (if (looking-at #\+) 1 -1))
(incf current-position)
(setf tz-hours (eat-int 2 #\:))
(setf tz-minutes (eat-int 2))
(setf tz (* tz-sign (+ tz-hours (/ tz-minutes 60)))))
(t (parse-error "Illegal timezone in ~S" str)))
(when (< current-position strlen)
(parse-error "Garbage after timezone in ~S" str))))
(t (setf tz nil))))
;;nil
(cond ((null error-msg)
(make-instance 'datetime
:time (- (encode-universal-time seconds minutes hours day month year tz) sb-impl::unix-to-universal-time) :usec usec
:year year :month month :day day :hours hours :minutes minutes :seconds seconds :tz-str tz-string :tz tz))
(t
(list nil error-msg)))
))))
(defun datetime-canonic-string (dt)
(format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0D~{~C~}~A"
(datetime-year dt)
(datetime-month dt)
(datetime-day dt)
(datetime-hours dt)
(datetime-minutes dt)
(datetime-seconds dt)
(let ((num (datetime-usec dt)))
(and (> num 0)
(loop with characters = nil
with digit
for i from 1 to 6
do (progn
(multiple-value-setq (num digit) (floor num 10))
(when (or (> digit 0) (not (null characters)))
(push (code-char (+ digit (char-code #\0))) characters)))
finally (return (cons #\. characters)))))
(datetime-tz-string dt)))
(defun datetime-in-seconds (dt)
(encode-universal-time (datetime-seconds dt)
(datetime-minutes dt)
(datetime-hours dt)
(datetime-day dt)
(datetime-month dt)
(datetime-year dt)
(datetime-tz dt)))
| null | https://raw.githubusercontent.com/aaltodsg/instans/5ffc90e733e76ab911165f205ba57a7b3b200945/src/sparql/datetime.lisp | lisp | Syntax : COMMON - LISP ; Base : 10 ; Package : INSTANS -*-
nil | Author : ( )
(in-package #:instans)
(define-class datetime ()
((time :initarg :time :accessor datetime-time)
(usec :initarg :usec :accessor datetime-usec)
(year :initform nil :initarg :year)
(month :initform nil :initarg :month)
(day :initform nil :initarg :day)
(hours :initform nil :initarg :hours)
(minutes :initform nil :initarg :minutes)
(seconds :initform nil :initarg :seconds)
(tz :initform nil :initarg :tz)
(tz-str :initform nil :initarg :tz-str)))
(defmethod print-object ((this datetime) stream)
(format stream "#<~S ~S>" (type-of this) (datetime-canonic-string this)))
(defun datetime-fill-slots (x)
(multiple-value-bind (seconds minutes hours day month year day-of-week dst tz)
(decode-universal-time (+ (datetime-time x) sb-impl::unix-to-universal-time))
(declare (ignore day-of-week))
(when dst (incf tz))
(setf (slot-value x 'year) year)
(setf (slot-value x 'month) month)
(setf (slot-value x 'day) day)
(setf (slot-value x 'hours) hours)
(setf (slot-value x 'minutes) minutes)
(setf (slot-value x 'seconds) seconds)
(setf (slot-value x 'tz) tz)))
(defmacro define-datetime-lazy-getter (slot-name)
(let ((getter-name (fmt-intern "~A-~A" 'datetime slot-name)))
`(defun ,getter-name (x)
(unless (slot-value x 'year)
(datetime-fill-slots x))
(slot-value x ',slot-name))))
(define-datetime-lazy-getter year)
(define-datetime-lazy-getter month)
(define-datetime-lazy-getter day)
(define-datetime-lazy-getter hours)
(define-datetime-lazy-getter minutes)
(define-datetime-lazy-getter seconds)
(define-datetime-lazy-getter tz)
(defun datetime-tz-string (dt)
(or (slot-value dt 'tz-str)
(let* ((tz (datetime-tz dt))
(tz-str (cond ((or (null tz) (zerop tz)) "")
(t
(multiple-value-bind (tz-h tz-m) (floor (abs tz) 1)
(concatenate 'string (if (< tz 0) "-" "+") (format nil "~2,'0D:~2,'0D" tz-h (* 60 tz-m))))))))
(setf (slot-value dt 'tz-str) tz-str)
tz-str)))
(defun datetime-compare (dt1 dt2)
(let ((ut1 (datetime-time dt1))
(ut2 (datetime-time dt2)))
(cond ((< ut1 ut2) -1)
((> ut1 ut2) 1)
(t
(signum (- (datetime-usec dt1) (datetime-usec dt2)))))))
(defun datetime= (dt1 dt2)
(= (datetime-compare dt1 dt2) 0))
(defun datetime< (dt1 dt2)
(< (datetime-compare dt1 dt2) 0))
(defun datetime<= (dt1 dt2)
(<= (datetime-compare dt1 dt2) 0))
(defun datetime> (dt1 dt2)
(> (datetime-compare dt1 dt2) 0))
(defun datetime>= (dt1 dt2)
(>= (datetime-compare dt1 dt2) 0))
(defun datetime-plain ()
(make-instance 'datetime :time 0 :usec 0))
(defun datetime-now ()
(multiple-value-bind (time-t suseconds-t)
(sb-unix::get-time-of-day)
(make-instance 'datetime :time time-t :usec suseconds-t)))
(defun datetime-from-string (str)
(let (year month day hours minutes seconds usec tz-string tz)
(catch 'parse-error
(let ((strlen (length str))
(error-msg nil)
(current-position 0))
(labels ((looking-at (ch) (and (< current-position strlen) (char= (char str current-position) ch)))
(eat-int (&optional length delim)
(loop with result = 0
with start = current-position
with max = (if (null length) strlen (min strlen (+ start length)))
while (and (< current-position max)
(let ((ch (char str current-position)))
(if (digit-char-p ch)
(progn
(setf result (+ (* 10 result) (+ (- (char-code ch) (char-code #\0)))))
(incf current-position))
nil)))
finally (return (progn
(cond ((null length)
(when (= current-position start) (parse-error "Could not parse an int in ~S starting at index ~D" str start)))
(t
(when (not (= current-position (+ start length))) (parse-error "Could not parse an int of length ~D in ~S starting at index ~D" length str start))))
(when delim (if (looking-at delim) (incf current-position) (parse-error "Missing delimiter '~A' in ~S at ~D" delim str current-position)))
result))))
(parse-error (fmt &rest args)
(setf error-msg (apply #'format nil fmt args))
(throw 'parse-error (values nil error-msg))))
(let* ((year-sign (if (looking-at #\-) (progn (incf current-position) -1) 1))
(cp current-position))
(setf year (eat-int nil #\-))
(when (zerop year) (parse-error "No year zero allowed in ~S" str))
(when (and (> (- current-position cp) 4) (char= (char str cp) #\0))
(parse-error "Leading '0' not allowed in year in ~S" str))
(setf year (* year-sign year)))
(setf month (eat-int 2 #\-))
(setf day (eat-int 2 #\T))
(setf hours (eat-int 2 #\:))
(setf minutes (eat-int 2 #\:))
(setf seconds (eat-int 2))
(cond ((looking-at #\.)
(incf current-position)
(let ((cp current-position))
(setf usec (eat-int))
(loop for i from 1 to (- 6 (- current-position cp))
do (setf usec (* 10 usec)))))
(t
(setf usec 0)))
( setf tz - string ( subseq str current - position ) )
(cond ((< current-position strlen)
(let (tz-sign tz-hours tz-minutes)
(cond ((looking-at #\Z)
(incf current-position)
(setf tz 0)
(setf tz-string "Z"))
((or (looking-at #\+) (looking-at #\-))
(setf tz-sign (if (looking-at #\+) 1 -1))
(incf current-position)
(setf tz-hours (eat-int 2 #\:))
(setf tz-minutes (eat-int 2))
(setf tz (* tz-sign (+ tz-hours (/ tz-minutes 60)))))
(t (parse-error "Illegal timezone in ~S" str)))
(when (< current-position strlen)
(parse-error "Garbage after timezone in ~S" str))))
(t (setf tz nil))))
(cond ((null error-msg)
(make-instance 'datetime
:time (- (encode-universal-time seconds minutes hours day month year tz) sb-impl::unix-to-universal-time) :usec usec
:year year :month month :day day :hours hours :minutes minutes :seconds seconds :tz-str tz-string :tz tz))
(t
(list nil error-msg)))
))))
(defun datetime-canonic-string (dt)
(format nil "~4,'0D-~2,'0D-~2,'0DT~2,'0D:~2,'0D:~2,'0D~{~C~}~A"
(datetime-year dt)
(datetime-month dt)
(datetime-day dt)
(datetime-hours dt)
(datetime-minutes dt)
(datetime-seconds dt)
(let ((num (datetime-usec dt)))
(and (> num 0)
(loop with characters = nil
with digit
for i from 1 to 6
do (progn
(multiple-value-setq (num digit) (floor num 10))
(when (or (> digit 0) (not (null characters)))
(push (code-char (+ digit (char-code #\0))) characters)))
finally (return (cons #\. characters)))))
(datetime-tz-string dt)))
(defun datetime-in-seconds (dt)
(encode-universal-time (datetime-seconds dt)
(datetime-minutes dt)
(datetime-hours dt)
(datetime-day dt)
(datetime-month dt)
(datetime-year dt)
(datetime-tz dt)))
|
26c7337f826933ebdcb25d625a24692d73c3514c279206eebb0e06f011e4ce09 | mzp/coq-ide-for-ios | reductionops.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
i $ I d : reductionops.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
(*i*)
open Names
open Term
open Univ
open Evd
open Environ
open Closure
(*i*)
(* Reduction Functions. *)
exception Elimconst
(************************************************************************)
s A [ stack ] is a context of arguments , arguments are pushed by
[ append_stack ] one array at a time but popped with [ decomp_stack ]
one by one
[append_stack] one array at a time but popped with [decomp_stack]
one by one *)
type 'a stack_member =
| Zapp of 'a list
| Zcase of case_info * 'a * 'a array
| Zfix of 'a * 'a stack
| Zshift of int
| Zupdate of 'a
and 'a stack = 'a stack_member list
val empty_stack : 'a stack
val append_stack : 'a array -> 'a stack -> 'a stack
val append_stack_list : 'a list -> 'a stack -> 'a stack
val decomp_stack : 'a stack -> ('a * 'a stack) option
val list_of_stack : 'a stack -> 'a list
val array_of_stack : 'a stack -> 'a array
val stack_assign : 'a stack -> int -> 'a -> 'a stack
val stack_args_size : 'a stack -> int
val app_stack : constr * constr stack -> constr
val stack_tail : int -> 'a stack -> 'a stack
val stack_nth : 'a stack -> int -> 'a
(************************************************************************)
type state = constr * constr stack
type contextual_reduction_function = env -> evar_map -> constr -> constr
type reduction_function = contextual_reduction_function
type local_reduction_function = evar_map -> constr -> constr
type contextual_stack_reduction_function =
env -> evar_map -> constr -> constr * constr list
type stack_reduction_function = contextual_stack_reduction_function
type local_stack_reduction_function =
evar_map -> constr -> constr * constr list
type contextual_state_reduction_function =
env -> evar_map -> state -> state
type state_reduction_function = contextual_state_reduction_function
type local_state_reduction_function = evar_map -> state -> state
(* Removes cast and put into applicative form *)
val whd_stack : local_stack_reduction_function
(* For compatibility: alias for whd\_stack *)
val whd_castapp_stack : local_stack_reduction_function
s Reduction Function Operators
val strong : reduction_function -> reduction_function
val local_strong : local_reduction_function -> local_reduction_function
val strong_prodspine : local_reduction_function -> local_reduction_function
(*i
val stack_reduction_of_reduction :
'a reduction_function -> 'a state_reduction_function
i*)
val stacklam : (state -> 'a) -> constr list -> constr -> constr stack -> 'a
s Generic Optimized Reduction Function using Closures
val clos_norm_flags : Closure.RedFlags.reds -> reduction_function
(* Same as [(strong whd_beta[delta][iota])], but much faster on big terms *)
val nf_beta : local_reduction_function
val nf_betaiota : local_reduction_function
val nf_betadeltaiota : reduction_function
val nf_evar : evar_map -> constr -> constr
val nf_betaiota_preserving_vm_cast : reduction_function
(* Lazy strategy, weak head reduction *)
val whd_evar : evar_map -> constr -> constr
val whd_beta : local_reduction_function
val whd_betaiota : local_reduction_function
val whd_betaiotazeta : local_reduction_function
val whd_betadeltaiota : contextual_reduction_function
val whd_betadeltaiota_nolet : contextual_reduction_function
val whd_betaetalet : local_reduction_function
val whd_betalet : local_reduction_function
val whd_beta_stack : local_stack_reduction_function
val whd_betaiota_stack : local_stack_reduction_function
val whd_betaiotazeta_stack : local_stack_reduction_function
val whd_betadeltaiota_stack : contextual_stack_reduction_function
val whd_betadeltaiota_nolet_stack : contextual_stack_reduction_function
val whd_betaetalet_stack : local_stack_reduction_function
val whd_betalet_stack : local_stack_reduction_function
val whd_beta_state : local_state_reduction_function
val whd_betaiota_state : local_state_reduction_function
val whd_betaiotazeta_state : local_state_reduction_function
val whd_betadeltaiota_state : contextual_state_reduction_function
val whd_betadeltaiota_nolet_state : contextual_state_reduction_function
val whd_betaetalet_state : local_state_reduction_function
val whd_betalet_state : local_state_reduction_function
(*s Head normal forms *)
val whd_delta_stack : stack_reduction_function
val whd_delta_state : state_reduction_function
val whd_delta : reduction_function
val whd_betadelta_stack : stack_reduction_function
val whd_betadelta_state : state_reduction_function
val whd_betadelta : reduction_function
val whd_betadeltaeta_stack : stack_reduction_function
val whd_betadeltaeta_state : state_reduction_function
val whd_betadeltaeta : reduction_function
val whd_betadeltaiotaeta_stack : stack_reduction_function
val whd_betadeltaiotaeta_state : state_reduction_function
val whd_betadeltaiotaeta : reduction_function
val whd_eta : constr -> constr
val whd_zeta : constr -> constr
(* Various reduction functions *)
val safe_evar_value : evar_map -> existential -> constr option
val beta_applist : constr * constr list -> constr
val hnf_prod_app : env -> evar_map -> constr -> constr -> constr
val hnf_prod_appvect : env -> evar_map -> constr -> constr array -> constr
val hnf_prod_applist : env -> evar_map -> constr -> constr list -> constr
val hnf_lam_app : env -> evar_map -> constr -> constr -> constr
val hnf_lam_appvect : env -> evar_map -> constr -> constr array -> constr
val hnf_lam_applist : env -> evar_map -> constr -> constr list -> constr
val splay_prod : env -> evar_map -> constr -> (name * constr) list * constr
val splay_lam : env -> evar_map -> constr -> (name * constr) list * constr
val splay_arity : env -> evar_map -> constr -> (name * constr) list * sorts
val sort_of_arity : env -> constr -> sorts
val splay_prod_n : env -> evar_map -> int -> constr -> rel_context * constr
val splay_lam_n : env -> evar_map -> int -> constr -> rel_context * constr
val splay_prod_assum :
env -> evar_map -> constr -> rel_context * constr
val decomp_sort : env -> evar_map -> types -> sorts
val is_sort : env -> evar_map -> types -> bool
type 'a miota_args = {
mP : constr; (* the result type *)
mconstr : constr; (* the constructor *)
mci : case_info; (* special info to re-build pattern *)
mcargs : 'a list; (* the constructor's arguments *)
mlf : 'a array } (* the branch code vector *)
val reducible_mind_case : constr -> bool
val reduce_mind_case : constr miota_args -> constr
val find_conclusion : env -> evar_map -> constr -> (constr,constr) kind_of_term
val is_arity : env -> evar_map -> constr -> bool
val whd_programs : reduction_function
(* [reduce_fix redfun fix stk] contracts [fix stk] if it is actually
reducible; the structural argument is reduced by [redfun] *)
type fix_reduction_result = NotReducible | Reduced of state
val fix_recarg : fixpoint -> constr stack -> (int * constr) option
val reduce_fix : local_state_reduction_function -> evar_map -> fixpoint
-> constr stack -> fix_reduction_result
(*s Querying the kernel conversion oracle: opaque/transparent constants *)
val is_transparent : 'a tableKey -> bool
(*s Conversion Functions (uses closures, lazy strategy) *)
type conversion_test = constraints -> constraints
val pb_is_equal : conv_pb -> bool
val pb_equal : conv_pb -> conv_pb
val sort_cmp : conv_pb -> sorts -> sorts -> conversion_test
val is_conv : env -> evar_map -> constr -> constr -> bool
val is_conv_leq : env -> evar_map -> constr -> constr -> bool
val is_fconv : conv_pb -> env -> evar_map -> constr -> constr -> bool
val is_trans_conv : transparent_state -> env -> evar_map -> constr -> constr -> bool
val is_trans_conv_leq : transparent_state -> env -> evar_map -> constr -> constr -> bool
val is_trans_fconv : conv_pb -> transparent_state -> env -> evar_map -> constr -> constr -> bool
(*s Special-Purpose Reduction Functions *)
val whd_meta : evar_map -> constr -> constr
val plain_instance : (metavariable * constr) list -> constr -> constr
val instance :evar_map -> (metavariable * constr) list -> constr -> constr
val head_unfold_under_prod : transparent_state -> reduction_function
(*s Heuristic for Conversion with Evar *)
val whd_betaiota_deltazeta_for_iota_state : state_reduction_function
s Meta - related reduction functions
val meta_instance : evar_map -> constr freelisted -> constr
val nf_meta : evar_map -> constr -> constr
val meta_reducible_instance : evar_map -> constr freelisted -> constr
| null | https://raw.githubusercontent.com/mzp/coq-ide-for-ios/4cdb389bbecd7cdd114666a8450ecf5b5f0391d3/coqlib/pretyping/reductionops.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i
i
Reduction Functions.
**********************************************************************
**********************************************************************
Removes cast and put into applicative form
For compatibility: alias for whd\_stack
i
val stack_reduction_of_reduction :
'a reduction_function -> 'a state_reduction_function
i
Same as [(strong whd_beta[delta][iota])], but much faster on big terms
Lazy strategy, weak head reduction
s Head normal forms
Various reduction functions
the result type
the constructor
special info to re-build pattern
the constructor's arguments
the branch code vector
[reduce_fix redfun fix stk] contracts [fix stk] if it is actually
reducible; the structural argument is reduced by [redfun]
s Querying the kernel conversion oracle: opaque/transparent constants
s Conversion Functions (uses closures, lazy strategy)
s Special-Purpose Reduction Functions
s Heuristic for Conversion with Evar | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
i $ I d : reductionops.mli 13323 2010 - 07 - 24 15:57:30Z herbelin $ i
open Names
open Term
open Univ
open Evd
open Environ
open Closure
exception Elimconst
s A [ stack ] is a context of arguments , arguments are pushed by
[ append_stack ] one array at a time but popped with [ decomp_stack ]
one by one
[append_stack] one array at a time but popped with [decomp_stack]
one by one *)
type 'a stack_member =
| Zapp of 'a list
| Zcase of case_info * 'a * 'a array
| Zfix of 'a * 'a stack
| Zshift of int
| Zupdate of 'a
and 'a stack = 'a stack_member list
val empty_stack : 'a stack
val append_stack : 'a array -> 'a stack -> 'a stack
val append_stack_list : 'a list -> 'a stack -> 'a stack
val decomp_stack : 'a stack -> ('a * 'a stack) option
val list_of_stack : 'a stack -> 'a list
val array_of_stack : 'a stack -> 'a array
val stack_assign : 'a stack -> int -> 'a -> 'a stack
val stack_args_size : 'a stack -> int
val app_stack : constr * constr stack -> constr
val stack_tail : int -> 'a stack -> 'a stack
val stack_nth : 'a stack -> int -> 'a
type state = constr * constr stack
type contextual_reduction_function = env -> evar_map -> constr -> constr
type reduction_function = contextual_reduction_function
type local_reduction_function = evar_map -> constr -> constr
type contextual_stack_reduction_function =
env -> evar_map -> constr -> constr * constr list
type stack_reduction_function = contextual_stack_reduction_function
type local_stack_reduction_function =
evar_map -> constr -> constr * constr list
type contextual_state_reduction_function =
env -> evar_map -> state -> state
type state_reduction_function = contextual_state_reduction_function
type local_state_reduction_function = evar_map -> state -> state
val whd_stack : local_stack_reduction_function
val whd_castapp_stack : local_stack_reduction_function
s Reduction Function Operators
val strong : reduction_function -> reduction_function
val local_strong : local_reduction_function -> local_reduction_function
val strong_prodspine : local_reduction_function -> local_reduction_function
val stacklam : (state -> 'a) -> constr list -> constr -> constr stack -> 'a
s Generic Optimized Reduction Function using Closures
val clos_norm_flags : Closure.RedFlags.reds -> reduction_function
val nf_beta : local_reduction_function
val nf_betaiota : local_reduction_function
val nf_betadeltaiota : reduction_function
val nf_evar : evar_map -> constr -> constr
val nf_betaiota_preserving_vm_cast : reduction_function
val whd_evar : evar_map -> constr -> constr
val whd_beta : local_reduction_function
val whd_betaiota : local_reduction_function
val whd_betaiotazeta : local_reduction_function
val whd_betadeltaiota : contextual_reduction_function
val whd_betadeltaiota_nolet : contextual_reduction_function
val whd_betaetalet : local_reduction_function
val whd_betalet : local_reduction_function
val whd_beta_stack : local_stack_reduction_function
val whd_betaiota_stack : local_stack_reduction_function
val whd_betaiotazeta_stack : local_stack_reduction_function
val whd_betadeltaiota_stack : contextual_stack_reduction_function
val whd_betadeltaiota_nolet_stack : contextual_stack_reduction_function
val whd_betaetalet_stack : local_stack_reduction_function
val whd_betalet_stack : local_stack_reduction_function
val whd_beta_state : local_state_reduction_function
val whd_betaiota_state : local_state_reduction_function
val whd_betaiotazeta_state : local_state_reduction_function
val whd_betadeltaiota_state : contextual_state_reduction_function
val whd_betadeltaiota_nolet_state : contextual_state_reduction_function
val whd_betaetalet_state : local_state_reduction_function
val whd_betalet_state : local_state_reduction_function
val whd_delta_stack : stack_reduction_function
val whd_delta_state : state_reduction_function
val whd_delta : reduction_function
val whd_betadelta_stack : stack_reduction_function
val whd_betadelta_state : state_reduction_function
val whd_betadelta : reduction_function
val whd_betadeltaeta_stack : stack_reduction_function
val whd_betadeltaeta_state : state_reduction_function
val whd_betadeltaeta : reduction_function
val whd_betadeltaiotaeta_stack : stack_reduction_function
val whd_betadeltaiotaeta_state : state_reduction_function
val whd_betadeltaiotaeta : reduction_function
val whd_eta : constr -> constr
val whd_zeta : constr -> constr
val safe_evar_value : evar_map -> existential -> constr option
val beta_applist : constr * constr list -> constr
val hnf_prod_app : env -> evar_map -> constr -> constr -> constr
val hnf_prod_appvect : env -> evar_map -> constr -> constr array -> constr
val hnf_prod_applist : env -> evar_map -> constr -> constr list -> constr
val hnf_lam_app : env -> evar_map -> constr -> constr -> constr
val hnf_lam_appvect : env -> evar_map -> constr -> constr array -> constr
val hnf_lam_applist : env -> evar_map -> constr -> constr list -> constr
val splay_prod : env -> evar_map -> constr -> (name * constr) list * constr
val splay_lam : env -> evar_map -> constr -> (name * constr) list * constr
val splay_arity : env -> evar_map -> constr -> (name * constr) list * sorts
val sort_of_arity : env -> constr -> sorts
val splay_prod_n : env -> evar_map -> int -> constr -> rel_context * constr
val splay_lam_n : env -> evar_map -> int -> constr -> rel_context * constr
val splay_prod_assum :
env -> evar_map -> constr -> rel_context * constr
val decomp_sort : env -> evar_map -> types -> sorts
val is_sort : env -> evar_map -> types -> bool
type 'a miota_args = {
val reducible_mind_case : constr -> bool
val reduce_mind_case : constr miota_args -> constr
val find_conclusion : env -> evar_map -> constr -> (constr,constr) kind_of_term
val is_arity : env -> evar_map -> constr -> bool
val whd_programs : reduction_function
type fix_reduction_result = NotReducible | Reduced of state
val fix_recarg : fixpoint -> constr stack -> (int * constr) option
val reduce_fix : local_state_reduction_function -> evar_map -> fixpoint
-> constr stack -> fix_reduction_result
val is_transparent : 'a tableKey -> bool
type conversion_test = constraints -> constraints
val pb_is_equal : conv_pb -> bool
val pb_equal : conv_pb -> conv_pb
val sort_cmp : conv_pb -> sorts -> sorts -> conversion_test
val is_conv : env -> evar_map -> constr -> constr -> bool
val is_conv_leq : env -> evar_map -> constr -> constr -> bool
val is_fconv : conv_pb -> env -> evar_map -> constr -> constr -> bool
val is_trans_conv : transparent_state -> env -> evar_map -> constr -> constr -> bool
val is_trans_conv_leq : transparent_state -> env -> evar_map -> constr -> constr -> bool
val is_trans_fconv : conv_pb -> transparent_state -> env -> evar_map -> constr -> constr -> bool
val whd_meta : evar_map -> constr -> constr
val plain_instance : (metavariable * constr) list -> constr -> constr
val instance :evar_map -> (metavariable * constr) list -> constr -> constr
val head_unfold_under_prod : transparent_state -> reduction_function
val whd_betaiota_deltazeta_for_iota_state : state_reduction_function
s Meta - related reduction functions
val meta_instance : evar_map -> constr freelisted -> constr
val nf_meta : evar_map -> constr -> constr
val meta_reducible_instance : evar_map -> constr freelisted -> constr
|
d13f1f240c5bed0051e042b69827ca1b3bf60cf30ab278adbd83c426f2d4a940 | plum-umd/fundamentals | defns.rkt | #lang racket
(provide (all-defined-out))
(define m1-date "Oct 1")
(define m2-date "Nov 5")
(define final-date "Dec 13, 4--6 pm (ATL 1113)")
(define semester "fall")
(define year "2018")
(define courseno "CMSC 131A")
(define elms-url "")
| null | https://raw.githubusercontent.com/plum-umd/fundamentals/eb01ac528d42855be53649991a17d19c025a97ad/1/www/defns.rkt | racket | #lang racket
(provide (all-defined-out))
(define m1-date "Oct 1")
(define m2-date "Nov 5")
(define final-date "Dec 13, 4--6 pm (ATL 1113)")
(define semester "fall")
(define year "2018")
(define courseno "CMSC 131A")
(define elms-url "")
|
|
75a5517f3735b0a922a75eacf144537ef98053a2ebe9c17c66bf860786c43817 | rescript-lang/rescript-compiler | belt_HashSet.mli | Copyright ( C ) 2018 Authors of ReScript
*
* 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 , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
*
A * * mutable * * Hash set which allows customized ` hash ` behavior .
All data are parameterized by not its only type but also a unique identity in
the time of initialization , so that two _ HashSets of ints _ initialized with
different _ hash _ functions will have different type .
For example :
` ` ` res prelude
module I0 = unpack (
Belt . Id.hashableU (
~hash= ( . a : int ) = > land(a , 65535 ) ,
~eq= ( . a , b ) = > a = = b ,
)
)
let s0 = Belt . HashSet.make(~id = ) , ~hintSize=40 )
module I1 = unpack (
Belt . Id.hashableU (
~hash= ( . a : int ) = > land(a , 255 ) ,
~eq= ( . a , b ) = > a = = b ,
)
)
let s1 = Belt . HashSet.make(~id = , ~hintSize=40 )
Belt . HashSet.add(s1 , 0 )
Belt . HashSet.add(s1 , 1 )
` ` `
The invariant must be held : for two elements who are equal , their hashed
value should be the same .
Here the compiler would infer ` s0 ` and ` s1 ` having different type so that it
would not mix .
` ` ` res sig
let s0 : Belt . HashSet.t < int , I0.identity >
let s1 : Belt . HashSet.t < int , I1.identity >
` ` `
We can add elements to the collection ( see last two lines in the example
above ) . Since this is an mutable data structure , ` s1 ` will contain two pairs .
A **mutable** Hash set which allows customized `hash` behavior.
All data are parameterized by not its only type but also a unique identity in
the time of initialization, so that two _HashSets of ints_ initialized with
different _hash_ functions will have different type.
For example:
```res prelude
module I0 = unpack(
Belt.Id.hashableU(
~hash=(. a: int) => land(a, 65535),
~eq=(. a, b) => a == b,
)
)
let s0 = Belt.HashSet.make(~id=module(I0), ~hintSize=40)
module I1 = unpack(
Belt.Id.hashableU(
~hash=(. a: int) => land(a, 255),
~eq=(. a, b) => a == b,
)
)
let s1 = Belt.HashSet.make(~id=module(I1), ~hintSize=40)
Belt.HashSet.add(s1, 0)
Belt.HashSet.add(s1, 1)
```
The invariant must be held: for two elements who are equal, their hashed
value should be the same.
Here the compiler would infer `s0` and `s1` having different type so that it
would not mix.
```res sig
let s0: Belt.HashSet.t<int, I0.identity>
let s1: Belt.HashSet.t<int, I1.identity>
```
We can add elements to the collection (see last two lines in the example
above). Since this is an mutable data structure, `s1` will contain two pairs.
*)
* when key type is ` int ` , more efficient
than the generic type
than the generic type *)
module Int = Belt_HashSetInt
* when key type is ` string ` , more efficient
than the generic type
than the generic type *)
module String = Belt_HashSetString
TODO : add a poly module
module Poly = Belt_HashSetPoly
challenge :
- generic equal handles JS data structure
- eq / hash consistent
module Poly = Belt_HashSetPoly
challenge:
- generic equal handles JS data structure
- eq/hash consistent
*)
type ('a, 'id) t
(** The type of hash tables from type `'a` to type `'b`. *)
type ('a, 'id) id = ('a, 'id) Belt_Id.hashable
val make: hintSize:int -> id:('a,'id) id -> ('a, 'id) t
val clear: ('a, 'id) t -> unit
val isEmpty: _ t -> bool
val add: ('a, 'id) t -> 'a -> unit
val copy: ('a, 'id) t -> ('a, 'id) t
val has: ('a, 'id) t -> 'a -> bool
val remove: ('a, 'id) t -> 'a -> unit
val forEachU: ('a, 'id) t -> ('a -> unit [@bs]) -> unit
val forEach: ('a, 'id) t -> ('a -> unit) -> unit
(** Order unspecified. *)
val reduceU: ('a, 'id) t -> 'c -> ('c -> 'a -> 'c [@bs]) -> 'c
val reduce: ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c
(** Order unspecified. *)
val size: ('a, 'id) t -> int
val logStats: _ t -> unit
val toArray: ('a,'id) t -> 'a array
val fromArray: 'a array -> id:('a,'id) id -> ('a,'id) t
val mergeMany: ('a,'id) t -> 'a array -> unit
val getBucketHistogram: _ t -> int array
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/c3fcc430360079546a6aabd2b2770303480f8486/jscomp/others/belt_HashSet.mli | ocaml | * The type of hash tables from type `'a` to type `'b`.
* Order unspecified.
* Order unspecified. | Copyright ( C ) 2018 Authors of ReScript
*
* 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 , either version 3 of the License , or
* ( at your option ) any later version .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* 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, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
*
A * * mutable * * Hash set which allows customized ` hash ` behavior .
All data are parameterized by not its only type but also a unique identity in
the time of initialization , so that two _ HashSets of ints _ initialized with
different _ hash _ functions will have different type .
For example :
` ` ` res prelude
module I0 = unpack (
Belt . Id.hashableU (
~hash= ( . a : int ) = > land(a , 65535 ) ,
~eq= ( . a , b ) = > a = = b ,
)
)
let s0 = Belt . HashSet.make(~id = ) , ~hintSize=40 )
module I1 = unpack (
Belt . Id.hashableU (
~hash= ( . a : int ) = > land(a , 255 ) ,
~eq= ( . a , b ) = > a = = b ,
)
)
let s1 = Belt . HashSet.make(~id = , ~hintSize=40 )
Belt . HashSet.add(s1 , 0 )
Belt . HashSet.add(s1 , 1 )
` ` `
The invariant must be held : for two elements who are equal , their hashed
value should be the same .
Here the compiler would infer ` s0 ` and ` s1 ` having different type so that it
would not mix .
` ` ` res sig
let s0 : Belt . HashSet.t < int , I0.identity >
let s1 : Belt . HashSet.t < int , I1.identity >
` ` `
We can add elements to the collection ( see last two lines in the example
above ) . Since this is an mutable data structure , ` s1 ` will contain two pairs .
A **mutable** Hash set which allows customized `hash` behavior.
All data are parameterized by not its only type but also a unique identity in
the time of initialization, so that two _HashSets of ints_ initialized with
different _hash_ functions will have different type.
For example:
```res prelude
module I0 = unpack(
Belt.Id.hashableU(
~hash=(. a: int) => land(a, 65535),
~eq=(. a, b) => a == b,
)
)
let s0 = Belt.HashSet.make(~id=module(I0), ~hintSize=40)
module I1 = unpack(
Belt.Id.hashableU(
~hash=(. a: int) => land(a, 255),
~eq=(. a, b) => a == b,
)
)
let s1 = Belt.HashSet.make(~id=module(I1), ~hintSize=40)
Belt.HashSet.add(s1, 0)
Belt.HashSet.add(s1, 1)
```
The invariant must be held: for two elements who are equal, their hashed
value should be the same.
Here the compiler would infer `s0` and `s1` having different type so that it
would not mix.
```res sig
let s0: Belt.HashSet.t<int, I0.identity>
let s1: Belt.HashSet.t<int, I1.identity>
```
We can add elements to the collection (see last two lines in the example
above). Since this is an mutable data structure, `s1` will contain two pairs.
*)
* when key type is ` int ` , more efficient
than the generic type
than the generic type *)
module Int = Belt_HashSetInt
* when key type is ` string ` , more efficient
than the generic type
than the generic type *)
module String = Belt_HashSetString
TODO : add a poly module
module Poly = Belt_HashSetPoly
challenge :
- generic equal handles JS data structure
- eq / hash consistent
module Poly = Belt_HashSetPoly
challenge:
- generic equal handles JS data structure
- eq/hash consistent
*)
type ('a, 'id) t
type ('a, 'id) id = ('a, 'id) Belt_Id.hashable
val make: hintSize:int -> id:('a,'id) id -> ('a, 'id) t
val clear: ('a, 'id) t -> unit
val isEmpty: _ t -> bool
val add: ('a, 'id) t -> 'a -> unit
val copy: ('a, 'id) t -> ('a, 'id) t
val has: ('a, 'id) t -> 'a -> bool
val remove: ('a, 'id) t -> 'a -> unit
val forEachU: ('a, 'id) t -> ('a -> unit [@bs]) -> unit
val forEach: ('a, 'id) t -> ('a -> unit) -> unit
val reduceU: ('a, 'id) t -> 'c -> ('c -> 'a -> 'c [@bs]) -> 'c
val reduce: ('a, 'id) t -> 'c -> ('c -> 'a -> 'c) -> 'c
val size: ('a, 'id) t -> int
val logStats: _ t -> unit
val toArray: ('a,'id) t -> 'a array
val fromArray: 'a array -> id:('a,'id) id -> ('a,'id) t
val mergeMany: ('a,'id) t -> 'a array -> unit
val getBucketHistogram: _ t -> int array
|
54899ea01fc059271bd0f651d5b72f95bba175892ccfb2ca5b22007192d0bc6f | eeng/mercurius | channel_based_pub_sub.clj | (ns mercurius.core.infrastructure.messaging.channel-based-pub-sub
(:require [clojure.core.async :refer [put! chan close! go-loop <! sliding-buffer]]
[clojure.string :as str]
[taoensso.timbre :as log]
[mercurius.core.adapters.messaging.pub-sub :refer [PubSub]]
[mercurius.util.uuid :refer [uuid]]))
(defrecord ChannelBasedPubSub [in-chan subscribers]
PubSub
(publish [_ topic message]
(log/debug "Publish" [topic message])
(put! in-chan [topic message]))
(subscribe [_ topic-pattern {:keys [on-message subscription-id] :or {subscription-id (uuid)}}]
(log/debug "Subscribing to" topic-pattern "- Subscription:" subscription-id "- Callback:" on-message)
(swap! subscribers assoc subscription-id [topic-pattern on-message])
subscription-id)
(unsubscribe [_ subscription-id]
(log/debug "Unsubscribing" subscription-id)
(swap! subscribers dissoc subscription-id)
:ok))
(defn match-topic? [pattern topic]
(if (str/includes? pattern "*")
(str/starts-with? topic (str/replace pattern "*" ""))
(= pattern topic)))
(defn- start-listener [in-chan subscribers]
(go-loop []
(when-some [[topic msg] (<! in-chan)]
(doseq [[topic-pattern callback] (vals @subscribers)
:when (match-topic? topic-pattern topic)]
(try
(callback msg)
(catch Exception e
(log/error "Error processing" {:msg msg :topic-pattern topic-pattern :callback callback})
(log/error e))))
(recur))))
(defn start-channel-based-pub-sub []
(log/info "Starting channel based pubsub")
(let [in-chan (chan (sliding-buffer 1048576))
subscribers (atom {})]
(start-listener in-chan subscribers)
(ChannelBasedPubSub. in-chan subscribers)))
(defn stop-channel-based-pub-sub [{:keys [in-chan]}]
(log/info "Stopping channel based pubsub")
(close! in-chan))
| null | https://raw.githubusercontent.com/eeng/mercurius/f83778ddde99aa13692e4fe2e70b2e9dc2fd70e9/src/mercurius/core/infrastructure/messaging/channel_based_pub_sub.clj | clojure | (ns mercurius.core.infrastructure.messaging.channel-based-pub-sub
(:require [clojure.core.async :refer [put! chan close! go-loop <! sliding-buffer]]
[clojure.string :as str]
[taoensso.timbre :as log]
[mercurius.core.adapters.messaging.pub-sub :refer [PubSub]]
[mercurius.util.uuid :refer [uuid]]))
(defrecord ChannelBasedPubSub [in-chan subscribers]
PubSub
(publish [_ topic message]
(log/debug "Publish" [topic message])
(put! in-chan [topic message]))
(subscribe [_ topic-pattern {:keys [on-message subscription-id] :or {subscription-id (uuid)}}]
(log/debug "Subscribing to" topic-pattern "- Subscription:" subscription-id "- Callback:" on-message)
(swap! subscribers assoc subscription-id [topic-pattern on-message])
subscription-id)
(unsubscribe [_ subscription-id]
(log/debug "Unsubscribing" subscription-id)
(swap! subscribers dissoc subscription-id)
:ok))
(defn match-topic? [pattern topic]
(if (str/includes? pattern "*")
(str/starts-with? topic (str/replace pattern "*" ""))
(= pattern topic)))
(defn- start-listener [in-chan subscribers]
(go-loop []
(when-some [[topic msg] (<! in-chan)]
(doseq [[topic-pattern callback] (vals @subscribers)
:when (match-topic? topic-pattern topic)]
(try
(callback msg)
(catch Exception e
(log/error "Error processing" {:msg msg :topic-pattern topic-pattern :callback callback})
(log/error e))))
(recur))))
(defn start-channel-based-pub-sub []
(log/info "Starting channel based pubsub")
(let [in-chan (chan (sliding-buffer 1048576))
subscribers (atom {})]
(start-listener in-chan subscribers)
(ChannelBasedPubSub. in-chan subscribers)))
(defn stop-channel-based-pub-sub [{:keys [in-chan]}]
(log/info "Stopping channel based pubsub")
(close! in-chan))
|
|
05415063f52dea1f40fc5b8e0bb9ffd1b7a0185236f4e46bb3b03f9b912e02ff | fujita-y/ypsilon | syntmp.scm | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
;;; See LICENSE file for terms and conditions of use.
(define collect-rename-ids
(lambda (template ranks)
(let ((ids (collect-unique-macro-ids template)))
(let loop ((lst ids))
(if (null? lst)
lst
(if (assq (car lst) ranks)
(loop (cdr lst))
(cons (car lst) (loop (cdr lst)))))))))
(define parse-ellipsis-splicing
(lambda (form)
(let loop ((len 2) (tail (cdddr form)))
(cond ((and (pair? tail) (ellipsis-id? (car tail)))
(loop (+ len 1) (cdr tail)))
(else
(values (list-head form len) tail len))))))
(define check-template
(lambda (tmpl ranks)
(define control-patvar-exists?
(lambda (tmpl depth)
(let loop ((lst tmpl) (depth depth))
(cond ((symbol? lst) (>= (rank-of lst ranks) depth))
((ellipsis-quote? lst)
(any1 (lambda (id) (>= (rank-of id ranks) depth)) (collect-unique-macro-ids lst)))
((ellipsis-splicing-pair? lst)
(let-values (((body tail len) (parse-ellipsis-splicing lst)))
(or (loop body (+ depth 1)) (and (loop body 1) (loop tail depth)))))
((ellipsis-pair? lst)
(or (loop (car lst) (+ depth 1)) (and (loop (car lst) 1) (loop (cddr lst) depth))))
((pair? lst) (or (loop (car lst) depth) (loop (cdr lst) depth)))
((vector? lst) (loop (vector->list lst) depth))
(else #f)))))
(define check-escaped
(lambda (lst depth)
(let loop ((lst lst))
(cond ((symbol? lst)
(and (< 0 (rank-of lst ranks) depth)
(syntax-violation "syntax template" "too few ellipsis following subtemplate" tmpl lst)))
((pair? lst) (loop (car lst)) (loop (cdr lst)))
((vector? lst) (loop (vector->list lst)))))))
(if (and (= (safe-length tmpl) 2) (ellipsis-id? (car tmpl)))
(check-escaped (cadr tmpl) 0)
(let loop ((lst tmpl) (depth 0))
(cond ((symbol? lst)
(and (ellipsis-id? lst) (syntax-violation "syntax template" "misplaced ellipsis" tmpl))
(and (> (rank-of lst ranks) depth)
(syntax-violation "syntax template" "too few ellipsis following subtemplate" tmpl lst)))
((ellipsis-quote? lst) (check-escaped (cadr lst) depth))
((ellipsis-splicing-pair? lst)
(let-values (((body tail len) (parse-ellipsis-splicing lst)))
(and (= depth 0)
(or (control-patvar-exists? (car lst) len)
(syntax-violation
"syntax template"
"missing pattern variable that used in same level as in pattern"
tmpl
lst)))
(loop body (+ depth 1))
(loop tail depth)))
((ellipsis-pair? lst)
(cond ((symbol? (car lst))
(let ((rank (rank-of (car lst) ranks)))
(cond ((< rank 0)
(syntax-violation
"syntax template"
"misplace ellipsis following literal"
tmpl
(car lst)))
((= rank 0)
(syntax-violation
"syntax template"
"too many ellipsis following subtemplate"
tmpl
(car lst)))
((> rank (+ depth 1))
(syntax-violation
"syntax template"
"too few ellipsis following subtemplate"
tmpl
(car lst)))
(else (loop (cddr lst) depth)))))
((pair? (car lst))
(and (= depth 0)
(or (control-patvar-exists? (car lst) (+ depth 1))
(syntax-violation
"syntax template"
"missing pattern variable that used in same level as in pattern"
tmpl
(car lst))))
(loop (car lst) (+ depth 1))
(loop (cddr lst) depth))
((null? (car lst))
(syntax-violation "syntax template" "misplaced ellipsis following empty list" tmpl))
(else
(syntax-violation "syntax template" "misplaced ellipsis following literal" tmpl (car lst)))))
((pair? lst) (loop (car lst) depth) (loop (cdr lst) depth))
((vector? lst) (loop (vector->list lst) depth)))))))
(define rank-of
(lambda (name ranks)
(let ((slot (assq name ranks)))
(if slot (cdr slot) -1))))
(define subform-of
(lambda (name vars)
(cdr (assq name vars))))
(define collect-ellipsis-vars
(lambda (tmpl ranks depth vars)
(let ((ids (collect-unique-macro-ids tmpl)))
(filter values
(map (lambda (slot)
(and (memq (car slot) ids)
(let ((rank (cdr (assq (car slot) ranks))))
(cond ((< rank depth) slot)
((null? (cdr slot)) slot)
(else (cons (car slot) (cadr slot)))))))
vars)))))
;; consumed exhausted return
;; #t #t --> #f error, different size of matched subform
;; #t #f --> remains more variable to reveal
# f # t -- > # t all variable revealed
# f # f -- > ( ) no variable revealed
(define consume-ellipsis-vars
(lambda (ranks depth vars)
(let ((exhausted #f) (consumed #f))
(let ((remains
(let loop ((lst vars))
(cond ((null? lst) lst)
((< (rank-of (caar lst) ranks) depth)
(cons (car lst) (loop (cdr lst))))
((null? (cdar lst))
(loop (cdr lst)))
((null? (cddar lst))
(set! exhausted #t) (loop (cdr lst)))
(else
(set! consumed #t)
(acons (caar lst) (cddar lst) (loop (cdr lst))))))))
(if consumed (and (not exhausted) remains) (or exhausted '()))))))
(define transcribe-template
(lambda (in-form in-ranks in-vars aliases emit)
(define remove-duplicates
(lambda (alist)
(or (let loop ((lst alist)) (cond ((null? lst) alist) ((assq (caar lst) (cdr lst)) #f) (else (loop (cdr lst)))))
(let loop ((lst alist) (acc '()))
(cond ((null? lst) acc)
((assq (caar lst) acc) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc))))))))
(let ((tmpl in-form) (ranks in-ranks) (vars (remove-duplicates in-vars)))
(define expand-var
(lambda (tmpl vars)
(cond ((assq tmpl vars)
=> (lambda (slot) (cond ((null? (cdr slot)) '()) (emit (emit (cadr slot))) (else (cadr slot)))))
((and (assq tmpl in-ranks) (not (assq tmpl in-vars)))
(syntax-violation "syntax template" (format "pattern variable ~u out of context" tmpl) in-form))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars))))))
(define expand-ellipsis-var
(lambda (tmpl vars)
(cond ((assq tmpl vars)
=> (lambda (slot) (cond ((null? (cdr slot)) '()) (emit (map emit (cadr slot))) (else (cadr slot)))))
((and (assq tmpl in-ranks) (not (assq tmpl in-vars)))
(syntax-violation "syntax template" (format "pattern variable ~u out of context" tmpl) in-form))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars))))))
(define expand-ellipsis-template
(lambda (tmpl depth vars)
(let loop ((expr '()) (remains (collect-ellipsis-vars tmpl ranks depth vars)))
(cond ((pair? remains)
(loop (cons (expand-template tmpl depth remains) expr) (consume-ellipsis-vars ranks depth remains)))
((null? remains) '())
((eq? remains #t) (reverse expr))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars)))))))
(define expand-escaped-template
(lambda (tmpl depth vars)
(cond ((symbol? tmpl)
(if (< (rank-of tmpl ranks) 0) (cond ((assq tmpl aliases) => cdr) (else tmpl)) (expand-var tmpl vars)))
((pair? tmpl)
(if (and emit (null? (car tmpl)))
(cons '|.&NIL| (expand-escaped-template (cdr tmpl) depth vars))
(cons (expand-escaped-template (car tmpl) depth vars)
(expand-escaped-template (cdr tmpl) depth vars))))
((vector? tmpl) (list->vector (expand-escaped-template (vector->list tmpl) depth vars)))
(else tmpl))))
(define expand-template
(lambda (tmpl depth vars)
(cond ((symbol? tmpl)
(if (< (rank-of tmpl ranks) 0) (cond ((assq tmpl aliases) => cdr) (else tmpl)) (expand-var tmpl vars)))
((ellipsis-quote? tmpl) (expand-escaped-template (cadr tmpl) depth vars))
((ellipsis-splicing-pair? tmpl)
(let-values (((body tail len) (parse-ellipsis-splicing tmpl)))
(append
(apply append (expand-ellipsis-template body (+ depth 1) vars))
(expand-template tail depth vars))))
((ellipsis-pair? tmpl)
(cond ((symbol? (car tmpl))
(let ((rank (rank-of (car tmpl) ranks)))
(cond
((= rank (+ depth 1))
(append (expand-ellipsis-var (car tmpl) vars) (expand-template (cddr tmpl) depth vars))))))
((pair? (car tmpl))
(append
(expand-ellipsis-template (car tmpl) (+ depth 1) vars)
(expand-template (cddr tmpl) depth vars)))))
((pair? tmpl)
(if (and emit (null? (car tmpl)))
(cons '|.&NIL| (expand-template (cdr tmpl) depth vars))
(cons (expand-template (car tmpl) depth vars) (expand-template (cdr tmpl) depth vars))))
((vector? tmpl) (list->vector (expand-template (vector->list tmpl) depth vars)))
(else tmpl))))
(if (and (= (safe-length tmpl) 2) (ellipsis-id? (car tmpl)))
(expand-escaped-template (cadr tmpl) 0 vars)
(expand-template tmpl 0 vars)))))
| null | https://raw.githubusercontent.com/fujita-y/ypsilon/a67923c74a369ec369ab0545c52b014bacabbcd3/heap/boot/macro/syntmp.scm | scheme | See LICENSE file for terms and conditions of use.
consumed exhausted return
#t #t --> #f error, different size of matched subform
#t #f --> remains more variable to reveal | Copyright ( c ) 2004 - 2022 Yoshikatsu Fujita / LittleWing Company Limited .
(define collect-rename-ids
(lambda (template ranks)
(let ((ids (collect-unique-macro-ids template)))
(let loop ((lst ids))
(if (null? lst)
lst
(if (assq (car lst) ranks)
(loop (cdr lst))
(cons (car lst) (loop (cdr lst)))))))))
(define parse-ellipsis-splicing
(lambda (form)
(let loop ((len 2) (tail (cdddr form)))
(cond ((and (pair? tail) (ellipsis-id? (car tail)))
(loop (+ len 1) (cdr tail)))
(else
(values (list-head form len) tail len))))))
(define check-template
(lambda (tmpl ranks)
(define control-patvar-exists?
(lambda (tmpl depth)
(let loop ((lst tmpl) (depth depth))
(cond ((symbol? lst) (>= (rank-of lst ranks) depth))
((ellipsis-quote? lst)
(any1 (lambda (id) (>= (rank-of id ranks) depth)) (collect-unique-macro-ids lst)))
((ellipsis-splicing-pair? lst)
(let-values (((body tail len) (parse-ellipsis-splicing lst)))
(or (loop body (+ depth 1)) (and (loop body 1) (loop tail depth)))))
((ellipsis-pair? lst)
(or (loop (car lst) (+ depth 1)) (and (loop (car lst) 1) (loop (cddr lst) depth))))
((pair? lst) (or (loop (car lst) depth) (loop (cdr lst) depth)))
((vector? lst) (loop (vector->list lst) depth))
(else #f)))))
(define check-escaped
(lambda (lst depth)
(let loop ((lst lst))
(cond ((symbol? lst)
(and (< 0 (rank-of lst ranks) depth)
(syntax-violation "syntax template" "too few ellipsis following subtemplate" tmpl lst)))
((pair? lst) (loop (car lst)) (loop (cdr lst)))
((vector? lst) (loop (vector->list lst)))))))
(if (and (= (safe-length tmpl) 2) (ellipsis-id? (car tmpl)))
(check-escaped (cadr tmpl) 0)
(let loop ((lst tmpl) (depth 0))
(cond ((symbol? lst)
(and (ellipsis-id? lst) (syntax-violation "syntax template" "misplaced ellipsis" tmpl))
(and (> (rank-of lst ranks) depth)
(syntax-violation "syntax template" "too few ellipsis following subtemplate" tmpl lst)))
((ellipsis-quote? lst) (check-escaped (cadr lst) depth))
((ellipsis-splicing-pair? lst)
(let-values (((body tail len) (parse-ellipsis-splicing lst)))
(and (= depth 0)
(or (control-patvar-exists? (car lst) len)
(syntax-violation
"syntax template"
"missing pattern variable that used in same level as in pattern"
tmpl
lst)))
(loop body (+ depth 1))
(loop tail depth)))
((ellipsis-pair? lst)
(cond ((symbol? (car lst))
(let ((rank (rank-of (car lst) ranks)))
(cond ((< rank 0)
(syntax-violation
"syntax template"
"misplace ellipsis following literal"
tmpl
(car lst)))
((= rank 0)
(syntax-violation
"syntax template"
"too many ellipsis following subtemplate"
tmpl
(car lst)))
((> rank (+ depth 1))
(syntax-violation
"syntax template"
"too few ellipsis following subtemplate"
tmpl
(car lst)))
(else (loop (cddr lst) depth)))))
((pair? (car lst))
(and (= depth 0)
(or (control-patvar-exists? (car lst) (+ depth 1))
(syntax-violation
"syntax template"
"missing pattern variable that used in same level as in pattern"
tmpl
(car lst))))
(loop (car lst) (+ depth 1))
(loop (cddr lst) depth))
((null? (car lst))
(syntax-violation "syntax template" "misplaced ellipsis following empty list" tmpl))
(else
(syntax-violation "syntax template" "misplaced ellipsis following literal" tmpl (car lst)))))
((pair? lst) (loop (car lst) depth) (loop (cdr lst) depth))
((vector? lst) (loop (vector->list lst) depth)))))))
(define rank-of
(lambda (name ranks)
(let ((slot (assq name ranks)))
(if slot (cdr slot) -1))))
(define subform-of
(lambda (name vars)
(cdr (assq name vars))))
(define collect-ellipsis-vars
(lambda (tmpl ranks depth vars)
(let ((ids (collect-unique-macro-ids tmpl)))
(filter values
(map (lambda (slot)
(and (memq (car slot) ids)
(let ((rank (cdr (assq (car slot) ranks))))
(cond ((< rank depth) slot)
((null? (cdr slot)) slot)
(else (cons (car slot) (cadr slot)))))))
vars)))))
# f # t -- > # t all variable revealed
# f # f -- > ( ) no variable revealed
(define consume-ellipsis-vars
(lambda (ranks depth vars)
(let ((exhausted #f) (consumed #f))
(let ((remains
(let loop ((lst vars))
(cond ((null? lst) lst)
((< (rank-of (caar lst) ranks) depth)
(cons (car lst) (loop (cdr lst))))
((null? (cdar lst))
(loop (cdr lst)))
((null? (cddar lst))
(set! exhausted #t) (loop (cdr lst)))
(else
(set! consumed #t)
(acons (caar lst) (cddar lst) (loop (cdr lst))))))))
(if consumed (and (not exhausted) remains) (or exhausted '()))))))
(define transcribe-template
(lambda (in-form in-ranks in-vars aliases emit)
(define remove-duplicates
(lambda (alist)
(or (let loop ((lst alist)) (cond ((null? lst) alist) ((assq (caar lst) (cdr lst)) #f) (else (loop (cdr lst)))))
(let loop ((lst alist) (acc '()))
(cond ((null? lst) acc)
((assq (caar lst) acc) (loop (cdr lst) acc))
(else (loop (cdr lst) (cons (car lst) acc))))))))
(let ((tmpl in-form) (ranks in-ranks) (vars (remove-duplicates in-vars)))
(define expand-var
(lambda (tmpl vars)
(cond ((assq tmpl vars)
=> (lambda (slot) (cond ((null? (cdr slot)) '()) (emit (emit (cadr slot))) (else (cadr slot)))))
((and (assq tmpl in-ranks) (not (assq tmpl in-vars)))
(syntax-violation "syntax template" (format "pattern variable ~u out of context" tmpl) in-form))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars))))))
(define expand-ellipsis-var
(lambda (tmpl vars)
(cond ((assq tmpl vars)
=> (lambda (slot) (cond ((null? (cdr slot)) '()) (emit (map emit (cadr slot))) (else (cadr slot)))))
((and (assq tmpl in-ranks) (not (assq tmpl in-vars)))
(syntax-violation "syntax template" (format "pattern variable ~u out of context" tmpl) in-form))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars))))))
(define expand-ellipsis-template
(lambda (tmpl depth vars)
(let loop ((expr '()) (remains (collect-ellipsis-vars tmpl ranks depth vars)))
(cond ((pair? remains)
(loop (cons (expand-template tmpl depth remains) expr) (consume-ellipsis-vars ranks depth remains)))
((null? remains) '())
((eq? remains #t) (reverse expr))
(else
(assertion-violation
"syntax template"
"subforms have different size of matched input"
`(template: ,in-form)
`(subforms: ,@in-vars)))))))
(define expand-escaped-template
(lambda (tmpl depth vars)
(cond ((symbol? tmpl)
(if (< (rank-of tmpl ranks) 0) (cond ((assq tmpl aliases) => cdr) (else tmpl)) (expand-var tmpl vars)))
((pair? tmpl)
(if (and emit (null? (car tmpl)))
(cons '|.&NIL| (expand-escaped-template (cdr tmpl) depth vars))
(cons (expand-escaped-template (car tmpl) depth vars)
(expand-escaped-template (cdr tmpl) depth vars))))
((vector? tmpl) (list->vector (expand-escaped-template (vector->list tmpl) depth vars)))
(else tmpl))))
(define expand-template
(lambda (tmpl depth vars)
(cond ((symbol? tmpl)
(if (< (rank-of tmpl ranks) 0) (cond ((assq tmpl aliases) => cdr) (else tmpl)) (expand-var tmpl vars)))
((ellipsis-quote? tmpl) (expand-escaped-template (cadr tmpl) depth vars))
((ellipsis-splicing-pair? tmpl)
(let-values (((body tail len) (parse-ellipsis-splicing tmpl)))
(append
(apply append (expand-ellipsis-template body (+ depth 1) vars))
(expand-template tail depth vars))))
((ellipsis-pair? tmpl)
(cond ((symbol? (car tmpl))
(let ((rank (rank-of (car tmpl) ranks)))
(cond
((= rank (+ depth 1))
(append (expand-ellipsis-var (car tmpl) vars) (expand-template (cddr tmpl) depth vars))))))
((pair? (car tmpl))
(append
(expand-ellipsis-template (car tmpl) (+ depth 1) vars)
(expand-template (cddr tmpl) depth vars)))))
((pair? tmpl)
(if (and emit (null? (car tmpl)))
(cons '|.&NIL| (expand-template (cdr tmpl) depth vars))
(cons (expand-template (car tmpl) depth vars) (expand-template (cdr tmpl) depth vars))))
((vector? tmpl) (list->vector (expand-template (vector->list tmpl) depth vars)))
(else tmpl))))
(if (and (= (safe-length tmpl) 2) (ellipsis-id? (car tmpl)))
(expand-escaped-template (cadr tmpl) 0 vars)
(expand-template tmpl 0 vars)))))
|
fb3473f4d0272f75a0063419eed6646358148bf58b3f2e9589909e35ef770ec1 | MLstate/opalang | bslGeneration.ml |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
Wrapper around BslRegisterLib to make it easier to call from outside code .
Most of this file used to be part of bslregister.ml . This was
refactor to make it easier to call the plugin compiler from the
rest of the code .
Wrapper around BslRegisterLib to make it easier to call from outside code.
Most of this file used to be part of bslregister.ml. This was
refactor to make it easier to call the plugin compiler from the
rest of the code.
*)
module String = Base.String
module BI = BslInterface
module BR = BslRegisterLib
module List = BaseList
let ( / ) a b =
if a = "" then b
linux or compliant , ok for build see for user 's space use
let files_generated = ref 0
type options = {
(** A boolean to say if we want to generate the Plugin and the
Loader file. these files are used to link statically a plugin
with an executable, so that there is no need to load dynamically
a .bypass file for being able to load bypasses of a given plugin.
Currently, the static mode is used only for the opabsl, and the
resulting plugin is linked with opa.exe
The loader file can be used for interpreter in ml only (opatop)
to add new primitives. *)
static: bool;
* A boolean to say that generated files should be put in the
build_dir directly , without storing them in a opp directory .
build_dir directly, without storing them in a opp directory. *)
no_opp: bool;
(** Flag that says whether identifiers in the nodejs plugin should
be exported into the global namespace or if they should be used
as regular module exports (i.e. "exports.foo = foo;") *)
modular_plugins: bool;
build_dir: string;
bsl_pref: string;
auto_build: bool;
check_style: bool;
clean: bool;
clean_would_only: bool;
default_iformats: bool;
extrapaths: string list;
unsafe_js: bool;
unsafe_opa: bool;
bypass_plugins: BslDynlink.bypass_plugin_file list;
files: string list;
package_version: string;
spec_process: string StringMap.t;
ml_flags: string list;
mlopt_flags: string list;
js_validator: string option;
js_validator_files: string list;
js_validator_options: string list;
pprocess: string option;
js_classic_bypass_syntax: bool;
}
let default_opts = {
static = false;
no_opp = false;
modular_plugins = false;
build_dir = "";
bsl_pref = "default";
auto_build = false;
check_style = false;
clean = false;
clean_would_only = false;
default_iformats = false;
extrapaths = [];
unsafe_js = false;
unsafe_opa = false;
bypass_plugins = [];
files = [];
package_version = "0.1.0";
spec_process = StringMap.empty;
ml_flags = [];
mlopt_flags = [];
js_validator = None;
js_validator_files = [];
js_validator_options = [];
pprocess = None;
js_classic_bypass_syntax = true;
}
type files = {
opp_dir: string;
js_files: string list;
nodejs_files: string list;
nodejspackage: string;
package_json: string;
jskeys: string;
loader: string;
marshalplugin: string;
mlruntime: string;
mlruntime_mli: string;
plugin: string;
makefile: string;
stamp: string;
stamp_date: string;
}
* These are the inclusion to give for compiling plugins . This text
will be produced in the Makefile , which will interpret shell
expansion like $ ( MY_VAR )
will be produced in the Makefile, which will interpret shell
expansion like $(MY_VAR) *)
let static_extrapaths () =
Printf.sprintf "-I $(%s)/%s" InstallDir.name InstallDir.lib_opa
*
outputs in build_dir / libname.opp / libnameSuffix.ext
path to file may be absolute , in this case , produces
all the absolute path inside the build dir
outputs in build_dir/libname.opp/libnameSuffix.ext
path to file may be absolute, in this case, produces
all the absolute path inside the build dir
*)
let opp_dir opt =
if opt.no_opp then opt.build_dir
else
let opp = opt.bsl_pref ^ "." ^ BslConvention.Extension.plugin in
opt.build_dir / opp
let output_prefix ?(mkdir=true) opt prefix filename =
(*
info about the file
*)
let dirname =
let d = Filename.dirname filename in
if d = "." then "" else d
in
let basename = Filename.basename filename in
let filename = prefix ^ basename in
(*
output directory
*)
let directory = opp_dir opt in
let directory = directory/dirname in
let filename = directory/filename in
(*
eventually, check or create the directory
*)
if mkdir then (
if not (File.check_create_path filename) then
OManager.error "cannot create directory %s" directory
);
filename
let files_of_opt opt =
let map f = output_prefix opt opt.bsl_pref f in
let module S = BslConvention.Suffix in
let module E = BslConvention.Extension in
let has_extension ext f = File.extension f = ext in
let js_files = List.filter (has_extension "js") opt.files in
let nodejs_files = List.filter (has_extension "nodejs") opt.files in
{
opp_dir = opp_dir opt;
js_files;
nodejs_files;
nodejspackage = map (S.nodejspackage ^ ".js");
package_json = output_prefix opt "" "package.json";
jskeys = map (S.jskeys ^ ".js");
loader = map (S.loader ^ ".ml");
marshalplugin = map (S.marshalplugin ^ "." ^ E.bypass);
mlruntime = map (S.mlruntime ^ ".ml");
mlruntime_mli = map (S.mlruntime ^ ".mli");
plugin = map (S.plugin ^ ".ml");
makefile = output_prefix opt "" "Makefile";
stamp = output_prefix opt "" "stamp";
stamp_date = DebugTracer.now ();
}
(*
This function is used for itering opa and js generated files
*)
let prefix opt filename =
output_prefix opt (opt.bsl_pref ^ "_") filename
let js_code opt = prefix opt
let opa_code opt = prefix opt
let opa_interface opt f = (prefix opt f)^"i"
(* ======================================================================= *)
* { 6 Makefile Generation }
(* ======================================================================= *)
module Makefile :
sig
*
Return a buffer containing the generated Makefile .
Return a buffer containing the generated Makefile.
*)
val generate : options -> files -> Buffer.t
end =
struct
* For lisibility of this generation there , we use the
add_substitute function of the [ Buffer ] module . This means that
we use a list of binding for inserting dynamic parts into this
generated makefile . As we generating a Makefile , we need to
generate the $ character , in this case , it is escaped ' \$ ' .
add_substitute function of the [Buffer] module. This means that
we use a list of binding for inserting dynamic parts into this
generated makefile. As we generating a Makefile, we need to
generate the $ character, in this case, it is escaped '\$'. *)
let bindings opt fs =
let extrapaths =
static_extrapaths () ^ (
String.concat_map ~left:" " " " (Printf.sprintf "-I %s")
opt.extrapaths
) in
let suffix = String.concat " " (
BslConvention.Suffix.mlruntime ::
if opt.static then [
BslConvention.Suffix.loader ;
BslConvention.Suffix.plugin ;
] else []
)
in
let date = fs.stamp_date in
[
(* c *)
"command", String.concat " " (Array.to_list Sys.argv) ;
(* d *)
"date", date ;
(* g *)
"generator", Sys.argv.(0) ;
(* i *)
"include", extrapaths ;
(* m *)
"ml_flags", String.concat " " opt.ml_flags;
"mlopt_flags", String.concat " " opt.mlopt_flags;
(* p *)
"plugin", opt.bsl_pref ;
(* s *)
"suffix", suffix ;
(* v *)
"version", BuildInfos.version_id ;
]
let makefile_pattern =
"# ============================== #
# ==== BSL-CUSTOMLIB-MAKER ===== #
# ========== MLstate =========== #
# Generated Makefile by $(generator) version $(version) : $(date)
# from command : $(command)
OPP=$(plugin)
SUFFIX=$(suffix)
INCLUDE=$(include)
OCAML_FLAGS=$(ml_flags)
OCAMLOPT_FLAGS=$(mlopt_flags)
"
let static_part = "
TARGETS_CMI=$(patsubst %, $(OPP)%.cmi, $(SUFFIX))
TARGETS_CMX=$(patsubst %, $(OPP)%.cmx, $(SUFFIX))
TARGETS_CMXA=$(patsubst %, $(OPP)%.cmxa, $(SUFFIX))
all: $(TARGETS_CMI) $(TARGETS_CMX) $(TARGETS_CMXA)
OCAMLOPT ?= ocamlopt.opt
TRX ?= $(MLSTATELIBS)/bin/trx
%.ml : %.trx
\t$(TRX) $^ > $@
%.cmx : %.ml %.cmi
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
%.cmxa : %.cmx
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -a $< -o $@
%.cmi : %.mli
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
%.cmi : %.ml
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
clean :
\trm -f *.cmx *.cmo *.o *.cmi
wclean :
\t@echo \"Would remove *.cmx *.cmo *.o *.cmi\"
"
let generate opt fs =
let bindings = bindings opt fs in
let map = StringMap.from_list bindings in
let subst var =
try StringMap.find var map with
| Not_found ->
OManager.apologies ();
OManager.printf (
"@[<2>@{<bright>Hint@}:@\nvar %S is not found during Makefile generation.@]@\n"
)
var
;
assert false
in
let buf = Buffer.create 1024 in
let () =
try
Buffer.add_substitute buf subst makefile_pattern
with
| Not_found ->
OManager.apologies ();
OManager.printf (
"@[<2>@{<bright>Hint@}:@\nthe closing character of a parenthesized variable@\n"^^
"cannot be found during Makefile generation.@]@\n"
) ;
assert false
in
Buffer.add_string buf static_part ;
buf
end
(* ======================================================================= *)
let bslregisterlib_options opt fs =
let js_validator =
Option.map (
fun js ->
opt.build_dir, (js, opt.js_validator_files), opt.js_validator_options
) (opt.js_validator)
in
let options = {
BI.
basename = Some opt.bsl_pref;
bypass_plugins = opt.bypass_plugins;
check_style = opt.check_style;
js_files = fs.js_files;
nodejs_files = fs.nodejs_files;
js_validator ;
ml_plugin_filename = fs.plugin;
ml_runtime_filename = fs.mlruntime;
modular_plugins = opt.modular_plugins;
unsafe_js = opt.unsafe_js;
unsafe_opa = opt.unsafe_opa;
js_classic_bypass_syntax = opt.js_classic_bypass_syntax;
} in
options
let iter_generated_files opt fs fct =
List.iter (
fun f ->
match File.extension f with
| "opa" ->
fct (opa_code opt f) ;
fct (opa_interface opt f) ;
()
| "js" ->
fct (js_code opt f) ;
()
| "nodejs" ->
fct (js_code opt f) ;
()
| _ -> ()
) opt.files ;
fct fs.nodejspackage ;
fct fs.jskeys ;
fct fs.marshalplugin ;
fct fs.mlruntime ;
fct fs.mlruntime_mli ;
if opt.static then (
fct fs.loader ;
fct fs.plugin ;
) ;
fct fs.makefile ;
fct fs.stamp ;
()
let check_safety_overwrite opt fs =
let fct n =
if List.mem n opt.files then (
OManager.error (
"@[<2><!> bslregister refuses to do that !@\n"^^
"The file @{<bright>%S@} would be @{<bright>overwritten@} during the process@]"
) n
) in
iter_generated_files opt fs fct
let remove_file f =
try Unix.unlink f with Unix.Unix_error (e,_,_) ->
OManager.verbose
"@[<2><!> Cannot clean @{<bright>%s@}:@\n%s@]" f (Unix.error_message e)
(* clean, or just say what would be cleaned *)
let may_clean opt fs =
if opt.clean then (
let rm f =
if opt.clean_would_only
then OManager.printf "Would remove @{<bright>%s@}@\n" f
else (
OManager.unquiet "rm -f %s" f ;
remove_file f ;
()
)
in iter_generated_files opt fs rm;
exit 0
)
preprocessing format , for # # include
let may_add_format opt =
if opt.default_iformats then (
BslLib.HLParser.add_iformat BslLib.HLParser.default_opa_iformats ;
()
)
open_out_bin : read ,
Marshal should be used with binary channel
for a win OS compatilibity
Marshal should be used with binary channel
for a win OS compatilibity *)
let handle_open_out file =
try open_out_bin (PathTransform.string_to_mysys file)
with
| Sys_error s ->
OManager.error
"@[<2>@{<bright>bslregister@}: cannot open_out opa file @{<bright>%s@}:@\n%s@]"
file s
let handle_close_out file oc =
try close_out oc
with
| Sys_error s ->
OManager.error
"@[<2>@{<bright>bslregister@}: cannot close_out @{<bright>%s@}:@\n%s@]"
file s
let output filename pp a =
OManager.verbose "writing file @{<bright>%S@}..." filename ;
let oc = handle_open_out filename in
pp oc a ;
handle_close_out filename oc ;
incr(files_generated) ;
()
let make_iterator rename =
let output filename =
let filename = rename filename in
output filename
in
{ BR.output = output }
(* after finalization of register session, actually produce files *)
let files_generation (opt : options) (fs : files) (fin : BR.finalized_t) =
let iterator_opa_code = make_iterator (opa_code opt) in
let iterator_opa_interface = make_iterator (opa_interface opt) in
BR.out_opa_code iterator_opa_code fin;
BR.out_opa_interface iterator_opa_interface fin;
BR.write_nodejs_pack fs.nodejspackage fin;
output fs.jskeys BR.out_js_keys fin;
output fs.marshalplugin BR.out_ml_marshal_plugin fin;
if opt.static then (
output fs.loader BR.out_ml_loader fin;
output fs.plugin BR.out_ml_plugin fin;
) ;
if BR.need_makefile fin then (
let makefile = Makefile.generate opt fs in
output fs.mlruntime BR.out_ml_runtime fin;
output fs.mlruntime_mli BR.out_ml_runtime_mli fin;
output fs.makefile Buffer.output_buffer makefile;
);
output fs.stamp Pervasives.output_string fs.stamp_date;
()
let process opt =
let fs = files_of_opt opt in
check_safety_overwrite opt fs;
may_clean opt fs;
may_add_format opt;
let session =
let options = bslregisterlib_options opt fs in
BR.create ~options
in
let session =
let pprocess filename content =
match
try
Some (StringMap.find filename opt.spec_process)
with Not_found -> opt.pprocess
with None -> content
| Some command ->
try
let command = Printf.sprintf "%s \"%s\"" command filename in
let ic = Unix.open_process_in command in
let rec aux lines =
try
let line = input_line ic in
aux (line::lines)
with
| End_of_file ->
match Unix.close_process_in ic with
| Unix.WEXITED 0 -> String.rev_concat_map "\n" (fun s -> s) lines
| _ -> OManager.error "Error while preprocessing file '%s', command '%s'"
filename command
in
aux []
with
| Unix.Unix_error (error, a, b) ->
OManager.error "Unix_error (%S, %S, %S)" (Unix.error_message error) a b
in
BR.set_pprocess ~pprocess session
in
let session = List.fold_left (
fun session file ->
OManager.verbose "registering file @{<bright>%S@}" file ;
BR.preprocess_file session file
) session opt.files
in
OManager.verbose "generating files ...";
let finalized_t = BR.finalize session in
files_generation opt fs finalized_t ;
BR.js_validator finalized_t;
OManager.verbose "successful generation of plugin files : @{<bright>%d@} files"
!files_generated ;
if opt.auto_build && BR.need_makefile finalized_t then (
OManager.verbose "building plugin...";
let cmd = Printf.sprintf "%s -C %s -f %s"
Config.makebinary fs.opp_dir
(Filename.basename fs.makefile)
in
let log = Printf.sprintf "%s/compilation.log" fs.opp_dir in
let ret =
let system_call cmd =
let ic, oc = Unix.open_process cmd in
let buf = Buffer.create 16 in
(try
while true do
Buffer.add_channel buf ic 1
done
with End_of_file -> ());
let ret = Unix.close_process (ic, oc) in
Buffer.contents buf, ret
in
let std, ret =
system_call cmd
in
ignore (File.output log std);
match ret with
| Unix.WSIGNALED _
| Unix.WSTOPPED _ -> 1
| Unix.WEXITED x -> x
in
if ret <> 0
then
OManager.error
("Building failure due to error(s) in source files@\n"^^
"The command was @{<bright>%s@}, log is in @{<bright>%s@}")
cmd log
else
OManager.verbose "successful compilation of plugin @{<bright>%s@}"
opt.bsl_pref
);
(* if success : remove unused logs from previous error *)
if not (opt.unsafe_opa || opt.unsafe_js) then ignore (Sys.command "rm -f bsl_log_*");
| null | https://raw.githubusercontent.com/MLstate/opalang/424b369160ce693406cece6ac033d75d85f5df4f/compiler/libbsl/bslGeneration.ml | ocaml | * A boolean to say if we want to generate the Plugin and the
Loader file. these files are used to link statically a plugin
with an executable, so that there is no need to load dynamically
a .bypass file for being able to load bypasses of a given plugin.
Currently, the static mode is used only for the opabsl, and the
resulting plugin is linked with opa.exe
The loader file can be used for interpreter in ml only (opatop)
to add new primitives.
* Flag that says whether identifiers in the nodejs plugin should
be exported into the global namespace or if they should be used
as regular module exports (i.e. "exports.foo = foo;")
info about the file
output directory
eventually, check or create the directory
This function is used for itering opa and js generated files
=======================================================================
=======================================================================
c
d
g
i
m
p
s
v
=======================================================================
clean, or just say what would be cleaned
after finalization of register session, actually produce files
if success : remove unused logs from previous error |
Copyright © 2011 , 2012 MLstate
This file is part of .
is free software : you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License , version 3 , as published by
the Free Software Foundation .
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 . If not , see < / > .
Copyright © 2011, 2012 MLstate
This file is part of Opa.
Opa is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License, version 3, as published by
the Free Software Foundation.
Opa 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 Opa. If not, see </>.
*)
*
Wrapper around BslRegisterLib to make it easier to call from outside code .
Most of this file used to be part of bslregister.ml . This was
refactor to make it easier to call the plugin compiler from the
rest of the code .
Wrapper around BslRegisterLib to make it easier to call from outside code.
Most of this file used to be part of bslregister.ml. This was
refactor to make it easier to call the plugin compiler from the
rest of the code.
*)
module String = Base.String
module BI = BslInterface
module BR = BslRegisterLib
module List = BaseList
let ( / ) a b =
if a = "" then b
linux or compliant , ok for build see for user 's space use
let files_generated = ref 0
type options = {
static: bool;
* A boolean to say that generated files should be put in the
build_dir directly , without storing them in a opp directory .
build_dir directly, without storing them in a opp directory. *)
no_opp: bool;
modular_plugins: bool;
build_dir: string;
bsl_pref: string;
auto_build: bool;
check_style: bool;
clean: bool;
clean_would_only: bool;
default_iformats: bool;
extrapaths: string list;
unsafe_js: bool;
unsafe_opa: bool;
bypass_plugins: BslDynlink.bypass_plugin_file list;
files: string list;
package_version: string;
spec_process: string StringMap.t;
ml_flags: string list;
mlopt_flags: string list;
js_validator: string option;
js_validator_files: string list;
js_validator_options: string list;
pprocess: string option;
js_classic_bypass_syntax: bool;
}
let default_opts = {
static = false;
no_opp = false;
modular_plugins = false;
build_dir = "";
bsl_pref = "default";
auto_build = false;
check_style = false;
clean = false;
clean_would_only = false;
default_iformats = false;
extrapaths = [];
unsafe_js = false;
unsafe_opa = false;
bypass_plugins = [];
files = [];
package_version = "0.1.0";
spec_process = StringMap.empty;
ml_flags = [];
mlopt_flags = [];
js_validator = None;
js_validator_files = [];
js_validator_options = [];
pprocess = None;
js_classic_bypass_syntax = true;
}
type files = {
opp_dir: string;
js_files: string list;
nodejs_files: string list;
nodejspackage: string;
package_json: string;
jskeys: string;
loader: string;
marshalplugin: string;
mlruntime: string;
mlruntime_mli: string;
plugin: string;
makefile: string;
stamp: string;
stamp_date: string;
}
* These are the inclusion to give for compiling plugins . This text
will be produced in the Makefile , which will interpret shell
expansion like $ ( MY_VAR )
will be produced in the Makefile, which will interpret shell
expansion like $(MY_VAR) *)
let static_extrapaths () =
Printf.sprintf "-I $(%s)/%s" InstallDir.name InstallDir.lib_opa
*
outputs in build_dir / libname.opp / libnameSuffix.ext
path to file may be absolute , in this case , produces
all the absolute path inside the build dir
outputs in build_dir/libname.opp/libnameSuffix.ext
path to file may be absolute, in this case, produces
all the absolute path inside the build dir
*)
let opp_dir opt =
if opt.no_opp then opt.build_dir
else
let opp = opt.bsl_pref ^ "." ^ BslConvention.Extension.plugin in
opt.build_dir / opp
let output_prefix ?(mkdir=true) opt prefix filename =
let dirname =
let d = Filename.dirname filename in
if d = "." then "" else d
in
let basename = Filename.basename filename in
let filename = prefix ^ basename in
let directory = opp_dir opt in
let directory = directory/dirname in
let filename = directory/filename in
if mkdir then (
if not (File.check_create_path filename) then
OManager.error "cannot create directory %s" directory
);
filename
let files_of_opt opt =
let map f = output_prefix opt opt.bsl_pref f in
let module S = BslConvention.Suffix in
let module E = BslConvention.Extension in
let has_extension ext f = File.extension f = ext in
let js_files = List.filter (has_extension "js") opt.files in
let nodejs_files = List.filter (has_extension "nodejs") opt.files in
{
opp_dir = opp_dir opt;
js_files;
nodejs_files;
nodejspackage = map (S.nodejspackage ^ ".js");
package_json = output_prefix opt "" "package.json";
jskeys = map (S.jskeys ^ ".js");
loader = map (S.loader ^ ".ml");
marshalplugin = map (S.marshalplugin ^ "." ^ E.bypass);
mlruntime = map (S.mlruntime ^ ".ml");
mlruntime_mli = map (S.mlruntime ^ ".mli");
plugin = map (S.plugin ^ ".ml");
makefile = output_prefix opt "" "Makefile";
stamp = output_prefix opt "" "stamp";
stamp_date = DebugTracer.now ();
}
let prefix opt filename =
output_prefix opt (opt.bsl_pref ^ "_") filename
let js_code opt = prefix opt
let opa_code opt = prefix opt
let opa_interface opt f = (prefix opt f)^"i"
* { 6 Makefile Generation }
module Makefile :
sig
*
Return a buffer containing the generated Makefile .
Return a buffer containing the generated Makefile.
*)
val generate : options -> files -> Buffer.t
end =
struct
* For lisibility of this generation there , we use the
add_substitute function of the [ Buffer ] module . This means that
we use a list of binding for inserting dynamic parts into this
generated makefile . As we generating a Makefile , we need to
generate the $ character , in this case , it is escaped ' \$ ' .
add_substitute function of the [Buffer] module. This means that
we use a list of binding for inserting dynamic parts into this
generated makefile. As we generating a Makefile, we need to
generate the $ character, in this case, it is escaped '\$'. *)
let bindings opt fs =
let extrapaths =
static_extrapaths () ^ (
String.concat_map ~left:" " " " (Printf.sprintf "-I %s")
opt.extrapaths
) in
let suffix = String.concat " " (
BslConvention.Suffix.mlruntime ::
if opt.static then [
BslConvention.Suffix.loader ;
BslConvention.Suffix.plugin ;
] else []
)
in
let date = fs.stamp_date in
[
"command", String.concat " " (Array.to_list Sys.argv) ;
"date", date ;
"generator", Sys.argv.(0) ;
"include", extrapaths ;
"ml_flags", String.concat " " opt.ml_flags;
"mlopt_flags", String.concat " " opt.mlopt_flags;
"plugin", opt.bsl_pref ;
"suffix", suffix ;
"version", BuildInfos.version_id ;
]
let makefile_pattern =
"# ============================== #
# ==== BSL-CUSTOMLIB-MAKER ===== #
# ========== MLstate =========== #
# Generated Makefile by $(generator) version $(version) : $(date)
# from command : $(command)
OPP=$(plugin)
SUFFIX=$(suffix)
INCLUDE=$(include)
OCAML_FLAGS=$(ml_flags)
OCAMLOPT_FLAGS=$(mlopt_flags)
"
let static_part = "
TARGETS_CMI=$(patsubst %, $(OPP)%.cmi, $(SUFFIX))
TARGETS_CMX=$(patsubst %, $(OPP)%.cmx, $(SUFFIX))
TARGETS_CMXA=$(patsubst %, $(OPP)%.cmxa, $(SUFFIX))
all: $(TARGETS_CMI) $(TARGETS_CMX) $(TARGETS_CMXA)
OCAMLOPT ?= ocamlopt.opt
TRX ?= $(MLSTATELIBS)/bin/trx
%.ml : %.trx
\t$(TRX) $^ > $@
%.cmx : %.ml %.cmi
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
%.cmxa : %.cmx
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -a $< -o $@
%.cmi : %.mli
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
%.cmi : %.ml
\t$(OCAMLOPT) $(OCAML_FLAGS) $(OCAMLOPT_FLAGS) $(INCLUDE) -c $<
clean :
\trm -f *.cmx *.cmo *.o *.cmi
wclean :
\t@echo \"Would remove *.cmx *.cmo *.o *.cmi\"
"
let generate opt fs =
let bindings = bindings opt fs in
let map = StringMap.from_list bindings in
let subst var =
try StringMap.find var map with
| Not_found ->
OManager.apologies ();
OManager.printf (
"@[<2>@{<bright>Hint@}:@\nvar %S is not found during Makefile generation.@]@\n"
)
var
;
assert false
in
let buf = Buffer.create 1024 in
let () =
try
Buffer.add_substitute buf subst makefile_pattern
with
| Not_found ->
OManager.apologies ();
OManager.printf (
"@[<2>@{<bright>Hint@}:@\nthe closing character of a parenthesized variable@\n"^^
"cannot be found during Makefile generation.@]@\n"
) ;
assert false
in
Buffer.add_string buf static_part ;
buf
end
let bslregisterlib_options opt fs =
let js_validator =
Option.map (
fun js ->
opt.build_dir, (js, opt.js_validator_files), opt.js_validator_options
) (opt.js_validator)
in
let options = {
BI.
basename = Some opt.bsl_pref;
bypass_plugins = opt.bypass_plugins;
check_style = opt.check_style;
js_files = fs.js_files;
nodejs_files = fs.nodejs_files;
js_validator ;
ml_plugin_filename = fs.plugin;
ml_runtime_filename = fs.mlruntime;
modular_plugins = opt.modular_plugins;
unsafe_js = opt.unsafe_js;
unsafe_opa = opt.unsafe_opa;
js_classic_bypass_syntax = opt.js_classic_bypass_syntax;
} in
options
let iter_generated_files opt fs fct =
List.iter (
fun f ->
match File.extension f with
| "opa" ->
fct (opa_code opt f) ;
fct (opa_interface opt f) ;
()
| "js" ->
fct (js_code opt f) ;
()
| "nodejs" ->
fct (js_code opt f) ;
()
| _ -> ()
) opt.files ;
fct fs.nodejspackage ;
fct fs.jskeys ;
fct fs.marshalplugin ;
fct fs.mlruntime ;
fct fs.mlruntime_mli ;
if opt.static then (
fct fs.loader ;
fct fs.plugin ;
) ;
fct fs.makefile ;
fct fs.stamp ;
()
let check_safety_overwrite opt fs =
let fct n =
if List.mem n opt.files then (
OManager.error (
"@[<2><!> bslregister refuses to do that !@\n"^^
"The file @{<bright>%S@} would be @{<bright>overwritten@} during the process@]"
) n
) in
iter_generated_files opt fs fct
let remove_file f =
try Unix.unlink f with Unix.Unix_error (e,_,_) ->
OManager.verbose
"@[<2><!> Cannot clean @{<bright>%s@}:@\n%s@]" f (Unix.error_message e)
let may_clean opt fs =
if opt.clean then (
let rm f =
if opt.clean_would_only
then OManager.printf "Would remove @{<bright>%s@}@\n" f
else (
OManager.unquiet "rm -f %s" f ;
remove_file f ;
()
)
in iter_generated_files opt fs rm;
exit 0
)
preprocessing format , for # # include
let may_add_format opt =
if opt.default_iformats then (
BslLib.HLParser.add_iformat BslLib.HLParser.default_opa_iformats ;
()
)
open_out_bin : read ,
Marshal should be used with binary channel
for a win OS compatilibity
Marshal should be used with binary channel
for a win OS compatilibity *)
let handle_open_out file =
try open_out_bin (PathTransform.string_to_mysys file)
with
| Sys_error s ->
OManager.error
"@[<2>@{<bright>bslregister@}: cannot open_out opa file @{<bright>%s@}:@\n%s@]"
file s
let handle_close_out file oc =
try close_out oc
with
| Sys_error s ->
OManager.error
"@[<2>@{<bright>bslregister@}: cannot close_out @{<bright>%s@}:@\n%s@]"
file s
let output filename pp a =
OManager.verbose "writing file @{<bright>%S@}..." filename ;
let oc = handle_open_out filename in
pp oc a ;
handle_close_out filename oc ;
incr(files_generated) ;
()
let make_iterator rename =
let output filename =
let filename = rename filename in
output filename
in
{ BR.output = output }
let files_generation (opt : options) (fs : files) (fin : BR.finalized_t) =
let iterator_opa_code = make_iterator (opa_code opt) in
let iterator_opa_interface = make_iterator (opa_interface opt) in
BR.out_opa_code iterator_opa_code fin;
BR.out_opa_interface iterator_opa_interface fin;
BR.write_nodejs_pack fs.nodejspackage fin;
output fs.jskeys BR.out_js_keys fin;
output fs.marshalplugin BR.out_ml_marshal_plugin fin;
if opt.static then (
output fs.loader BR.out_ml_loader fin;
output fs.plugin BR.out_ml_plugin fin;
) ;
if BR.need_makefile fin then (
let makefile = Makefile.generate opt fs in
output fs.mlruntime BR.out_ml_runtime fin;
output fs.mlruntime_mli BR.out_ml_runtime_mli fin;
output fs.makefile Buffer.output_buffer makefile;
);
output fs.stamp Pervasives.output_string fs.stamp_date;
()
let process opt =
let fs = files_of_opt opt in
check_safety_overwrite opt fs;
may_clean opt fs;
may_add_format opt;
let session =
let options = bslregisterlib_options opt fs in
BR.create ~options
in
let session =
let pprocess filename content =
match
try
Some (StringMap.find filename opt.spec_process)
with Not_found -> opt.pprocess
with None -> content
| Some command ->
try
let command = Printf.sprintf "%s \"%s\"" command filename in
let ic = Unix.open_process_in command in
let rec aux lines =
try
let line = input_line ic in
aux (line::lines)
with
| End_of_file ->
match Unix.close_process_in ic with
| Unix.WEXITED 0 -> String.rev_concat_map "\n" (fun s -> s) lines
| _ -> OManager.error "Error while preprocessing file '%s', command '%s'"
filename command
in
aux []
with
| Unix.Unix_error (error, a, b) ->
OManager.error "Unix_error (%S, %S, %S)" (Unix.error_message error) a b
in
BR.set_pprocess ~pprocess session
in
let session = List.fold_left (
fun session file ->
OManager.verbose "registering file @{<bright>%S@}" file ;
BR.preprocess_file session file
) session opt.files
in
OManager.verbose "generating files ...";
let finalized_t = BR.finalize session in
files_generation opt fs finalized_t ;
BR.js_validator finalized_t;
OManager.verbose "successful generation of plugin files : @{<bright>%d@} files"
!files_generated ;
if opt.auto_build && BR.need_makefile finalized_t then (
OManager.verbose "building plugin...";
let cmd = Printf.sprintf "%s -C %s -f %s"
Config.makebinary fs.opp_dir
(Filename.basename fs.makefile)
in
let log = Printf.sprintf "%s/compilation.log" fs.opp_dir in
let ret =
let system_call cmd =
let ic, oc = Unix.open_process cmd in
let buf = Buffer.create 16 in
(try
while true do
Buffer.add_channel buf ic 1
done
with End_of_file -> ());
let ret = Unix.close_process (ic, oc) in
Buffer.contents buf, ret
in
let std, ret =
system_call cmd
in
ignore (File.output log std);
match ret with
| Unix.WSIGNALED _
| Unix.WSTOPPED _ -> 1
| Unix.WEXITED x -> x
in
if ret <> 0
then
OManager.error
("Building failure due to error(s) in source files@\n"^^
"The command was @{<bright>%s@}, log is in @{<bright>%s@}")
cmd log
else
OManager.verbose "successful compilation of plugin @{<bright>%s@}"
opt.bsl_pref
);
if not (opt.unsafe_opa || opt.unsafe_js) then ignore (Sys.command "rm -f bsl_log_*");
|
d84f0965f35ef6179935df64c8a1f94c205b0a30e1717d83b6254bec4d0d7c66 | jabber-at/ejabberd-contrib | fusco_protocol.erl | %%%=============================================================================
( C ) 2013 , Erlang Solutions Ltd
@author < >
%%% @doc
%%%
%%% @end
%%%=============================================================================
-module(fusco_protocol).
-copyright("2013, Erlang Solutions Ltd.").
-include("fusco.hrl").
-define(SIZE(Data, Response), Response#response{size = Response#response.size + byte_size(Data)}).
-define(RECEPTION(Data, Response), Response#response{size = byte_size(Data),
in_timestamp = os:timestamp()}).
-define(TOUT, 1000).
%% Latency is here defined as the time from the start of packet transmission to the start of packet reception
%% API
-export([recv/2, recv/3,
decode_cookie/1]).
%% TEST
-export([decode_header_value/5, decode_header_value/6,
decode_header/3, decode_header/4]).
TODO handle partial downloads
recv(Socket, Ssl) ->
recv(Socket, Ssl, infinity).
recv(Socket, Ssl, Timeout) ->
case fusco_sock:recv(Socket, Ssl, Timeout) of
{ok, Data} ->
decode_status_line(<< Data/binary >>,
?RECEPTION(Data, #response{socket = Socket, ssl = Ssl}), Timeout);
{error, Reason} ->
{error, Reason}
end.
decode_status_line(<<"HTTP/1.0\s",C1,C2,C3,$\s,Rest/bits>>, Response, Timeout) ->
decode_reason_phrase(Rest, <<>>, Response#response{version = {1,0},
status_code = <<C1,C2,C3>>}, Timeout);
decode_status_line(<<"HTTP/1.1\s",C1,C2,C3,$\s,Rest/bits>>, Response, Timeout) ->
decode_reason_phrase(Rest, <<>>, Response#response{version = {1,1},
status_code = <<C1,C2,C3>>}, Timeout);
decode_status_line(Bin, Response = #response{size = Size}, Timeout) when Size < 13 ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_status_line(<<Bin/binary, Data/binary>>, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_status_line(_, _, _) ->
{error, status_line}.
decode_reason_phrase(<<>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_reason_phrase(Data, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_reason_phrase(<<$\r>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_reason_phrase(<<$\r, Data/binary>>, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_reason_phrase(<<$\n, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{reason = Acc}, Timeout);
decode_reason_phrase(<<$\r,$\n, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{reason = Acc}, Timeout);
decode_reason_phrase(<<C, Rest/bits>>, Acc, Response, Timeout) ->
decode_reason_phrase(Rest, <<Acc/binary, C>>, Response, Timeout).
decode_header(Data, Acc, Response) ->
decode_header(Data, Acc, Response, infinity).
decode_header(<<>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header(Data, Acc, ?SIZE(Data, Response), Timeout);
{error, closed} ->
case Acc of
<<>> ->
decode_body(<<>>, Response, Timeout);
_ ->
{error, closed}
end;
{error, Reason} ->
{error, Reason}
end;
decode_header(<<$\r>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header(<<$\r, Data/binary>>, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header(<<$\s, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, Acc, Response, Timeout);
decode_header(<<$:, Rest/bits>>, Header, Response, Timeout) ->
decode_header_value_ws(Rest, Header, Response, Timeout);
decode_header(<<$\n, Rest/bits>>, <<>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_header(<<$\r, $\n, Rest/bits>>, <<>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_header(<<$\r, $\n, _Rest/bits>>, _, _Response, _Timeout) ->
{error, header};
decode_header(<<$A, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $a>>, Response, Timeout);
decode_header(<<$B, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $b>>, Response, Timeout);
decode_header(<<$C, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $c>>, Response, Timeout);
decode_header(<<$D, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $d>>, Response, Timeout);
decode_header(<<$E, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $e>>, Response, Timeout);
decode_header(<<$F, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $f>>, Response, Timeout);
decode_header(<<$G, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $g>>, Response, Timeout);
decode_header(<<$H, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $h>>, Response, Timeout);
decode_header(<<$I, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $i>>, Response, Timeout);
decode_header(<<$J, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $j>>, Response, Timeout);
decode_header(<<$K, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $k>>, Response, Timeout);
decode_header(<<$L, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $l>>, Response, Timeout);
decode_header(<<$M, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $m>>, Response, Timeout);
decode_header(<<$N, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $n>>, Response, Timeout);
decode_header(<<$O, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $o>>, Response, Timeout);
decode_header(<<$P, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $p>>, Response, Timeout);
decode_header(<<$Q, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $q>>, Response, Timeout);
decode_header(<<$R, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $r>>, Response, Timeout);
decode_header(<<$S, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $s>>, Response, Timeout);
decode_header(<<$T, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $t>>, Response, Timeout);
decode_header(<<$U, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $u>>, Response, Timeout);
decode_header(<<$V, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $v>>, Response, Timeout);
decode_header(<<$W, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $w>>, Response, Timeout);
decode_header(<<$X, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $x>>, Response, Timeout);
decode_header(<<$Y, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $y>>, Response, Timeout);
decode_header(<<$Z, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $z>>, Response, Timeout);
decode_header(<<C, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, C>>, Response, Timeout).
decode_header_value_ws(<<$\s, Rest/bits>>, H, S, Timeout) ->
decode_header_value_ws(Rest, H, S, Timeout);
decode_header_value_ws(<<$\t, Rest/bits>>, H, S, Timeout) ->
decode_header_value_ws(Rest, H, S, Timeout);
decode_header_value_ws(Rest, <<"connection">> = H, S, Timeout) ->
decode_header_value_lc(Rest, H, <<>>, <<>>, S, Timeout);
decode_header_value_ws(Rest, <<"transfer-encoding">> = H, S, Timeout) ->
decode_header_value_lc(Rest, H, <<>>, <<>>, S, Timeout);
decode_header_value_ws(Rest, H, S, Timeout) ->
decode_header_value(Rest, H, <<>>, <<>>, S, Timeout).
decode_header_value(Data, H, V, T, Response) ->
decode_header_value(Data, H, V, T, Response, infinity).
decode_header_value(<<>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value(Data, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value(<<$\r>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value(<<$\r, Data/binary>>, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value(<<$\n, Rest/bits>>, <<"content-length">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
content_length = binary_to_integer(V)}, Timeout);
decode_header_value(<<$\n, Rest/bits>>, <<"set-cookie">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{cookies = [decode_cookie(V)
| Response#response.cookies],
headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\r, $\n, Rest/bits>>, <<"set-cookie">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{cookies = [decode_cookie(V)
| Response#response.cookies],
headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\r,$\n, Rest/bits>>, <<"content-length">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
content_length = binary_to_integer(V)}, Timeout);
decode_header_value(<<$\r, $\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\s, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, V, <<T/binary, $\s>>, Response, Timeout);
decode_header_value(<<$\t, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, V, <<T/binary, $\t>>, Response, Timeout);
decode_header_value(<<C, Rest/bits>>, H, V, <<>>, Response, Timeout) ->
decode_header_value(Rest, H, <<V/binary, C>>, <<>>, Response, Timeout);
decode_header_value(<<C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, <<V/binary, T/binary, C>>, <<>>, Response, Timeout).
decode_header_value_lc(<<>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value_lc(Data, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value_lc(<<$\r>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value_lc(<<$\r, Data/binary>>, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value_lc(<<$\n, Rest/bits>>, <<"transfer-encoding">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
transfer_encoding = V}, Timeout);
decode_header_value_lc(<<$\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
connection = V}, Timeout);
decode_header_value_lc(<<$\r, $\n, Rest/bits>>, <<"transfer-encoding">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
transfer_encoding = V}, Timeout);
decode_header_value_lc(<<$\r, $\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
connection = V}, Timeout);
decode_header_value_lc(<<$\s, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, V, <<T/binary, $\s>>, Response, Timeout);
decode_header_value_lc(<<$\t, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, V, <<T/binary, $\t>>, Response, Timeout);
decode_header_value_lc(<<$A, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $a>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$B, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $b>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $c>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$D, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $d>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$E, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $e>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$F, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $f>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$G, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $g>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$H, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $h>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$I, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $i>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$J, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $j>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$K, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $k>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$L, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $l>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$M, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $m>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$N, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $n>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$O, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $o>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$P, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $p>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Q, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $q>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$R, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $r>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$S, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $s>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$T, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $t>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$U, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $u>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$V, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $v>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$W, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $w>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$X, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $x>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Y, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $y>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Z, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $z>>, <<>>, Response, Timeout);
decode_header_value_lc(<<C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, C>>, <<>>, Response, Timeout).
%% RFC 6265
TODO decode cookie values , this only accepts ' a = b '
decode_cookie(Cookie) ->
decode_cookie_name(Cookie, <<>>).
decode_cookie_name(<<$\s, Rest/bits>>, N) ->
decode_cookie_name(Rest, N);
decode_cookie_name(<<$\t, Rest/bits>>, N) ->
decode_cookie_name(Rest, N);
decode_cookie_name(<<$=, Rest/bits>>, N) ->
decode_cookie_value(Rest, N, <<>>);
decode_cookie_name(<<C, Rest/bits>>, N) ->
decode_cookie_name(Rest, <<N/binary, C>>).
decode_cookie_value(<<$\s, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, V);
decode_cookie_value(<<$\t, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, V);
decode_cookie_value(<<$;, Rest/bits>>, N, V) ->
decode_cookie_av_ws(Rest, #fusco_cookie{name = N, value = V});
decode_cookie_value(<<C, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, <<V/binary, C>>);
decode_cookie_value(<<>>, N, V) ->
#fusco_cookie{name = N, value = V}.
decode_cookie_av_ws(<<$\s, Rest/bits>>, C) ->
decode_cookie_av_ws(Rest, C);
decode_cookie_av_ws(<<$\t, Rest/bits>>, C) ->
decode_cookie_av_ws(Rest, C);
We are only interested on Expires , , Path , Domain
decode_cookie_av_ws(<<$e, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$e>>);
decode_cookie_av_ws(<<$E, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$e>>);
decode_cookie_av_ws(<<$m, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$m>>);
decode_cookie_av_ws(<<$M, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$m>>);
decode_cookie_av_ws(<<$p, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$p>>);
decode_cookie_av_ws(<<$P, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$p>>);
decode_cookie_av_ws(<<$d, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$d>>);
decode_cookie_av_ws(<<$D, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$d>>);
decode_cookie_av_ws(Rest, C) ->
ignore_cookie_av(Rest, C).
ignore_cookie_av(<<$;, Rest/bits>>, Co) ->
decode_cookie_av_ws(Rest, Co);
ignore_cookie_av(<<_, Rest/bits>>, Co) ->
ignore_cookie_av(Rest, Co);
ignore_cookie_av(<<>>, Co) ->
Co.
Match only uppercase chars on Expires , , Path , Domain
decode_cookie_av(<<$=, Rest/bits>>, Co, AV) ->
decode_cookie_av_value(Rest, Co, AV, <<>>);
decode_cookie_av(<<$D, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $d>>);
decode_cookie_av(<<$O, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $o>>);
decode_cookie_av(<<$N, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $n>>);
decode_cookie_av(<<$E, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $e>>);
decode_cookie_av(<<$X, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $x>>);
decode_cookie_av(<<$P, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $p>>);
decode_cookie_av(<<$I, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $i>>);
decode_cookie_av(<<$R, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $r>>);
decode_cookie_av(<<$S, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $s>>);
decode_cookie_av(<<$M, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $m>>);
decode_cookie_av(<<$A, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $a>>);
decode_cookie_av(<<$G, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $g>>);
decode_cookie_av(<<$T, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $t>>);
decode_cookie_av(<<$H, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $h>>);
decode_cookie_av(<<$;, Rest/bits>>, Co, _AV) ->
decode_cookie_av_ws(Rest, Co);
decode_cookie_av(<<C, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, C>>);
decode_cookie_av(<<>>, Co, _AV) ->
ignore_cookie_av(<<>>, Co).
decode_cookie_av_value(<<>>, Co, <<"path">>, Value) ->
Co#fusco_cookie{path_tokens = binary:split(Value, <<"/">>, [global]),
path = Value};
decode_cookie_av_value(<<>>, Co, <<"max-age">>, Value) ->
Co#fusco_cookie{max_age = max_age(Value)};
decode_cookie_av_value(<<>>, Co, <<"expires">>, Value) ->
Co#fusco_cookie{expires = expires(Value)};
decode_cookie_av_value(<<>>, Co, <<"domain">>, Value) ->
Co#fusco_cookie{domain = Value};
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"path">>, Value) ->
Path = binary:split(Value, <<"/">>, [global]),
decode_cookie_av_ws(Rest, Co#fusco_cookie{path_tokens = Path,
path = Value});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"max-age">>, Value) ->
decode_cookie_av_ws(Rest, Co#fusco_cookie{
max_age = max_age(Value)});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"expires">>, Value) ->
TODO parse expires
decode_cookie_av_ws(Rest, Co#fusco_cookie{expires = expires(Value)});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"domain">>, Value) ->
decode_cookie_av_ws(Rest, Co#fusco_cookie{domain = Value});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, _, _) ->
decode_cookie_av_ws(Rest, Co);
decode_cookie_av_value(<<C, Rest/bits>>, Co, AV, Value) ->
decode_cookie_av_value(Rest, Co, AV, <<Value/binary, C>>).
decode_body(<<>>, Response = #response{status_code = <<$1, _, _>>,
transfer_encoding = TE}, _Timeout)
when TE =/= <<"chunked">> ->
return(<<>>, Response);
decode_body(<<$\r, $\n, Rest/bits>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_body(Rest, Response = #response{status_code = <<$1, _, _>>,
transfer_encoding = TE}, Timeout)
when TE =/= <<"chunked">> ->
decode_status_line(Rest, #response{socket = Response#response.socket,
ssl = Response#response.ssl,
in_timestamp = Response#response.in_timestamp}, Timeout);
decode_body(Rest, Response = #response{transfer_encoding = <<"chunked">>}, Timeout) ->
decode_chunked_body(Rest, <<>>, <<>>, Response, Timeout);
decode_body(Rest, Response, Timeout) ->
case byte_size(Rest) >= Response#response.content_length of
true ->
return(Rest, Response);
false ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_body(<<Rest/binary, Data/binary>>, ?SIZE(Data, Response), Timeout);
_ ->
%% NOTE: Return what we have so far
return(Rest, Response)
end
end.
download_chunked_body(Rest, Acc, Size, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_chunked_body(<<Rest/bits, Data/bits>>, Acc, Size,
?SIZE(Data, Response), Timeout);
_ ->
return(Acc, Response)
end.
decode_chunked_body(<<$0,$\r,$\n,$\r,$\n>>, Acc, _, Response, _Timeout) ->
return(Acc, Response);
decode_chunked_body(<<$0, Rest/bits>> = R, Acc, Size, Response, Timeout)
when is_binary(Size), byte_size(Rest) < 4 ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(<<$\r>> = R, Acc, Size, Response, Timeout) when is_binary(Size) ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(<<$\r,$\n, Rest/bits>>, Acc, <<>>, Response, Timeout) ->
decode_chunked_body(Rest, Acc, <<>>, Response, Timeout);
decode_chunked_body(<<$\r,$\n, Rest/bits>>, Acc, Size, Response, Timeout) when is_binary(Size) ->
IntSize = erlang:binary_to_integer(Size, 16),
decode_chunked_body(Rest, Acc, IntSize, Response, Timeout);
decode_chunked_body(<<C, Rest/bits>>, Acc, Size, Response, Timeout) when is_binary(Size) ->
decode_chunked_body(Rest, Acc, <<Size/bits, C>>, Response, Timeout);
decode_chunked_body(<<>> = R, Acc, Size, Response, Timeout) when is_binary(Size) ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(Rest, Acc, Size, Response, Timeout) when is_integer(Size) ->
case byte_size(Rest) of
S when S == Size ->
decode_chunked_body(<<>>, <<Acc/bits, Rest/bits>>, <<>>, Response, Timeout);
S when S < Size ->
download_chunked_body(Rest, Acc, Size, Response, Timeout);
S when S > Size ->
Current = binary:part(Rest, 0, Size),
Next = binary:part(Rest, Size, S - Size),
decode_chunked_body(Next, <<Acc/bits, Current/bits>>, <<>>, Response, Timeout)
end.
return(Body, Response) ->
Response#response{body = Body}.
max_age(Value) ->
binary_to_integer(Value) * 1000000.
%% #section-3.3.1
Supports some non - standard datetime ( Tomcat ) Tue , 06 - Nov-1994 08:49:37 GMT
expires(<<_,_,_,$,,$\s,D1,D2,$\s,M1,M2,M3,$\s,Y1,Y2,Y3,Y4,$\s,Rest/bits>>) ->
expires(Rest, {list_to_integer([Y1,Y2,Y3,Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])});
expires(<<_,_,_,$\s,Mo1,Mo2,Mo3,$\s,D1,D2,$\s,H1,H2,$:,M1,M2,$:,S1,S2,$\s,Y1,Y2,Y3,Y4,_Rest/bits>>) ->
{{list_to_integer([Y1,Y2,Y3,Y4]),month(<<Mo1,Mo2,Mo3>>),list_to_integer([D1,D2])},
{list_to_integer([H1,H2]), list_to_integer([M1,M2]), list_to_integer([S1,S2])}};
expires(<<_,_,_,$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Monday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Tuesday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Wednesday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Thursday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Friday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Saturday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Sunday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<D1,D2,$\-,M1,M2,M3,$\-,Y1,Y2,Y3,Y4,$\s,Rest/bits>>) ->
expires(Rest, {list_to_integer([Y1,Y2,Y3,Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])});
expires(<<D1,D2,$\-,M1,M2,M3,$\-,Y3,Y4,$\s,Rest/bits>>) ->
#section-19.3
%% HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
which appears to be more than 50 years in the future is in fact
%% in the past (this helps solve the "year 2000" problem).
expires(Rest, {to_year([Y3, Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])}).
to_year(List) ->
Int = list_to_integer(List),
{Y, _, _} = date(),
case (2000 + Int - Y) > 50 of
true ->
1900 + Int;
false ->
2000 + Int
end.
expires(<<H1,H2,$:,M1,M2,$:,S1,S2,_Rest/bits>>, Date) ->
{Date, {list_to_integer([H1,H2]), list_to_integer([M1,M2]), list_to_integer([S1,S2])}}.
month(<<$J,$a,$n>>) ->
1;
month(<<$F,$e,$b>>) ->
2;
month(<<$M,$a,$r>>) ->
3;
month(<<$A,$p,$r>>) ->
4;
month(<<$M,$a,$y>>) ->
5;
month(<<$J,$u,$n>>) ->
6;
month(<<$J,$u,$l>>) ->
7;
month(<<$A,$u,$g>>) ->
8;
month(<<$S,$e,$p>>) ->
9;
month(<<$O,$c,$t>>) ->
10;
month(<<$N,$o,$v>>) ->
11;
month(<<$D,$e,$c>>) ->
12.
| null | https://raw.githubusercontent.com/jabber-at/ejabberd-contrib/d5eb036b786c822d9fd56f881d27e31688ec6e91/ejabberd_auth_http/deps/fusco/src/fusco_protocol.erl | erlang | =============================================================================
@doc
@end
=============================================================================
Latency is here defined as the time from the start of packet transmission to the start of packet reception
API
TEST
RFC 6265
NOTE: Return what we have so far
#section-3.3.1
HTTP/1.1 clients and caches SHOULD assume that an RFC-850 date
in the past (this helps solve the "year 2000" problem). | ( C ) 2013 , Erlang Solutions Ltd
@author < >
-module(fusco_protocol).
-copyright("2013, Erlang Solutions Ltd.").
-include("fusco.hrl").
-define(SIZE(Data, Response), Response#response{size = Response#response.size + byte_size(Data)}).
-define(RECEPTION(Data, Response), Response#response{size = byte_size(Data),
in_timestamp = os:timestamp()}).
-define(TOUT, 1000).
-export([recv/2, recv/3,
decode_cookie/1]).
-export([decode_header_value/5, decode_header_value/6,
decode_header/3, decode_header/4]).
TODO handle partial downloads
recv(Socket, Ssl) ->
recv(Socket, Ssl, infinity).
recv(Socket, Ssl, Timeout) ->
case fusco_sock:recv(Socket, Ssl, Timeout) of
{ok, Data} ->
decode_status_line(<< Data/binary >>,
?RECEPTION(Data, #response{socket = Socket, ssl = Ssl}), Timeout);
{error, Reason} ->
{error, Reason}
end.
decode_status_line(<<"HTTP/1.0\s",C1,C2,C3,$\s,Rest/bits>>, Response, Timeout) ->
decode_reason_phrase(Rest, <<>>, Response#response{version = {1,0},
status_code = <<C1,C2,C3>>}, Timeout);
decode_status_line(<<"HTTP/1.1\s",C1,C2,C3,$\s,Rest/bits>>, Response, Timeout) ->
decode_reason_phrase(Rest, <<>>, Response#response{version = {1,1},
status_code = <<C1,C2,C3>>}, Timeout);
decode_status_line(Bin, Response = #response{size = Size}, Timeout) when Size < 13 ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_status_line(<<Bin/binary, Data/binary>>, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_status_line(_, _, _) ->
{error, status_line}.
decode_reason_phrase(<<>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_reason_phrase(Data, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_reason_phrase(<<$\r>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_reason_phrase(<<$\r, Data/binary>>, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_reason_phrase(<<$\n, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{reason = Acc}, Timeout);
decode_reason_phrase(<<$\r,$\n, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{reason = Acc}, Timeout);
decode_reason_phrase(<<C, Rest/bits>>, Acc, Response, Timeout) ->
decode_reason_phrase(Rest, <<Acc/binary, C>>, Response, Timeout).
decode_header(Data, Acc, Response) ->
decode_header(Data, Acc, Response, infinity).
decode_header(<<>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header(Data, Acc, ?SIZE(Data, Response), Timeout);
{error, closed} ->
case Acc of
<<>> ->
decode_body(<<>>, Response, Timeout);
_ ->
{error, closed}
end;
{error, Reason} ->
{error, Reason}
end;
decode_header(<<$\r>>, Acc, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header(<<$\r, Data/binary>>, Acc, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header(<<$\s, Rest/bits>>, Acc, Response, Timeout) ->
decode_header(Rest, Acc, Response, Timeout);
decode_header(<<$:, Rest/bits>>, Header, Response, Timeout) ->
decode_header_value_ws(Rest, Header, Response, Timeout);
decode_header(<<$\n, Rest/bits>>, <<>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_header(<<$\r, $\n, Rest/bits>>, <<>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_header(<<$\r, $\n, _Rest/bits>>, _, _Response, _Timeout) ->
{error, header};
decode_header(<<$A, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $a>>, Response, Timeout);
decode_header(<<$B, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $b>>, Response, Timeout);
decode_header(<<$C, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $c>>, Response, Timeout);
decode_header(<<$D, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $d>>, Response, Timeout);
decode_header(<<$E, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $e>>, Response, Timeout);
decode_header(<<$F, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $f>>, Response, Timeout);
decode_header(<<$G, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $g>>, Response, Timeout);
decode_header(<<$H, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $h>>, Response, Timeout);
decode_header(<<$I, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $i>>, Response, Timeout);
decode_header(<<$J, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $j>>, Response, Timeout);
decode_header(<<$K, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $k>>, Response, Timeout);
decode_header(<<$L, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $l>>, Response, Timeout);
decode_header(<<$M, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $m>>, Response, Timeout);
decode_header(<<$N, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $n>>, Response, Timeout);
decode_header(<<$O, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $o>>, Response, Timeout);
decode_header(<<$P, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $p>>, Response, Timeout);
decode_header(<<$Q, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $q>>, Response, Timeout);
decode_header(<<$R, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $r>>, Response, Timeout);
decode_header(<<$S, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $s>>, Response, Timeout);
decode_header(<<$T, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $t>>, Response, Timeout);
decode_header(<<$U, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $u>>, Response, Timeout);
decode_header(<<$V, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $v>>, Response, Timeout);
decode_header(<<$W, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $w>>, Response, Timeout);
decode_header(<<$X, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $x>>, Response, Timeout);
decode_header(<<$Y, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $y>>, Response, Timeout);
decode_header(<<$Z, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, $z>>, Response, Timeout);
decode_header(<<C, Rest/bits>>, Header, Response, Timeout) ->
decode_header(Rest, <<Header/binary, C>>, Response, Timeout).
decode_header_value_ws(<<$\s, Rest/bits>>, H, S, Timeout) ->
decode_header_value_ws(Rest, H, S, Timeout);
decode_header_value_ws(<<$\t, Rest/bits>>, H, S, Timeout) ->
decode_header_value_ws(Rest, H, S, Timeout);
decode_header_value_ws(Rest, <<"connection">> = H, S, Timeout) ->
decode_header_value_lc(Rest, H, <<>>, <<>>, S, Timeout);
decode_header_value_ws(Rest, <<"transfer-encoding">> = H, S, Timeout) ->
decode_header_value_lc(Rest, H, <<>>, <<>>, S, Timeout);
decode_header_value_ws(Rest, H, S, Timeout) ->
decode_header_value(Rest, H, <<>>, <<>>, S, Timeout).
decode_header_value(Data, H, V, T, Response) ->
decode_header_value(Data, H, V, T, Response, infinity).
decode_header_value(<<>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value(Data, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value(<<$\r>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value(<<$\r, Data/binary>>, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value(<<$\n, Rest/bits>>, <<"content-length">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
content_length = binary_to_integer(V)}, Timeout);
decode_header_value(<<$\n, Rest/bits>>, <<"set-cookie">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{cookies = [decode_cookie(V)
| Response#response.cookies],
headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\r, $\n, Rest/bits>>, <<"set-cookie">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{cookies = [decode_cookie(V)
| Response#response.cookies],
headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\r,$\n, Rest/bits>>, <<"content-length">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
content_length = binary_to_integer(V)}, Timeout);
decode_header_value(<<$\r, $\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers]}, Timeout);
decode_header_value(<<$\s, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, V, <<T/binary, $\s>>, Response, Timeout);
decode_header_value(<<$\t, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, V, <<T/binary, $\t>>, Response, Timeout);
decode_header_value(<<C, Rest/bits>>, H, V, <<>>, Response, Timeout) ->
decode_header_value(Rest, H, <<V/binary, C>>, <<>>, Response, Timeout);
decode_header_value(<<C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value(Rest, H, <<V/binary, T/binary, C>>, <<>>, Response, Timeout).
decode_header_value_lc(<<>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value_lc(Data, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value_lc(<<$\r>>, H, V, T, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_header_value_lc(<<$\r, Data/binary>>, H, V, T, ?SIZE(Data, Response), Timeout);
{error, Reason} ->
{error, Reason}
end;
decode_header_value_lc(<<$\n, Rest/bits>>, <<"transfer-encoding">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
transfer_encoding = V}, Timeout);
decode_header_value_lc(<<$\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
connection = V}, Timeout);
decode_header_value_lc(<<$\r, $\n, Rest/bits>>, <<"transfer-encoding">> = H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
transfer_encoding = V}, Timeout);
decode_header_value_lc(<<$\r, $\n, Rest/bits>>, H, V, _T, Response, Timeout) ->
decode_header(Rest, <<>>, Response#response{headers = [{H, V} | Response#response.headers],
connection = V}, Timeout);
decode_header_value_lc(<<$\s, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, V, <<T/binary, $\s>>, Response, Timeout);
decode_header_value_lc(<<$\t, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, V, <<T/binary, $\t>>, Response, Timeout);
decode_header_value_lc(<<$A, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $a>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$B, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $b>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $c>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$D, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $d>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$E, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $e>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$F, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $f>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$G, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $g>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$H, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $h>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$I, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $i>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$J, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $j>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$K, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $k>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$L, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $l>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$M, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $m>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$N, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $n>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$O, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $o>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$P, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $p>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Q, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $q>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$R, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $r>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$S, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $s>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$T, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $t>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$U, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $u>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$V, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $v>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$W, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $w>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$X, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $x>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Y, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $y>>, <<>>, Response, Timeout);
decode_header_value_lc(<<$Z, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, $z>>, <<>>, Response, Timeout);
decode_header_value_lc(<<C, Rest/bits>>, H, V, T, Response, Timeout) ->
decode_header_value_lc(Rest, H, <<V/binary, T/binary, C>>, <<>>, Response, Timeout).
TODO decode cookie values , this only accepts ' a = b '
decode_cookie(Cookie) ->
decode_cookie_name(Cookie, <<>>).
decode_cookie_name(<<$\s, Rest/bits>>, N) ->
decode_cookie_name(Rest, N);
decode_cookie_name(<<$\t, Rest/bits>>, N) ->
decode_cookie_name(Rest, N);
decode_cookie_name(<<$=, Rest/bits>>, N) ->
decode_cookie_value(Rest, N, <<>>);
decode_cookie_name(<<C, Rest/bits>>, N) ->
decode_cookie_name(Rest, <<N/binary, C>>).
decode_cookie_value(<<$\s, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, V);
decode_cookie_value(<<$\t, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, V);
decode_cookie_value(<<$;, Rest/bits>>, N, V) ->
decode_cookie_av_ws(Rest, #fusco_cookie{name = N, value = V});
decode_cookie_value(<<C, Rest/bits>>, N, V) ->
decode_cookie_value(Rest, N, <<V/binary, C>>);
decode_cookie_value(<<>>, N, V) ->
#fusco_cookie{name = N, value = V}.
decode_cookie_av_ws(<<$\s, Rest/bits>>, C) ->
decode_cookie_av_ws(Rest, C);
decode_cookie_av_ws(<<$\t, Rest/bits>>, C) ->
decode_cookie_av_ws(Rest, C);
We are only interested on Expires , , Path , Domain
decode_cookie_av_ws(<<$e, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$e>>);
decode_cookie_av_ws(<<$E, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$e>>);
decode_cookie_av_ws(<<$m, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$m>>);
decode_cookie_av_ws(<<$M, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$m>>);
decode_cookie_av_ws(<<$p, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$p>>);
decode_cookie_av_ws(<<$P, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$p>>);
decode_cookie_av_ws(<<$d, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$d>>);
decode_cookie_av_ws(<<$D, Rest/bits>>, C) ->
decode_cookie_av(Rest, C, <<$d>>);
decode_cookie_av_ws(Rest, C) ->
ignore_cookie_av(Rest, C).
ignore_cookie_av(<<$;, Rest/bits>>, Co) ->
decode_cookie_av_ws(Rest, Co);
ignore_cookie_av(<<_, Rest/bits>>, Co) ->
ignore_cookie_av(Rest, Co);
ignore_cookie_av(<<>>, Co) ->
Co.
Match only uppercase chars on Expires , , Path , Domain
decode_cookie_av(<<$=, Rest/bits>>, Co, AV) ->
decode_cookie_av_value(Rest, Co, AV, <<>>);
decode_cookie_av(<<$D, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $d>>);
decode_cookie_av(<<$O, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $o>>);
decode_cookie_av(<<$N, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $n>>);
decode_cookie_av(<<$E, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $e>>);
decode_cookie_av(<<$X, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $x>>);
decode_cookie_av(<<$P, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $p>>);
decode_cookie_av(<<$I, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $i>>);
decode_cookie_av(<<$R, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $r>>);
decode_cookie_av(<<$S, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $s>>);
decode_cookie_av(<<$M, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $m>>);
decode_cookie_av(<<$A, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $a>>);
decode_cookie_av(<<$G, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $g>>);
decode_cookie_av(<<$T, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $t>>);
decode_cookie_av(<<$H, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, $h>>);
decode_cookie_av(<<$;, Rest/bits>>, Co, _AV) ->
decode_cookie_av_ws(Rest, Co);
decode_cookie_av(<<C, Rest/bits>>, Co, AV) ->
decode_cookie_av(Rest, Co, <<AV/binary, C>>);
decode_cookie_av(<<>>, Co, _AV) ->
ignore_cookie_av(<<>>, Co).
decode_cookie_av_value(<<>>, Co, <<"path">>, Value) ->
Co#fusco_cookie{path_tokens = binary:split(Value, <<"/">>, [global]),
path = Value};
decode_cookie_av_value(<<>>, Co, <<"max-age">>, Value) ->
Co#fusco_cookie{max_age = max_age(Value)};
decode_cookie_av_value(<<>>, Co, <<"expires">>, Value) ->
Co#fusco_cookie{expires = expires(Value)};
decode_cookie_av_value(<<>>, Co, <<"domain">>, Value) ->
Co#fusco_cookie{domain = Value};
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"path">>, Value) ->
Path = binary:split(Value, <<"/">>, [global]),
decode_cookie_av_ws(Rest, Co#fusco_cookie{path_tokens = Path,
path = Value});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"max-age">>, Value) ->
decode_cookie_av_ws(Rest, Co#fusco_cookie{
max_age = max_age(Value)});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"expires">>, Value) ->
TODO parse expires
decode_cookie_av_ws(Rest, Co#fusco_cookie{expires = expires(Value)});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, <<"domain">>, Value) ->
decode_cookie_av_ws(Rest, Co#fusco_cookie{domain = Value});
decode_cookie_av_value(<<$;, Rest/bits>>, Co, _, _) ->
decode_cookie_av_ws(Rest, Co);
decode_cookie_av_value(<<C, Rest/bits>>, Co, AV, Value) ->
decode_cookie_av_value(Rest, Co, AV, <<Value/binary, C>>).
decode_body(<<>>, Response = #response{status_code = <<$1, _, _>>,
transfer_encoding = TE}, _Timeout)
when TE =/= <<"chunked">> ->
return(<<>>, Response);
decode_body(<<$\r, $\n, Rest/bits>>, Response, Timeout) ->
decode_body(Rest, Response, Timeout);
decode_body(Rest, Response = #response{status_code = <<$1, _, _>>,
transfer_encoding = TE}, Timeout)
when TE =/= <<"chunked">> ->
decode_status_line(Rest, #response{socket = Response#response.socket,
ssl = Response#response.ssl,
in_timestamp = Response#response.in_timestamp}, Timeout);
decode_body(Rest, Response = #response{transfer_encoding = <<"chunked">>}, Timeout) ->
decode_chunked_body(Rest, <<>>, <<>>, Response, Timeout);
decode_body(Rest, Response, Timeout) ->
case byte_size(Rest) >= Response#response.content_length of
true ->
return(Rest, Response);
false ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_body(<<Rest/binary, Data/binary>>, ?SIZE(Data, Response), Timeout);
_ ->
return(Rest, Response)
end
end.
download_chunked_body(Rest, Acc, Size, Response, Timeout) ->
case fusco_sock:recv(Response#response.socket, Response#response.ssl, Timeout) of
{ok, Data} ->
decode_chunked_body(<<Rest/bits, Data/bits>>, Acc, Size,
?SIZE(Data, Response), Timeout);
_ ->
return(Acc, Response)
end.
decode_chunked_body(<<$0,$\r,$\n,$\r,$\n>>, Acc, _, Response, _Timeout) ->
return(Acc, Response);
decode_chunked_body(<<$0, Rest/bits>> = R, Acc, Size, Response, Timeout)
when is_binary(Size), byte_size(Rest) < 4 ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(<<$\r>> = R, Acc, Size, Response, Timeout) when is_binary(Size) ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(<<$\r,$\n, Rest/bits>>, Acc, <<>>, Response, Timeout) ->
decode_chunked_body(Rest, Acc, <<>>, Response, Timeout);
decode_chunked_body(<<$\r,$\n, Rest/bits>>, Acc, Size, Response, Timeout) when is_binary(Size) ->
IntSize = erlang:binary_to_integer(Size, 16),
decode_chunked_body(Rest, Acc, IntSize, Response, Timeout);
decode_chunked_body(<<C, Rest/bits>>, Acc, Size, Response, Timeout) when is_binary(Size) ->
decode_chunked_body(Rest, Acc, <<Size/bits, C>>, Response, Timeout);
decode_chunked_body(<<>> = R, Acc, Size, Response, Timeout) when is_binary(Size) ->
download_chunked_body(R, Acc, Size, Response, Timeout);
decode_chunked_body(Rest, Acc, Size, Response, Timeout) when is_integer(Size) ->
case byte_size(Rest) of
S when S == Size ->
decode_chunked_body(<<>>, <<Acc/bits, Rest/bits>>, <<>>, Response, Timeout);
S when S < Size ->
download_chunked_body(Rest, Acc, Size, Response, Timeout);
S when S > Size ->
Current = binary:part(Rest, 0, Size),
Next = binary:part(Rest, Size, S - Size),
decode_chunked_body(Next, <<Acc/bits, Current/bits>>, <<>>, Response, Timeout)
end.
return(Body, Response) ->
Response#response{body = Body}.
max_age(Value) ->
binary_to_integer(Value) * 1000000.
Supports some non - standard datetime ( Tomcat ) Tue , 06 - Nov-1994 08:49:37 GMT
expires(<<_,_,_,$,,$\s,D1,D2,$\s,M1,M2,M3,$\s,Y1,Y2,Y3,Y4,$\s,Rest/bits>>) ->
expires(Rest, {list_to_integer([Y1,Y2,Y3,Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])});
expires(<<_,_,_,$\s,Mo1,Mo2,Mo3,$\s,D1,D2,$\s,H1,H2,$:,M1,M2,$:,S1,S2,$\s,Y1,Y2,Y3,Y4,_Rest/bits>>) ->
{{list_to_integer([Y1,Y2,Y3,Y4]),month(<<Mo1,Mo2,Mo3>>),list_to_integer([D1,D2])},
{list_to_integer([H1,H2]), list_to_integer([M1,M2]), list_to_integer([S1,S2])}};
expires(<<_,_,_,$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Monday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Tuesday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Wednesday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Thursday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Friday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Saturday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<"Sunday",$,,$\s,Rest/bits>>) ->
expires(Rest);
expires(<<D1,D2,$\-,M1,M2,M3,$\-,Y1,Y2,Y3,Y4,$\s,Rest/bits>>) ->
expires(Rest, {list_to_integer([Y1,Y2,Y3,Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])});
expires(<<D1,D2,$\-,M1,M2,M3,$\-,Y3,Y4,$\s,Rest/bits>>) ->
#section-19.3
which appears to be more than 50 years in the future is in fact
expires(Rest, {to_year([Y3, Y4]),month(<<M1,M2,M3>>),list_to_integer([D1,D2])}).
to_year(List) ->
Int = list_to_integer(List),
{Y, _, _} = date(),
case (2000 + Int - Y) > 50 of
true ->
1900 + Int;
false ->
2000 + Int
end.
expires(<<H1,H2,$:,M1,M2,$:,S1,S2,_Rest/bits>>, Date) ->
{Date, {list_to_integer([H1,H2]), list_to_integer([M1,M2]), list_to_integer([S1,S2])}}.
month(<<$J,$a,$n>>) ->
1;
month(<<$F,$e,$b>>) ->
2;
month(<<$M,$a,$r>>) ->
3;
month(<<$A,$p,$r>>) ->
4;
month(<<$M,$a,$y>>) ->
5;
month(<<$J,$u,$n>>) ->
6;
month(<<$J,$u,$l>>) ->
7;
month(<<$A,$u,$g>>) ->
8;
month(<<$S,$e,$p>>) ->
9;
month(<<$O,$c,$t>>) ->
10;
month(<<$N,$o,$v>>) ->
11;
month(<<$D,$e,$c>>) ->
12.
|
457d63eefffebf61eaa30e05a68fe4dd75c761edc83f1e782bcc04503b5152be | 2600hz/kazoo | knm_options.erl | %%%-----------------------------------------------------------------------------
( C ) 2015 - 2020 , 2600Hz
%%% @doc
@author
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%%
%%% @end
%%%-----------------------------------------------------------------------------
-module(knm_options).
-export([assign_to/1, assign_to/2, set_assign_to/2
,auth_by/1, auth_by/2
,dry_run/1, dry_run/2
,batch_run/1, batch_run/2
,mdn_run/1
,module_name/1
,ported_in/1
,public_fields/1
,state/1, state/2
,crossbar/1, crossbar/2
,default/0
,mdn_options/0
,to_phone_number_setters/1
]).
-export([account_id/1, set_account_id/2
,has_pending_port/1
,inbound_cnam_enabled/1
,is_local_number/1
,number/1
,prepend/1
,ringback_media_id/1
,should_force_outbound/1
,transfer_media_id/1
]).
-export([is_defined/2
,are_defined/2
]).
-include("knm.hrl").
-type crossbar_option() :: {'services', kz_services:services()} |
{'account_id', kz_term:api_ne_binary()} |
{'reseller_id', kz_term:api_ne_binary()}.
-type crossbar_options() :: [crossbar_option()].
-type assign_to() :: kz_term:api_ne_binary().
-type option() :: {'assign_to', assign_to()} |
{'auth_by', kz_term:api_ne_binary()} |
{'batch_run', boolean()} |
{'crossbar', crossbar_options()} |
{'dry_run', boolean()} |
{'mdn_run', boolean()} |
{'module_name', kz_term:ne_binary()} |
{'ported_in', boolean()} |
{'public_fields', kz_json:object()} |
{'state', kz_term:ne_binary()}.
-type options() :: [option()].
-type extra_option() :: {'account_id', kz_term:ne_binary()} | %%api
{'force_outbound', boolean()} |
{'inbound_cnam', boolean()} |
{'local', boolean()} |
{'number', kz_term:ne_binary()} | %%api
{'pending_port', boolean()} |
{'prepend', kz_term:api_binary()} | %%|false
{'ringback_media', kz_term:api_binary()} |
{'transfer_media', kz_term:api_binary()}.
-type extra_options() :: [extra_option()].
-export_type([option/0, options/0
,extra_option/0, extra_options/0
]).
-spec default() -> options().
default() ->
[{'auth_by', ?KNM_DEFAULT_AUTH_BY}
,{'batch_run', 'false'}
,{'mdn_run', 'false'}
].
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec is_defined(options(), fun() | {fun(), any()}) -> boolean().
is_defined(Options, {Getter, ExpectedVal}) when is_function(Getter, 2) ->
case Getter(Options, ExpectedVal) of
ExpectedVal -> 'true';
_ -> 'false'
end;
is_defined(Options, Getter) when is_function(Getter, 1) ->
case Getter(Options) of
'undefined' -> 'false';
[] -> 'false';
<<>> -> 'false';
_ -> 'true'
end.
-spec are_defined(options(), [fun() | {fun(), any()}]) -> boolean().
are_defined(Options, Getters) ->
lists:all(fun(Getter) -> is_defined(Options, Getter) end, Getters).
%%------------------------------------------------------------------------------
%% @doc
%% @end
%%------------------------------------------------------------------------------
-spec mdn_options() -> options().
mdn_options() ->
props:set_value('mdn_run', 'true', default()).
-spec to_phone_number_setters(options()) -> knm_phone_number:set_functions().
to_phone_number_setters(Options) ->
[{setter_fun(Option), Value}
|| {Option, Value} <- props:unique(Options),
is_atom(Option),
Option =/= 'crossbar'
].
-spec setter_fun(atom()) -> knm_phone_number:set_function().
setter_fun('public_fields') ->
fun knm_phone_number:reset_doc/2;
setter_fun(Option) ->
FName = list_to_existing_atom("set_" ++ atom_to_list(Option)),
fun knm_phone_number:FName/2.
-spec dry_run(options()) -> boolean().
dry_run(Options) ->
dry_run(Options, 'false').
-spec dry_run(options(), Default) -> boolean() | Default.
dry_run(Options, Default) ->
maybe_dry_run(props:get_is_true('dry_run', Options, Default)).
-spec maybe_dry_run(DryRun) -> DryRun
when DryRun :: boolean().
maybe_dry_run('true') ->
lager:debug("dry_run-ing btw"),
'true';
maybe_dry_run(DryRun) -> DryRun.
-spec batch_run(options()) -> boolean().
batch_run(Options) ->
batch_run(Options, 'false').
-spec batch_run(options(), Default) -> boolean() | Default.
batch_run(Options, Default) ->
R = props:get_is_true('batch_run', Options, Default),
_ = R
andalso lager:debug("batch_run-ing btw"),
R.
-spec mdn_run(options()) -> boolean().
mdn_run(Options) ->
R = props:get_is_true('mdn_run', Options, 'false'),
_ = R
andalso lager:debug("mdn_run-ing btw"),
R.
-spec assign_to(options()) -> assign_to().
assign_to(Options) ->
assign_to(Options, 'undefined').
-spec assign_to(options(), Default) -> assign_to() | Default.
assign_to(Options, Default) ->
props:get_binary_value('assign_to', Options, Default).
-spec set_assign_to(options(), assign_to()) -> options().
set_assign_to(Options, ?MATCH_ACCOUNT_RAW(AssignTo)) ->
props:set_value('assign_to', AssignTo, Options).
-spec auth_by(options()) -> kz_term:api_ne_binary().
auth_by(Options) ->
auth_by(Options, 'undefined').
-spec auth_by(options(), Default) -> kz_term:ne_binary() | Default.
auth_by(Options, Default) ->
props:get_binary_value('auth_by', Options, Default).
-spec public_fields(options()) -> kz_term:api_object().
public_fields(Options) ->
props:get_value('public_fields', Options, kz_json:new()).
-spec state(options()) -> kz_term:api_ne_binary().
state(Options) ->
state(Options, 'undefined').
-spec state(options(), Default) -> kz_term:ne_binary() | Default.
state(Options, Default) ->
props:get_binary_value('state', Options, Default).
-spec crossbar(options()) -> kz_term:api_proplist().
crossbar(Options) ->
crossbar(Options, 'undefined').
-spec crossbar(options(), Default) -> kz_term:api_proplist() | Default.
crossbar(Options, Default) ->
props:get_value('crossbar', Options, Default).
-spec ported_in(options()) -> boolean().
ported_in(Options) ->
props:get_is_true('ported_in', Options, 'false').
-spec module_name(options()) -> kz_term:ne_binary().
module_name(Options) ->
case props:get_ne_binary_value('module_name', Options) of
'undefined' -> knm_carriers:default_carrier();
ModuleName -> ModuleName
end.
%%------------------------------------------------------------------------------
%% Public get/set extra_options()
%%------------------------------------------------------------------------------
-spec account_id(extra_options()) -> kz_term:ne_binary().
account_id(Props) when is_list(Props) ->
props:get_ne_binary_value('account_id', Props).
-spec set_account_id(extra_options(), kz_term:ne_binary()) -> extra_options().
set_account_id(Props, AccountId=?MATCH_ACCOUNT_RAW(_)) when is_list(Props) ->
props:set_value('account_id', AccountId, Props).
-spec has_pending_port(extra_options()) -> boolean().
has_pending_port(Props) when is_list(Props) ->
props:get_is_true('pending_port', Props).
-spec inbound_cnam_enabled(extra_options()) -> boolean().
inbound_cnam_enabled(Props) when is_list(Props) ->
props:get_is_true('inbound_cnam', Props).
-spec is_local_number(extra_options()) -> boolean().
is_local_number(Props) when is_list(Props) ->
props:get_is_true('local', Props).
-spec number(extra_options()) -> kz_term:ne_binary().
number(Props) when is_list(Props) ->
props:get_ne_binary_value('number', Props).
-spec prepend(extra_options()) -> kz_term:api_binary().
prepend(Props) when is_list(Props) ->
props:get_value('prepend', Props).
-spec ringback_media_id(extra_options()) -> kz_term:api_binary().
ringback_media_id(Props) when is_list(Props) ->
props:get_value('ringback_media', Props).
-spec should_force_outbound(extra_options()) -> boolean().
should_force_outbound(Props) when is_list(Props) ->
props:get_is_true('force_outbound', Props).
-spec transfer_media_id(extra_options()) -> kz_term:api_binary().
transfer_media_id(Props) when is_list(Props) ->
props:get_value('transfer_media', Props).
| null | https://raw.githubusercontent.com/2600hz/kazoo/24519b9af9792caa67f7c09bbb9d27e2418f7ad6/core/kazoo_numbers/src/knm_options.erl | erlang | -----------------------------------------------------------------------------
@doc
@end
-----------------------------------------------------------------------------
api
api
|false
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
@doc
@end
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Public get/set extra_options()
------------------------------------------------------------------------------ | ( C ) 2015 - 2020 , 2600Hz
@author
@author
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
-module(knm_options).
-export([assign_to/1, assign_to/2, set_assign_to/2
,auth_by/1, auth_by/2
,dry_run/1, dry_run/2
,batch_run/1, batch_run/2
,mdn_run/1
,module_name/1
,ported_in/1
,public_fields/1
,state/1, state/2
,crossbar/1, crossbar/2
,default/0
,mdn_options/0
,to_phone_number_setters/1
]).
-export([account_id/1, set_account_id/2
,has_pending_port/1
,inbound_cnam_enabled/1
,is_local_number/1
,number/1
,prepend/1
,ringback_media_id/1
,should_force_outbound/1
,transfer_media_id/1
]).
-export([is_defined/2
,are_defined/2
]).
-include("knm.hrl").
-type crossbar_option() :: {'services', kz_services:services()} |
{'account_id', kz_term:api_ne_binary()} |
{'reseller_id', kz_term:api_ne_binary()}.
-type crossbar_options() :: [crossbar_option()].
-type assign_to() :: kz_term:api_ne_binary().
-type option() :: {'assign_to', assign_to()} |
{'auth_by', kz_term:api_ne_binary()} |
{'batch_run', boolean()} |
{'crossbar', crossbar_options()} |
{'dry_run', boolean()} |
{'mdn_run', boolean()} |
{'module_name', kz_term:ne_binary()} |
{'ported_in', boolean()} |
{'public_fields', kz_json:object()} |
{'state', kz_term:ne_binary()}.
-type options() :: [option()].
{'force_outbound', boolean()} |
{'inbound_cnam', boolean()} |
{'local', boolean()} |
{'pending_port', boolean()} |
{'ringback_media', kz_term:api_binary()} |
{'transfer_media', kz_term:api_binary()}.
-type extra_options() :: [extra_option()].
-export_type([option/0, options/0
,extra_option/0, extra_options/0
]).
-spec default() -> options().
default() ->
[{'auth_by', ?KNM_DEFAULT_AUTH_BY}
,{'batch_run', 'false'}
,{'mdn_run', 'false'}
].
-spec is_defined(options(), fun() | {fun(), any()}) -> boolean().
is_defined(Options, {Getter, ExpectedVal}) when is_function(Getter, 2) ->
case Getter(Options, ExpectedVal) of
ExpectedVal -> 'true';
_ -> 'false'
end;
is_defined(Options, Getter) when is_function(Getter, 1) ->
case Getter(Options) of
'undefined' -> 'false';
[] -> 'false';
<<>> -> 'false';
_ -> 'true'
end.
-spec are_defined(options(), [fun() | {fun(), any()}]) -> boolean().
are_defined(Options, Getters) ->
lists:all(fun(Getter) -> is_defined(Options, Getter) end, Getters).
-spec mdn_options() -> options().
mdn_options() ->
props:set_value('mdn_run', 'true', default()).
-spec to_phone_number_setters(options()) -> knm_phone_number:set_functions().
to_phone_number_setters(Options) ->
[{setter_fun(Option), Value}
|| {Option, Value} <- props:unique(Options),
is_atom(Option),
Option =/= 'crossbar'
].
-spec setter_fun(atom()) -> knm_phone_number:set_function().
setter_fun('public_fields') ->
fun knm_phone_number:reset_doc/2;
setter_fun(Option) ->
FName = list_to_existing_atom("set_" ++ atom_to_list(Option)),
fun knm_phone_number:FName/2.
-spec dry_run(options()) -> boolean().
dry_run(Options) ->
dry_run(Options, 'false').
-spec dry_run(options(), Default) -> boolean() | Default.
dry_run(Options, Default) ->
maybe_dry_run(props:get_is_true('dry_run', Options, Default)).
-spec maybe_dry_run(DryRun) -> DryRun
when DryRun :: boolean().
maybe_dry_run('true') ->
lager:debug("dry_run-ing btw"),
'true';
maybe_dry_run(DryRun) -> DryRun.
-spec batch_run(options()) -> boolean().
batch_run(Options) ->
batch_run(Options, 'false').
-spec batch_run(options(), Default) -> boolean() | Default.
batch_run(Options, Default) ->
R = props:get_is_true('batch_run', Options, Default),
_ = R
andalso lager:debug("batch_run-ing btw"),
R.
-spec mdn_run(options()) -> boolean().
mdn_run(Options) ->
R = props:get_is_true('mdn_run', Options, 'false'),
_ = R
andalso lager:debug("mdn_run-ing btw"),
R.
-spec assign_to(options()) -> assign_to().
assign_to(Options) ->
assign_to(Options, 'undefined').
-spec assign_to(options(), Default) -> assign_to() | Default.
assign_to(Options, Default) ->
props:get_binary_value('assign_to', Options, Default).
-spec set_assign_to(options(), assign_to()) -> options().
set_assign_to(Options, ?MATCH_ACCOUNT_RAW(AssignTo)) ->
props:set_value('assign_to', AssignTo, Options).
-spec auth_by(options()) -> kz_term:api_ne_binary().
auth_by(Options) ->
auth_by(Options, 'undefined').
-spec auth_by(options(), Default) -> kz_term:ne_binary() | Default.
auth_by(Options, Default) ->
props:get_binary_value('auth_by', Options, Default).
-spec public_fields(options()) -> kz_term:api_object().
public_fields(Options) ->
props:get_value('public_fields', Options, kz_json:new()).
-spec state(options()) -> kz_term:api_ne_binary().
state(Options) ->
state(Options, 'undefined').
-spec state(options(), Default) -> kz_term:ne_binary() | Default.
state(Options, Default) ->
props:get_binary_value('state', Options, Default).
-spec crossbar(options()) -> kz_term:api_proplist().
crossbar(Options) ->
crossbar(Options, 'undefined').
-spec crossbar(options(), Default) -> kz_term:api_proplist() | Default.
crossbar(Options, Default) ->
props:get_value('crossbar', Options, Default).
-spec ported_in(options()) -> boolean().
ported_in(Options) ->
props:get_is_true('ported_in', Options, 'false').
-spec module_name(options()) -> kz_term:ne_binary().
module_name(Options) ->
case props:get_ne_binary_value('module_name', Options) of
'undefined' -> knm_carriers:default_carrier();
ModuleName -> ModuleName
end.
-spec account_id(extra_options()) -> kz_term:ne_binary().
account_id(Props) when is_list(Props) ->
props:get_ne_binary_value('account_id', Props).
-spec set_account_id(extra_options(), kz_term:ne_binary()) -> extra_options().
set_account_id(Props, AccountId=?MATCH_ACCOUNT_RAW(_)) when is_list(Props) ->
props:set_value('account_id', AccountId, Props).
-spec has_pending_port(extra_options()) -> boolean().
has_pending_port(Props) when is_list(Props) ->
props:get_is_true('pending_port', Props).
-spec inbound_cnam_enabled(extra_options()) -> boolean().
inbound_cnam_enabled(Props) when is_list(Props) ->
props:get_is_true('inbound_cnam', Props).
-spec is_local_number(extra_options()) -> boolean().
is_local_number(Props) when is_list(Props) ->
props:get_is_true('local', Props).
-spec number(extra_options()) -> kz_term:ne_binary().
number(Props) when is_list(Props) ->
props:get_ne_binary_value('number', Props).
-spec prepend(extra_options()) -> kz_term:api_binary().
prepend(Props) when is_list(Props) ->
props:get_value('prepend', Props).
-spec ringback_media_id(extra_options()) -> kz_term:api_binary().
ringback_media_id(Props) when is_list(Props) ->
props:get_value('ringback_media', Props).
-spec should_force_outbound(extra_options()) -> boolean().
should_force_outbound(Props) when is_list(Props) ->
props:get_is_true('force_outbound', Props).
-spec transfer_media_id(extra_options()) -> kz_term:api_binary().
transfer_media_id(Props) when is_list(Props) ->
props:get_value('transfer_media', Props).
|
731c276a1a6600422735c84b99324773a277ad7d02a542af0d0ac1a5b21cd010 | hoodunit/grub | util.cljc | (ns grub.util)
(defn map-by-key [key coll]
(->> coll
(map (fn [a] [(keyword (get a key)) a]))
(into {})))
(defn rand-str [n]
(let [chars "0123456789abcdefghijklmnopqrstuvwxyz"
rand-index #(rand-int (count chars))]
(->> (repeatedly n rand-index)
(map #(.charAt chars %))
(clojure.string/join))))
| null | https://raw.githubusercontent.com/hoodunit/grub/6e47218c34a724d1123717997eac5e196a5bba9b/src/cljc/grub/util.cljc | clojure | (ns grub.util)
(defn map-by-key [key coll]
(->> coll
(map (fn [a] [(keyword (get a key)) a]))
(into {})))
(defn rand-str [n]
(let [chars "0123456789abcdefghijklmnopqrstuvwxyz"
rand-index #(rand-int (count chars))]
(->> (repeatedly n rand-index)
(map #(.charAt chars %))
(clojure.string/join))))
|
|
aa84a32cd3c24febcbb1970785d5c27382da8e9da701c2328479bea7987f552c | mirage/ocaml-asl | reporter.ml |
* Copyright ( c ) 2015 Unikernel Systems
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2015 Unikernel Systems
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
let src =
let src = Logs.Src.create "test" ~doc:"Test ASL using the logs library" in
Logs.Src.set_level src (Some Logs.Debug);
src
module Log = (val Logs.src_log src : Logs.LOG)
let _ =
let client = Asl.Client.create ~ident:(Sys.executable_name) ~facility:"Daemon" () in
Logs.set_reporter (Log_asl.reporter ~client ());
Log.err (fun f -> f "This is an error");
Log.info (fun f -> f "This is informational");
Log.debug (fun f -> f "This is lowly debugging data");
()
| null | https://raw.githubusercontent.com/mirage/ocaml-asl/95732a5d3a4f066ba14477e0621f3d946aff2ad4/examples/reporter.ml | ocaml |
* Copyright ( c ) 2015 Unikernel Systems
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
*
* Copyright (c) 2015 Unikernel Systems
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*)
let src =
let src = Logs.Src.create "test" ~doc:"Test ASL using the logs library" in
Logs.Src.set_level src (Some Logs.Debug);
src
module Log = (val Logs.src_log src : Logs.LOG)
let _ =
let client = Asl.Client.create ~ident:(Sys.executable_name) ~facility:"Daemon" () in
Logs.set_reporter (Log_asl.reporter ~client ());
Log.err (fun f -> f "This is an error");
Log.info (fun f -> f "This is informational");
Log.debug (fun f -> f "This is lowly debugging data");
()
|
|
6f369e213829d4d2252102d2bfb24ca3efb2321c41e6da4f68f31402961d1b7b | archaelus/tsung | ts_mysql.erl | Created : July 2008 by < >
From : ts_pgsql.erl by < >
Note : Based on erlang - mysql by < >
%%
%%% This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
%%% (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%%% GNU General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
%%%
%%% In addition, as a special exception, you have the permission to
%%% link the code of this program with any library released under
the EPL license and distribute linked combinations including
the two .
%%% ---------------------------------------------------------------------
Purpose : plugin for mysql > = 4.1
Dependancies : none
%%% Note: Packet fragmentation isnt implemented yet
%%% ---------------------------------------------------------------------
-module(ts_mysql).
-vc('$Id:$ ').
-author('').
-include("ts_profile.hrl").
-include("ts_mysql.hrl").
-export([init_dynparams/0,
add_dynparams/4,
get_message/1,
session_defaults/0,
parse/2,
parse_config/2,
new_session/0]).
%%----------------------------------------------------------------------
%% Function: session_default/0
%% Purpose: default parameters for session
%% Returns: {ok, ack_type = parse|no_ack|local, persistent = true|false}
%%----------------------------------------------------------------------
session_defaults() ->
{ok, true}.
%%----------------------------------------------------------------------
%% Function: new_session/0
%% Purpose: initialize session information
%% Returns: record or []
%%----------------------------------------------------------------------
new_session() ->
#mysql{}.
%%----------------------------------------------------------------------
%% Function: get_message/21
%% Purpose: Build a message/request ,
: record
%% Returns: binary
%%----------------------------------------------------------------------
get_message(#mysql_request{type=connect}) ->
Packet=list_to_binary([]),
?LOGF("Opening socket. ~p ~n",[Packet], ?DEB),
Packet;
get_message(#mysql_request{type=authenticate, database=Database, username=Username, passwd=Password, salt=Salt}) ->
Packet=add_header(make_auth(Username, Password, Database, Salt),1),
?LOGF("Auth packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet;
get_message(#mysql_request{type=sql,sql=Query}) ->
Packet=add_header([?MYSQL_QUERY_OP, Query],0),
?LOGF("Query packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet;
get_message(#mysql_request{type=close}) ->
Packet=add_header([?MYSQL_CLOSE_OP],0),
?LOGF("Close packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet.
%%----------------------------------------------------------------------
%% Function: parse/2
%% Purpose: parse the response from the server and keep information
%% about the response in State#state_rcv.session
: Data ( binary ) , State ( # state_rcv )
Returns : { NewState , Options for socket ( list ) , Close = true|false }
%%----------------------------------------------------------------------
parse(closed, State) ->
?LOG("Parsing> socket closed ~n", ?WARN),
{State#state_rcv{ack_done = true, datasize=0}, [], true};
parse(Data, State)->
<<PacketSize:24/little,_PacketNum:8/little,PacketBody/binary>> = Data,
case PacketSize =< size(PacketBody) of
true ->
?LOG("Parsing> full packet ~n",?DEB),
Request = State#state_rcv.request,
Param = Request#ts_request.param,
case Param#mysql_request.type of
connect ->
parse_greeting(PacketBody,State);
authenticate ->
parse_result(PacketBody,State);
sql ->
parse_result(PacketBody,State);
close ->
{State#state_rcv{ack_done = true, datasize=size(Data)},[],false}
end;
false ->
?LOGF("Parsing> incomplete packet: size->~p body->~p ~n",[PacketSize,size(PacketBody)], ?WARN),
{State#state_rcv{ack_done = false, datasize=size(Data), acc=PacketBody},[],false}
end.
parse_greeting(Data, State=#state_rcv{acc = [],dyndata=DynData, datasize= 0}) ->
?LOGF("Parsing greeting ~p ~n",[Data], ?DEB),
Salt= get_salt(Data),
NewDynData=DynData#dyndata{proto=#mysql_dyndata{salt=Salt}},
{State#state_rcv{ack_done = true, datasize=size(Data), dyndata=NewDynData},[],false}.
parse_result(Data,State)->
case Data of
<<Fieldcount:8, Rest2/binary>> ->
case Fieldcount of
0 ->
%% No Tabular data
<<AffectedRows:8, _Rest2/binary>> = Rest2,
?LOGF("OK, No Data, Row affected: ~p (~s)~n", [AffectedRows,Data], ?DEB);
255 ->
<<Errno:16/little, _Marker:8, SQLState:5/binary, Message/binary>> = Rest2,
?LOGF("Error: ~p ~s ~s ~n", [Errno,SQLState, Message], ?WARN),
%% FIXME: should we stop if an error occurs ?
ts_mon:add({ count, list_to_atom("error_mysql_"++integer_to_list(Errno))});
254 when size(Rest2) < 9 ->
?LOGF("EOF: (~p) ~n", [Rest2], ?DEB);
_ ->
?LOGF("OK, Tabular Data, Columns count: ~p (~s)~n", [Fieldcount,Data], ?DEB)
end,
{State#state_rcv{ack_done = true,datasize=size(Data)},[],false};
_ ->
?LOG("Bad packet ", ?ERR),
ts_mon:add({ count, error_mysql_badpacket}),
{State#state_rcv{ack_done = true,datasize=size(Data)},[],false}
end.
%%----------------------------------------------------------------------
%% Function: parse_config/2
Purpose : parse tags in the XML config file related to the protocol
%% Returns: List
%%----------------------------------------------------------------------
parse_config(Element, Conf) ->
ts_config_mysql:parse_config(Element, Conf).
%%----------------------------------------------------------------------
Function : add_dynparams/4
%% Purpose: add dynamic parameters to build the message
%% (this is used for ex. for Cookies in HTTP)
%% for postgres, use this to store the auth method and salt
: ( true|false ) , DynData = # dyndata , Param = # myproto_request
%% Host = String
Returns : # mysql_request
%%----------------------------------------------------------------------
add_dynparams(false, DynData, Param, HostData) ->
add_dynparams(DynData#dyndata.proto, Param, HostData);
add_dynparams(true, DynData, Param, HostData) ->
NewParam = subst(Param, DynData#dyndata.dynvars),
add_dynparams(DynData#dyndata.proto,NewParam, HostData).
add_dynparams(DynMysql, Param, _HostData) ->
Param#mysql_request{salt=DynMysql#mysql_dyndata.salt}.
%%----------------------------------------------------------------------
%% Function: init_dynparams/0
%% Purpose: initial dynamic parameters value
Returns : # dyndata
%%----------------------------------------------------------------------
init_dynparams() ->
#dyndata{proto=#mysql_dyndata{}}.
%%----------------------------------------------------------------------
%% Function: subst/2
%% Purpose: Replace on the fly dynamic element of the request.
Returns : # mysql_request
%%----------------------------------------------------------------------
subst(Req=#mysql_request{sql=SQL}, DynData) ->
Req#mysql_request{sql=ts_search:subst(SQL, DynData)}.
%%% -- Internal funs --------------------
add_header(Packet,SeqNum) ->
BPacket=list_to_binary(Packet),
<<(size(BPacket)):24/little, SeqNum:8, BPacket/binary>>.
get_salt(PacketBody) ->
<< _Protocol:8/little, Rest/binary>> = PacketBody,
{_Version, Rest2} = asciz_binary(Rest,[]),
<<_TreadID:32/little, Rest3/binary>> = Rest2,
{Salt, Rest4} = asciz_binary(Rest3,[]),
<<_Caps:16/little, Rest5/binary>> = Rest4,
<<_ServerChar:16/binary-unit:8, Rest6/binary>> = Rest5,
{Salt2, _Rest7} = asciz_binary(Rest6,[]),
Salt ++ Salt2.
make_auth(User, Password, Database, Salt) ->
EncryptedPassword = encrypt_password(Password, Salt),
Caps = ?LONG_PASSWORD bor ?LONG_FLAG bor ?PROTOCOL_41 bor ?TRANSACTIONS
bor ?SECURE_CONNECTION bor ?CONNECT_WITH_DB,
Maxsize = ?MAX_PACKET_SIZE,
UserB = list_to_binary(User),
PasswordL = size(EncryptedPassword),
DatabaseB = list_to_binary(Database),
binary_to_list(<<Caps:32/little, Maxsize:32/little, 8:8, 0:23/integer-unit:8,
UserB/binary, 0:8, PasswordL:8, EncryptedPassword/binary, DatabaseB/binary>>).
encrypt_password(Password, Salt) ->
Stage1= case catch crypto:sha(Password) of
{'EXIT',_} ->
crypto:start(),
crypto:sha(Password);
Sha -> Sha
end,
Stage2 = crypto:sha(Stage1),
Res = crypto:sha_final(
crypto:sha_update(
crypto:sha_update(crypto:sha_init(), Salt),
Stage2)
),
bxor_binary(Res, Stage1).
@doc Find the first zero - byte in Data and add everything before it
to Acc , as a string .
%%
%% @spec asciz_binary(Data::binary(), Acc::list()) ->
{ ( ) , Rest::binary ( ) }
asciz_binary(<<>>, Acc) ->
{lists:reverse(Acc)};
asciz_binary(<<0:8, Rest/binary>>, Acc) ->
{lists:reverse(Acc), Rest};
asciz_binary(<<C:8, Rest/binary>>, Acc) ->
asciz_binary(Rest, [C | Acc]).
dualmap(_F, [], []) ->
[];
dualmap(F, [E1 | R1], [E2 | R2]) ->
[F(E1, E2) | dualmap(F, R1, R2)].
bxor_binary(B1, B2) ->
list_to_binary(dualmap(fun (E1, E2) ->
E1 bxor E2
end, binary_to_list(B1), binary_to_list(B2))).
| null | https://raw.githubusercontent.com/archaelus/tsung/b4ea0419c6902d8bb63795200964d25b19e46532/src/tsung/ts_mysql.erl | erlang |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with this program; if not, write to the Free Software
In addition, as a special exception, you have the permission to
link the code of this program with any library released under
---------------------------------------------------------------------
Note: Packet fragmentation isnt implemented yet
---------------------------------------------------------------------
----------------------------------------------------------------------
Function: session_default/0
Purpose: default parameters for session
Returns: {ok, ack_type = parse|no_ack|local, persistent = true|false}
----------------------------------------------------------------------
----------------------------------------------------------------------
Function: new_session/0
Purpose: initialize session information
Returns: record or []
----------------------------------------------------------------------
----------------------------------------------------------------------
Function: get_message/21
Purpose: Build a message/request ,
Returns: binary
----------------------------------------------------------------------
----------------------------------------------------------------------
Function: parse/2
Purpose: parse the response from the server and keep information
about the response in State#state_rcv.session
----------------------------------------------------------------------
No Tabular data
FIXME: should we stop if an error occurs ?
----------------------------------------------------------------------
Function: parse_config/2
Returns: List
----------------------------------------------------------------------
----------------------------------------------------------------------
Purpose: add dynamic parameters to build the message
(this is used for ex. for Cookies in HTTP)
for postgres, use this to store the auth method and salt
Host = String
----------------------------------------------------------------------
----------------------------------------------------------------------
Function: init_dynparams/0
Purpose: initial dynamic parameters value
----------------------------------------------------------------------
----------------------------------------------------------------------
Function: subst/2
Purpose: Replace on the fly dynamic element of the request.
----------------------------------------------------------------------
-- Internal funs --------------------
@spec asciz_binary(Data::binary(), Acc::list()) -> | Created : July 2008 by < >
From : ts_pgsql.erl by < >
Note : Based on erlang - mysql by < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 , USA .
the EPL license and distribute linked combinations including
the two .
Purpose : plugin for mysql > = 4.1
Dependancies : none
-module(ts_mysql).
-vc('$Id:$ ').
-author('').
-include("ts_profile.hrl").
-include("ts_mysql.hrl").
-export([init_dynparams/0,
add_dynparams/4,
get_message/1,
session_defaults/0,
parse/2,
parse_config/2,
new_session/0]).
session_defaults() ->
{ok, true}.
new_session() ->
#mysql{}.
: record
get_message(#mysql_request{type=connect}) ->
Packet=list_to_binary([]),
?LOGF("Opening socket. ~p ~n",[Packet], ?DEB),
Packet;
get_message(#mysql_request{type=authenticate, database=Database, username=Username, passwd=Password, salt=Salt}) ->
Packet=add_header(make_auth(Username, Password, Database, Salt),1),
?LOGF("Auth packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet;
get_message(#mysql_request{type=sql,sql=Query}) ->
Packet=add_header([?MYSQL_QUERY_OP, Query],0),
?LOGF("Query packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet;
get_message(#mysql_request{type=close}) ->
Packet=add_header([?MYSQL_CLOSE_OP],0),
?LOGF("Close packet: ~p (~s)~n",[Packet,Packet], ?DEB),
Packet.
: Data ( binary ) , State ( # state_rcv )
Returns : { NewState , Options for socket ( list ) , Close = true|false }
parse(closed, State) ->
?LOG("Parsing> socket closed ~n", ?WARN),
{State#state_rcv{ack_done = true, datasize=0}, [], true};
parse(Data, State)->
<<PacketSize:24/little,_PacketNum:8/little,PacketBody/binary>> = Data,
case PacketSize =< size(PacketBody) of
true ->
?LOG("Parsing> full packet ~n",?DEB),
Request = State#state_rcv.request,
Param = Request#ts_request.param,
case Param#mysql_request.type of
connect ->
parse_greeting(PacketBody,State);
authenticate ->
parse_result(PacketBody,State);
sql ->
parse_result(PacketBody,State);
close ->
{State#state_rcv{ack_done = true, datasize=size(Data)},[],false}
end;
false ->
?LOGF("Parsing> incomplete packet: size->~p body->~p ~n",[PacketSize,size(PacketBody)], ?WARN),
{State#state_rcv{ack_done = false, datasize=size(Data), acc=PacketBody},[],false}
end.
parse_greeting(Data, State=#state_rcv{acc = [],dyndata=DynData, datasize= 0}) ->
?LOGF("Parsing greeting ~p ~n",[Data], ?DEB),
Salt= get_salt(Data),
NewDynData=DynData#dyndata{proto=#mysql_dyndata{salt=Salt}},
{State#state_rcv{ack_done = true, datasize=size(Data), dyndata=NewDynData},[],false}.
parse_result(Data,State)->
case Data of
<<Fieldcount:8, Rest2/binary>> ->
case Fieldcount of
0 ->
<<AffectedRows:8, _Rest2/binary>> = Rest2,
?LOGF("OK, No Data, Row affected: ~p (~s)~n", [AffectedRows,Data], ?DEB);
255 ->
<<Errno:16/little, _Marker:8, SQLState:5/binary, Message/binary>> = Rest2,
?LOGF("Error: ~p ~s ~s ~n", [Errno,SQLState, Message], ?WARN),
ts_mon:add({ count, list_to_atom("error_mysql_"++integer_to_list(Errno))});
254 when size(Rest2) < 9 ->
?LOGF("EOF: (~p) ~n", [Rest2], ?DEB);
_ ->
?LOGF("OK, Tabular Data, Columns count: ~p (~s)~n", [Fieldcount,Data], ?DEB)
end,
{State#state_rcv{ack_done = true,datasize=size(Data)},[],false};
_ ->
?LOG("Bad packet ", ?ERR),
ts_mon:add({ count, error_mysql_badpacket}),
{State#state_rcv{ack_done = true,datasize=size(Data)},[],false}
end.
Purpose : parse tags in the XML config file related to the protocol
parse_config(Element, Conf) ->
ts_config_mysql:parse_config(Element, Conf).
Function : add_dynparams/4
: ( true|false ) , DynData = # dyndata , Param = # myproto_request
Returns : # mysql_request
add_dynparams(false, DynData, Param, HostData) ->
add_dynparams(DynData#dyndata.proto, Param, HostData);
add_dynparams(true, DynData, Param, HostData) ->
NewParam = subst(Param, DynData#dyndata.dynvars),
add_dynparams(DynData#dyndata.proto,NewParam, HostData).
add_dynparams(DynMysql, Param, _HostData) ->
Param#mysql_request{salt=DynMysql#mysql_dyndata.salt}.
Returns : # dyndata
init_dynparams() ->
#dyndata{proto=#mysql_dyndata{}}.
Returns : # mysql_request
subst(Req=#mysql_request{sql=SQL}, DynData) ->
Req#mysql_request{sql=ts_search:subst(SQL, DynData)}.
add_header(Packet,SeqNum) ->
BPacket=list_to_binary(Packet),
<<(size(BPacket)):24/little, SeqNum:8, BPacket/binary>>.
get_salt(PacketBody) ->
<< _Protocol:8/little, Rest/binary>> = PacketBody,
{_Version, Rest2} = asciz_binary(Rest,[]),
<<_TreadID:32/little, Rest3/binary>> = Rest2,
{Salt, Rest4} = asciz_binary(Rest3,[]),
<<_Caps:16/little, Rest5/binary>> = Rest4,
<<_ServerChar:16/binary-unit:8, Rest6/binary>> = Rest5,
{Salt2, _Rest7} = asciz_binary(Rest6,[]),
Salt ++ Salt2.
make_auth(User, Password, Database, Salt) ->
EncryptedPassword = encrypt_password(Password, Salt),
Caps = ?LONG_PASSWORD bor ?LONG_FLAG bor ?PROTOCOL_41 bor ?TRANSACTIONS
bor ?SECURE_CONNECTION bor ?CONNECT_WITH_DB,
Maxsize = ?MAX_PACKET_SIZE,
UserB = list_to_binary(User),
PasswordL = size(EncryptedPassword),
DatabaseB = list_to_binary(Database),
binary_to_list(<<Caps:32/little, Maxsize:32/little, 8:8, 0:23/integer-unit:8,
UserB/binary, 0:8, PasswordL:8, EncryptedPassword/binary, DatabaseB/binary>>).
encrypt_password(Password, Salt) ->
Stage1= case catch crypto:sha(Password) of
{'EXIT',_} ->
crypto:start(),
crypto:sha(Password);
Sha -> Sha
end,
Stage2 = crypto:sha(Stage1),
Res = crypto:sha_final(
crypto:sha_update(
crypto:sha_update(crypto:sha_init(), Salt),
Stage2)
),
bxor_binary(Res, Stage1).
@doc Find the first zero - byte in Data and add everything before it
to Acc , as a string .
{ ( ) , Rest::binary ( ) }
asciz_binary(<<>>, Acc) ->
{lists:reverse(Acc)};
asciz_binary(<<0:8, Rest/binary>>, Acc) ->
{lists:reverse(Acc), Rest};
asciz_binary(<<C:8, Rest/binary>>, Acc) ->
asciz_binary(Rest, [C | Acc]).
dualmap(_F, [], []) ->
[];
dualmap(F, [E1 | R1], [E2 | R2]) ->
[F(E1, E2) | dualmap(F, R1, R2)].
bxor_binary(B1, B2) ->
list_to_binary(dualmap(fun (E1, E2) ->
E1 bxor E2
end, binary_to_list(B1), binary_to_list(B2))).
|
7252d2e7423ca60831c6518152c7edf00acc3d3008ff3347f3cd59cb5b6316bd | steveshogren/cis-194-yorgey-course | DateStuff.hs | module DateStuff (ExpectedDays, generateLastNDays , getTime, makeDateString) where
import Control.Monad(liftM2, liftM)
import System.Locale (defaultTimeLocale)
import Data.Time (formatTime, showGregorian, addDays, localDay, getCurrentTime, getCurrentTimeZone, utcToLocalTime)
import Control.Applicative ((<$>))
type ExpectedDays = [String]
stringNDaysAgo :: Integer -> IO String
stringNDaysAgo n = do
time <- liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime
return $ showGregorian $ addDays (-n) $ localDay time
getTime :: IO String
getTime =
formatTime defaultTimeLocale "%H:%M:%S"
<$> liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime
generateLastNDays :: Integer -> IO ExpectedDays
generateLastNDays n = liftM reverse $ mapM stringNDaysAgo [0..(n-1)]
makeDateString :: String -> String -> String
makeDateString t d =
" --date=\"" ++ d ++ " " ++ t ++ "\""
| null | https://raw.githubusercontent.com/steveshogren/cis-194-yorgey-course/01592a39cdacccaba0438b1cc3c9e176b1b098b2/DateStuff.hs | haskell | module DateStuff (ExpectedDays, generateLastNDays , getTime, makeDateString) where
import Control.Monad(liftM2, liftM)
import System.Locale (defaultTimeLocale)
import Data.Time (formatTime, showGregorian, addDays, localDay, getCurrentTime, getCurrentTimeZone, utcToLocalTime)
import Control.Applicative ((<$>))
type ExpectedDays = [String]
stringNDaysAgo :: Integer -> IO String
stringNDaysAgo n = do
time <- liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime
return $ showGregorian $ addDays (-n) $ localDay time
getTime :: IO String
getTime =
formatTime defaultTimeLocale "%H:%M:%S"
<$> liftM2 utcToLocalTime getCurrentTimeZone getCurrentTime
generateLastNDays :: Integer -> IO ExpectedDays
generateLastNDays n = liftM reverse $ mapM stringNDaysAgo [0..(n-1)]
makeDateString :: String -> String -> String
makeDateString t d =
" --date=\"" ++ d ++ " " ++ t ++ "\""
|
|
3d0d109754377bd8c8f3f2fee70f31272a58c1be889aec43be8d2ee844a183a9 | logicblocks/salutem | checks.clj | (ns salutem.core.checks
"Provides constructors, predicates and evaluation functions for checks."
(:require
[clojure.core.async :as async]
[tick.alpha.api :as t]
[cartus.core :as log]
[cartus.null :as cartus-null]
[salutem.core.results :as results]))
(defn- check
([check-name check-fn]
(check check-name check-fn {}))
([check-name check-fn
{:keys [salutem/timeout]
:or {timeout (t/new-duration 10 :seconds)}
:as opts}]
(merge
opts
{:salutem/name check-name
:salutem/check-fn check-fn
:salutem/timeout timeout})))
(defn background-check
"Constructs a background check with the provided name and check function.
A background check is one that is evaluated periodically with the result
cached in a registry until the next evaluation, conducted by a maintenance
pipeline, which will occur once the time to re-evaluation of the check has
passed.
Background checks are useful for external dependencies where it is
important not to perform the check too frequently and where the health
status only needs to be accurate on the order of the time to re-evaluation.
Takes the following parameters:
- `check-name`: a keyword representing the name of the check
- `check-fn`: an arity-2 function, with the first argument being a context
map as provided during evaluation or at maintenance pipeline construction
and the second argument being a callback function which should be called
with the result of the check to signal the check is complete; note, check
functions _must_ be non-blocking.
- `opts`: an optional map of additional options for the check, containing:
- `:salutem/timeout`: a [[salutem.time/duration]] representing the amount
of time to wait for the check to complete before considering it failed,
defaulting to 10 seconds.
- `:salutem/time-to-re-evaluation`: a [[salutem.time/duration]]
representing the time to wait after a check is evaluated before
attempting to re-evaluate it, defaulting to 10 seconds.
Any extra entries provided in the `opts` map are retained on the check for
later use.
Note that a result for a background check may live for longer than the
time to re-evaluation since evaluation takes time and the result will
continue to be returned from the registry whenever the check is resolved
until the evaluation has completed and the new result has been added to the
registry."
([check-name check-fn]
(background-check check-name check-fn {}))
([check-name check-fn opts]
(let [time-to-re-evaluation
(or
(:salutem/time-to-re-evaluation opts)
(:salutem/ttl opts)
(t/new-duration 10 :seconds))]
(check check-name check-fn
(merge
{:salutem/time-to-re-evaluation time-to-re-evaluation}
(dissoc opts :salutem/time-to-re-evaluation :salutem/ttl)
{:salutem/type :background})))))
(defn realtime-check
"Constructs a realtime check with the provided name and check function.
A realtime check is one that is re-evaluated whenever the check is resolved,
with no caching of results taking place.
Realtime checks are useful when the accuracy of the check needs to be very
high or where the check itself is inexpensive.
Takes the following parameters:
- `check-name`: a keyword representing the name of the check
- `check-fn`: an arity-2 function, with the first argument being a context
map as provided during evaluation or at maintenance pipeline construction
and the second argument being a callback function which should be called
with the result fo the check to signal the check is complete; note, check
functions _must_ be non-blocking.
- `opts`: an optional map of additional options for the check, containing:
- `:salutem/timeout`: a [[salutem.time/duration]] representing the amount
of time to wait for the check to complete before considering it failed,
defaulting to 10 seconds.
Any extra entries provided in the `opts` map are retained on the check for
later use."
([check-name check-fn]
(realtime-check check-name check-fn {}))
([check-name check-fn opts]
(check check-name check-fn
(merge
opts
{:salutem/type :realtime}))))
(defn background?
"Returns `true` if the provided check is a background check, `false`
otherwise."
[check]
(= (:salutem/type check) :background))
(defn realtime?
"Returns `true` if the provided check is a realtime check, `false`
otherwise."
[check]
(= (:salutem/type check) :realtime))
(defn check-name
"Returns the name of the provided check."
[check]
(:salutem/name check))
(defn attempt
"Attempts to obtain a result for a check, handling timeouts and exceptions.
Takes the following parameters:
- `dependencies`: A map of dependencies used by `attempt` in obtaining the
result, currently supporting only a `:logger` entry with a
[`cartus.core/Logger`](#var-Logger)
value.
- `trigger-id`: An ID identifying the attempt in any subsequently produced
messages and used in logging.
- `check`: the check to be attempted.
- `context`: an optional map containing arbitrary context required by the
check in order to run and passed to the check functions as the first
argument; defaults to an empty map.
- `result-channel`: an optional channel on which to send the result message;
defaults to a channel with a buffer length of 1.
The attempt is performed asynchronously and the result channel is returned
immediately.
In the case that the attempt takes longer than the check's timeout, an
unhealthy result is produced, including `:salutem/reason` as `:timed-out`.
In the case that the attempt throws an exception, an unhealthy result is
produced, including `:salutem/reason` as `:exception-thrown` and including
the exception at `:salutem/exception`.
In all other cases, the result produced by the check is passed on to the
result channel.
All produced results include a `:salutem/evaluation-duration` entry with the
time taken to obtain the result, which can be overridden within check
functions if required."
([dependencies trigger-id check]
(attempt dependencies trigger-id check {}))
([dependencies trigger-id check context]
(attempt dependencies trigger-id check context (async/chan 1)))
([dependencies trigger-id check context result-channel]
(let [logger (or (:logger dependencies) (cartus-null/logger))
check-name (:salutem/name check)]
(async/go
(let [{:keys [salutem/check-fn salutem/timeout]} check
callback-channel (async/chan)
exception-channel (async/chan 1)
before (t/now)]
(log/info logger ::attempt.starting
{:trigger-id trigger-id
:check-name check-name})
(try
(check-fn context
(fn [result]
(async/put! callback-channel result)))
(catch Exception exception
(async/>! exception-channel exception)))
(async/alt!
exception-channel
([exception]
(let [after (t/now)
duration (t/between before after)]
(log/info logger ::attempt.threw-exception
{:trigger-id trigger-id
:check-name check-name
:exception exception})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result (results/unhealthy
{:salutem/reason :threw-exception
:salutem/exception exception
:salutem/evaluation-duration duration})})))
(async/timeout (t/millis timeout))
(let [after (t/now)
duration (t/between before after)]
(log/info logger ::attempt.timed-out
{:trigger-id trigger-id
:check-name check-name})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result (results/unhealthy
{:salutem/reason :timed-out
:salutem/evaluation-duration duration})}))
callback-channel
([result]
(let [after (t/now)
duration (t/between before after)
result (results/prepend result
{:salutem/evaluation-duration duration})]
(log/info logger ::attempt.completed
{:trigger-id trigger-id
:check-name check-name
:result result})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result result})))
:priority true)
(async/close! exception-channel)
(async/close! callback-channel))))
result-channel))
(defn- evaluation-attempt [check context]
(let [logger (or (:logger context) (cartus-null/logger))
trigger-id (or (:trigger-id context) :ad-hoc)]
(attempt {:logger logger} trigger-id check context
(async/chan 1 (map :result)))))
(defn evaluate
"Evaluates the provided check, returning the result of the evaluation.
Optionally takes a context map containing arbitrary context required by the
check in order to run and passed to the check function as the first argument.
By default, the check is evaluated synchronously. If a callback function is
provided, the function starts evaluation asynchronously, returns immediately
and invokes the callback function with the result once available."
([check] (evaluate check {}))
([check context]
(async/<!! (evaluation-attempt check context)))
([check context callback-fn]
(async/go (callback-fn (async/<! (evaluation-attempt check context))))))
| null | https://raw.githubusercontent.com/logicblocks/salutem/9854c151b69c80c481f48d8be7ee7273831cb79b/core/src/salutem/core/checks.clj | clojure | note, check
note, check
defaults to an empty map.
| (ns salutem.core.checks
"Provides constructors, predicates and evaluation functions for checks."
(:require
[clojure.core.async :as async]
[tick.alpha.api :as t]
[cartus.core :as log]
[cartus.null :as cartus-null]
[salutem.core.results :as results]))
(defn- check
([check-name check-fn]
(check check-name check-fn {}))
([check-name check-fn
{:keys [salutem/timeout]
:or {timeout (t/new-duration 10 :seconds)}
:as opts}]
(merge
opts
{:salutem/name check-name
:salutem/check-fn check-fn
:salutem/timeout timeout})))
(defn background-check
"Constructs a background check with the provided name and check function.
A background check is one that is evaluated periodically with the result
cached in a registry until the next evaluation, conducted by a maintenance
pipeline, which will occur once the time to re-evaluation of the check has
passed.
Background checks are useful for external dependencies where it is
important not to perform the check too frequently and where the health
status only needs to be accurate on the order of the time to re-evaluation.
Takes the following parameters:
- `check-name`: a keyword representing the name of the check
- `check-fn`: an arity-2 function, with the first argument being a context
map as provided during evaluation or at maintenance pipeline construction
and the second argument being a callback function which should be called
functions _must_ be non-blocking.
- `opts`: an optional map of additional options for the check, containing:
- `:salutem/timeout`: a [[salutem.time/duration]] representing the amount
of time to wait for the check to complete before considering it failed,
defaulting to 10 seconds.
- `:salutem/time-to-re-evaluation`: a [[salutem.time/duration]]
representing the time to wait after a check is evaluated before
attempting to re-evaluate it, defaulting to 10 seconds.
Any extra entries provided in the `opts` map are retained on the check for
later use.
Note that a result for a background check may live for longer than the
time to re-evaluation since evaluation takes time and the result will
continue to be returned from the registry whenever the check is resolved
until the evaluation has completed and the new result has been added to the
registry."
([check-name check-fn]
(background-check check-name check-fn {}))
([check-name check-fn opts]
(let [time-to-re-evaluation
(or
(:salutem/time-to-re-evaluation opts)
(:salutem/ttl opts)
(t/new-duration 10 :seconds))]
(check check-name check-fn
(merge
{:salutem/time-to-re-evaluation time-to-re-evaluation}
(dissoc opts :salutem/time-to-re-evaluation :salutem/ttl)
{:salutem/type :background})))))
(defn realtime-check
"Constructs a realtime check with the provided name and check function.
A realtime check is one that is re-evaluated whenever the check is resolved,
with no caching of results taking place.
Realtime checks are useful when the accuracy of the check needs to be very
high or where the check itself is inexpensive.
Takes the following parameters:
- `check-name`: a keyword representing the name of the check
- `check-fn`: an arity-2 function, with the first argument being a context
map as provided during evaluation or at maintenance pipeline construction
and the second argument being a callback function which should be called
functions _must_ be non-blocking.
- `opts`: an optional map of additional options for the check, containing:
- `:salutem/timeout`: a [[salutem.time/duration]] representing the amount
of time to wait for the check to complete before considering it failed,
defaulting to 10 seconds.
Any extra entries provided in the `opts` map are retained on the check for
later use."
([check-name check-fn]
(realtime-check check-name check-fn {}))
([check-name check-fn opts]
(check check-name check-fn
(merge
opts
{:salutem/type :realtime}))))
(defn background?
"Returns `true` if the provided check is a background check, `false`
otherwise."
[check]
(= (:salutem/type check) :background))
(defn realtime?
"Returns `true` if the provided check is a realtime check, `false`
otherwise."
[check]
(= (:salutem/type check) :realtime))
(defn check-name
"Returns the name of the provided check."
[check]
(:salutem/name check))
(defn attempt
"Attempts to obtain a result for a check, handling timeouts and exceptions.
Takes the following parameters:
- `dependencies`: A map of dependencies used by `attempt` in obtaining the
result, currently supporting only a `:logger` entry with a
[`cartus.core/Logger`](#var-Logger)
value.
- `trigger-id`: An ID identifying the attempt in any subsequently produced
messages and used in logging.
- `check`: the check to be attempted.
- `context`: an optional map containing arbitrary context required by the
check in order to run and passed to the check functions as the first
defaults to a channel with a buffer length of 1.
The attempt is performed asynchronously and the result channel is returned
immediately.
In the case that the attempt takes longer than the check's timeout, an
unhealthy result is produced, including `:salutem/reason` as `:timed-out`.
In the case that the attempt throws an exception, an unhealthy result is
produced, including `:salutem/reason` as `:exception-thrown` and including
the exception at `:salutem/exception`.
In all other cases, the result produced by the check is passed on to the
result channel.
All produced results include a `:salutem/evaluation-duration` entry with the
time taken to obtain the result, which can be overridden within check
functions if required."
([dependencies trigger-id check]
(attempt dependencies trigger-id check {}))
([dependencies trigger-id check context]
(attempt dependencies trigger-id check context (async/chan 1)))
([dependencies trigger-id check context result-channel]
(let [logger (or (:logger dependencies) (cartus-null/logger))
check-name (:salutem/name check)]
(async/go
(let [{:keys [salutem/check-fn salutem/timeout]} check
callback-channel (async/chan)
exception-channel (async/chan 1)
before (t/now)]
(log/info logger ::attempt.starting
{:trigger-id trigger-id
:check-name check-name})
(try
(check-fn context
(fn [result]
(async/put! callback-channel result)))
(catch Exception exception
(async/>! exception-channel exception)))
(async/alt!
exception-channel
([exception]
(let [after (t/now)
duration (t/between before after)]
(log/info logger ::attempt.threw-exception
{:trigger-id trigger-id
:check-name check-name
:exception exception})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result (results/unhealthy
{:salutem/reason :threw-exception
:salutem/exception exception
:salutem/evaluation-duration duration})})))
(async/timeout (t/millis timeout))
(let [after (t/now)
duration (t/between before after)]
(log/info logger ::attempt.timed-out
{:trigger-id trigger-id
:check-name check-name})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result (results/unhealthy
{:salutem/reason :timed-out
:salutem/evaluation-duration duration})}))
callback-channel
([result]
(let [after (t/now)
duration (t/between before after)
result (results/prepend result
{:salutem/evaluation-duration duration})]
(log/info logger ::attempt.completed
{:trigger-id trigger-id
:check-name check-name
:result result})
(async/>! result-channel
{:trigger-id trigger-id
:check check
:result result})))
:priority true)
(async/close! exception-channel)
(async/close! callback-channel))))
result-channel))
(defn- evaluation-attempt [check context]
(let [logger (or (:logger context) (cartus-null/logger))
trigger-id (or (:trigger-id context) :ad-hoc)]
(attempt {:logger logger} trigger-id check context
(async/chan 1 (map :result)))))
(defn evaluate
"Evaluates the provided check, returning the result of the evaluation.
Optionally takes a context map containing arbitrary context required by the
check in order to run and passed to the check function as the first argument.
By default, the check is evaluated synchronously. If a callback function is
provided, the function starts evaluation asynchronously, returns immediately
and invokes the callback function with the result once available."
([check] (evaluate check {}))
([check context]
(async/<!! (evaluation-attempt check context)))
([check context callback-fn]
(async/go (callback-fn (async/<! (evaluation-attempt check context))))))
|
71a4f7113be4061951109c4327a5c30b15013a9e26a37935428d0e93431f20c4 | janestreet/async_kernel | job.mli | open! Core
open! Import
type t = Types.Job.t [@@deriving sexp_of]
| null | https://raw.githubusercontent.com/janestreet/async_kernel/9575c63faac6c2d6af20f0f21ec535401f310296/src/job.mli | ocaml | open! Core
open! Import
type t = Types.Job.t [@@deriving sexp_of]
|
|
88eb8e425266fd45f7fa13a961f6d1594cb1663c5d6886eb90cd1038dce61ee2 | acl2/acl2 | operations.lisp | C Library
;
Copyright ( C ) 2023 Kestrel Institute ( )
Copyright ( C ) 2023 Kestrel Technology LLC ( )
;
License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 .
;
Author : ( )
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package "C")
(include-book "scalar-operations")
(include-book "array-operations")
(include-book "structure-operations")
(local (include-book "kestrel/built-ins/disable" :dir :system))
(local (acl2::disable-most-builtin-logic-defuns))
(local (acl2::disable-builtin-rewrite-rules-for-defaults))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defxdoc+ operations
:parents (language)
:short "Operations on C values."
:order-subtopics t
:default-parent t)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define test-value ((val valuep))
:returns (res boolean-resultp)
:short "Test a value logically."
:long
(xdoc::topstring
(xdoc::p
"In some contexts (e.g. conditional tests),
a value is treated as a logical boolean.
The value must be scalar; see @(tsee test-scalar-value) for details."))
(if (value-scalarp val)
(test-scalar-value val)
(error (list :test-mistype
:required :scalar
:supplied (value-fix val))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define plus-value ((val valuep))
:returns (resval value-resultp)
:short "Apply unary @('+') to a value [C:6.5.3.3/1] [C:6.5.3.3/2]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not arithmetic."))
(if (value-arithmeticp val)
(plus-arithmetic-value val)
(error (list :plus-mistype
:required :arithmetic
:supplied (value-fix val))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define minus-value ((val valuep))
:returns (resval value-resultp)
:short "Apply unary @('-') to a value [C:6.5.3.3/1] [C:6.5.3.3/3]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not arithmetic."))
(if (value-arithmeticp val)
(minus-arithmetic-value val)
(error (list :minus-mistype
:required :arithmetic
:supplied (value-fix val))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define bitnot-value ((val valuep))
:returns (resval value-resultp)
:short "Apply @('~') to a value [C:6.5.3.3/1] [C:6.5.3.3/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not integer.
If it is integer, we promote it and then we flip its bits."))
(if (value-integerp val)
(bitnot-integer-value (promote-value val))
(error (list :bitnot-mistype
:required :integer
:supplied (value-fix val))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define lognot-value ((val valuep))
:returns (resval value-resultp)
:short "Apply @('!') to a value [C:6.5.3.3/1] [C:6.5.3.3/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not scalar."))
(if (value-scalarp val)
(lognot-scalar-value val)
(error (list :lognot-mistype
:required :scalar
:supplied (value-fix val))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define mul-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('*') to values [C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(mul-arithmetic-values val1 val2)
(error (list :mul-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define div-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('/') to values [C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(div-arithmetic-values val1 val2)
(error (list :div-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define rem-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('%') to values
[C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/5] [C:6.5.5/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(rem-arithmetic-values val1 val2)
(error (list :rem-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define add-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('+') to values [C:6.5.5/2] [C:6.5.5/5]."
:long
(xdoc::topstring
(xdoc::p
"We only support arithmetic values for now (no pointer arithmetic)."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(add-arithmetic-values val1 val2)
(error (list :add-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define sub-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('-') to values [C:6.5.5/3] [C:6.5.5/6]."
:long
(xdoc::topstring
(xdoc::p
"We only support arithmetic values for now (no pointer arithmetic)."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(sub-arithmetic-values val1 val2)
(error (list :sub-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define shl-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<<') to values [C:6.5.7/2] [C:6.5.7/3] [C:6.5.7/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we promote them
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(shl-integer-values (promote-value val1)
(promote-value val2))
(error (list :shl-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define shr-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>>') to values [C:6.5.7/2] [C:6.5.7/3] [C:6.5.7/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we promote them
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(shr-integer-values (promote-value val1)
(promote-value val2))
(error (list :shr-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define lt-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not real;
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(lt-real-values val1 val2)
(error (list :lt-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define gt-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not real;
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(gt-real-values val1 val2)
(error (list :gt-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define le-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<=') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not real;
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(le-real-values val1 val2)
(error (list :le-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ge-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>=') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not real;
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(ge-real-values val1 val2)
(error (list :ge-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define eq-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('==') to values [C:6.5.9/2] [C:6.5.9/3] [C:6.5.9/4]."
:long
(xdoc::topstring
(xdoc::p
"For now we only support arithmetic types."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(eq-arithmetic-values val1 val2)
(error (list :eq-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ne-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('!=') to values [C:6.5.9/2] [C:6.5.9/3] [C:6.5.9/4]."
:long
(xdoc::topstring
(xdoc::p
"For now we only support arithmetic types."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(ne-arithmetic-values val1 val2)
(error (list :ne-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define bitand-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('&') to values [C:6.5.10/2] [C:6.5.10/3] [C:6.5.10/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitand-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define bitxor-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('^') to values [C:6.5.11/2] [C:6.5.11/3] [C:6.5.11/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitxor-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define bitior-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('|') to values [C:6.5.12/2] [C:6.5.12/3] [C:6.5.12/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitior-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
| null | https://raw.githubusercontent.com/acl2/acl2/44f76f208004466a9e6cdf3a07dac98b3799817d/books/kestrel/c/language/operations.lisp | lisp |
see @(tsee test-scalar-value) for details."))
| C Library
Copyright ( C ) 2023 Kestrel Institute ( )
Copyright ( C ) 2023 Kestrel Technology LLC ( )
License : A 3 - clause BSD license . See the LICENSE file distributed with ACL2 .
Author : ( )
(in-package "C")
(include-book "scalar-operations")
(include-book "array-operations")
(include-book "structure-operations")
(local (include-book "kestrel/built-ins/disable" :dir :system))
(local (acl2::disable-most-builtin-logic-defuns))
(local (acl2::disable-builtin-rewrite-rules-for-defaults))
(defxdoc+ operations
:parents (language)
:short "Operations on C values."
:order-subtopics t
:default-parent t)
(define test-value ((val valuep))
:returns (res boolean-resultp)
:short "Test a value logically."
:long
(xdoc::topstring
(xdoc::p
"In some contexts (e.g. conditional tests),
a value is treated as a logical boolean.
(if (value-scalarp val)
(test-scalar-value val)
(error (list :test-mistype
:required :scalar
:supplied (value-fix val))))
:hooks (:fix))
(define plus-value ((val valuep))
:returns (resval value-resultp)
:short "Apply unary @('+') to a value [C:6.5.3.3/1] [C:6.5.3.3/2]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not arithmetic."))
(if (value-arithmeticp val)
(plus-arithmetic-value val)
(error (list :plus-mistype
:required :arithmetic
:supplied (value-fix val))))
:hooks (:fix))
(define minus-value ((val valuep))
:returns (resval value-resultp)
:short "Apply unary @('-') to a value [C:6.5.3.3/1] [C:6.5.3.3/3]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not arithmetic."))
(if (value-arithmeticp val)
(minus-arithmetic-value val)
(error (list :minus-mistype
:required :arithmetic
:supplied (value-fix val))))
:hooks (:fix))
(define bitnot-value ((val valuep))
:returns (resval value-resultp)
:short "Apply @('~') to a value [C:6.5.3.3/1] [C:6.5.3.3/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not integer.
If it is integer, we promote it and then we flip its bits."))
(if (value-integerp val)
(bitnot-integer-value (promote-value val))
(error (list :bitnot-mistype
:required :integer
:supplied (value-fix val))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
(define lognot-value ((val valuep))
:returns (resval value-resultp)
:short "Apply @('!') to a value [C:6.5.3.3/1] [C:6.5.3.3/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the value is not scalar."))
(if (value-scalarp val)
(lognot-scalar-value val)
(error (list :lognot-mistype
:required :scalar
:supplied (value-fix val))))
:hooks (:fix))
(define mul-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('*') to values [C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(mul-arithmetic-values val1 val2)
(error (list :mul-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define div-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('/') to values [C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(div-arithmetic-values val1 val2)
(error (list :div-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define rem-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('%') to values
[C:6.5.5/2] [C:6.5.5/3] [C:6.5.5/5] [C:6.5.5/6]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not arithmetic."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(rem-arithmetic-values val1 val2)
(error (list :rem-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define add-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('+') to values [C:6.5.5/2] [C:6.5.5/5]."
:long
(xdoc::topstring
(xdoc::p
"We only support arithmetic values for now (no pointer arithmetic)."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(add-arithmetic-values val1 val2)
(error (list :add-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define sub-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply binary @('-') to values [C:6.5.5/3] [C:6.5.5/6]."
:long
(xdoc::topstring
(xdoc::p
"We only support arithmetic values for now (no pointer arithmetic)."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(sub-arithmetic-values val1 val2)
(error (list :sub-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define shl-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<<') to values [C:6.5.7/2] [C:6.5.7/3] [C:6.5.7/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we promote them
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(shl-integer-values (promote-value val1)
(promote-value val2))
(error (list :shl-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
(define shr-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>>') to values [C:6.5.7/2] [C:6.5.7/3] [C:6.5.7/5]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we promote them
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(shr-integer-values (promote-value val1)
(promote-value val2))
(error (list :shr-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp)))
:hooks (:fix))
(define lt-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(lt-real-values val1 val2)
(error (list :lt-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define gt-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(gt-real-values val1 val2)
(error (list :gt-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define le-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('<=') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(le-real-values val1 val2)
(error (list :le-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define ge-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('>=') to values [C:6.5.8/2] [C:6.5.8/3] [C:6.5.8/6]."
:long
(xdoc::topstring
(xdoc::p
we do not support comparison of pointers yet."))
(if (and (value-realp val1)
(value-realp val2))
(ge-real-values val1 val2)
(error (list :ge-mistype
:required :real :real
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define eq-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('==') to values [C:6.5.9/2] [C:6.5.9/3] [C:6.5.9/4]."
:long
(xdoc::topstring
(xdoc::p
"For now we only support arithmetic types."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(eq-arithmetic-values val1 val2)
(error (list :eq-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define ne-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('!=') to values [C:6.5.9/2] [C:6.5.9/3] [C:6.5.9/4]."
:long
(xdoc::topstring
(xdoc::p
"For now we only support arithmetic types."))
(if (and (value-arithmeticp val1)
(value-arithmeticp val2))
(ne-arithmetic-values val1 val2)
(error (list :ne-mistype
:required :arithmetic :arithmetic
:supplied (value-fix val1) (value-fix val2))))
:hooks (:fix))
(define bitand-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('&') to values [C:6.5.10/2] [C:6.5.10/3] [C:6.5.10/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitand-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
(define bitxor-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('^') to values [C:6.5.11/2] [C:6.5.11/3] [C:6.5.11/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitxor-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
(define bitior-values ((val1 valuep) (val2 valuep))
:returns (resval value-resultp)
:short "Apply @('|') to values [C:6.5.12/2] [C:6.5.12/3] [C:6.5.12/4]."
:long
(xdoc::topstring
(xdoc::p
"It is an error if the values are not integers.
If they are integers, we perform the usual arithmetic conversions
and then we call the operation on integer values."))
(if (and (value-integerp val1)
(value-integerp val2))
(b* (((mv val1 val2) (uaconvert-values val1 val2)))
(bitior-integer-values val1 val2))
(error (list :bitand-mistype
:required :integer :integer
:supplied (value-fix val1) (value-fix val2))))
:guard-hints (("Goal" :in-theory (enable value-arithmeticp
value-realp
type-of-value-of-uaconvert-values)))
:hooks (:fix))
|
40d49c7698214b2250734ee23ce7d06c96cff661286a3319e71579951dc495ef | jimcrayne/jhc | tc191.hs | {-# OPTIONS -fglasgow-exts #-}
-- This only typechecks if forall-hoisting works ok when
-- importing from an interface file. The type of Twins.gzipWithQ
-- is this:
-- type GenericQ r = forall a. Data a => a -> r
-- gzipWithQ :: GenericQ (GenericQ r) -> GenericQ (GenericQ [r])
-- It's kept this way in the interface file for brevity and documentation,
-- but when the type synonym is expanded, the foralls need expanding
module Foo where
import Data.Generics.Basics
import Data.Generics.Aliases
import Data.Generics.Twins(gzipWithQ)
| Generic equality : an alternative to
geq :: Data a => a -> a -> Bool
geq x y = geq' x y
where
-- This type signature no longer works, because it is
-- insufficiently polymoprhic.
-- geq' :: forall a b. (Data a, Data b) => a -> b -> Bool
geq' :: GenericQ (GenericQ Bool)
geq' x y = (toConstr x == toConstr y)
&& and (gzipWithQ geq' x y)
| null | https://raw.githubusercontent.com/jimcrayne/jhc/1ff035af3d697f9175f8761c8d08edbffde03b4e/regress/tests/1_typecheck/2_pass/ghc/uncat/tc191.hs | haskell | # OPTIONS -fglasgow-exts #
This only typechecks if forall-hoisting works ok when
importing from an interface file. The type of Twins.gzipWithQ
is this:
type GenericQ r = forall a. Data a => a -> r
gzipWithQ :: GenericQ (GenericQ r) -> GenericQ (GenericQ [r])
It's kept this way in the interface file for brevity and documentation,
but when the type synonym is expanded, the foralls need expanding
This type signature no longer works, because it is
insufficiently polymoprhic.
geq' :: forall a b. (Data a, Data b) => a -> b -> Bool |
module Foo where
import Data.Generics.Basics
import Data.Generics.Aliases
import Data.Generics.Twins(gzipWithQ)
| Generic equality : an alternative to
geq :: Data a => a -> a -> Bool
geq x y = geq' x y
where
geq' :: GenericQ (GenericQ Bool)
geq' x y = (toConstr x == toConstr y)
&& and (gzipWithQ geq' x y)
|
b4f04b89c347a00e67bd7b0ea9d11dfc785e2549338ddaddd81378d1fbc2fd9c | marigold-dev/deku | parse.mli | type 'a start =
| Module : (Script.var option * Script.definition) start
| Script : Script.script start
| Script1 : Script.script start
exception Syntax of Source.region * string
val parse : string -> Lexing.lexbuf -> 'a start -> 'a (* raises Syntax *)
val string_to_script : string -> Script.script (* raises Syntax *)
val string_to_module : string -> Script.definition (* raises Syntax *)
| null | https://raw.githubusercontent.com/marigold-dev/deku/a26f31e0560ad12fd86cf7fa4667bb147247c7ef/deku-c/interpreter/text/parse.mli | ocaml | raises Syntax
raises Syntax
raises Syntax | type 'a start =
| Module : (Script.var option * Script.definition) start
| Script : Script.script start
| Script1 : Script.script start
exception Syntax of Source.region * string
|
f80cb24ebb89f551850e50434d54c46c79d7e95340dc2879fe86ee587e482536 | bobzhang/fan | meta.ml |
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} ;
- : Ast.str_item =
`External
(, "\\$:i", `Ant (, "\\$ctyp:t"), `LCons ("gho", `Ant (, "\\$str_list:x")))
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} |> ME.meta_str_item _loc ;
- : FanAst.expr =
`ExApp
(,
`ExApp
(,
`ExApp
(, `ExApp (, `ExVrn (, "External"), `Id (, `Lid (, "_loc"))),
`Str (, "\\$:i")),
`Ant (, "\\$ctyp:t")),
`ExApp
(, `ExApp (, `ExVrn (, "LCons"), `Str (, "gho")),
`Ant (, "\\$str_list:x")))
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} |> ME.meta_str_item _loc |> expr_filter;
- : Ast.expr =
`ExApp
(,
`ExApp
(,
`ExApp
(, `ExApp (, `ExVrn (, "External"), `Id (, `Lid (, "_loc"))),
`Id (, `Lid (, "i"))),
`Id (, `Lid (, "t"))),
`ExApp
(, `ExApp (, `ExVrn (, "LCons"), `Str (, "gho")), `Id (, `Lid (, "x"))))
(* A file demonstrate how meta works*)
let u = Ast.ExInt _loc "\\$int:\"32\""; (* came from $(int:"32") *)
(* directly dump will cause an error here *)
Meta.ME.meta_expr _loc u;
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "\\$int:\"32\""))
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "32"))
(Expr.antiquot_expander ~parse_patt:Syntax.AntiquotSyntax.parse_patt ~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Ast.ExStr _loc "\\$int:\"32\"");
- : Lib.Expr.Ast.expr = ExStr (, "32")
Syntax.AntiquotSyntax.parse_expr FanLoc.string_loc "\"32\"";
- : Ast.expr = ExStr (, "32")
let u = Ast.ExInt _loc "\\$int:x";
Meta.ME.meta_expr _loc u;
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "\\$int:x"))
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
- : Lib.Expr.Ast.expr =
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExId (, IdLid (, "x")))
sequence:
[ "let"; opt_rec{rf}; binding{bi}; "in"; expr{e}; sequence'{k} ->
k {:expr| let $rec:rf $bi in $e |}
| "let"; opt_rec{rf}; binding{bi}; ";"; SELF{el} ->
{:expr| let $rec:rf $bi in $(Expr.mksequence _loc el) |}
| "let"; "module"; a_UIDENT{m}; module_binding0{mb}; "in"; expr{e}; sequence'{k} ->
k {:expr| let module $m = $mb in $e |}
| "let"; "module"; a_UIDENT{m}; module_binding0{mb}; ";"; SELF{el} ->
{:expr| let module $m = $mb in $(Expr.mksequence _loc el) |}
| "let"; "open"; module_longident{i}; "in"; SELF{e} ->
{:expr| let open $id:i in $e |}
| `ANTIQUOT (("list" as n),s) -> {:expr| $(anti:mk_anti ~c:"expr;" n s) |}
| expr{e}; sequence'{k} -> k e ]
{:expr| begin $list:x end|}
let u = Ast.ExAnt _loc (mk_anti ~c:"expr;" "list" "fuck") ;
val u : Ast.expr = ExAnt (, "\\$listexpr;:fuck")
Meta.ME.meta_expr _loc u;
- : Lib.Meta.Ast.Ast.expr = ExAnt (, "\\$listexpr;:fuck")
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdLid (, "exSem_of_list"))),
ExId (, IdLid (, "fuck")))
let u =Ast.ExAnt _loc (mk_anti ~c:"anti" "list" "fuck") ;
val u : Ast.expr = ExAnt (, "\\$listanti:fuck")
Meta.ME.meta_expr _loc u;
- : Lib.Meta.Ast.Ast.expr = ExAnt (, "\\$listanti:fuck")
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
- : Lib.Expr.Ast.expr = ExId (, IdLid (, "fuck"))
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/testr/meta.ml | ocaml | A file demonstrate how meta works
came from $(int:"32")
directly dump will cause an error here |
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} ;
- : Ast.str_item =
`External
(, "\\$:i", `Ant (, "\\$ctyp:t"), `LCons ("gho", `Ant (, "\\$str_list:x")))
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} |> ME.meta_str_item _loc ;
- : FanAst.expr =
`ExApp
(,
`ExApp
(,
`ExApp
(, `ExApp (, `ExVrn (, "External"), `Id (, `Lid (, "_loc"))),
`Str (, "\\$:i")),
`Ant (, "\\$ctyp:t")),
`ExApp
(, `ExApp (, `ExVrn (, "LCons"), `Str (, "gho")),
`Ant (, "\\$str_list:x")))
t str_item {:str| external $i : $t = "gho" $x $y "gho" |} |> ME.meta_str_item _loc |> expr_filter;
- : Ast.expr =
`ExApp
(,
`ExApp
(,
`ExApp
(, `ExApp (, `ExVrn (, "External"), `Id (, `Lid (, "_loc"))),
`Id (, `Lid (, "i"))),
`Id (, `Lid (, "t"))),
`ExApp
(, `ExApp (, `ExVrn (, "LCons"), `Str (, "gho")), `Id (, `Lid (, "x"))))
Meta.ME.meta_expr _loc u;
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "\\$int:\"32\""))
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "32"))
(Expr.antiquot_expander ~parse_patt:Syntax.AntiquotSyntax.parse_patt ~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Ast.ExStr _loc "\\$int:\"32\"");
- : Lib.Expr.Ast.expr = ExStr (, "32")
Syntax.AntiquotSyntax.parse_expr FanLoc.string_loc "\"32\"";
- : Ast.expr = ExStr (, "32")
let u = Ast.ExInt _loc "\\$int:x";
Meta.ME.meta_expr _loc u;
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExStr (, "\\$int:x"))
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
- : Lib.Expr.Ast.expr =
ExApp (,
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdUid (, "ExInt"))),
ExId (, IdLid (, "_loc"))),
ExId (, IdLid (, "x")))
sequence:
[ "let"; opt_rec{rf}; binding{bi}; "in"; expr{e}; sequence'{k} ->
k {:expr| let $rec:rf $bi in $e |}
| "let"; opt_rec{rf}; binding{bi}; ";"; SELF{el} ->
{:expr| let $rec:rf $bi in $(Expr.mksequence _loc el) |}
| "let"; "module"; a_UIDENT{m}; module_binding0{mb}; "in"; expr{e}; sequence'{k} ->
k {:expr| let module $m = $mb in $e |}
| "let"; "module"; a_UIDENT{m}; module_binding0{mb}; ";"; SELF{el} ->
{:expr| let module $m = $mb in $(Expr.mksequence _loc el) |}
| "let"; "open"; module_longident{i}; "in"; SELF{e} ->
{:expr| let open $id:i in $e |}
| `ANTIQUOT (("list" as n),s) -> {:expr| $(anti:mk_anti ~c:"expr;" n s) |}
| expr{e}; sequence'{k} -> k e ]
{:expr| begin $list:x end|}
let u = Ast.ExAnt _loc (mk_anti ~c:"expr;" "list" "fuck") ;
val u : Ast.expr = ExAnt (, "\\$listexpr;:fuck")
Meta.ME.meta_expr _loc u;
- : Lib.Meta.Ast.Ast.expr = ExAnt (, "\\$listexpr;:fuck")
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
ExApp (, ExId (, IdAcc (, IdUid (, "Ast"), IdLid (, "exSem_of_list"))),
ExId (, IdLid (, "fuck")))
let u =Ast.ExAnt _loc (mk_anti ~c:"anti" "list" "fuck") ;
val u : Ast.expr = ExAnt (, "\\$listanti:fuck")
Meta.ME.meta_expr _loc u;
- : Lib.Meta.Ast.Ast.expr = ExAnt (, "\\$listanti:fuck")
(Expr.antiquot_expander
~parse_patt:Syntax.AntiquotSyntax.parse_patt
~parse_expr:Syntax.AntiquotSyntax.parse_expr)#expr (Meta.ME.meta_expr _loc u);
- : Lib.Expr.Ast.expr = ExId (, IdLid (, "fuck"))
|
acef2ee20c3228b3dffa252ade6e9e9819b715cde47fdf12921cec65c408c5e1 | aryx/xix | main.ml | (*
* todo:
* - make it an independent program and a library (so avoid some forks)
* - compare to ?
*)
| null | https://raw.githubusercontent.com/aryx/xix/60ce1bd9a3f923e0e8bb2192f8938a9aa49c739c/macroprocessor/main.ml | ocaml |
* todo:
* - make it an independent program and a library (so avoid some forks)
* - compare to ?
| |
d0c0595a74584124770640f7f98c3e8816bcf7438524363e67afa45bb2b81f0b | fold-lang/pratt | Pratt.ml |
let inspect pp =
Format.fprintf Fmt.stderr "@[%a@.@]" pp
let log fmt =
Format.kfprintf (fun f -> Format.pp_print_newline f ()) Fmt.stderr fmt
let constantly x _ = x
let (<<) f g = fun x -> f (g x)
let is_some = function Some _ -> true | None -> false
let flip f x y = f y x
(* TODO: When failing show the so-far parsed result. *)
type 'a fmt = Format.formatter -> 'a -> unit
type 'a comparator = 'a -> 'a -> int
module Stream = Stream
module type Token = sig
type t
val pp : t fmt
val compare : t comparator
end
module Make (Token : Token) = struct
module Table = struct
include Map.Make(Token)
let get tbl x =
try Some (find tbl x)
with Not_found -> None
end
type token = Token.t
let pp_token = Token.pp
type error =
| Unexpected of { expected : token option; actual : token option }
| Invalid_infix of token
| Invalid_prefix of token
| Zero
let unexpected_token ?expected actual =
Unexpected {expected; actual = Some actual}
let unexpected_end ?expected () =
Unexpected {expected; actual = None}
let invalid_prefix t =
Invalid_prefix t
let invalid_infix t =
Invalid_infix t
let error_to_string = function
| Unexpected {expected = Some t1; actual = Some t2} ->
Fmt.strf "Syntax error: expected '%a' but got '%a'" pp_token t1 pp_token t2
| Unexpected { expected = Some t; actual = None } ->
Fmt.strf "Syntax error: unexpected end of file while parsing '%a'" pp_token t
| Unexpected { expected = None; actual = None } ->
Fmt.strf "Syntax error: unexpected end of file"
| Unexpected { expected = None; actual = Some t } ->
Fmt.strf "Syntax error: unexpected token '%a'" pp_token t
| Invalid_infix token ->
Fmt.strf "Syntax error: '%a' cannot be used in infix postion" pp_token token
| Invalid_prefix token ->
Fmt.strf "Syntax error: '%a' cannot be used in prefix position" pp_token token
| Zero ->
Fmt.strf "Syntax error: empty parser result"
let pp_error ppf = function
| Unexpected { expected; actual } ->
Fmt.pf ppf "@[<2>Unexpected@ {@ expected =@ @[%a@];@ actual =@ @[%a@] }@]"
(Fmt.Dump.option pp_token) expected (Fmt.Dump.option pp_token) actual
| Invalid_infix token ->
Fmt.pf ppf "@[<2>Invalid_infix@ @[%a@] @]" pp_token token
| Invalid_prefix token ->
Fmt.pf ppf "@[<2>Invalid_prefix@ @[%a@] @]" pp_token token
| Zero -> Fmt.pf ppf "Empty"
type 'a parser = token Stream.t -> ('a * token Stream.t, error) result
let return x =
fun input -> Ok (x, input)
let (>>=) p f =
fun input ->
match p input with
| Ok (x, input') ->
let p' = f x in p' input'
| Error e -> Error e
let put s = fun _ -> Ok ((), s)
let get = fun s -> Ok (s, s)
let zero = fun _input -> Error Zero
let (<|>) p q = fun input ->
match p input with
| Ok value -> Ok value
| Error _ -> q input
(* XXX: What if p consumes input? *)
(* | Error Empty -> q input *)
(* | Error e -> Error e *)
let default x p =
p <|> return x
let rec many p =
(p >>= fun x -> many p >>= fun xs -> return (x :: xs))
|> default []
let combine p1 p2 =
p1 >>= fun x ->
p2 >>= fun y -> return (x, y)
let rec some p =
combine p (many p)
let optional p =
default () (p >>= fun _ -> return ())
let error e =
fun _state -> Error e
let advance s =
let p =
get >>= fun stream ->
match Stream.next stream with
| Some (token, stream') -> put stream'
| None -> return () in
p s
let current = fun s ->
let p = get >>= fun state ->
match Stream.head state with
| Some token -> return token
| None -> error (unexpected_end ()) in
p s
let next s =
let p =
current >>= fun x ->
advance >>= fun () -> return x in
p s
let expect expected : 'a parser =
get >>= fun stream ->
match Stream.head stream with
| Some actual when actual = expected -> return actual
| Some actual -> error (unexpected_token ~expected actual)
| None -> error (unexpected_end ~expected ())
let consume tok =
expect tok >>= fun _ -> advance
let exactly x =
expect x >>= fun x -> advance >>= fun () -> return x
let satisfy test =
next >>= function
| actual when test actual -> return actual
| actual -> error (unexpected_token actual)
let any s = (satisfy (constantly true)) s
let from list =
satisfy (fun x -> List.mem x list)
let none list =
satisfy (fun x -> not (List.mem x list))
let range ?(compare = Pervasives.compare) s e =
let (<=) a b = not (compare a b > 0) in
satisfy (fun x -> s <= x && x <= e)
let rec choice ps =
match ps with
| [] -> zero
| p :: ps' -> p <|> choice ps'
let guard = function
| true -> return ()
| false -> zero
let when' test m =
if test then m
else return ()
let unless test m =
if test then return ()
else m
let many_while test p =
many (current >>= (guard << test) >>= fun () -> p)
let some_while test p =
some (current >>= (guard << test) >>= fun () -> p)
type 'a grammar = {
data : 'a scope list;
term : 'a null
}
and 'a scope = {
null : 'a null Table.t;
left : 'a left Table.t;
}
and 'a null = ('a grammar -> 'a parser)
and 'a left = ('a grammar -> 'a -> 'a parser) * int
type 'a rule =
| Term of 'a null
| Null of token * 'a null
| Left of token * 'a left
module Grammar = struct
type 'a t = 'a grammar
let make_scope () = {
null = Table.empty;
left = Table.empty
}
let empty = {
term = (fun g -> current >>= fun t -> error (Invalid_prefix t));
data = [];
}
let add rule grammar =
let scope, data =
match grammar.data with
| [] -> make_scope (), []
| scope :: grammar' -> scope, grammar' in
match rule with
| Term term -> { grammar with term }
| Null (t, rule) ->
let scope = { scope with null = Table.add t rule scope.null } in
{ grammar with data = scope :: data }
| Left (t, rule) ->
let scope = { scope with left = Table.add t rule scope.left } in
{ grammar with data = scope :: data }
let dump pp_token grammar =
let dump_scope scope =
Fmt.pr "grammar.null:\n";
Table.iter (fun t _ -> Fmt.pr "- %a\n" pp_token t) scope.null;
Fmt.pr "grammar.left:\n";
Table.iter (fun t _ -> Fmt.pr "- %a\n" pp_token t) scope.left in
let rec loop (data : 'a scope list) =
match data with
| [] -> ()
| scope :: data' ->
dump_scope scope;
Fmt.pr "***@.";
loop data' in
loop grammar.data
let get_left token grammar =
let rec find data =
match data with
| [] -> None
| scope :: data' ->
begin match Table.get token scope.left with
| Some rule -> Some rule
| None -> find data'
end in
find grammar.data
let get_null token grammar =
let rec find data =
match data with
| [] -> None
| scope :: data' ->
begin match Table.get token scope.null with
| Some rule -> Some rule
| None -> find data'
end in
find grammar.data
let has_null token grammar =
is_some (get_null token grammar)
let has_left token grammar =
is_some (get_left token grammar)
let new_scope grammar =
{ grammar with data = make_scope () :: grammar.data }
let pop_scope grammar =
let data =
match grammar.data with
| [] -> []
| _ :: data' -> data' in
{ grammar with data }
let get_term grammar =
grammar.term
end
let nud rbp grammar =
current >>= fun token ->
match Grammar.get_null token grammar with
| Some parse -> parse grammar
| None ->
(* Infix tokens can only be a valid prefix if they are directly defined
as such. If the token has a led definition it is not consumed,
otherwise the term parser is called. *)
if Grammar.has_left token grammar then
error (invalid_prefix token)
else
let parse = Grammar.get_term grammar in
parse grammar
let rec led rbp grammar x =
get >>= fun stream ->
match Stream.head stream with
| Some token ->
begin match Grammar.get_left token grammar with
| Some (parse, lbp) ->
if lbp > rbp then
parse grammar x >>= led rbp grammar
else
return x
| None ->
return x
end
| None ->
return x
let parse ?precedence:(rbp = 0) grammar =
nud rbp grammar >>= led rbp grammar
let parse_many grammar =
many begin
current >>= fun token ->
guard (not (Grammar.has_left token grammar)) >>= fun () ->
nud 0 grammar
end
let parse_some grammar =
some begin
current >>= fun token ->
guard (not (Grammar.has_left token grammar)) >>= fun () ->
nud 0 grammar
end
let grammar rules =
List.fold_left (flip Grammar.add) Grammar.empty rules
let run p stream =
match p stream with
| Ok (x, stream') -> Ok (x, stream')
| Error e -> Error e
let rule token parse =
Null (token, parse)
let term parse =
Term parse
let infix precedence token f =
let parse grammar x =
advance >>= fun () ->
parse ~precedence grammar >>= fun y ->
return (f x y) in
Left (token, (parse, precedence))
let infixr precedence token f =
let parse grammar x =
advance >>= fun () ->
parse ~precedence:(precedence - 1) grammar >>= fun y ->
return (f x y) in
Left (token, (parse, precedence))
let prefix token f =
let parse grammar =
advance >>= fun () ->
parse grammar >>= fun x ->
return (f x) in
Null (token, parse)
let postfix precedence token f =
let parse grammar x =
advance >>= fun () ->
return (f x) in
Left (token, (parse, precedence))
let between token1 token2 f =
let parse grammar =
advance >>= fun () ->
parse grammar >>= fun x ->
consume token2 >>= fun () ->
return (f x) in
Null (token1, parse)
let delimiter token =
let parse g x = error (Invalid_infix token) in
Left (token, (parse, 0))
let null token parse =
Null (token, parse)
let left precedence token parse =
Left (token, (parse, precedence))
let binary f = fun g a ->
advance >>= fun () ->
parse g >>= fun b ->
return (f a b)
let unary f = fun g ->
advance >>= fun () ->
parse g >>= fun a ->
return (f a)
end
| null | https://raw.githubusercontent.com/fold-lang/pratt/8a8d2fd439e5e30b5ae587bd71e810c8bc6adf42/src/Pratt.ml | ocaml | TODO: When failing show the so-far parsed result.
XXX: What if p consumes input?
| Error Empty -> q input
| Error e -> Error e
Infix tokens can only be a valid prefix if they are directly defined
as such. If the token has a led definition it is not consumed,
otherwise the term parser is called. |
let inspect pp =
Format.fprintf Fmt.stderr "@[%a@.@]" pp
let log fmt =
Format.kfprintf (fun f -> Format.pp_print_newline f ()) Fmt.stderr fmt
let constantly x _ = x
let (<<) f g = fun x -> f (g x)
let is_some = function Some _ -> true | None -> false
let flip f x y = f y x
type 'a fmt = Format.formatter -> 'a -> unit
type 'a comparator = 'a -> 'a -> int
module Stream = Stream
module type Token = sig
type t
val pp : t fmt
val compare : t comparator
end
module Make (Token : Token) = struct
module Table = struct
include Map.Make(Token)
let get tbl x =
try Some (find tbl x)
with Not_found -> None
end
type token = Token.t
let pp_token = Token.pp
type error =
| Unexpected of { expected : token option; actual : token option }
| Invalid_infix of token
| Invalid_prefix of token
| Zero
let unexpected_token ?expected actual =
Unexpected {expected; actual = Some actual}
let unexpected_end ?expected () =
Unexpected {expected; actual = None}
let invalid_prefix t =
Invalid_prefix t
let invalid_infix t =
Invalid_infix t
let error_to_string = function
| Unexpected {expected = Some t1; actual = Some t2} ->
Fmt.strf "Syntax error: expected '%a' but got '%a'" pp_token t1 pp_token t2
| Unexpected { expected = Some t; actual = None } ->
Fmt.strf "Syntax error: unexpected end of file while parsing '%a'" pp_token t
| Unexpected { expected = None; actual = None } ->
Fmt.strf "Syntax error: unexpected end of file"
| Unexpected { expected = None; actual = Some t } ->
Fmt.strf "Syntax error: unexpected token '%a'" pp_token t
| Invalid_infix token ->
Fmt.strf "Syntax error: '%a' cannot be used in infix postion" pp_token token
| Invalid_prefix token ->
Fmt.strf "Syntax error: '%a' cannot be used in prefix position" pp_token token
| Zero ->
Fmt.strf "Syntax error: empty parser result"
let pp_error ppf = function
| Unexpected { expected; actual } ->
Fmt.pf ppf "@[<2>Unexpected@ {@ expected =@ @[%a@];@ actual =@ @[%a@] }@]"
(Fmt.Dump.option pp_token) expected (Fmt.Dump.option pp_token) actual
| Invalid_infix token ->
Fmt.pf ppf "@[<2>Invalid_infix@ @[%a@] @]" pp_token token
| Invalid_prefix token ->
Fmt.pf ppf "@[<2>Invalid_prefix@ @[%a@] @]" pp_token token
| Zero -> Fmt.pf ppf "Empty"
type 'a parser = token Stream.t -> ('a * token Stream.t, error) result
let return x =
fun input -> Ok (x, input)
let (>>=) p f =
fun input ->
match p input with
| Ok (x, input') ->
let p' = f x in p' input'
| Error e -> Error e
let put s = fun _ -> Ok ((), s)
let get = fun s -> Ok (s, s)
let zero = fun _input -> Error Zero
let (<|>) p q = fun input ->
match p input with
| Ok value -> Ok value
| Error _ -> q input
let default x p =
p <|> return x
let rec many p =
(p >>= fun x -> many p >>= fun xs -> return (x :: xs))
|> default []
let combine p1 p2 =
p1 >>= fun x ->
p2 >>= fun y -> return (x, y)
let rec some p =
combine p (many p)
let optional p =
default () (p >>= fun _ -> return ())
let error e =
fun _state -> Error e
let advance s =
let p =
get >>= fun stream ->
match Stream.next stream with
| Some (token, stream') -> put stream'
| None -> return () in
p s
let current = fun s ->
let p = get >>= fun state ->
match Stream.head state with
| Some token -> return token
| None -> error (unexpected_end ()) in
p s
let next s =
let p =
current >>= fun x ->
advance >>= fun () -> return x in
p s
let expect expected : 'a parser =
get >>= fun stream ->
match Stream.head stream with
| Some actual when actual = expected -> return actual
| Some actual -> error (unexpected_token ~expected actual)
| None -> error (unexpected_end ~expected ())
let consume tok =
expect tok >>= fun _ -> advance
let exactly x =
expect x >>= fun x -> advance >>= fun () -> return x
let satisfy test =
next >>= function
| actual when test actual -> return actual
| actual -> error (unexpected_token actual)
let any s = (satisfy (constantly true)) s
let from list =
satisfy (fun x -> List.mem x list)
let none list =
satisfy (fun x -> not (List.mem x list))
let range ?(compare = Pervasives.compare) s e =
let (<=) a b = not (compare a b > 0) in
satisfy (fun x -> s <= x && x <= e)
let rec choice ps =
match ps with
| [] -> zero
| p :: ps' -> p <|> choice ps'
let guard = function
| true -> return ()
| false -> zero
let when' test m =
if test then m
else return ()
let unless test m =
if test then return ()
else m
let many_while test p =
many (current >>= (guard << test) >>= fun () -> p)
let some_while test p =
some (current >>= (guard << test) >>= fun () -> p)
type 'a grammar = {
data : 'a scope list;
term : 'a null
}
and 'a scope = {
null : 'a null Table.t;
left : 'a left Table.t;
}
and 'a null = ('a grammar -> 'a parser)
and 'a left = ('a grammar -> 'a -> 'a parser) * int
type 'a rule =
| Term of 'a null
| Null of token * 'a null
| Left of token * 'a left
module Grammar = struct
type 'a t = 'a grammar
let make_scope () = {
null = Table.empty;
left = Table.empty
}
let empty = {
term = (fun g -> current >>= fun t -> error (Invalid_prefix t));
data = [];
}
let add rule grammar =
let scope, data =
match grammar.data with
| [] -> make_scope (), []
| scope :: grammar' -> scope, grammar' in
match rule with
| Term term -> { grammar with term }
| Null (t, rule) ->
let scope = { scope with null = Table.add t rule scope.null } in
{ grammar with data = scope :: data }
| Left (t, rule) ->
let scope = { scope with left = Table.add t rule scope.left } in
{ grammar with data = scope :: data }
let dump pp_token grammar =
let dump_scope scope =
Fmt.pr "grammar.null:\n";
Table.iter (fun t _ -> Fmt.pr "- %a\n" pp_token t) scope.null;
Fmt.pr "grammar.left:\n";
Table.iter (fun t _ -> Fmt.pr "- %a\n" pp_token t) scope.left in
let rec loop (data : 'a scope list) =
match data with
| [] -> ()
| scope :: data' ->
dump_scope scope;
Fmt.pr "***@.";
loop data' in
loop grammar.data
let get_left token grammar =
let rec find data =
match data with
| [] -> None
| scope :: data' ->
begin match Table.get token scope.left with
| Some rule -> Some rule
| None -> find data'
end in
find grammar.data
let get_null token grammar =
let rec find data =
match data with
| [] -> None
| scope :: data' ->
begin match Table.get token scope.null with
| Some rule -> Some rule
| None -> find data'
end in
find grammar.data
let has_null token grammar =
is_some (get_null token grammar)
let has_left token grammar =
is_some (get_left token grammar)
let new_scope grammar =
{ grammar with data = make_scope () :: grammar.data }
let pop_scope grammar =
let data =
match grammar.data with
| [] -> []
| _ :: data' -> data' in
{ grammar with data }
let get_term grammar =
grammar.term
end
let nud rbp grammar =
current >>= fun token ->
match Grammar.get_null token grammar with
| Some parse -> parse grammar
| None ->
if Grammar.has_left token grammar then
error (invalid_prefix token)
else
let parse = Grammar.get_term grammar in
parse grammar
let rec led rbp grammar x =
get >>= fun stream ->
match Stream.head stream with
| Some token ->
begin match Grammar.get_left token grammar with
| Some (parse, lbp) ->
if lbp > rbp then
parse grammar x >>= led rbp grammar
else
return x
| None ->
return x
end
| None ->
return x
let parse ?precedence:(rbp = 0) grammar =
nud rbp grammar >>= led rbp grammar
let parse_many grammar =
many begin
current >>= fun token ->
guard (not (Grammar.has_left token grammar)) >>= fun () ->
nud 0 grammar
end
let parse_some grammar =
some begin
current >>= fun token ->
guard (not (Grammar.has_left token grammar)) >>= fun () ->
nud 0 grammar
end
let grammar rules =
List.fold_left (flip Grammar.add) Grammar.empty rules
let run p stream =
match p stream with
| Ok (x, stream') -> Ok (x, stream')
| Error e -> Error e
let rule token parse =
Null (token, parse)
let term parse =
Term parse
let infix precedence token f =
let parse grammar x =
advance >>= fun () ->
parse ~precedence grammar >>= fun y ->
return (f x y) in
Left (token, (parse, precedence))
let infixr precedence token f =
let parse grammar x =
advance >>= fun () ->
parse ~precedence:(precedence - 1) grammar >>= fun y ->
return (f x y) in
Left (token, (parse, precedence))
let prefix token f =
let parse grammar =
advance >>= fun () ->
parse grammar >>= fun x ->
return (f x) in
Null (token, parse)
let postfix precedence token f =
let parse grammar x =
advance >>= fun () ->
return (f x) in
Left (token, (parse, precedence))
let between token1 token2 f =
let parse grammar =
advance >>= fun () ->
parse grammar >>= fun x ->
consume token2 >>= fun () ->
return (f x) in
Null (token1, parse)
let delimiter token =
let parse g x = error (Invalid_infix token) in
Left (token, (parse, 0))
let null token parse =
Null (token, parse)
let left precedence token parse =
Left (token, (parse, precedence))
let binary f = fun g a ->
advance >>= fun () ->
parse g >>= fun b ->
return (f a b)
let unary f = fun g ->
advance >>= fun () ->
parse g >>= fun a ->
return (f a)
end
|
38ddb4c845495194ea81edc45bffc9ac69ea5d35d6a371196a37ee6e27fd3efb | gvannest/piscine_OCaml | eu_dist.ml | let eu_dist (a:float array) (b:float array) : float =
let diff (x:float) (y:float) = x -. y
in
let square (x:float) = x *. x
in
let sum (x:float) (y:float) = x +. y
in
let sroot ( n : float ) =
let p = 0.0001 in
let rec loop x = match x * . x with
| m when m > n - . p & & m < = n + . p - > m
| _ - > print_float x ; print_char ' \n ' ; loop ( x + . ( n /. x ) ) /. 2.0
in
loop ( n /. 2.0 )
in
let p = 0.0001 in
let rec loop x = match x *. x with
| m when m > n -. p && m <= n +. p -> m
| _ -> print_float x ; print_char '\n' ; loop (x +. (n /. x)) /. 2.0
in
loop (n /. 2.0)
in *)
let toSum = Array.map square (Array.map2 diff a b) in
let toSroot = Array.fold_left sum 0.0 toSum in
sqrt toSroot
let () =
let a = [|1.; 1.; 1.; 1.|] in
let b = [|2.; 2.; 2.; 2.|] in
print_string "Eu_dist [|1.; 1.; 1.; 1.|] and [|2.; 2.; 2.; 2.|] = ";
print_float (eu_dist a b);
print_endline "";
print_string "Eu_dist [|4.5; 1.0; (-2.5); 0.4|] and [|2.; 3.; 12.; (-42.)|] = ";
print_float (eu_dist [|4.5; 1.0; (-2.5); 0.4|] [|2.; 3.; 12.; (-42.)|]);
print_endline "";
print_string "Eu_dist [|1.; (-2.)|] and [| 4.; 2.|] = ";
print_float (eu_dist [|1.; (-2.)|] [| 4.; 2.|]);
print_endline "" | null | https://raw.githubusercontent.com/gvannest/piscine_OCaml/2533c6152cfb46c637d48a6d0718f7c7262b3ba6/d05/ex05/eu_dist.ml | ocaml | let eu_dist (a:float array) (b:float array) : float =
let diff (x:float) (y:float) = x -. y
in
let square (x:float) = x *. x
in
let sum (x:float) (y:float) = x +. y
in
let sroot ( n : float ) =
let p = 0.0001 in
let rec loop x = match x * . x with
| m when m > n - . p & & m < = n + . p - > m
| _ - > print_float x ; print_char ' \n ' ; loop ( x + . ( n /. x ) ) /. 2.0
in
loop ( n /. 2.0 )
in
let p = 0.0001 in
let rec loop x = match x *. x with
| m when m > n -. p && m <= n +. p -> m
| _ -> print_float x ; print_char '\n' ; loop (x +. (n /. x)) /. 2.0
in
loop (n /. 2.0)
in *)
let toSum = Array.map square (Array.map2 diff a b) in
let toSroot = Array.fold_left sum 0.0 toSum in
sqrt toSroot
let () =
let a = [|1.; 1.; 1.; 1.|] in
let b = [|2.; 2.; 2.; 2.|] in
print_string "Eu_dist [|1.; 1.; 1.; 1.|] and [|2.; 2.; 2.; 2.|] = ";
print_float (eu_dist a b);
print_endline "";
print_string "Eu_dist [|4.5; 1.0; (-2.5); 0.4|] and [|2.; 3.; 12.; (-42.)|] = ";
print_float (eu_dist [|4.5; 1.0; (-2.5); 0.4|] [|2.; 3.; 12.; (-42.)|]);
print_endline "";
print_string "Eu_dist [|1.; (-2.)|] and [| 4.; 2.|] = ";
print_float (eu_dist [|1.; (-2.)|] [| 4.; 2.|]);
print_endline "" |
|
faca4399ae138a3f47826203563c20dc00a6678577c26ffb29c08a798a5d070b | tezos/tezos-mirror | dal_helpers.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2022 Nomadic Labs , < >
(* *)
(* Permission is hereby granted, free of charge, to any person obtaining a *)
(* copy of this software and associated documentation files (the "Software"),*)
to deal in the Software without restriction , including without limitation
(* the rights to use, copy, modify, merge, publish, distribute, sublicense, *)
and/or sell copies of the Software , and to permit persons to whom the
(* Software is furnished to do so, subject to the following conditions: *)
(* *)
(* The above copyright notice and this permission notice shall be included *)
(* in all copies or substantial portions of the Software. *)
(* *)
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
(* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *)
(* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *)
(* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER*)
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
(* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *)
(* DEALINGS IN THE SOFTWARE. *)
(* *)
(*****************************************************************************)
open Protocol
module S = Dal_slot_repr
module P = S.Page
module Hist = S.History
module Ihist = Hist.Internal_for_tests
(** Error used below for functions that don't return their failures in the monad
error. *)
type error += Test_failure of string
let () =
let open Data_encoding in
register_error_kind
`Permanent
~id:(Protocol.name ^ "_test_failure")
~title:"Test failure"
~description:"Test failure."
~pp:(fun ppf e -> Format.fprintf ppf "Test failure: %s" e)
(obj1 (req "error" string))
(function Test_failure e -> Some e | _ -> None)
(fun e -> Test_failure e)
let mk_cryptobox dal_params =
let open Result_syntax in
let parameters =
Cryptobox.Internal_for_tests.parameters_initialisation dal_params
in
let () = Cryptobox.Internal_for_tests.load_parameters parameters in
match Cryptobox.make dal_params with
| Ok dal -> return dal
| Error (`Fail s) -> fail [Test_failure s]
let derive_dal_parameters (reference : Cryptobox.parameters) ~redundancy_factor
~constants_divider =
{
S.redundancy_factor;
page_size = reference.page_size / constants_divider;
slot_size = reference.slot_size / constants_divider;
number_of_shards = reference.number_of_shards / constants_divider;
}
module Make (Parameters : sig
val dal_parameters : Alpha_context.Constants.Parametric.dal
val cryptobox : Cryptobox.t
end) =
struct
(* Some global constants. *)
let params = Parameters.dal_parameters.cryptobox_parameters
let cryptobox = Parameters.cryptobox
let genesis_history = Hist.genesis
let genesis_history_cache = Hist.History_cache.empty ~capacity:3000L
let level_one = Raw_level_repr.(succ root)
let level_ten = Raw_level_repr.(of_int32_exn 10l)
(* Helper functions. *)
let get_history cache h = Hist.History_cache.find h cache |> Lwt.return
let dal_mk_polynomial_from_slot slot_data =
let open Result_syntax in
match Cryptobox.polynomial_from_slot cryptobox slot_data with
| Ok p -> return p
| Error (`Slot_wrong_size s) ->
fail
[
Test_failure
(Format.sprintf "polynomial_from_slot: Slot_wrong_size (%s)" s);
]
let dal_mk_prove_page polynomial page_id =
let open Result_syntax in
match Cryptobox.prove_page cryptobox polynomial page_id.P.page_index with
| Ok p -> return p
| Error `Segment_index_out_of_range ->
fail [Test_failure "compute_proof_segment: Segment_index_out_of_range"]
| Error
(`Invalid_degree_strictly_less_than_expected
Cryptobox.{given; expected}) ->
fail
[
Test_failure
(Format.sprintf
"Got %d, expecting a value strictly less than %d"
given
expected);
]
let mk_slot ?(level = level_one) ?(index = S.Index.zero)
?(fill_function = fun _i -> 'x') () =
let open Result_syntax in
let slot_data = Bytes.init params.slot_size fill_function in
let* polynomial = dal_mk_polynomial_from_slot slot_data in
let* commitment =
match Cryptobox.commit cryptobox polynomial with
| Ok cm -> return cm
| Error
(`Invalid_degree_strictly_less_than_expected
Cryptobox.{given; expected}) ->
fail
[
Test_failure
(Format.sprintf
"Got %d, expecting a value strictly less than %d"
given
expected);
]
in
return
( slot_data,
polynomial,
S.Header.{id = {published_level = level; index}; commitment} )
let mk_page_id published_level slot_index page_index =
P.{slot_id = {published_level; index = slot_index}; page_index}
let no_data = Some (fun ~default_char:_ _ -> None)
let mk_page_info ?(default_char = 'x') ?level ?(page_index = P.Index.zero)
?(custom_data = None) (slot : S.Header.t) polynomial =
let open Result_syntax in
let level =
match level with None -> slot.id.published_level | Some level -> level
in
let page_id = mk_page_id level slot.id.index page_index in
let* page_proof = dal_mk_prove_page polynomial page_id in
match custom_data with
| None ->
let page_data = Bytes.make params.page_size default_char in
return (Some (page_data, page_proof), page_id)
| Some mk_data -> (
match mk_data ~default_char params.page_size with
| None -> return (None, page_id)
| Some page_data -> return (Some (page_data, page_proof), page_id))
let succ_slot_index index =
Option.value_f
S.Index.(of_int (to_int index + 1))
~default:(fun () -> S.Index.zero)
let next_char c = Char.(chr ((code c + 1) mod 255))
(** Auxiliary test function used by both unit and PBT tests: This function
produces a proof from the given information and verifies the produced result,
if any. The result of each step is checked with [check_produce_result] and
[check_verify_result], respectively. *)
let produce_and_verify_proof ~check_produce ?check_verify ~get_history
skip_list ~page_info ~page_id =
let open Lwt_result_syntax in
let*! res =
Hist.produce_proof params ~page_info page_id ~get_history skip_list
|> Lwt.map Environment.wrap_tzresult
in
let* () = check_produce res page_info in
match check_verify with
| None -> return_unit
| Some check_verify ->
let*? proof, _input_opt = res in
let res =
Hist.verify_proof params page_id skip_list proof
|> Environment.wrap_tzresult
in
check_verify res page_info
(* Some check functions. *)
(** Check that/if the returned content is the expected one. *)
let assert_content_is ~__LOC__ ~expected returned =
Assert.equal
~loc:__LOC__
(Option.equal Bytes.equal)
"Returned %s doesn't match the expected one"
(fun fmt opt ->
match opt with
| None -> Format.fprintf fmt "<None>"
| Some bs -> Format.fprintf fmt "<Some:%s>" (Bytes.to_string bs))
returned
expected
let expected_data page_info proof_status =
match (page_info, proof_status) with
| Some (d, _p), `Confirmed -> Some d
| None, `Confirmed -> assert false
| _ -> None
let proof_status_to_string = function
| `Confirmed -> "CONFIRMED"
| `Unconfirmed -> "UNCONFIRMED"
let successful_check_produce_result ~__LOC__ proof_status res page_info =
let open Lwt_result_syntax in
let* proof, input_opt = Assert.get_ok ~__LOC__ res in
let* () =
if Hist.Internal_for_tests.proof_statement_is proof proof_status then
return_unit
else
failwith
"Expected to have a %s page proof. Got %a@."
(proof_status_to_string proof_status)
(Hist.pp_proof ~serialized:false)
proof
in
assert_content_is
~__LOC__
input_opt
~expected:(expected_data page_info proof_status)
let failing_check_produce_result ~__LOC__ ~expected_error res _page_info =
Assert.proto_error ~loc:__LOC__ res (fun e ->
match (e, expected_error) with
| Hist.Dal_proof_error s, Hist.Dal_proof_error expected ->
String.equal s expected
| ( Hist.Unexpected_page_size {expected_size = e1; page_size = p1},
Hist.Unexpected_page_size {expected_size = e2; page_size = p2} ) ->
e1 = e2 && p1 = p2
| _ -> false)
let successful_check_verify_result ~__LOC__ proof_status res page_info =
let open Lwt_result_syntax in
let* content = Assert.get_ok ~__LOC__ res in
let expected = expected_data page_info proof_status in
assert_content_is ~__LOC__ ~expected content
* Checks if the two provided are equal .
let eq_page_proof =
let bytes_opt_of_proof page_proof =
Data_encoding.Binary.to_bytes_opt P.proof_encoding page_proof
in
fun pp1 pp2 ->
Option.equal Bytes.equal (bytes_opt_of_proof pp1) (bytes_opt_of_proof pp2)
let slot_confirmed_but_page_data_not_provided ~__LOC__ =
failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"The page ID's slot is confirmed, but no page content and proof are \
provided.")
let slot_not_confirmed_but_page_data_provided ~__LOC__ =
failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"The page ID's slot is not confirmed, but page content and proof \
are provided.")
end
| null | https://raw.githubusercontent.com/tezos/tezos-mirror/39e976ad6eae6446af8ca17ef4a63475ab9fe2b9/src/proto_016_PtMumbai/lib_protocol/test/helpers/dal_helpers.ml | ocaml | ***************************************************************************
Open Source License
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
***************************************************************************
* Error used below for functions that don't return their failures in the monad
error.
Some global constants.
Helper functions.
* Auxiliary test function used by both unit and PBT tests: This function
produces a proof from the given information and verifies the produced result,
if any. The result of each step is checked with [check_produce_result] and
[check_verify_result], respectively.
Some check functions.
* Check that/if the returned content is the expected one. | Copyright ( c ) 2022 Nomadic Labs , < >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
open Protocol
module S = Dal_slot_repr
module P = S.Page
module Hist = S.History
module Ihist = Hist.Internal_for_tests
type error += Test_failure of string
let () =
let open Data_encoding in
register_error_kind
`Permanent
~id:(Protocol.name ^ "_test_failure")
~title:"Test failure"
~description:"Test failure."
~pp:(fun ppf e -> Format.fprintf ppf "Test failure: %s" e)
(obj1 (req "error" string))
(function Test_failure e -> Some e | _ -> None)
(fun e -> Test_failure e)
let mk_cryptobox dal_params =
let open Result_syntax in
let parameters =
Cryptobox.Internal_for_tests.parameters_initialisation dal_params
in
let () = Cryptobox.Internal_for_tests.load_parameters parameters in
match Cryptobox.make dal_params with
| Ok dal -> return dal
| Error (`Fail s) -> fail [Test_failure s]
let derive_dal_parameters (reference : Cryptobox.parameters) ~redundancy_factor
~constants_divider =
{
S.redundancy_factor;
page_size = reference.page_size / constants_divider;
slot_size = reference.slot_size / constants_divider;
number_of_shards = reference.number_of_shards / constants_divider;
}
module Make (Parameters : sig
val dal_parameters : Alpha_context.Constants.Parametric.dal
val cryptobox : Cryptobox.t
end) =
struct
let params = Parameters.dal_parameters.cryptobox_parameters
let cryptobox = Parameters.cryptobox
let genesis_history = Hist.genesis
let genesis_history_cache = Hist.History_cache.empty ~capacity:3000L
let level_one = Raw_level_repr.(succ root)
let level_ten = Raw_level_repr.(of_int32_exn 10l)
let get_history cache h = Hist.History_cache.find h cache |> Lwt.return
let dal_mk_polynomial_from_slot slot_data =
let open Result_syntax in
match Cryptobox.polynomial_from_slot cryptobox slot_data with
| Ok p -> return p
| Error (`Slot_wrong_size s) ->
fail
[
Test_failure
(Format.sprintf "polynomial_from_slot: Slot_wrong_size (%s)" s);
]
let dal_mk_prove_page polynomial page_id =
let open Result_syntax in
match Cryptobox.prove_page cryptobox polynomial page_id.P.page_index with
| Ok p -> return p
| Error `Segment_index_out_of_range ->
fail [Test_failure "compute_proof_segment: Segment_index_out_of_range"]
| Error
(`Invalid_degree_strictly_less_than_expected
Cryptobox.{given; expected}) ->
fail
[
Test_failure
(Format.sprintf
"Got %d, expecting a value strictly less than %d"
given
expected);
]
let mk_slot ?(level = level_one) ?(index = S.Index.zero)
?(fill_function = fun _i -> 'x') () =
let open Result_syntax in
let slot_data = Bytes.init params.slot_size fill_function in
let* polynomial = dal_mk_polynomial_from_slot slot_data in
let* commitment =
match Cryptobox.commit cryptobox polynomial with
| Ok cm -> return cm
| Error
(`Invalid_degree_strictly_less_than_expected
Cryptobox.{given; expected}) ->
fail
[
Test_failure
(Format.sprintf
"Got %d, expecting a value strictly less than %d"
given
expected);
]
in
return
( slot_data,
polynomial,
S.Header.{id = {published_level = level; index}; commitment} )
let mk_page_id published_level slot_index page_index =
P.{slot_id = {published_level; index = slot_index}; page_index}
let no_data = Some (fun ~default_char:_ _ -> None)
let mk_page_info ?(default_char = 'x') ?level ?(page_index = P.Index.zero)
?(custom_data = None) (slot : S.Header.t) polynomial =
let open Result_syntax in
let level =
match level with None -> slot.id.published_level | Some level -> level
in
let page_id = mk_page_id level slot.id.index page_index in
let* page_proof = dal_mk_prove_page polynomial page_id in
match custom_data with
| None ->
let page_data = Bytes.make params.page_size default_char in
return (Some (page_data, page_proof), page_id)
| Some mk_data -> (
match mk_data ~default_char params.page_size with
| None -> return (None, page_id)
| Some page_data -> return (Some (page_data, page_proof), page_id))
let succ_slot_index index =
Option.value_f
S.Index.(of_int (to_int index + 1))
~default:(fun () -> S.Index.zero)
let next_char c = Char.(chr ((code c + 1) mod 255))
let produce_and_verify_proof ~check_produce ?check_verify ~get_history
skip_list ~page_info ~page_id =
let open Lwt_result_syntax in
let*! res =
Hist.produce_proof params ~page_info page_id ~get_history skip_list
|> Lwt.map Environment.wrap_tzresult
in
let* () = check_produce res page_info in
match check_verify with
| None -> return_unit
| Some check_verify ->
let*? proof, _input_opt = res in
let res =
Hist.verify_proof params page_id skip_list proof
|> Environment.wrap_tzresult
in
check_verify res page_info
let assert_content_is ~__LOC__ ~expected returned =
Assert.equal
~loc:__LOC__
(Option.equal Bytes.equal)
"Returned %s doesn't match the expected one"
(fun fmt opt ->
match opt with
| None -> Format.fprintf fmt "<None>"
| Some bs -> Format.fprintf fmt "<Some:%s>" (Bytes.to_string bs))
returned
expected
let expected_data page_info proof_status =
match (page_info, proof_status) with
| Some (d, _p), `Confirmed -> Some d
| None, `Confirmed -> assert false
| _ -> None
let proof_status_to_string = function
| `Confirmed -> "CONFIRMED"
| `Unconfirmed -> "UNCONFIRMED"
let successful_check_produce_result ~__LOC__ proof_status res page_info =
let open Lwt_result_syntax in
let* proof, input_opt = Assert.get_ok ~__LOC__ res in
let* () =
if Hist.Internal_for_tests.proof_statement_is proof proof_status then
return_unit
else
failwith
"Expected to have a %s page proof. Got %a@."
(proof_status_to_string proof_status)
(Hist.pp_proof ~serialized:false)
proof
in
assert_content_is
~__LOC__
input_opt
~expected:(expected_data page_info proof_status)
let failing_check_produce_result ~__LOC__ ~expected_error res _page_info =
Assert.proto_error ~loc:__LOC__ res (fun e ->
match (e, expected_error) with
| Hist.Dal_proof_error s, Hist.Dal_proof_error expected ->
String.equal s expected
| ( Hist.Unexpected_page_size {expected_size = e1; page_size = p1},
Hist.Unexpected_page_size {expected_size = e2; page_size = p2} ) ->
e1 = e2 && p1 = p2
| _ -> false)
let successful_check_verify_result ~__LOC__ proof_status res page_info =
let open Lwt_result_syntax in
let* content = Assert.get_ok ~__LOC__ res in
let expected = expected_data page_info proof_status in
assert_content_is ~__LOC__ ~expected content
* Checks if the two provided are equal .
let eq_page_proof =
let bytes_opt_of_proof page_proof =
Data_encoding.Binary.to_bytes_opt P.proof_encoding page_proof
in
fun pp1 pp2 ->
Option.equal Bytes.equal (bytes_opt_of_proof pp1) (bytes_opt_of_proof pp2)
let slot_confirmed_but_page_data_not_provided ~__LOC__ =
failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"The page ID's slot is confirmed, but no page content and proof are \
provided.")
let slot_not_confirmed_but_page_data_provided ~__LOC__ =
failing_check_produce_result
~__LOC__
~expected_error:
(Hist.Dal_proof_error
"The page ID's slot is not confirmed, but page content and proof \
are provided.")
end
|
656aeb311885e1f47366dfbe3516ce1a570c99a248756a0c2501f5501a6e089d | GaloisInc/cryptol | AST.hs | -- |
Module : Cryptol . . AST
Copyright : ( c ) 2013 - 2016 Galois , Inc.
-- License : BSD3
-- Maintainer :
-- Stability : provisional
-- Portability : portable
{-# LANGUAGE Safe #-}
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveFoldable #
{-# LANGUAGE DeriveTraversable #-}
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE FlexibleInstances #
module Cryptol.Parser.AST
( -- * Names
Ident, mkIdent, mkInfix, isInfixIdent, nullIdent, identText
, ModName, modRange
, PName(..), getModName, getIdent, mkUnqual, mkQual
, Named(..)
, Pass(..)
, Assoc(..)
-- * Types
, Schema(..)
, TParam(..)
, Kind(..)
, Type(..)
, Prop(..)
, tsName
, psName
, tsFixity
, psFixity
-- * Declarations
, Module
, ModuleG(..)
, mImports
, mSubmoduleImports
, Program(..)
, TopDecl(..)
, Decl(..)
, Fixity(..), defaultFixity
, FixityCmp(..), compareFixity
, TySyn(..)
, PropSyn(..)
, Bind(..)
, BindDef(..), LBindDef
, Pragma(..)
, ExportType(..)
, TopLevel(..)
, Import, ImportG(..), ImportSpec(..), ImpName(..)
, Newtype(..)
, PrimType(..)
, ParameterType(..)
, ParameterFun(..)
, NestedModule(..)
, PropGuardCase(..)
-- * Interactive
, ReplInput(..)
-- * Expressions
, Expr(..)
, Literal(..), NumInfo(..), FracInfo(..)
, Match(..)
, Pattern(..)
, Selector(..)
, TypeInst(..)
, UpdField(..)
, UpdHow(..)
, FunDesc(..)
, emptyFunDesc
, PrefixOp(..)
, prefixFixity
, asEApps
-- * Positions
, Located(..)
, LPName, LString, LIdent
, NoPos(..)
-- * Pretty-printing
, cppKind, ppSelector
) where
import Cryptol.Parser.Name
import Cryptol.Parser.Position
import Cryptol.Parser.Selector
import Cryptol.Utils.Fixity
import Cryptol.Utils.Ident
import Cryptol.Utils.RecordMap
import Cryptol.Utils.PP
import Data.List(intersperse)
import Data.Bits(shiftR)
import Data.Maybe (catMaybes)
import Data.Ratio(numerator,denominator)
import Data.Text (Text)
import Numeric(showIntAtBase,showFloat,showHFloat)
import GHC.Generics (Generic)
import Control.DeepSeq
import Prelude ()
import Prelude.Compat
-- AST -------------------------------------------------------------------------
-- | A name with location information.
type LPName = Located PName
-- | An identifier with location information.
type LIdent = Located Ident
-- | A string with location information.
type LString = Located String
-- | A record with located ident fields
type Rec e = RecordMap Ident (Range, e)
newtype Program name = Program [TopDecl name]
deriving (Show)
-- | A parsed module.
data ModuleG mname name = Module
{ mName :: Located mname -- ^ Name of the module
, mInstance :: !(Maybe (Located ModName)) -- ^ Functor to instantiate
-- (if this is a functor instnaces)
-- , mImports :: [Located Import] -- ^ Imports for the module
, mDecls :: [TopDecl name] -- ^ Declartions for the module
} deriving (Show, Generic, NFData)
mImports :: ModuleG mname name -> [ Located Import ]
mImports m =
[ li { thing = i { iModule = n } }
| DImport li <- mDecls m
, let i = thing li
, ImpTop n <- [iModule i]
]
mSubmoduleImports :: ModuleG mname name -> [ Located (ImportG name) ]
mSubmoduleImports m =
[ li { thing = i { iModule = n } }
| DImport li <- mDecls m
, let i = thing li
, ImpNested n <- [iModule i]
]
type Module = ModuleG ModName
newtype NestedModule name = NestedModule (ModuleG name name)
deriving (Show,Generic,NFData)
modRange :: Module name -> Range
modRange m = rCombs $ catMaybes
[ getLoc (mName m)
, getLoc (mImports m)
, getLoc (mDecls m)
, Just (Range { from = start, to = start, source = "" })
]
data TopDecl name =
Decl (TopLevel (Decl name))
| DPrimType (TopLevel (PrimType name))
| TDNewtype (TopLevel (Newtype name)) -- ^ @newtype T as = t
| Include (Located FilePath) -- ^ @include File@
^ type T : # @
| DParameterConstraint [Located (Prop name)]
^ type constraint ( fin T)@
^ someVal : [ 256]@
| DModule (TopLevel (NestedModule name)) -- ^ Nested module
| DImport (Located (ImportG (ImpName name))) -- ^ An import declaration
deriving (Show, Generic, NFData)
data ImpName name =
ImpTop ModName
| ImpNested name
deriving (Show, Generic, NFData)
data Decl name = DSignature [Located name] (Schema name)
| DFixity !Fixity [Located name]
| DPragma [Located name] Pragma
| DBind (Bind name)
| DRec [Bind name]
-- ^ A group of recursive bindings, introduced by the renamer.
| DPatBind (Pattern name) (Expr name)
| DType (TySyn name)
| DProp (PropSyn name)
| DLocated (Decl name) Range
deriving (Eq, Show, Generic, NFData, Functor)
-- | A type parameter
data ParameterType name = ParameterType
{ ptName :: Located name -- ^ name of type parameter
, ptKind :: Kind -- ^ kind of parameter
, ptDoc :: Maybe Text -- ^ optional documentation
, ptFixity :: Maybe Fixity -- ^ info for infix use
, ptNumber :: !Int -- ^ number of the parameter
} deriving (Eq,Show,Generic,NFData)
-- | A value parameter
data ParameterFun name = ParameterFun
{ pfName :: Located name -- ^ name of value parameter
, pfSchema :: Schema name -- ^ schema for parameter
, pfDoc :: Maybe Text -- ^ optional documentation
, pfFixity :: Maybe Fixity -- ^ info for infix use
} deriving (Eq,Show,Generic,NFData)
-- | An import declaration.
data ImportG mname = Import
{ iModule :: !mname
, iAs :: Maybe ModName
, iSpec :: Maybe ImportSpec
} deriving (Eq, Show, Generic, NFData)
type Import = ImportG ModName
-- | The list of names following an import.
data ImportSpec = Hiding [Ident]
| Only [Ident]
deriving (Eq, Show, Generic, NFData)
The ' Maybe Fixity ' field is filled in by the NoPat pass .
data TySyn n = TySyn (Located n) (Maybe Fixity) [TParam n] (Type n)
deriving (Eq, Show, Generic, NFData, Functor)
The ' Maybe Fixity ' field is filled in by the NoPat pass .
data PropSyn n = PropSyn (Located n) (Maybe Fixity) [TParam n] [Prop n]
deriving (Eq, Show, Generic, NFData, Functor)
tsName :: TySyn name -> Located name
tsName (TySyn lqn _ _ _) = lqn
psName :: PropSyn name -> Located name
psName (PropSyn lqn _ _ _) = lqn
tsFixity :: TySyn name -> Maybe Fixity
tsFixity (TySyn _ f _ _) = f
psFixity :: PropSyn name -> Maybe Fixity
psFixity (PropSyn _ f _ _) = f
{- | Bindings. Notes:
* The parser does not associate type signatures and pragmas with
their bindings: this is done in a separate pass, after de-sugaring
pattern bindings. In this way we can associate pragmas and type
signatures with the variables defined by pattern bindings as well.
* Currently, there is no surface syntax for defining monomorphic
bindings (i.e., bindings that will not be automatically generalized
by the type checker. However, they are useful when de-sugaring
patterns.
-}
data Bind name = Bind
{ bName :: Located name -- ^ Defined thing
, bParams :: [Pattern name] -- ^ Parameters
, bDef :: Located (BindDef name) -- ^ Definition
, bSignature :: Maybe (Schema name) -- ^ Optional type sig
, bInfix :: Bool -- ^ Infix operator?
, bFixity :: Maybe Fixity -- ^ Optional fixity info
, bPragmas :: [Pragma] -- ^ Optional pragmas
, bMono :: Bool -- ^ Is this a monomorphic binding
, bDoc :: Maybe Text -- ^ Optional doc string
, bExport :: !ExportType
} deriving (Eq, Generic, NFData, Functor, Show)
type LBindDef = Located (BindDef PName)
data BindDef name = DPrim
| DForeign
| DExpr (Expr name)
| DPropGuards [PropGuardCase name]
deriving (Eq, Show, Generic, NFData, Functor)
data PropGuardCase name = PropGuardCase
{ pgcProps :: [Located (Prop name)]
, pgcExpr :: Expr name
}
deriving (Eq,Generic,NFData,Functor,Show)
data Pragma = PragmaNote String
| PragmaProperty
deriving (Eq, Show, Generic, NFData)
data Newtype name = Newtype { nName :: Located name -- ^ Type name
, nParams :: [TParam name] -- ^ Type params
, nBody :: Rec (Type name) -- ^ Body
} deriving (Eq, Show, Generic, NFData)
-- | A declaration for a type with no implementation.
data PrimType name = PrimType { primTName :: Located name
, primTKind :: Located Kind
, primTCts :: ([TParam name], [Prop name])
-- ^ parameters are in the order used
-- by the type constructor.
, primTFixity :: Maybe Fixity
} deriving (Show,Generic,NFData)
| Input at the REPL , which can be an expression , a
-- statement, or empty (possibly a comment).
data ReplInput name = ExprInput (Expr name)
| LetInput [Decl name]
| EmptyInput
deriving (Eq, Show)
-- | Export information for a declaration.
data ExportType = Public
| Private
deriving (Eq, Show, Ord, Generic, NFData)
-- | A top-level module declaration.
data TopLevel a = TopLevel { tlExport :: ExportType
, tlDoc :: Maybe (Located Text)
, tlValue :: a
}
deriving (Show, Generic, NFData, Functor, Foldable, Traversable)
-- | Infromation about the representation of a numeric constant.
data NumInfo = BinLit Text Int -- ^ n-digit binary literal
| OctLit Text Int -- ^ n-digit octal literal
| DecLit Text -- ^ overloaded decimal literal
| HexLit Text Int -- ^ n-digit hex literal
| PolyLit Int -- ^ polynomial literal
deriving (Eq, Show, Generic, NFData)
-- | Information about fractional literals.
data FracInfo = BinFrac Text
| OctFrac Text
| DecFrac Text
| HexFrac Text
deriving (Eq,Show,Generic,NFData)
-- | Literals.
^ ( HexLit 2 )
| ECChar Char -- ^ @'a'@
^ @1.2e3@
| ECString String -- ^ @\"hello\"@
deriving (Eq, Show, Generic, NFData)
data Expr n = EVar n -- ^ @ x @
^ @ 0x10 @
| EGenerate (Expr n) -- ^ @ generate f @
| ETuple [Expr n] -- ^ @ (1,2,3) @
^ @ { x = 1 , y = 2 } @
| ESel (Expr n) Selector -- ^ @ e.l @
| EUpd (Maybe (Expr n)) [ UpdField n ] -- ^ @ { r | x = e } @
| EList [Expr n] -- ^ @ [1,2,3] @
| EFromTo (Type n) (Maybe (Type n)) (Type n) (Maybe (Type n))
^ @ [ 1 , 5 .. 117 : t ] @
| EFromToBy Bool (Type n) (Type n) (Type n) (Maybe (Type n))
^ @ [ 1 .. 10 by 2 : t ] @
| EFromToDownBy Bool (Type n) (Type n) (Type n) (Maybe (Type n))
^ @ [ 10 .. 1 down by 2 : t ] @
| EFromToLessThan (Type n) (Type n) (Maybe (Type n))
^ @ [ 1 .. < 10 : t ] @
^ @ [ 1 , 3 ... ] @
^ @ [ 1 | x < - xs ] @
| EApp (Expr n) (Expr n) -- ^ @ f x @
^ @ f ` { x = 8 } , f`{8 } @
| EIf (Expr n) (Expr n) (Expr n) -- ^ @ if ok then e1 else e2 @
^ @ 1 + x where { x = 2 } @
^ @ 1 : [ 8 ] @
| ETypeVal (Type n) -- ^ @ `(x + 1)@, @x@ is a type
| EFun (FunDesc n) [Pattern n] (Expr n) -- ^ @ \\x y -> x @
| ELocated (Expr n) Range -- ^ position annotation
^ @ splitAt x @ ( Introduced by NoPat )
| EParens (Expr n) -- ^ @ (e) @ (Removed by Fixity)
| EInfix (Expr n) (Located n) Fixity (Expr n)-- ^ @ a + b @ (Removed by Fixity)
| EPrefix PrefixOp (Expr n) -- ^ @ -1, ~1 @
deriving (Eq, Show, Generic, NFData, Functor)
-- | Prefix operator.
data PrefixOp = PrefixNeg -- ^ @ - @
| PrefixComplement -- ^ @ ~ @
deriving (Eq, Show, Generic, NFData)
prefixFixity :: PrefixOp -> Fixity
prefixFixity op = Fixity { fAssoc = LeftAssoc, .. }
where fLevel = case op of
PrefixNeg -> 80
PrefixComplement -> 100
-- | Description of functions. Only trivial information is provided here
by the parser . The NoPat pass fills this in as required .
data FunDesc n =
FunDesc
^ Name of this function , if it has one
, funDescrArgOffset :: Int -- ^ number of previous arguments to this function
bound in surrounding lambdas ( defaults to 0 )
}
deriving (Eq, Show, Generic, NFData, Functor)
emptyFunDesc :: FunDesc n
emptyFunDesc = FunDesc Nothing 0
data UpdField n = UpdField UpdHow [Located Selector] (Expr n)
-- ^ non-empty list @ x.y = e@
deriving (Eq, Show, Generic, NFData, Functor)
data UpdHow = UpdSet | UpdFun -- ^ Are we setting or updating a field.
deriving (Eq, Show, Generic, NFData)
data TypeInst name = NamedInst (Named (Type name))
| PosInst (Type name)
deriving (Eq, Show, Generic, NFData, Functor)
data Match name = Match (Pattern name) (Expr name) -- ^ p <- e
| MatchLet (Bind name)
deriving (Eq, Show, Generic, NFData, Functor)
data Pattern n = PVar (Located n) -- ^ @ x @
| PWild -- ^ @ _ @
| PTuple [Pattern n] -- ^ @ (x,y,z) @
| PRecord (Rec (Pattern n)) -- ^ @ { x = (a,b,c), y = z } @
| PList [ Pattern n ] -- ^ @ [ x, y, z ] @
^ @ x : [ 8 ] @
| PSplit (Pattern n) (Pattern n)-- ^ @ (x # y) @
| PLocated (Pattern n) Range -- ^ Location information
deriving (Eq, Show, Generic, NFData, Functor)
data Named a = Named { name :: Located Ident, value :: a }
deriving (Eq, Show, Foldable, Traversable, Generic, NFData, Functor)
data Schema n = Forall [TParam n] [Prop n] (Type n) (Maybe Range)
deriving (Eq, Show, Generic, NFData, Functor)
data Kind = KProp | KNum | KType | KFun Kind Kind
deriving (Eq, Show, Generic, NFData)
data TParam n = TParam { tpName :: n
, tpKind :: Maybe Kind
, tpRange :: Maybe Range
}
deriving (Eq, Show, Generic, NFData, Functor)
data Type n = TFun (Type n) (Type n) -- ^ @[8] -> [8]@
| TSeq (Type n) (Type n) -- ^ @[8] a@
^ @Bit@
| TNum Integer -- ^ @10@
| TChar Char -- ^ @'a'@
| TUser n [Type n] -- ^ A type variable or synonym
^ @ ` { x = [ 8 ] , y = Integer } @
^ @ { x : [ 8 ] , y : [ 32 ] } @
^ @([8 ] , [ 32])@
| TWild -- ^ @_@, just some type.
| TLocated (Type n) Range -- ^ Location information
| TParens (Type n) -- ^ @ (ty) @
| TInfix (Type n) (Located n) Fixity (Type n) -- ^ @ ty + ty @
deriving (Eq, Show, Generic, NFData, Functor)
| A ' Prop ' is a ' Type ' that represents a type constraint .
newtype Prop n = CType (Type n)
deriving (Eq, Show, Generic, NFData, Functor)
--------------------------------------------------------------------------------
-- Note: When an explicit location is missing, we could use the sub-components
-- to try to estimate a location...
instance AddLoc (Expr n) where
addLoc x@ELocated{} _ = x
addLoc x r = ELocated x r
dropLoc (ELocated e _) = dropLoc e
dropLoc e = e
instance HasLoc (Expr name) where
getLoc (ELocated _ r) = Just r
getLoc _ = Nothing
instance HasLoc (TParam name) where
getLoc (TParam _ _ r) = r
instance AddLoc (TParam name) where
addLoc (TParam a b _) l = TParam a b (Just l)
dropLoc (TParam a b _) = TParam a b Nothing
instance HasLoc (Type name) where
getLoc (TLocated _ r) = Just r
getLoc _ = Nothing
instance AddLoc (Type name) where
addLoc = TLocated
dropLoc (TLocated e _) = dropLoc e
dropLoc e = e
instance AddLoc (Pattern name) where
addLoc = PLocated
dropLoc (PLocated e _) = dropLoc e
dropLoc e = e
instance HasLoc (Pattern name) where
getLoc (PLocated _ r) = Just r
getLoc (PTyped r _) = getLoc r
getLoc (PVar x) = getLoc x
getLoc _ = Nothing
instance HasLoc (Bind name) where
getLoc b = getLoc (bName b, bDef b)
instance HasLoc (Match name) where
getLoc (Match p e) = getLoc (p,e)
getLoc (MatchLet b) = getLoc b
instance HasLoc a => HasLoc (Named a) where
getLoc l = getLoc (name l, value l)
instance HasLoc (Schema name) where
getLoc (Forall _ _ _ r) = r
instance AddLoc (Schema name) where
addLoc (Forall xs ps t _) r = Forall xs ps t (Just r)
dropLoc (Forall xs ps t _) = Forall xs ps t Nothing
instance HasLoc (Decl name) where
getLoc (DLocated _ r) = Just r
getLoc _ = Nothing
instance AddLoc (Decl name) where
addLoc d r = DLocated d r
dropLoc (DLocated d _) = dropLoc d
dropLoc d = d
instance HasLoc a => HasLoc (TopLevel a) where
getLoc = getLoc . tlValue
instance HasLoc (TopDecl name) where
getLoc td =
case td of
Decl tld -> getLoc tld
DPrimType pt -> getLoc pt
TDNewtype n -> getLoc n
Include lfp -> getLoc lfp
DParameterType d -> getLoc d
DParameterFun d -> getLoc d
DParameterConstraint d -> getLoc d
DModule d -> getLoc d
DImport d -> getLoc d
instance HasLoc (PrimType name) where
getLoc pt = Just (rComb (srcRange (primTName pt)) (srcRange (primTKind pt)))
instance HasLoc (ParameterType name) where
getLoc a = getLoc (ptName a)
instance HasLoc (ParameterFun name) where
getLoc a = getLoc (pfName a)
instance HasLoc (ModuleG mname name) where
getLoc m
| null locs = Nothing
| otherwise = Just (rCombs locs)
where
locs = catMaybes [ getLoc (mName m)
, getLoc (mImports m)
, getLoc (mDecls m)
]
instance HasLoc (NestedModule name) where
getLoc (NestedModule m) = getLoc m
instance HasLoc (Newtype name) where
getLoc n
| null locs = Nothing
| otherwise = Just (rCombs locs)
where
locs = catMaybes ([ getLoc (nName n)] ++ map (Just . fst . snd) (displayFields (nBody n)))
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Pretty printing
ppL :: PP a => Located a -> Doc
ppL = pp . thing
ppNamed :: PP a => String -> Named a -> Doc
ppNamed s x = ppL (name x) <+> text s <+> pp (value x)
ppNamed' :: PP a => String -> (Ident, (Range, a)) -> Doc
ppNamed' s (i,(_,v)) = pp i <+> text s <+> pp v
instance (Show name, PPName mname, PPName name) => PP (ModuleG mname name) where
ppPrec _ = ppModule 0
ppModule :: (Show name, PPName mname, PPName name) =>
Int -> ModuleG mname name -> Doc
ppModule n m =
text "module" <+> ppL (mName m) <+> text "where" $$ nest n body
where
body = vcat (map ppL (mImports m))
$$ vcat (map pp (mDecls m))
instance (Show name, PPName name) => PP (NestedModule name) where
ppPrec _ (NestedModule m) = ppModule 2 m
instance (Show name, PPName name) => PP (Program name) where
ppPrec _ (Program ds) = vcat (map pp ds)
instance (Show name, PPName name) => PP (TopDecl name) where
ppPrec _ top_decl =
case top_decl of
Decl d -> pp d
DPrimType p -> pp p
TDNewtype n -> pp n
Include l -> text "include" <+> text (show (thing l))
DParameterFun d -> pp d
DParameterType d -> pp d
DParameterConstraint d ->
"parameter" <+> "type" <+> "constraint" <+> prop
where prop = case map (pp . thing) d of
[x] -> x
[] -> "()"
xs -> nest 1 (parens (commaSepFill xs))
DModule d -> pp d
DImport i -> pp (thing i)
instance (Show name, PPName name) => PP (PrimType name) where
ppPrec _ pt =
"primitive" <+> "type" <+> pp (primTName pt) <+> ":" <+> pp (primTKind pt)
instance (Show name, PPName name) => PP (ParameterType name) where
ppPrec _ a = text "parameter" <+> text "type" <+>
ppPrefixName (ptName a) <+> text ":" <+> pp (ptKind a)
instance (Show name, PPName name) => PP (ParameterFun name) where
ppPrec _ a = text "parameter" <+> ppPrefixName (pfName a) <+> text ":"
<+> pp (pfSchema a)
instance (Show name, PPName name) => PP (Decl name) where
ppPrec n decl =
case decl of
DSignature xs s -> commaSep (map ppL xs) <+> text ":" <+> pp s
DPatBind p e -> pp p <+> text "=" <+> pp e
DBind b -> ppPrec n b
DRec bs -> nest 2 (vcat ("recursive" : map (ppPrec n) bs))
DFixity f ns -> ppFixity f ns
DPragma xs p -> ppPragma xs p
DType ts -> ppPrec n ts
DProp ps -> ppPrec n ps
DLocated d _ -> ppPrec n d
ppFixity :: PPName name => Fixity -> [Located name] -> Doc
ppFixity (Fixity LeftAssoc i) ns = text "infixl" <+> int i <+> commaSep (map pp ns)
ppFixity (Fixity RightAssoc i) ns = text "infixr" <+> int i <+> commaSep (map pp ns)
ppFixity (Fixity NonAssoc i) ns = text "infix" <+> int i <+> commaSep (map pp ns)
instance PPName name => PP (Newtype name) where
ppPrec _ nt = nest 2 $ sep
[ fsep $ [text "newtype", ppL (nName nt)] ++ map pp (nParams nt) ++ [char '=']
, ppRecord (map (ppNamed' ":") (displayFields (nBody nt)))
]
instance PP mname => PP (ImportG mname) where
ppPrec _ d = text "import" <+> sep ([pp (iModule d)] ++ mbAs ++ mbSpec)
where
mbAs = maybe [] (\ name -> [text "as" <+> pp name]) (iAs d)
mbSpec = maybe [] (\x -> [pp x]) (iSpec d)
instance PP name => PP (ImpName name) where
ppPrec _ nm =
case nm of
ImpTop x -> pp x
ImpNested x -> "submodule" <+> pp x
instance PP ImportSpec where
ppPrec _ s = case s of
Hiding names -> text "hiding" <+> parens (commaSep (map pp names))
Only names -> parens (commaSep (map pp names))
-- TODO: come up with a good way of showing the export specification here
instance PP a => PP (TopLevel a) where
ppPrec _ tl = pp (tlValue tl)
instance PP Pragma where
ppPrec _ (PragmaNote x) = text x
ppPrec _ PragmaProperty = text "property"
ppPragma :: PPName name => [Located name] -> Pragma -> Doc
ppPragma xs p =
text "/*" <+> text "pragma" <+> commaSep (map ppL xs) <+> text ":" <+> pp p
<+> text "*/"
instance (Show name, PPName name) => PP (Bind name) where
ppPrec _ b = vcat (sig ++ [ ppPragma [f] p | p <- bPragmas b ] ++
[hang (def <+> eq) 4 (pp (thing (bDef b)))])
where def | bInfix b = lhsOp
| otherwise = lhs
f = bName b
sig = case bSignature b of
Nothing -> []
Just s -> [pp (DSignature [f] s)]
eq = if bMono b then text ":=" else text "="
lhs = fsep (ppL f : (map (ppPrec 3) (bParams b)))
lhsOp = case bParams b of
[x,y] -> pp x <+> ppL f <+> pp y
xs -> parens (parens (ppL f) <+> fsep (map (ppPrec 0) xs))
-- _ -> panic "AST" [ "Malformed infix operator", show b ]
instance (Show name, PPName name) => PP (BindDef name) where
ppPrec _ DPrim = text "<primitive>"
ppPrec _ DForeign = text "<foreign>"
ppPrec p (DExpr e) = ppPrec p e
ppPrec _p (DPropGuards _guards) = text "propguards"
instance PPName name => PP (TySyn name) where
ppPrec _ (TySyn x _ xs t) =
nest 2 $ sep $
[ fsep $ [text "type", ppL x] ++ map (ppPrec 1) xs ++ [text "="]
, pp t
]
instance PPName name => PP (PropSyn name) where
ppPrec _ (PropSyn x _ xs ps) =
nest 2 $ sep $
[ fsep $ [text "constraint", ppL x] ++ map (ppPrec 1) xs ++ [text "="]
, parens (commaSep (map pp ps))
]
instance PP Literal where
ppPrec _ lit =
case lit of
ECNum n i -> ppNumLit n i
ECChar c -> text (show c)
ECFrac n i -> ppFracLit n i
ECString s -> text (show s)
ppFracLit :: Rational -> FracInfo -> Doc
ppFracLit x i
| toRational dbl == x =
case i of
BinFrac _ -> frac
OctFrac _ -> frac
DecFrac _ -> text (showFloat dbl "")
HexFrac _ -> text (showHFloat dbl "")
| otherwise = frac
where
dbl = fromRational x :: Double
frac = "fraction`" <.> braces
(commaSep (map integer [ numerator x, denominator x ]))
ppNumLit :: Integer -> NumInfo -> Doc
ppNumLit n info =
case info of
DecLit _ -> integer n
BinLit _ w -> pad 2 "0b" w
OctLit _ w -> pad 8 "0o" w
HexLit _ w -> pad 16 "0x" w
PolyLit w -> text "<|" <+> poly w <+> text "|>"
where
pad base pref w =
let txt = showIntAtBase base ("0123456789abcdef" !!) n ""
in text pref <.> text (replicate (w - length txt) '0') <.> text txt
poly w = let (res,deg) = bits Nothing [] 0 n
z | w == 0 = []
| Just d <- deg, d + 1 == w = []
| otherwise = [polyTerm0 (w-1)]
in fsep $ intersperse (text "+") $ z ++ map polyTerm res
polyTerm 0 = text "1"
polyTerm 1 = text "x"
polyTerm p = text "x" <.> text "^^" <.> int p
polyTerm0 0 = text "0"
polyTerm0 p = text "0" <.> text "*" <.> polyTerm p
bits d res p num
| num == 0 = (res,d)
| even num = bits d res (p + 1) (num `shiftR` 1)
| otherwise = bits (Just p) (p : res) (p + 1) (num `shiftR` 1)
wrap :: Int -> Int -> Doc -> Doc
wrap contextPrec myPrec doc = optParens (myPrec < contextPrec) doc
isEApp :: Expr n -> Maybe (Expr n, Expr n)
isEApp (ELocated e _) = isEApp e
isEApp (EApp e1 e2) = Just (e1,e2)
isEApp _ = Nothing
asEApps :: Expr n -> (Expr n, [Expr n])
asEApps expr = go expr []
where go e es = case isEApp e of
Nothing -> (e, es)
Just (e1, e2) -> go e1 (e2 : es)
instance PPName name => PP (TypeInst name) where
ppPrec _ (PosInst t) = pp t
ppPrec _ (NamedInst x) = ppNamed "=" x
Precedences :
0 : lambda , if , where , type annotation
2 : infix expression ( separate precedence table )
3 : application , prefix expressions
0: lambda, if, where, type annotation
2: infix expression (separate precedence table)
3: application, prefix expressions
-}
instance (Show name, PPName name) => PP (Expr name) where
-- Wrap if top level operator in expression is less than `n`
ppPrec n expr =
case expr of
-- atoms
EVar x -> ppPrefixName x
ELit x -> pp x
EGenerate x -> wrap n 3 (text "generate" <+> ppPrec 4 x)
ETuple es -> parens (commaSep (map pp es))
ERecord fs -> braces (commaSep (map (ppNamed' "=") (displayFields fs)))
EList es -> brackets (commaSep (map pp es))
EFromTo e1 e2 e3 t1 -> brackets (pp e1 <.> step <+> text ".." <+> end)
where step = maybe mempty (\e -> comma <+> pp e) e2
end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
EFromToBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "by" <+> end)
where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
dots | isStrict = text ".. <"
| otherwise = text ".."
EFromToDownBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "down by" <+> end)
where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
dots | isStrict = text ".. >"
| otherwise = text ".."
EFromToLessThan e1 e2 t1 -> brackets (strt <+> text ".. <" <+> end)
where strt = maybe (pp e1) (\t -> pp e1 <+> colon <+> pp t) t1
end = pp e2
EInfFrom e1 e2 -> brackets (pp e1 <.> step <+> text "...")
where step = maybe mempty (\e -> comma <+> pp e) e2
EComp e mss -> brackets (pp e <> align (vcat (map arm mss)))
where arm ms = text " |" <+> commaSep (map pp ms)
EUpd mb fs -> braces (hd <+> "|" <+> commaSep (map pp fs))
where hd = maybe "_" pp mb
ETypeVal t -> text "`" <.> ppPrec 5 t -- XXX
EAppT e ts -> ppPrec 4 e <.> text "`" <.> braces (commaSep (map pp ts))
ESel e l -> ppPrec 4 e <.> text "." <.> pp l
-- low prec
EFun _ xs e -> wrap n 0 ((text "\\" <.> hsep (map (ppPrec 3) xs)) <+>
text "->" <+> pp e)
EIf e1 e2 e3 -> wrap n 0 $ sep [ text "if" <+> pp e1
, text "then" <+> pp e2
, text "else" <+> pp e3 ]
ETyped e t -> wrap n 0 (ppPrec 2 e <+> text ":" <+> pp t)
EWhere e ds -> wrap n 0 $ align $ vsep
[ pp e
, hang "where" 2 (vcat (map pp ds))
]
-- infix applications
_ | Just ifix <- isInfix expr ->
optParens (n > 2)
$ ppInfix 2 isInfix ifix
EApp _ _ -> let (e, es) = asEApps expr in
wrap n 3 (ppPrec 3 e <+> fsep (map (ppPrec 4) es))
ELocated e _ -> ppPrec n e
ESplit e -> wrap n 3 (text "splitAt" <+> ppPrec 4 e)
EParens e -> parens (pp e)
-- NOTE: these don't produce correctly parenthesized expressions without
-- explicit EParens nodes when necessary, since we don't check the actual
-- fixities of the operators.
EInfix e1 op _ e2 -> wrap n 0 (pp e1 <+> ppInfixName (thing op) <+> pp e2)
EPrefix op e -> wrap n 3 (text (prefixText op) <.> ppPrec 4 e)
where
isInfix (EApp (EApp (EVar ieOp) ieLeft) ieRight) = do
ieFixity <- ppNameFixity ieOp
return Infix { .. }
isInfix _ = Nothing
prefixText PrefixNeg = "-"
prefixText PrefixComplement = "~"
instance (Show name, PPName name) => PP (UpdField name) where
ppPrec _ (UpdField h xs e) = ppNestedSels (map thing xs) <+> pp h <+> pp e
instance PP UpdHow where
ppPrec _ h = case h of
UpdSet -> "="
UpdFun -> "->"
instance PPName name => PP (Pattern name) where
ppPrec n pat =
case pat of
PVar x -> pp (thing x)
PWild -> char '_'
PTuple ps -> ppTuple (map pp ps)
PRecord fs -> ppRecord (map (ppNamed' "=") (displayFields fs))
PList ps -> ppList (map pp ps)
PTyped p t -> wrap n 0 (ppPrec 1 p <+> text ":" <+> pp t)
PSplit p1 p2 -> wrap n 1 (ppPrec 1 p1 <+> text "#" <+> ppPrec 1 p2)
PLocated p _ -> ppPrec n p
instance (Show name, PPName name) => PP (Match name) where
ppPrec _ (Match p e) = pp p <+> text "<-" <+> pp e
ppPrec _ (MatchLet b) = pp b
instance PPName name => PP (Schema name) where
ppPrec _ (Forall xs ps t _) = sep (vars ++ preds ++ [pp t])
where vars = case xs of
[] -> []
_ -> [nest 1 (braces (commaSepFill (map pp xs)))]
preds = case ps of
[] -> []
_ -> [nest 1 (parens (commaSepFill (map pp ps))) <+> text "=>"]
instance PP Kind where
ppPrec _ KType = text "*"
ppPrec _ KNum = text "#"
ppPrec _ KProp = text "@"
ppPrec n (KFun k1 k2) = wrap n 1 (ppPrec 1 k1 <+> "->" <+> ppPrec 0 k2)
-- | "Conversational" printing of kinds (e.g., to use in error messages)
cppKind :: Kind -> Doc
cppKind KType = text "a value type"
cppKind KNum = text "a numeric type"
cppKind KProp = text "a constraint type"
cppKind (KFun {}) = text "a type-constructor type"
instance PPName name => PP (TParam name) where
ppPrec n (TParam p Nothing _) = ppPrec n p
ppPrec n (TParam p (Just k) _) = wrap n 1 (pp p <+> text ":" <+> pp k)
4 : atomic type expression
3 : [ _ ] t or application
2 : infix type
1 : function type
instance PPName name => PP (Type name) where
ppPrec n ty =
case ty of
TWild -> text "_"
TTuple ts -> parens $ commaSep $ map pp ts
TTyApp fs -> braces $ commaSep $ map (ppNamed " = ") fs
TRecord fs -> braces $ commaSep $ map (ppNamed' ":") (displayFields fs)
TBit -> text "Bit"
TNum x -> integer x
TChar x -> text (show x)
TSeq t1 TBit -> brackets (pp t1)
TSeq t1 t2 -> optParens (n > 3)
$ brackets (pp t1) <.> ppPrec 3 t2
TUser f [] -> ppPrefixName f
TUser f ts -> optParens (n > 3)
$ ppPrefixName f <+> fsep (map (ppPrec 4) ts)
TFun t1 t2 -> optParens (n > 1)
$ sep [ppPrec 2 t1 <+> text "->", ppPrec 1 t2]
TLocated t _ -> ppPrec n t
TParens t -> parens (pp t)
TInfix t1 o _ t2 -> optParens (n > 2)
$ sep [ppPrec 2 t1 <+> ppInfixName o, ppPrec 3 t2]
instance PPName name => PP (Prop name) where
ppPrec n (CType t) = ppPrec n t
instance PPName name => PP [Prop name] where
ppPrec n props = parens . commaSep . fmap (ppPrec n) $ props
--------------------------------------------------------------------------------
-- Drop all position information, so equality reflects program structure
class NoPos t where
noPos :: t -> t
WARNING : This does not call ` noPos ` on the ` thing ` inside
instance NoPos (Located t) where
noPos x = x { srcRange = rng }
where rng = Range { from = Position 0 0, to = Position 0 0, source = "" }
instance NoPos t => NoPos (Named t) where
noPos t = Named { name = noPos (name t), value = noPos (value t) }
instance NoPos Range where
noPos _ = Range { from = Position 0 0, to = Position 0 0, source = "" }
instance NoPos t => NoPos [t] where noPos = fmap noPos
instance NoPos t => NoPos (Maybe t) where noPos = fmap noPos
instance (NoPos a, NoPos b) => NoPos (a,b) where
noPos (a,b) = (noPos a, noPos b)
instance NoPos (Program name) where
noPos (Program x) = Program (noPos x)
instance NoPos (ModuleG mname name) where
noPos m = Module { mName = mName m
, mInstance = mInstance m
, mDecls = noPos (mDecls m)
}
instance NoPos (NestedModule name) where
noPos (NestedModule m) = NestedModule (noPos m)
instance NoPos (TopDecl name) where
noPos decl =
case decl of
Decl x -> Decl (noPos x)
DPrimType t -> DPrimType (noPos t)
TDNewtype n -> TDNewtype(noPos n)
Include x -> Include (noPos x)
DParameterFun d -> DParameterFun (noPos d)
DParameterType d -> DParameterType (noPos d)
DParameterConstraint d -> DParameterConstraint (noPos d)
DModule d -> DModule (noPos d)
DImport d -> DImport (noPos d)
instance NoPos (PrimType name) where
noPos x = x
instance NoPos (ParameterType name) where
noPos a = a
instance NoPos (ParameterFun x) where
noPos x = x { pfSchema = noPos (pfSchema x) }
instance NoPos a => NoPos (TopLevel a) where
noPos tl = tl { tlValue = noPos (tlValue tl) }
instance NoPos (Decl name) where
noPos decl =
case decl of
DSignature x y -> DSignature (noPos x) (noPos y)
DPragma x y -> DPragma (noPos x) (noPos y)
DPatBind x y -> DPatBind (noPos x) (noPos y)
DFixity f ns -> DFixity f (noPos ns)
DBind x -> DBind (noPos x)
DRec bs -> DRec (map noPos bs)
DType x -> DType (noPos x)
DProp x -> DProp (noPos x)
DLocated x _ -> noPos x
instance NoPos (Newtype name) where
noPos n = Newtype { nName = noPos (nName n)
, nParams = nParams n
, nBody = fmap noPos (nBody n)
}
instance NoPos (Bind name) where
noPos x = Bind { bName = noPos (bName x)
, bParams = noPos (bParams x)
, bDef = noPos (bDef x)
, bSignature = noPos (bSignature x)
, bInfix = bInfix x
, bFixity = bFixity x
, bPragmas = noPos (bPragmas x)
, bMono = bMono x
, bDoc = bDoc x
, bExport = bExport x
}
instance NoPos Pragma where
noPos p@(PragmaNote {}) = p
noPos p@(PragmaProperty) = p
instance NoPos (TySyn name) where
noPos (TySyn x f y z) = TySyn (noPos x) f (noPos y) (noPos z)
instance NoPos (PropSyn name) where
noPos (PropSyn x f y z) = PropSyn (noPos x) f (noPos y) (noPos z)
instance NoPos (Expr name) where
noPos expr =
case expr of
EVar x -> EVar x
ELit x -> ELit x
EGenerate x -> EGenerate (noPos x)
ETuple x -> ETuple (noPos x)
ERecord x -> ERecord (fmap noPos x)
ESel x y -> ESel (noPos x) y
EUpd x y -> EUpd (noPos x) (noPos y)
EList x -> EList (noPos x)
EFromTo x y z t -> EFromTo (noPos x) (noPos y) (noPos z) (noPos t)
EFromToBy isStrict x y z t
-> EFromToBy isStrict (noPos x) (noPos y) (noPos z) (noPos t)
EFromToDownBy isStrict x y z t
-> EFromToDownBy isStrict (noPos x) (noPos y) (noPos z) (noPos t)
EFromToLessThan x y t -> EFromToLessThan (noPos x) (noPos y) (noPos t)
EInfFrom x y -> EInfFrom (noPos x) (noPos y)
EComp x y -> EComp (noPos x) (noPos y)
EApp x y -> EApp (noPos x) (noPos y)
EAppT x y -> EAppT (noPos x) (noPos y)
EIf x y z -> EIf (noPos x) (noPos y) (noPos z)
EWhere x y -> EWhere (noPos x) (noPos y)
ETyped x y -> ETyped (noPos x) (noPos y)
ETypeVal x -> ETypeVal (noPos x)
EFun dsc x y -> EFun dsc (noPos x) (noPos y)
ELocated x _ -> noPos x
ESplit x -> ESplit (noPos x)
EParens e -> EParens (noPos e)
EInfix x y f z -> EInfix (noPos x) y f (noPos z)
EPrefix op x -> EPrefix op (noPos x)
instance NoPos (UpdField name) where
noPos (UpdField h xs e) = UpdField h xs (noPos e)
instance NoPos (TypeInst name) where
noPos (PosInst ts) = PosInst (noPos ts)
noPos (NamedInst fs) = NamedInst (noPos fs)
instance NoPos (Match name) where
noPos (Match x y) = Match (noPos x) (noPos y)
noPos (MatchLet b) = MatchLet (noPos b)
instance NoPos (Pattern name) where
noPos pat =
case pat of
PVar x -> PVar (noPos x)
PWild -> PWild
PTuple x -> PTuple (noPos x)
PRecord x -> PRecord (fmap noPos x)
PList x -> PList (noPos x)
PTyped x y -> PTyped (noPos x) (noPos y)
PSplit x y -> PSplit (noPos x) (noPos y)
PLocated x _ -> noPos x
instance NoPos (Schema name) where
noPos (Forall x y z _) = Forall (noPos x) (noPos y) (noPos z) Nothing
instance NoPos (TParam name) where
noPos (TParam x y _) = TParam x y Nothing
instance NoPos (Type name) where
noPos ty =
case ty of
TWild -> TWild
TUser x y -> TUser x (noPos y)
TTyApp x -> TTyApp (noPos x)
TRecord x -> TRecord (fmap noPos x)
TTuple x -> TTuple (noPos x)
TFun x y -> TFun (noPos x) (noPos y)
TSeq x y -> TSeq (noPos x) (noPos y)
TBit -> TBit
TNum n -> TNum n
TChar n -> TChar n
TLocated x _ -> noPos x
TParens x -> TParens (noPos x)
TInfix x y f z-> TInfix (noPos x) y f (noPos z)
instance NoPos (Prop name) where
noPos (CType t) = CType (noPos t)
| null | https://raw.githubusercontent.com/GaloisInc/cryptol/f8b55439467abe3e7427b80edc37ff95a13de62b/src/Cryptol/Parser/AST.hs | haskell | |
License : BSD3
Maintainer :
Stability : provisional
Portability : portable
# LANGUAGE Safe #
# LANGUAGE DeriveAnyClass #
# LANGUAGE DeriveTraversable #
# LANGUAGE OverloadedStrings #
* Names
* Types
* Declarations
* Interactive
* Expressions
* Positions
* Pretty-printing
AST -------------------------------------------------------------------------
| A name with location information.
| An identifier with location information.
| A string with location information.
| A record with located ident fields
| A parsed module.
^ Name of the module
^ Functor to instantiate
(if this is a functor instnaces)
, mImports :: [Located Import] -- ^ Imports for the module
^ Declartions for the module
^ @newtype T as = t
^ @include File@
^ Nested module
^ An import declaration
^ A group of recursive bindings, introduced by the renamer.
| A type parameter
^ name of type parameter
^ kind of parameter
^ optional documentation
^ info for infix use
^ number of the parameter
| A value parameter
^ name of value parameter
^ schema for parameter
^ optional documentation
^ info for infix use
| An import declaration.
| The list of names following an import.
| Bindings. Notes:
* The parser does not associate type signatures and pragmas with
their bindings: this is done in a separate pass, after de-sugaring
pattern bindings. In this way we can associate pragmas and type
signatures with the variables defined by pattern bindings as well.
* Currently, there is no surface syntax for defining monomorphic
bindings (i.e., bindings that will not be automatically generalized
by the type checker. However, they are useful when de-sugaring
patterns.
^ Defined thing
^ Parameters
^ Definition
^ Optional type sig
^ Infix operator?
^ Optional fixity info
^ Optional pragmas
^ Is this a monomorphic binding
^ Optional doc string
^ Type name
^ Type params
^ Body
| A declaration for a type with no implementation.
^ parameters are in the order used
by the type constructor.
statement, or empty (possibly a comment).
| Export information for a declaration.
| A top-level module declaration.
| Infromation about the representation of a numeric constant.
^ n-digit binary literal
^ n-digit octal literal
^ overloaded decimal literal
^ n-digit hex literal
^ polynomial literal
| Information about fractional literals.
| Literals.
^ @'a'@
^ @\"hello\"@
^ @ x @
^ @ generate f @
^ @ (1,2,3) @
^ @ e.l @
^ @ { r | x = e } @
^ @ [1,2,3] @
^ @ f x @
^ @ if ok then e1 else e2 @
^ @ `(x + 1)@, @x@ is a type
^ @ \\x y -> x @
^ position annotation
^ @ (e) @ (Removed by Fixity)
^ @ a + b @ (Removed by Fixity)
^ @ -1, ~1 @
| Prefix operator.
^ @ - @
^ @ ~ @
| Description of functions. Only trivial information is provided here
^ number of previous arguments to this function
^ non-empty list @ x.y = e@
^ Are we setting or updating a field.
^ p <- e
^ @ x @
^ @ _ @
^ @ (x,y,z) @
^ @ { x = (a,b,c), y = z } @
^ @ [ x, y, z ] @
^ @ (x # y) @
^ Location information
^ @[8] -> [8]@
^ @[8] a@
^ @10@
^ @'a'@
^ A type variable or synonym
^ @_@, just some type.
^ Location information
^ @ (ty) @
^ @ ty + ty @
------------------------------------------------------------------------------
Note: When an explicit location is missing, we could use the sub-components
to try to estimate a location...
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Pretty printing
TODO: come up with a good way of showing the export specification here
_ -> panic "AST" [ "Malformed infix operator", show b ]
Wrap if top level operator in expression is less than `n`
atoms
XXX
low prec
infix applications
NOTE: these don't produce correctly parenthesized expressions without
explicit EParens nodes when necessary, since we don't check the actual
fixities of the operators.
| "Conversational" printing of kinds (e.g., to use in error messages)
------------------------------------------------------------------------------
Drop all position information, so equality reflects program structure | Module : Cryptol . . AST
Copyright : ( c ) 2013 - 2016 Galois , Inc.
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE DeriveGeneric #
# LANGUAGE PatternGuards #
# LANGUAGE RecordWildCards #
# LANGUAGE FlexibleInstances #
module Cryptol.Parser.AST
Ident, mkIdent, mkInfix, isInfixIdent, nullIdent, identText
, ModName, modRange
, PName(..), getModName, getIdent, mkUnqual, mkQual
, Named(..)
, Pass(..)
, Assoc(..)
, Schema(..)
, TParam(..)
, Kind(..)
, Type(..)
, Prop(..)
, tsName
, psName
, tsFixity
, psFixity
, Module
, ModuleG(..)
, mImports
, mSubmoduleImports
, Program(..)
, TopDecl(..)
, Decl(..)
, Fixity(..), defaultFixity
, FixityCmp(..), compareFixity
, TySyn(..)
, PropSyn(..)
, Bind(..)
, BindDef(..), LBindDef
, Pragma(..)
, ExportType(..)
, TopLevel(..)
, Import, ImportG(..), ImportSpec(..), ImpName(..)
, Newtype(..)
, PrimType(..)
, ParameterType(..)
, ParameterFun(..)
, NestedModule(..)
, PropGuardCase(..)
, ReplInput(..)
, Expr(..)
, Literal(..), NumInfo(..), FracInfo(..)
, Match(..)
, Pattern(..)
, Selector(..)
, TypeInst(..)
, UpdField(..)
, UpdHow(..)
, FunDesc(..)
, emptyFunDesc
, PrefixOp(..)
, prefixFixity
, asEApps
, Located(..)
, LPName, LString, LIdent
, NoPos(..)
, cppKind, ppSelector
) where
import Cryptol.Parser.Name
import Cryptol.Parser.Position
import Cryptol.Parser.Selector
import Cryptol.Utils.Fixity
import Cryptol.Utils.Ident
import Cryptol.Utils.RecordMap
import Cryptol.Utils.PP
import Data.List(intersperse)
import Data.Bits(shiftR)
import Data.Maybe (catMaybes)
import Data.Ratio(numerator,denominator)
import Data.Text (Text)
import Numeric(showIntAtBase,showFloat,showHFloat)
import GHC.Generics (Generic)
import Control.DeepSeq
import Prelude ()
import Prelude.Compat
type LPName = Located PName
type LIdent = Located Ident
type LString = Located String
type Rec e = RecordMap Ident (Range, e)
newtype Program name = Program [TopDecl name]
deriving (Show)
data ModuleG mname name = Module
} deriving (Show, Generic, NFData)
mImports :: ModuleG mname name -> [ Located Import ]
mImports m =
[ li { thing = i { iModule = n } }
| DImport li <- mDecls m
, let i = thing li
, ImpTop n <- [iModule i]
]
mSubmoduleImports :: ModuleG mname name -> [ Located (ImportG name) ]
mSubmoduleImports m =
[ li { thing = i { iModule = n } }
| DImport li <- mDecls m
, let i = thing li
, ImpNested n <- [iModule i]
]
type Module = ModuleG ModName
newtype NestedModule name = NestedModule (ModuleG name name)
deriving (Show,Generic,NFData)
modRange :: Module name -> Range
modRange m = rCombs $ catMaybes
[ getLoc (mName m)
, getLoc (mImports m)
, getLoc (mDecls m)
, Just (Range { from = start, to = start, source = "" })
]
data TopDecl name =
Decl (TopLevel (Decl name))
| DPrimType (TopLevel (PrimType name))
^ type T : # @
| DParameterConstraint [Located (Prop name)]
^ type constraint ( fin T)@
^ someVal : [ 256]@
deriving (Show, Generic, NFData)
data ImpName name =
ImpTop ModName
| ImpNested name
deriving (Show, Generic, NFData)
data Decl name = DSignature [Located name] (Schema name)
| DFixity !Fixity [Located name]
| DPragma [Located name] Pragma
| DBind (Bind name)
| DRec [Bind name]
| DPatBind (Pattern name) (Expr name)
| DType (TySyn name)
| DProp (PropSyn name)
| DLocated (Decl name) Range
deriving (Eq, Show, Generic, NFData, Functor)
data ParameterType name = ParameterType
} deriving (Eq,Show,Generic,NFData)
data ParameterFun name = ParameterFun
} deriving (Eq,Show,Generic,NFData)
data ImportG mname = Import
{ iModule :: !mname
, iAs :: Maybe ModName
, iSpec :: Maybe ImportSpec
} deriving (Eq, Show, Generic, NFData)
type Import = ImportG ModName
data ImportSpec = Hiding [Ident]
| Only [Ident]
deriving (Eq, Show, Generic, NFData)
The ' Maybe Fixity ' field is filled in by the NoPat pass .
data TySyn n = TySyn (Located n) (Maybe Fixity) [TParam n] (Type n)
deriving (Eq, Show, Generic, NFData, Functor)
The ' Maybe Fixity ' field is filled in by the NoPat pass .
data PropSyn n = PropSyn (Located n) (Maybe Fixity) [TParam n] [Prop n]
deriving (Eq, Show, Generic, NFData, Functor)
tsName :: TySyn name -> Located name
tsName (TySyn lqn _ _ _) = lqn
psName :: PropSyn name -> Located name
psName (PropSyn lqn _ _ _) = lqn
tsFixity :: TySyn name -> Maybe Fixity
tsFixity (TySyn _ f _ _) = f
psFixity :: PropSyn name -> Maybe Fixity
psFixity (PropSyn _ f _ _) = f
data Bind name = Bind
, bExport :: !ExportType
} deriving (Eq, Generic, NFData, Functor, Show)
type LBindDef = Located (BindDef PName)
data BindDef name = DPrim
| DForeign
| DExpr (Expr name)
| DPropGuards [PropGuardCase name]
deriving (Eq, Show, Generic, NFData, Functor)
data PropGuardCase name = PropGuardCase
{ pgcProps :: [Located (Prop name)]
, pgcExpr :: Expr name
}
deriving (Eq,Generic,NFData,Functor,Show)
data Pragma = PragmaNote String
| PragmaProperty
deriving (Eq, Show, Generic, NFData)
} deriving (Eq, Show, Generic, NFData)
data PrimType name = PrimType { primTName :: Located name
, primTKind :: Located Kind
, primTCts :: ([TParam name], [Prop name])
, primTFixity :: Maybe Fixity
} deriving (Show,Generic,NFData)
| Input at the REPL , which can be an expression , a
data ReplInput name = ExprInput (Expr name)
| LetInput [Decl name]
| EmptyInput
deriving (Eq, Show)
data ExportType = Public
| Private
deriving (Eq, Show, Ord, Generic, NFData)
data TopLevel a = TopLevel { tlExport :: ExportType
, tlDoc :: Maybe (Located Text)
, tlValue :: a
}
deriving (Show, Generic, NFData, Functor, Foldable, Traversable)
deriving (Eq, Show, Generic, NFData)
data FracInfo = BinFrac Text
| OctFrac Text
| DecFrac Text
| HexFrac Text
deriving (Eq,Show,Generic,NFData)
^ ( HexLit 2 )
^ @1.2e3@
deriving (Eq, Show, Generic, NFData)
^ @ 0x10 @
^ @ { x = 1 , y = 2 } @
| EFromTo (Type n) (Maybe (Type n)) (Type n) (Maybe (Type n))
^ @ [ 1 , 5 .. 117 : t ] @
| EFromToBy Bool (Type n) (Type n) (Type n) (Maybe (Type n))
^ @ [ 1 .. 10 by 2 : t ] @
| EFromToDownBy Bool (Type n) (Type n) (Type n) (Maybe (Type n))
^ @ [ 10 .. 1 down by 2 : t ] @
| EFromToLessThan (Type n) (Type n) (Maybe (Type n))
^ @ [ 1 .. < 10 : t ] @
^ @ [ 1 , 3 ... ] @
^ @ [ 1 | x < - xs ] @
^ @ f ` { x = 8 } , f`{8 } @
^ @ 1 + x where { x = 2 } @
^ @ 1 : [ 8 ] @
^ @ splitAt x @ ( Introduced by NoPat )
deriving (Eq, Show, Generic, NFData, Functor)
deriving (Eq, Show, Generic, NFData)
prefixFixity :: PrefixOp -> Fixity
prefixFixity op = Fixity { fAssoc = LeftAssoc, .. }
where fLevel = case op of
PrefixNeg -> 80
PrefixComplement -> 100
by the parser . The NoPat pass fills this in as required .
data FunDesc n =
FunDesc
^ Name of this function , if it has one
bound in surrounding lambdas ( defaults to 0 )
}
deriving (Eq, Show, Generic, NFData, Functor)
emptyFunDesc :: FunDesc n
emptyFunDesc = FunDesc Nothing 0
data UpdField n = UpdField UpdHow [Located Selector] (Expr n)
deriving (Eq, Show, Generic, NFData, Functor)
deriving (Eq, Show, Generic, NFData)
data TypeInst name = NamedInst (Named (Type name))
| PosInst (Type name)
deriving (Eq, Show, Generic, NFData, Functor)
| MatchLet (Bind name)
deriving (Eq, Show, Generic, NFData, Functor)
^ @ x : [ 8 ] @
deriving (Eq, Show, Generic, NFData, Functor)
data Named a = Named { name :: Located Ident, value :: a }
deriving (Eq, Show, Foldable, Traversable, Generic, NFData, Functor)
data Schema n = Forall [TParam n] [Prop n] (Type n) (Maybe Range)
deriving (Eq, Show, Generic, NFData, Functor)
data Kind = KProp | KNum | KType | KFun Kind Kind
deriving (Eq, Show, Generic, NFData)
data TParam n = TParam { tpName :: n
, tpKind :: Maybe Kind
, tpRange :: Maybe Range
}
deriving (Eq, Show, Generic, NFData, Functor)
^ @Bit@
^ @ ` { x = [ 8 ] , y = Integer } @
^ @ { x : [ 8 ] , y : [ 32 ] } @
^ @([8 ] , [ 32])@
deriving (Eq, Show, Generic, NFData, Functor)
| A ' Prop ' is a ' Type ' that represents a type constraint .
newtype Prop n = CType (Type n)
deriving (Eq, Show, Generic, NFData, Functor)
instance AddLoc (Expr n) where
addLoc x@ELocated{} _ = x
addLoc x r = ELocated x r
dropLoc (ELocated e _) = dropLoc e
dropLoc e = e
instance HasLoc (Expr name) where
getLoc (ELocated _ r) = Just r
getLoc _ = Nothing
instance HasLoc (TParam name) where
getLoc (TParam _ _ r) = r
instance AddLoc (TParam name) where
addLoc (TParam a b _) l = TParam a b (Just l)
dropLoc (TParam a b _) = TParam a b Nothing
instance HasLoc (Type name) where
getLoc (TLocated _ r) = Just r
getLoc _ = Nothing
instance AddLoc (Type name) where
addLoc = TLocated
dropLoc (TLocated e _) = dropLoc e
dropLoc e = e
instance AddLoc (Pattern name) where
addLoc = PLocated
dropLoc (PLocated e _) = dropLoc e
dropLoc e = e
instance HasLoc (Pattern name) where
getLoc (PLocated _ r) = Just r
getLoc (PTyped r _) = getLoc r
getLoc (PVar x) = getLoc x
getLoc _ = Nothing
instance HasLoc (Bind name) where
getLoc b = getLoc (bName b, bDef b)
instance HasLoc (Match name) where
getLoc (Match p e) = getLoc (p,e)
getLoc (MatchLet b) = getLoc b
instance HasLoc a => HasLoc (Named a) where
getLoc l = getLoc (name l, value l)
instance HasLoc (Schema name) where
getLoc (Forall _ _ _ r) = r
instance AddLoc (Schema name) where
addLoc (Forall xs ps t _) r = Forall xs ps t (Just r)
dropLoc (Forall xs ps t _) = Forall xs ps t Nothing
instance HasLoc (Decl name) where
getLoc (DLocated _ r) = Just r
getLoc _ = Nothing
instance AddLoc (Decl name) where
addLoc d r = DLocated d r
dropLoc (DLocated d _) = dropLoc d
dropLoc d = d
instance HasLoc a => HasLoc (TopLevel a) where
getLoc = getLoc . tlValue
instance HasLoc (TopDecl name) where
getLoc td =
case td of
Decl tld -> getLoc tld
DPrimType pt -> getLoc pt
TDNewtype n -> getLoc n
Include lfp -> getLoc lfp
DParameterType d -> getLoc d
DParameterFun d -> getLoc d
DParameterConstraint d -> getLoc d
DModule d -> getLoc d
DImport d -> getLoc d
instance HasLoc (PrimType name) where
getLoc pt = Just (rComb (srcRange (primTName pt)) (srcRange (primTKind pt)))
instance HasLoc (ParameterType name) where
getLoc a = getLoc (ptName a)
instance HasLoc (ParameterFun name) where
getLoc a = getLoc (pfName a)
instance HasLoc (ModuleG mname name) where
getLoc m
| null locs = Nothing
| otherwise = Just (rCombs locs)
where
locs = catMaybes [ getLoc (mName m)
, getLoc (mImports m)
, getLoc (mDecls m)
]
instance HasLoc (NestedModule name) where
getLoc (NestedModule m) = getLoc m
instance HasLoc (Newtype name) where
getLoc n
| null locs = Nothing
| otherwise = Just (rCombs locs)
where
locs = catMaybes ([ getLoc (nName n)] ++ map (Just . fst . snd) (displayFields (nBody n)))
ppL :: PP a => Located a -> Doc
ppL = pp . thing
ppNamed :: PP a => String -> Named a -> Doc
ppNamed s x = ppL (name x) <+> text s <+> pp (value x)
ppNamed' :: PP a => String -> (Ident, (Range, a)) -> Doc
ppNamed' s (i,(_,v)) = pp i <+> text s <+> pp v
instance (Show name, PPName mname, PPName name) => PP (ModuleG mname name) where
ppPrec _ = ppModule 0
ppModule :: (Show name, PPName mname, PPName name) =>
Int -> ModuleG mname name -> Doc
ppModule n m =
text "module" <+> ppL (mName m) <+> text "where" $$ nest n body
where
body = vcat (map ppL (mImports m))
$$ vcat (map pp (mDecls m))
instance (Show name, PPName name) => PP (NestedModule name) where
ppPrec _ (NestedModule m) = ppModule 2 m
instance (Show name, PPName name) => PP (Program name) where
ppPrec _ (Program ds) = vcat (map pp ds)
instance (Show name, PPName name) => PP (TopDecl name) where
ppPrec _ top_decl =
case top_decl of
Decl d -> pp d
DPrimType p -> pp p
TDNewtype n -> pp n
Include l -> text "include" <+> text (show (thing l))
DParameterFun d -> pp d
DParameterType d -> pp d
DParameterConstraint d ->
"parameter" <+> "type" <+> "constraint" <+> prop
where prop = case map (pp . thing) d of
[x] -> x
[] -> "()"
xs -> nest 1 (parens (commaSepFill xs))
DModule d -> pp d
DImport i -> pp (thing i)
instance (Show name, PPName name) => PP (PrimType name) where
ppPrec _ pt =
"primitive" <+> "type" <+> pp (primTName pt) <+> ":" <+> pp (primTKind pt)
instance (Show name, PPName name) => PP (ParameterType name) where
ppPrec _ a = text "parameter" <+> text "type" <+>
ppPrefixName (ptName a) <+> text ":" <+> pp (ptKind a)
instance (Show name, PPName name) => PP (ParameterFun name) where
ppPrec _ a = text "parameter" <+> ppPrefixName (pfName a) <+> text ":"
<+> pp (pfSchema a)
instance (Show name, PPName name) => PP (Decl name) where
ppPrec n decl =
case decl of
DSignature xs s -> commaSep (map ppL xs) <+> text ":" <+> pp s
DPatBind p e -> pp p <+> text "=" <+> pp e
DBind b -> ppPrec n b
DRec bs -> nest 2 (vcat ("recursive" : map (ppPrec n) bs))
DFixity f ns -> ppFixity f ns
DPragma xs p -> ppPragma xs p
DType ts -> ppPrec n ts
DProp ps -> ppPrec n ps
DLocated d _ -> ppPrec n d
ppFixity :: PPName name => Fixity -> [Located name] -> Doc
ppFixity (Fixity LeftAssoc i) ns = text "infixl" <+> int i <+> commaSep (map pp ns)
ppFixity (Fixity RightAssoc i) ns = text "infixr" <+> int i <+> commaSep (map pp ns)
ppFixity (Fixity NonAssoc i) ns = text "infix" <+> int i <+> commaSep (map pp ns)
instance PPName name => PP (Newtype name) where
ppPrec _ nt = nest 2 $ sep
[ fsep $ [text "newtype", ppL (nName nt)] ++ map pp (nParams nt) ++ [char '=']
, ppRecord (map (ppNamed' ":") (displayFields (nBody nt)))
]
instance PP mname => PP (ImportG mname) where
ppPrec _ d = text "import" <+> sep ([pp (iModule d)] ++ mbAs ++ mbSpec)
where
mbAs = maybe [] (\ name -> [text "as" <+> pp name]) (iAs d)
mbSpec = maybe [] (\x -> [pp x]) (iSpec d)
instance PP name => PP (ImpName name) where
ppPrec _ nm =
case nm of
ImpTop x -> pp x
ImpNested x -> "submodule" <+> pp x
instance PP ImportSpec where
ppPrec _ s = case s of
Hiding names -> text "hiding" <+> parens (commaSep (map pp names))
Only names -> parens (commaSep (map pp names))
instance PP a => PP (TopLevel a) where
ppPrec _ tl = pp (tlValue tl)
instance PP Pragma where
ppPrec _ (PragmaNote x) = text x
ppPrec _ PragmaProperty = text "property"
ppPragma :: PPName name => [Located name] -> Pragma -> Doc
ppPragma xs p =
text "/*" <+> text "pragma" <+> commaSep (map ppL xs) <+> text ":" <+> pp p
<+> text "*/"
instance (Show name, PPName name) => PP (Bind name) where
ppPrec _ b = vcat (sig ++ [ ppPragma [f] p | p <- bPragmas b ] ++
[hang (def <+> eq) 4 (pp (thing (bDef b)))])
where def | bInfix b = lhsOp
| otherwise = lhs
f = bName b
sig = case bSignature b of
Nothing -> []
Just s -> [pp (DSignature [f] s)]
eq = if bMono b then text ":=" else text "="
lhs = fsep (ppL f : (map (ppPrec 3) (bParams b)))
lhsOp = case bParams b of
[x,y] -> pp x <+> ppL f <+> pp y
xs -> parens (parens (ppL f) <+> fsep (map (ppPrec 0) xs))
instance (Show name, PPName name) => PP (BindDef name) where
ppPrec _ DPrim = text "<primitive>"
ppPrec _ DForeign = text "<foreign>"
ppPrec p (DExpr e) = ppPrec p e
ppPrec _p (DPropGuards _guards) = text "propguards"
instance PPName name => PP (TySyn name) where
ppPrec _ (TySyn x _ xs t) =
nest 2 $ sep $
[ fsep $ [text "type", ppL x] ++ map (ppPrec 1) xs ++ [text "="]
, pp t
]
instance PPName name => PP (PropSyn name) where
ppPrec _ (PropSyn x _ xs ps) =
nest 2 $ sep $
[ fsep $ [text "constraint", ppL x] ++ map (ppPrec 1) xs ++ [text "="]
, parens (commaSep (map pp ps))
]
instance PP Literal where
ppPrec _ lit =
case lit of
ECNum n i -> ppNumLit n i
ECChar c -> text (show c)
ECFrac n i -> ppFracLit n i
ECString s -> text (show s)
ppFracLit :: Rational -> FracInfo -> Doc
ppFracLit x i
| toRational dbl == x =
case i of
BinFrac _ -> frac
OctFrac _ -> frac
DecFrac _ -> text (showFloat dbl "")
HexFrac _ -> text (showHFloat dbl "")
| otherwise = frac
where
dbl = fromRational x :: Double
frac = "fraction`" <.> braces
(commaSep (map integer [ numerator x, denominator x ]))
ppNumLit :: Integer -> NumInfo -> Doc
ppNumLit n info =
case info of
DecLit _ -> integer n
BinLit _ w -> pad 2 "0b" w
OctLit _ w -> pad 8 "0o" w
HexLit _ w -> pad 16 "0x" w
PolyLit w -> text "<|" <+> poly w <+> text "|>"
where
pad base pref w =
let txt = showIntAtBase base ("0123456789abcdef" !!) n ""
in text pref <.> text (replicate (w - length txt) '0') <.> text txt
poly w = let (res,deg) = bits Nothing [] 0 n
z | w == 0 = []
| Just d <- deg, d + 1 == w = []
| otherwise = [polyTerm0 (w-1)]
in fsep $ intersperse (text "+") $ z ++ map polyTerm res
polyTerm 0 = text "1"
polyTerm 1 = text "x"
polyTerm p = text "x" <.> text "^^" <.> int p
polyTerm0 0 = text "0"
polyTerm0 p = text "0" <.> text "*" <.> polyTerm p
bits d res p num
| num == 0 = (res,d)
| even num = bits d res (p + 1) (num `shiftR` 1)
| otherwise = bits (Just p) (p : res) (p + 1) (num `shiftR` 1)
wrap :: Int -> Int -> Doc -> Doc
wrap contextPrec myPrec doc = optParens (myPrec < contextPrec) doc
isEApp :: Expr n -> Maybe (Expr n, Expr n)
isEApp (ELocated e _) = isEApp e
isEApp (EApp e1 e2) = Just (e1,e2)
isEApp _ = Nothing
asEApps :: Expr n -> (Expr n, [Expr n])
asEApps expr = go expr []
where go e es = case isEApp e of
Nothing -> (e, es)
Just (e1, e2) -> go e1 (e2 : es)
instance PPName name => PP (TypeInst name) where
ppPrec _ (PosInst t) = pp t
ppPrec _ (NamedInst x) = ppNamed "=" x
Precedences :
0 : lambda , if , where , type annotation
2 : infix expression ( separate precedence table )
3 : application , prefix expressions
0: lambda, if, where, type annotation
2: infix expression (separate precedence table)
3: application, prefix expressions
-}
instance (Show name, PPName name) => PP (Expr name) where
ppPrec n expr =
case expr of
EVar x -> ppPrefixName x
ELit x -> pp x
EGenerate x -> wrap n 3 (text "generate" <+> ppPrec 4 x)
ETuple es -> parens (commaSep (map pp es))
ERecord fs -> braces (commaSep (map (ppNamed' "=") (displayFields fs)))
EList es -> brackets (commaSep (map pp es))
EFromTo e1 e2 e3 t1 -> brackets (pp e1 <.> step <+> text ".." <+> end)
where step = maybe mempty (\e -> comma <+> pp e) e2
end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
EFromToBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "by" <+> end)
where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
dots | isStrict = text ".. <"
| otherwise = text ".."
EFromToDownBy isStrict e1 e2 e3 t1 -> brackets (pp e1 <+> dots <+> pp e2 <+> text "down by" <+> end)
where end = maybe (pp e3) (\t -> pp e3 <+> colon <+> pp t) t1
dots | isStrict = text ".. >"
| otherwise = text ".."
EFromToLessThan e1 e2 t1 -> brackets (strt <+> text ".. <" <+> end)
where strt = maybe (pp e1) (\t -> pp e1 <+> colon <+> pp t) t1
end = pp e2
EInfFrom e1 e2 -> brackets (pp e1 <.> step <+> text "...")
where step = maybe mempty (\e -> comma <+> pp e) e2
EComp e mss -> brackets (pp e <> align (vcat (map arm mss)))
where arm ms = text " |" <+> commaSep (map pp ms)
EUpd mb fs -> braces (hd <+> "|" <+> commaSep (map pp fs))
where hd = maybe "_" pp mb
EAppT e ts -> ppPrec 4 e <.> text "`" <.> braces (commaSep (map pp ts))
ESel e l -> ppPrec 4 e <.> text "." <.> pp l
EFun _ xs e -> wrap n 0 ((text "\\" <.> hsep (map (ppPrec 3) xs)) <+>
text "->" <+> pp e)
EIf e1 e2 e3 -> wrap n 0 $ sep [ text "if" <+> pp e1
, text "then" <+> pp e2
, text "else" <+> pp e3 ]
ETyped e t -> wrap n 0 (ppPrec 2 e <+> text ":" <+> pp t)
EWhere e ds -> wrap n 0 $ align $ vsep
[ pp e
, hang "where" 2 (vcat (map pp ds))
]
_ | Just ifix <- isInfix expr ->
optParens (n > 2)
$ ppInfix 2 isInfix ifix
EApp _ _ -> let (e, es) = asEApps expr in
wrap n 3 (ppPrec 3 e <+> fsep (map (ppPrec 4) es))
ELocated e _ -> ppPrec n e
ESplit e -> wrap n 3 (text "splitAt" <+> ppPrec 4 e)
EParens e -> parens (pp e)
EInfix e1 op _ e2 -> wrap n 0 (pp e1 <+> ppInfixName (thing op) <+> pp e2)
EPrefix op e -> wrap n 3 (text (prefixText op) <.> ppPrec 4 e)
where
isInfix (EApp (EApp (EVar ieOp) ieLeft) ieRight) = do
ieFixity <- ppNameFixity ieOp
return Infix { .. }
isInfix _ = Nothing
prefixText PrefixNeg = "-"
prefixText PrefixComplement = "~"
instance (Show name, PPName name) => PP (UpdField name) where
ppPrec _ (UpdField h xs e) = ppNestedSels (map thing xs) <+> pp h <+> pp e
instance PP UpdHow where
ppPrec _ h = case h of
UpdSet -> "="
UpdFun -> "->"
instance PPName name => PP (Pattern name) where
ppPrec n pat =
case pat of
PVar x -> pp (thing x)
PWild -> char '_'
PTuple ps -> ppTuple (map pp ps)
PRecord fs -> ppRecord (map (ppNamed' "=") (displayFields fs))
PList ps -> ppList (map pp ps)
PTyped p t -> wrap n 0 (ppPrec 1 p <+> text ":" <+> pp t)
PSplit p1 p2 -> wrap n 1 (ppPrec 1 p1 <+> text "#" <+> ppPrec 1 p2)
PLocated p _ -> ppPrec n p
instance (Show name, PPName name) => PP (Match name) where
ppPrec _ (Match p e) = pp p <+> text "<-" <+> pp e
ppPrec _ (MatchLet b) = pp b
instance PPName name => PP (Schema name) where
ppPrec _ (Forall xs ps t _) = sep (vars ++ preds ++ [pp t])
where vars = case xs of
[] -> []
_ -> [nest 1 (braces (commaSepFill (map pp xs)))]
preds = case ps of
[] -> []
_ -> [nest 1 (parens (commaSepFill (map pp ps))) <+> text "=>"]
instance PP Kind where
ppPrec _ KType = text "*"
ppPrec _ KNum = text "#"
ppPrec _ KProp = text "@"
ppPrec n (KFun k1 k2) = wrap n 1 (ppPrec 1 k1 <+> "->" <+> ppPrec 0 k2)
cppKind :: Kind -> Doc
cppKind KType = text "a value type"
cppKind KNum = text "a numeric type"
cppKind KProp = text "a constraint type"
cppKind (KFun {}) = text "a type-constructor type"
instance PPName name => PP (TParam name) where
ppPrec n (TParam p Nothing _) = ppPrec n p
ppPrec n (TParam p (Just k) _) = wrap n 1 (pp p <+> text ":" <+> pp k)
4 : atomic type expression
3 : [ _ ] t or application
2 : infix type
1 : function type
instance PPName name => PP (Type name) where
ppPrec n ty =
case ty of
TWild -> text "_"
TTuple ts -> parens $ commaSep $ map pp ts
TTyApp fs -> braces $ commaSep $ map (ppNamed " = ") fs
TRecord fs -> braces $ commaSep $ map (ppNamed' ":") (displayFields fs)
TBit -> text "Bit"
TNum x -> integer x
TChar x -> text (show x)
TSeq t1 TBit -> brackets (pp t1)
TSeq t1 t2 -> optParens (n > 3)
$ brackets (pp t1) <.> ppPrec 3 t2
TUser f [] -> ppPrefixName f
TUser f ts -> optParens (n > 3)
$ ppPrefixName f <+> fsep (map (ppPrec 4) ts)
TFun t1 t2 -> optParens (n > 1)
$ sep [ppPrec 2 t1 <+> text "->", ppPrec 1 t2]
TLocated t _ -> ppPrec n t
TParens t -> parens (pp t)
TInfix t1 o _ t2 -> optParens (n > 2)
$ sep [ppPrec 2 t1 <+> ppInfixName o, ppPrec 3 t2]
instance PPName name => PP (Prop name) where
ppPrec n (CType t) = ppPrec n t
instance PPName name => PP [Prop name] where
ppPrec n props = parens . commaSep . fmap (ppPrec n) $ props
class NoPos t where
noPos :: t -> t
WARNING : This does not call ` noPos ` on the ` thing ` inside
instance NoPos (Located t) where
noPos x = x { srcRange = rng }
where rng = Range { from = Position 0 0, to = Position 0 0, source = "" }
instance NoPos t => NoPos (Named t) where
noPos t = Named { name = noPos (name t), value = noPos (value t) }
instance NoPos Range where
noPos _ = Range { from = Position 0 0, to = Position 0 0, source = "" }
instance NoPos t => NoPos [t] where noPos = fmap noPos
instance NoPos t => NoPos (Maybe t) where noPos = fmap noPos
instance (NoPos a, NoPos b) => NoPos (a,b) where
noPos (a,b) = (noPos a, noPos b)
instance NoPos (Program name) where
noPos (Program x) = Program (noPos x)
instance NoPos (ModuleG mname name) where
noPos m = Module { mName = mName m
, mInstance = mInstance m
, mDecls = noPos (mDecls m)
}
instance NoPos (NestedModule name) where
noPos (NestedModule m) = NestedModule (noPos m)
instance NoPos (TopDecl name) where
noPos decl =
case decl of
Decl x -> Decl (noPos x)
DPrimType t -> DPrimType (noPos t)
TDNewtype n -> TDNewtype(noPos n)
Include x -> Include (noPos x)
DParameterFun d -> DParameterFun (noPos d)
DParameterType d -> DParameterType (noPos d)
DParameterConstraint d -> DParameterConstraint (noPos d)
DModule d -> DModule (noPos d)
DImport d -> DImport (noPos d)
instance NoPos (PrimType name) where
noPos x = x
instance NoPos (ParameterType name) where
noPos a = a
instance NoPos (ParameterFun x) where
noPos x = x { pfSchema = noPos (pfSchema x) }
instance NoPos a => NoPos (TopLevel a) where
noPos tl = tl { tlValue = noPos (tlValue tl) }
instance NoPos (Decl name) where
noPos decl =
case decl of
DSignature x y -> DSignature (noPos x) (noPos y)
DPragma x y -> DPragma (noPos x) (noPos y)
DPatBind x y -> DPatBind (noPos x) (noPos y)
DFixity f ns -> DFixity f (noPos ns)
DBind x -> DBind (noPos x)
DRec bs -> DRec (map noPos bs)
DType x -> DType (noPos x)
DProp x -> DProp (noPos x)
DLocated x _ -> noPos x
instance NoPos (Newtype name) where
noPos n = Newtype { nName = noPos (nName n)
, nParams = nParams n
, nBody = fmap noPos (nBody n)
}
instance NoPos (Bind name) where
noPos x = Bind { bName = noPos (bName x)
, bParams = noPos (bParams x)
, bDef = noPos (bDef x)
, bSignature = noPos (bSignature x)
, bInfix = bInfix x
, bFixity = bFixity x
, bPragmas = noPos (bPragmas x)
, bMono = bMono x
, bDoc = bDoc x
, bExport = bExport x
}
instance NoPos Pragma where
noPos p@(PragmaNote {}) = p
noPos p@(PragmaProperty) = p
instance NoPos (TySyn name) where
noPos (TySyn x f y z) = TySyn (noPos x) f (noPos y) (noPos z)
instance NoPos (PropSyn name) where
noPos (PropSyn x f y z) = PropSyn (noPos x) f (noPos y) (noPos z)
instance NoPos (Expr name) where
noPos expr =
case expr of
EVar x -> EVar x
ELit x -> ELit x
EGenerate x -> EGenerate (noPos x)
ETuple x -> ETuple (noPos x)
ERecord x -> ERecord (fmap noPos x)
ESel x y -> ESel (noPos x) y
EUpd x y -> EUpd (noPos x) (noPos y)
EList x -> EList (noPos x)
EFromTo x y z t -> EFromTo (noPos x) (noPos y) (noPos z) (noPos t)
EFromToBy isStrict x y z t
-> EFromToBy isStrict (noPos x) (noPos y) (noPos z) (noPos t)
EFromToDownBy isStrict x y z t
-> EFromToDownBy isStrict (noPos x) (noPos y) (noPos z) (noPos t)
EFromToLessThan x y t -> EFromToLessThan (noPos x) (noPos y) (noPos t)
EInfFrom x y -> EInfFrom (noPos x) (noPos y)
EComp x y -> EComp (noPos x) (noPos y)
EApp x y -> EApp (noPos x) (noPos y)
EAppT x y -> EAppT (noPos x) (noPos y)
EIf x y z -> EIf (noPos x) (noPos y) (noPos z)
EWhere x y -> EWhere (noPos x) (noPos y)
ETyped x y -> ETyped (noPos x) (noPos y)
ETypeVal x -> ETypeVal (noPos x)
EFun dsc x y -> EFun dsc (noPos x) (noPos y)
ELocated x _ -> noPos x
ESplit x -> ESplit (noPos x)
EParens e -> EParens (noPos e)
EInfix x y f z -> EInfix (noPos x) y f (noPos z)
EPrefix op x -> EPrefix op (noPos x)
instance NoPos (UpdField name) where
noPos (UpdField h xs e) = UpdField h xs (noPos e)
instance NoPos (TypeInst name) where
noPos (PosInst ts) = PosInst (noPos ts)
noPos (NamedInst fs) = NamedInst (noPos fs)
instance NoPos (Match name) where
noPos (Match x y) = Match (noPos x) (noPos y)
noPos (MatchLet b) = MatchLet (noPos b)
instance NoPos (Pattern name) where
noPos pat =
case pat of
PVar x -> PVar (noPos x)
PWild -> PWild
PTuple x -> PTuple (noPos x)
PRecord x -> PRecord (fmap noPos x)
PList x -> PList (noPos x)
PTyped x y -> PTyped (noPos x) (noPos y)
PSplit x y -> PSplit (noPos x) (noPos y)
PLocated x _ -> noPos x
instance NoPos (Schema name) where
noPos (Forall x y z _) = Forall (noPos x) (noPos y) (noPos z) Nothing
instance NoPos (TParam name) where
noPos (TParam x y _) = TParam x y Nothing
instance NoPos (Type name) where
noPos ty =
case ty of
TWild -> TWild
TUser x y -> TUser x (noPos y)
TTyApp x -> TTyApp (noPos x)
TRecord x -> TRecord (fmap noPos x)
TTuple x -> TTuple (noPos x)
TFun x y -> TFun (noPos x) (noPos y)
TSeq x y -> TSeq (noPos x) (noPos y)
TBit -> TBit
TNum n -> TNum n
TChar n -> TChar n
TLocated x _ -> noPos x
TParens x -> TParens (noPos x)
TInfix x y f z-> TInfix (noPos x) y f (noPos z)
instance NoPos (Prop name) where
noPos (CType t) = CType (noPos t)
|
cc3390515bc8ee025ddc8aab45a8cf4186cd35015f98dd58ed468e2b9e76b424 | bufferswap/ViralityEngine | annotations.lisp | (in-package #:virality)
(defmacro define-annotation (name &key
(getter
'(lambda (value component)
(declare (ignore component)
value)))
(setter
'(lambda (value component)
(declare (ignore component)
value))))
`(register-annotation 'component ',name :initialized
:getter (function ,getter)
:setter (function ,setter)))
| null | https://raw.githubusercontent.com/bufferswap/ViralityEngine/df7bb4dffaecdcb6fdcbfa618031a5e1f85f4002/src/core-early/annotations.lisp | lisp | (in-package #:virality)
(defmacro define-annotation (name &key
(getter
'(lambda (value component)
(declare (ignore component)
value)))
(setter
'(lambda (value component)
(declare (ignore component)
value))))
`(register-annotation 'component ',name :initialized
:getter (function ,getter)
:setter (function ,setter)))
|
|
5ff1ac211b6b8c4b7aec6cd865a5eda8487eff95ce0c08d4ef79674caa6dd32f | dgtized/shimmers | ellipse.cljs | (ns shimmers.scratch.ellipse
"Experiments in clipping part of an ellipse into a bounded-box."
(:require
[shimmers.math.equations :as eq]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn clockwise-intercept [center bounds]
(let [midpoints (map (fn [[p q]] (tm/mix p q 0.5)) (g/edges bounds))]
(apply min (map #(g/heading (tm/- % center)) midpoints))))
(comment (clockwise-intercept (gv/vec2 -5 11) (rect/rect 10)))
(defn ellipse-arc [center a b intercept dt]
(for [t (range intercept (+ intercept eq/TAU) dt)]
(tm/+ center (gv/vec2 (* a (Math/cos t))
(* b (Math/sin t))))))
(comment (ellipse-arc (gv/vec2 1 0) 10 10 0 0.1))
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/scratch/ellipse.cljs | clojure | (ns shimmers.scratch.ellipse
"Experiments in clipping part of an ellipse into a bounded-box."
(:require
[shimmers.math.equations :as eq]
[thi.ng.geom.core :as g]
[thi.ng.geom.rect :as rect]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn clockwise-intercept [center bounds]
(let [midpoints (map (fn [[p q]] (tm/mix p q 0.5)) (g/edges bounds))]
(apply min (map #(g/heading (tm/- % center)) midpoints))))
(comment (clockwise-intercept (gv/vec2 -5 11) (rect/rect 10)))
(defn ellipse-arc [center a b intercept dt]
(for [t (range intercept (+ intercept eq/TAU) dt)]
(tm/+ center (gv/vec2 (* a (Math/cos t))
(* b (Math/sin t))))))
(comment (ellipse-arc (gv/vec2 1 0) 10 10 0 0.1))
|
|
e8f6248f962d9a23b5eb128b1f6581799af4300a7f141cac017113cafe0c7952 | mjsottile/publicstuff | Driver.hs | | diffusion limited aggregation , take 1
--
mjsottile\@computer.org
import DLA.Vec3
import DLA.KDTree
import DLA.Rmonad
import DLA.Params
import DLA.ConfigurationReader
import Debug.Trace
import System.Exit
import System.Environment (getArgs)
import System.Random.Mersenne.Pure64
type DLANode = KDTreeNode Int
--
-- draw a random number and see if the particle sticks
--
sticks :: DLAParams -> DLAMonad Bool
sticks params = do
d <- nextF 1.0
return $ d < (stickiness params)
--
-- where does a particle start given the step size, multipliers, and current
-- size of the aggregate
--
starting_radius :: Double -> Double -> Double -> Double -> Double
starting_radius min_inner_radius curr_max_radius inner_mult step_size =
max min_inner_radius (curr_max_radius + inner_mult * step_size)
--
-- where does a particle die given the current state of things
--
death_radius :: Double -> Double -> Double -> Double -> Double -> Double
death_radius min_inner_radius curr_max_radius inner_mult step_size outer_mult =
(starting_radius min_inner_radius curr_max_radius inner_mult step_size) +
outer_mult * step_size
update_params :: DLAParams -> Vec3 -> DLAParams
update_params params pos =
DLAParams { stickiness = (stickiness params),
death_rad = death_radius mir cmr imult ss omult,
starting_rad = new_srad,
min_inner_rad = mir,
inner_mult = imult,
outer_mult = omult,
curr_max_rad = cmr,
epsilon = (epsilon params),
step_size = ss,
rng_seed = (rng_seed params),
num_particles = (num_particles params)}
where
cmr = max (curr_max_rad params) (vecNorm pos)
mir = (min_inner_rad params)
imult = (inner_mult params)
ss = (step_size params)
omult = (outer_mult params)
new_srad = starting_radius mir cmr imult ss
--
-- walk a single particle
--
walk_particle :: DLAParams -> Vec3 -> DLANode -> Int
-> DLAMonad (Maybe (DLAParams, DLANode))
walk_particle params pos kdt n = do
1 . generate a random vector of length step_size
step <- randVec (step_size params)
2 . walk current position to new position using step
pos' <- return $ vecAdd pos step
3 . compute norm of new position ( used to see if it wandered too far )
distance <- return $ vecNorm pos'
4 . check if the move from pos to pos ' will collide with any known
-- particles already part of the aggregate
collide <- return $ kdtCollisionDetect kdt pos pos' (epsilon params)
5 . sample to see if it sticks
doesStick <- sticks params
6 . termination test : did we collide with one or more members of the
-- aggregate, and if so, did we stick?
termTest <- return $ (length collide) > 0 && doesStick
7 . have we walked into the death zone ?
deathTest <- return (distance > (death_rad params))
-- check termination test
case termTest of
-- yes! so return the updated parameters and the kdtree with the
-- new particle added.
True -> return $ Just (update_params params pos',
kdtAddPoints [(pos',n)] kdt)
-- no termination... check death test
False -> case deathTest of
-- wandered into the zone of no return. toss the particle,
-- return nothing and let the caller restart a new one.
True -> return Nothing
-- still good, keep walking
False -> walk_particle params pos' kdt n
--
-- initialize the world with a point at the origin
--
initialize_world :: DLAMonad DLANode
initialize_world = do
return $ kdtAddPoints [(Vec3 0.0 0.0 0.0, 0)] newKDTree
--
one step : generate a new particle and walk it
--
singleStep :: DLAParams -> DLANode -> Int
-> DLAMonad (DLAParams, DLANode)
singleStep params kdt n = do
sv <- randVec (starting_rad params)
newp <- walk_particle params sv kdt n
case newp of
Just p -> return p
Nothing -> singleStep params kdt n
nsteps :: DLAParams -> DLANode -> Int
-> DLAMonad (DLAParams, DLANode)
nsteps params kdt 0 = do return $ (params,kdt)
nsteps params kdt n = do
(params',kdt') <- singleStep params kdt ((num_particles params)+1-n)
nsteps params' kdt' (n-1)
driver :: DLAParams -> DLAMonad (DLAParams, DLANode)
driver params = do
t <- initialize_world
(parms, t') <- nsteps params t (num_particles params)
return (parms, t')
--
-- sanity check arguments to see if we have enough
--
validateArgs :: [String] -> IO ()
validateArgs s = do
if (length s < 2) then do putStrLn "Must specify config file and output file names."
exitFailure
else do return ()
--
-- main
--
main :: IO ()
main = do
args <- getArgs
validateArgs args
configFile <- return $ head args
outputFile <- return $ head (tail args)
params <- readParameters configFile
((params', t'), rngState) <- return $ runRmonad (driver params)
(pureMT (Prelude.fromIntegral $ rng_seed params))
dumpKDTree t' outputFile
return ()
| null | https://raw.githubusercontent.com/mjsottile/publicstuff/46fccc93cc62eb9de46186f53012381750fbb17b/dla3d/unoptimized-haskell/DLA/Driver.hs | haskell |
draw a random number and see if the particle sticks
where does a particle start given the step size, multipliers, and current
size of the aggregate
where does a particle die given the current state of things
walk a single particle
particles already part of the aggregate
aggregate, and if so, did we stick?
check termination test
yes! so return the updated parameters and the kdtree with the
new particle added.
no termination... check death test
wandered into the zone of no return. toss the particle,
return nothing and let the caller restart a new one.
still good, keep walking
initialize the world with a point at the origin
sanity check arguments to see if we have enough
main
| | diffusion limited aggregation , take 1
mjsottile\@computer.org
import DLA.Vec3
import DLA.KDTree
import DLA.Rmonad
import DLA.Params
import DLA.ConfigurationReader
import Debug.Trace
import System.Exit
import System.Environment (getArgs)
import System.Random.Mersenne.Pure64
type DLANode = KDTreeNode Int
sticks :: DLAParams -> DLAMonad Bool
sticks params = do
d <- nextF 1.0
return $ d < (stickiness params)
starting_radius :: Double -> Double -> Double -> Double -> Double
starting_radius min_inner_radius curr_max_radius inner_mult step_size =
max min_inner_radius (curr_max_radius + inner_mult * step_size)
death_radius :: Double -> Double -> Double -> Double -> Double -> Double
death_radius min_inner_radius curr_max_radius inner_mult step_size outer_mult =
(starting_radius min_inner_radius curr_max_radius inner_mult step_size) +
outer_mult * step_size
update_params :: DLAParams -> Vec3 -> DLAParams
update_params params pos =
DLAParams { stickiness = (stickiness params),
death_rad = death_radius mir cmr imult ss omult,
starting_rad = new_srad,
min_inner_rad = mir,
inner_mult = imult,
outer_mult = omult,
curr_max_rad = cmr,
epsilon = (epsilon params),
step_size = ss,
rng_seed = (rng_seed params),
num_particles = (num_particles params)}
where
cmr = max (curr_max_rad params) (vecNorm pos)
mir = (min_inner_rad params)
imult = (inner_mult params)
ss = (step_size params)
omult = (outer_mult params)
new_srad = starting_radius mir cmr imult ss
walk_particle :: DLAParams -> Vec3 -> DLANode -> Int
-> DLAMonad (Maybe (DLAParams, DLANode))
walk_particle params pos kdt n = do
1 . generate a random vector of length step_size
step <- randVec (step_size params)
2 . walk current position to new position using step
pos' <- return $ vecAdd pos step
3 . compute norm of new position ( used to see if it wandered too far )
distance <- return $ vecNorm pos'
4 . check if the move from pos to pos ' will collide with any known
collide <- return $ kdtCollisionDetect kdt pos pos' (epsilon params)
5 . sample to see if it sticks
doesStick <- sticks params
6 . termination test : did we collide with one or more members of the
termTest <- return $ (length collide) > 0 && doesStick
7 . have we walked into the death zone ?
deathTest <- return (distance > (death_rad params))
case termTest of
True -> return $ Just (update_params params pos',
kdtAddPoints [(pos',n)] kdt)
False -> case deathTest of
True -> return Nothing
False -> walk_particle params pos' kdt n
initialize_world :: DLAMonad DLANode
initialize_world = do
return $ kdtAddPoints [(Vec3 0.0 0.0 0.0, 0)] newKDTree
one step : generate a new particle and walk it
singleStep :: DLAParams -> DLANode -> Int
-> DLAMonad (DLAParams, DLANode)
singleStep params kdt n = do
sv <- randVec (starting_rad params)
newp <- walk_particle params sv kdt n
case newp of
Just p -> return p
Nothing -> singleStep params kdt n
nsteps :: DLAParams -> DLANode -> Int
-> DLAMonad (DLAParams, DLANode)
nsteps params kdt 0 = do return $ (params,kdt)
nsteps params kdt n = do
(params',kdt') <- singleStep params kdt ((num_particles params)+1-n)
nsteps params' kdt' (n-1)
driver :: DLAParams -> DLAMonad (DLAParams, DLANode)
driver params = do
t <- initialize_world
(parms, t') <- nsteps params t (num_particles params)
return (parms, t')
validateArgs :: [String] -> IO ()
validateArgs s = do
if (length s < 2) then do putStrLn "Must specify config file and output file names."
exitFailure
else do return ()
main :: IO ()
main = do
args <- getArgs
validateArgs args
configFile <- return $ head args
outputFile <- return $ head (tail args)
params <- readParameters configFile
((params', t'), rngState) <- return $ runRmonad (driver params)
(pureMT (Prelude.fromIntegral $ rng_seed params))
dumpKDTree t' outputFile
return ()
|
d65696b986ed67c50287e52738899dc0f5ffbc8bd781356931824fe0761bbdbc | robert-stuttaford/bridge | debug.clj | (ns bridge.web.debug
(:require [bridge.web.template :as web.template]
[buddy.auth :as buddy]
[clojure.pprint :as pprint]
[clojure.string :as str]
[bridge.config :as config]))
(defn pprint-str [val]
(binding [clojure.pprint/*print-right-margin* 120]
(with-out-str (pprint/pprint val))))
(defn debug-pre [val]
[:pre {:style {:white-space "pre-nowrap"
:font-family "Fira Code"}}
(pprint-str val)])
(defn system [req]
(if-not (buddy/authenticated? req)
(buddy/throw-unauthorized)
(web.template/hiccup-response
[:section.section
[:h1.title "System"]
(debug-pre (config/system))
[:hr]
[:h1.title "Request"]
(debug-pre (->> (-> req
(dissoc :body :cookies :session/key)
(update :headers dissoc "cookie"))
(reduce-kv (fn [m k v]
(cond-> m
(some? v) (assoc k v))) {})
(into (sorted-map))))])))
(def routes
{:routes
'{"/system" [:system]}
:handlers
{:system #'system}})
| null | https://raw.githubusercontent.com/robert-stuttaford/bridge/867d81354457c600cc5c25917de267a8e267c853/src/bridge/web/debug.clj | clojure | (ns bridge.web.debug
(:require [bridge.web.template :as web.template]
[buddy.auth :as buddy]
[clojure.pprint :as pprint]
[clojure.string :as str]
[bridge.config :as config]))
(defn pprint-str [val]
(binding [clojure.pprint/*print-right-margin* 120]
(with-out-str (pprint/pprint val))))
(defn debug-pre [val]
[:pre {:style {:white-space "pre-nowrap"
:font-family "Fira Code"}}
(pprint-str val)])
(defn system [req]
(if-not (buddy/authenticated? req)
(buddy/throw-unauthorized)
(web.template/hiccup-response
[:section.section
[:h1.title "System"]
(debug-pre (config/system))
[:hr]
[:h1.title "Request"]
(debug-pre (->> (-> req
(dissoc :body :cookies :session/key)
(update :headers dissoc "cookie"))
(reduce-kv (fn [m k v]
(cond-> m
(some? v) (assoc k v))) {})
(into (sorted-map))))])))
(def routes
{:routes
'{"/system" [:system]}
:handlers
{:system #'system}})
|
|
63fb313b49ab1f5b8501936c90f1b80227411ce6cb90b76272d3cf90e8e6d7d4 | astrada/google-drive-ocamlfuse | testBuffering.ml | open OUnit
open GapiMonad
let print_array arr =
let len = Bigarray.Array1.dim arr in
let r = Bytes.make len ' ' in
for i = 0 to len - 1 do
r.[i] <- arr.{i}
done;
Bytes.to_string r
let session =
{
GapiConversation.Session.curl = GapiCurl.Initialized;
config = GapiConfig.default;
auth = GapiConversation.Session.NoAuth;
cookies = [];
etag = "";
}
let test_with_lock_m () =
let counter1 = ref 0 in
let counter2 = ref 0 in
let x = ref false in
let mutex = Mutex.create () in
let switch _ =
Utils.with_lock_m mutex
( if !x = false then (
x := true;
counter1 := !counter1 + 1 )
else counter2 := !counter2 + 1;
SessionM.return () )
in
let tq = Queue.create () in
for _ = 1 to 10 do
let t = Thread.create switch session in
Queue.push t tq
done;
Queue.iter (fun t -> Thread.join t) tq;
assert_equal ~printer:string_of_bool true !x;
assert_equal ~printer:string_of_int 1 !counter1;
assert_equal ~printer:string_of_int 9 !counter2
let test_read_block () =
let remote_id = "test" in
let resource_size = 24L in
let pool_size = 160 in
let block_size = 16 in
let stream_block_size = 8 in
let fill_array offset arr =
if offset = 0L then (
Bigarray.Array1.fill arr 'a';
arr.{stream_block_size} <- 'c' )
else Bigarray.Array1.fill arr 'b';
SessionM.return ()
in
let memory_buffers = Buffering.MemoryBuffers.create block_size pool_size in
let destination =
Bigarray.Array1.create Bigarray.char Bigarray.c_layout
(Int64.to_int resource_size)
in
let init_subs i =
Bigarray.Array1.sub destination (i * stream_block_size) stream_block_size
in
let dest_arrs = Array.init 3 init_subs in
let stream buffer offset =
Buffering.MemoryBuffers.read_block remote_id offset resource_size
(fun start_pos block_buffer -> fill_array start_pos block_buffer)
~dest_arr:buffer memory_buffers
in
for i = 0 to (Int64.to_int resource_size / stream_block_size) - 1 do
let offset = Int64.of_int (i * stream_block_size) in
stream dest_arrs.(i) offset session |> ignore;
let result =
let arr =
Bigarray.Array1.create Bigarray.char Bigarray.c_layout stream_block_size
in
if i = 2 then Bigarray.Array1.fill arr 'b'
else (
Bigarray.Array1.fill arr 'a';
if i = 1 then arr.{0} <- 'c' );
arr
in
assert_equal ~printer:print_array result dest_arrs.(i)
done
let test_thread_m () =
let start_thread_m f s =
let t = Thread.create f s in
(t, s)
in
let b = ref false in
let action_m s =
b := true;
((), s)
in
let t = start_thread_m action_m session |> fst in
Thread.join t;
assert_equal ~printer:string_of_bool true !b
let suite =
"Buffering test"
>::: [
"test_with_lock_m" >:: test_with_lock_m;
"test_read_block" >:: test_read_block;
"test_thread_m" >:: test_thread_m;
]
| null | https://raw.githubusercontent.com/astrada/google-drive-ocamlfuse/7e22d03d6faeb76fb5b9306cf9a3562abad16461/test/testBuffering.ml | ocaml | open OUnit
open GapiMonad
let print_array arr =
let len = Bigarray.Array1.dim arr in
let r = Bytes.make len ' ' in
for i = 0 to len - 1 do
r.[i] <- arr.{i}
done;
Bytes.to_string r
let session =
{
GapiConversation.Session.curl = GapiCurl.Initialized;
config = GapiConfig.default;
auth = GapiConversation.Session.NoAuth;
cookies = [];
etag = "";
}
let test_with_lock_m () =
let counter1 = ref 0 in
let counter2 = ref 0 in
let x = ref false in
let mutex = Mutex.create () in
let switch _ =
Utils.with_lock_m mutex
( if !x = false then (
x := true;
counter1 := !counter1 + 1 )
else counter2 := !counter2 + 1;
SessionM.return () )
in
let tq = Queue.create () in
for _ = 1 to 10 do
let t = Thread.create switch session in
Queue.push t tq
done;
Queue.iter (fun t -> Thread.join t) tq;
assert_equal ~printer:string_of_bool true !x;
assert_equal ~printer:string_of_int 1 !counter1;
assert_equal ~printer:string_of_int 9 !counter2
let test_read_block () =
let remote_id = "test" in
let resource_size = 24L in
let pool_size = 160 in
let block_size = 16 in
let stream_block_size = 8 in
let fill_array offset arr =
if offset = 0L then (
Bigarray.Array1.fill arr 'a';
arr.{stream_block_size} <- 'c' )
else Bigarray.Array1.fill arr 'b';
SessionM.return ()
in
let memory_buffers = Buffering.MemoryBuffers.create block_size pool_size in
let destination =
Bigarray.Array1.create Bigarray.char Bigarray.c_layout
(Int64.to_int resource_size)
in
let init_subs i =
Bigarray.Array1.sub destination (i * stream_block_size) stream_block_size
in
let dest_arrs = Array.init 3 init_subs in
let stream buffer offset =
Buffering.MemoryBuffers.read_block remote_id offset resource_size
(fun start_pos block_buffer -> fill_array start_pos block_buffer)
~dest_arr:buffer memory_buffers
in
for i = 0 to (Int64.to_int resource_size / stream_block_size) - 1 do
let offset = Int64.of_int (i * stream_block_size) in
stream dest_arrs.(i) offset session |> ignore;
let result =
let arr =
Bigarray.Array1.create Bigarray.char Bigarray.c_layout stream_block_size
in
if i = 2 then Bigarray.Array1.fill arr 'b'
else (
Bigarray.Array1.fill arr 'a';
if i = 1 then arr.{0} <- 'c' );
arr
in
assert_equal ~printer:print_array result dest_arrs.(i)
done
let test_thread_m () =
let start_thread_m f s =
let t = Thread.create f s in
(t, s)
in
let b = ref false in
let action_m s =
b := true;
((), s)
in
let t = start_thread_m action_m session |> fst in
Thread.join t;
assert_equal ~printer:string_of_bool true !b
let suite =
"Buffering test"
>::: [
"test_with_lock_m" >:: test_with_lock_m;
"test_read_block" >:: test_read_block;
"test_thread_m" >:: test_thread_m;
]
|
|
1f5783153482425cd063c37df0235b6dc778131ba478b3b1d7f83227ed7697be | clojurecup2014/parade-route | teststm.clj | Copyright ( c ) . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
;
Author :
Simple test of the STM .
( f1 )
(ns clojure.teststm)
(defn sleep [time-ms] (System.Threading.Thread/Sleep time-ms))
(def a (ref #{}))
(def b (ref #{}))
(def cycle-continue true)
(defn make-future [id]
(future
(try
(loop [n 0]
;; join the party
(dosync
(alter a conj id)
(alter b conj id))
;; validate the refs
(dosync
(let [current-a @a
current-b @b]
(if (not (= current-a current-b))
(throw (Exception. (str (format "\n%s\n%s" current-a current-b)))))))
;; leave
(dosync
(alter a disj id)
(alter b disj id))
(if cycle-continue
(recur (inc n))))
(catch Exception ex
(def cycle-continue false)
(sleep 100)
(println ex)))))
; (f1 3 30)
should see 30 dots , then done , unless an error occurs . Then you will see an error message printed .
(defn f1 [nagts dur]
(future
(do
(def a (ref #{}))
(def b (ref #{}))
(def cycle-continue true)
(let [n-agents nagts
duration dur
futures (doall (map make-future (range n-agents)))]
(loop [i 0]
(sleep 1000)
(print ".") (flush)
(if (and (<= i duration) cycle-continue)
(recur (inc i)))))
(println "done")
(def cycle-continue false))))
| null | https://raw.githubusercontent.com/clojurecup2014/parade-route/adb2e1ea202228e3da07902849dee08f0bb8d81c/Assets/Clojure/Internal/Plugins/clojure/samples/stm/teststm.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
join the party
validate the refs
leave
(f1 3 30) | Copyright ( c ) . All rights reserved .
Author :
Simple test of the STM .
( f1 )
(ns clojure.teststm)
(defn sleep [time-ms] (System.Threading.Thread/Sleep time-ms))
(def a (ref #{}))
(def b (ref #{}))
(def cycle-continue true)
(defn make-future [id]
(future
(try
(loop [n 0]
(dosync
(alter a conj id)
(alter b conj id))
(dosync
(let [current-a @a
current-b @b]
(if (not (= current-a current-b))
(throw (Exception. (str (format "\n%s\n%s" current-a current-b)))))))
(dosync
(alter a disj id)
(alter b disj id))
(if cycle-continue
(recur (inc n))))
(catch Exception ex
(def cycle-continue false)
(sleep 100)
(println ex)))))
should see 30 dots , then done , unless an error occurs . Then you will see an error message printed .
(defn f1 [nagts dur]
(future
(do
(def a (ref #{}))
(def b (ref #{}))
(def cycle-continue true)
(let [n-agents nagts
duration dur
futures (doall (map make-future (range n-agents)))]
(loop [i 0]
(sleep 1000)
(print ".") (flush)
(if (and (<= i duration) cycle-continue)
(recur (inc i)))))
(println "done")
(def cycle-continue false))))
|
ce3f04ac2e2ce2ec075eee2bb83c5b9b023abc09714f7e469e35e5845d55a4ca | program-repair-project/bug-localizer | bugDesc.ml | module F = Format
type t = {
program : string;
compiler_type : string;
test_cases : string list;
test_time_limit : int;
}
let find : string -> Yojson.Safe.t -> Yojson.Safe.t =
fun name -> function
| `Assoc l -> List.find (function n, _ -> n = name) l |> snd
| _ -> raise Not_found
let to_string = function `String s -> s | _ -> raise Not_found
let to_int = function `Int i -> i | _ -> raise Not_found
let compiler_type_of desc = find "compiler" desc |> find "type" |> to_string
let program_of desc = find "program" desc |> to_string
let test_cases_of desc =
let test_info = find "test-harness" desc in
let num_of_passing = find "passing" test_info |> to_int in
let num_of_failing = find "failing" test_info |> to_int in
List.init num_of_passing (fun n -> "p" ^ string_of_int (n + 1))
@ List.init num_of_failing (fun n -> "n" ^ string_of_int (n + 1))
let test_limit_of desc = find "test-harness" desc |> find "time-limit" |> to_int
let read work_dir =
let json =
let fn = Filename.concat work_dir "bug_desc.json" in
if Sys.file_exists fn then Yojson.Safe.from_file fn
else
let fn = Filename.concat "/bugfixer" "bug_desc.json" in
if Sys.file_exists fn then Yojson.Safe.from_file fn
else failwith "Bug description not found"
in
Logging.log "Bug desc: %a" Yojson.Safe.pp json;
let program = program_of json in
let compiler_type = compiler_type_of json in
let test_cases = test_cases_of json in
let test_time_limit = test_limit_of json in
{ program; compiler_type; test_cases; test_time_limit }
let pp_test_cases fmt l =
F.fprintf fmt "[";
List.iter (fun x -> F.fprintf fmt "%s," x) l;
F.fprintf fmt "]"
let pp fmt desc =
F.fprintf fmt
"{program: %s, compiler_type: %s, test_cases: %a, test_time_limit: %d}"
desc.program desc.compiler_type pp_test_cases desc.test_cases
desc.test_time_limit
| null | https://raw.githubusercontent.com/program-repair-project/bug-localizer/370c4b42d14fca67337683eb819b2e2b60f4ed14/src/bugDesc.ml | ocaml | module F = Format
type t = {
program : string;
compiler_type : string;
test_cases : string list;
test_time_limit : int;
}
let find : string -> Yojson.Safe.t -> Yojson.Safe.t =
fun name -> function
| `Assoc l -> List.find (function n, _ -> n = name) l |> snd
| _ -> raise Not_found
let to_string = function `String s -> s | _ -> raise Not_found
let to_int = function `Int i -> i | _ -> raise Not_found
let compiler_type_of desc = find "compiler" desc |> find "type" |> to_string
let program_of desc = find "program" desc |> to_string
let test_cases_of desc =
let test_info = find "test-harness" desc in
let num_of_passing = find "passing" test_info |> to_int in
let num_of_failing = find "failing" test_info |> to_int in
List.init num_of_passing (fun n -> "p" ^ string_of_int (n + 1))
@ List.init num_of_failing (fun n -> "n" ^ string_of_int (n + 1))
let test_limit_of desc = find "test-harness" desc |> find "time-limit" |> to_int
let read work_dir =
let json =
let fn = Filename.concat work_dir "bug_desc.json" in
if Sys.file_exists fn then Yojson.Safe.from_file fn
else
let fn = Filename.concat "/bugfixer" "bug_desc.json" in
if Sys.file_exists fn then Yojson.Safe.from_file fn
else failwith "Bug description not found"
in
Logging.log "Bug desc: %a" Yojson.Safe.pp json;
let program = program_of json in
let compiler_type = compiler_type_of json in
let test_cases = test_cases_of json in
let test_time_limit = test_limit_of json in
{ program; compiler_type; test_cases; test_time_limit }
let pp_test_cases fmt l =
F.fprintf fmt "[";
List.iter (fun x -> F.fprintf fmt "%s," x) l;
F.fprintf fmt "]"
let pp fmt desc =
F.fprintf fmt
"{program: %s, compiler_type: %s, test_cases: %a, test_time_limit: %d}"
desc.program desc.compiler_type pp_test_cases desc.test_cases
desc.test_time_limit
|
|
7ebf379c976cfbc45a9911ba0b174ff0e68df0e0489d313d415f617316da2a84 | ucsd-progsys/liquidhaskell | ExactGADT7.hs | {-@ LIQUID "--expect-any-error" @-}
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
{-@ LIQUID "--prune-unsorted" @-}
{-@ LIQUID "--no-adt" @-}
{-@ LIQUID "--exact-data-con" @-}
module ExactGADT7 where
data Some a where
SomeBool :: Bool -> Some Bool
SomeInt :: Int -> Some Int
{-@ measure isBool @-}
isBool :: Some a -> Bool
isBool (SomeBool _) = True
isBool (SomeInt _) = False
{-@ type Thing = { v: Some Bool | isBool v } @-}
{-@ a :: Thing @-}
a = SomeBool True
{-@ b :: {v: Some Int | isBool v} @-}
b = SomeInt 5
| null | https://raw.githubusercontent.com/ucsd-progsys/liquidhaskell/f46dbafd6ce1f61af5b56f31924c21639c982a8a/tests/neg/ExactGADT7.hs | haskell | @ LIQUID "--expect-any-error" @
# LANGUAGE GADTs #
@ LIQUID "--prune-unsorted" @
@ LIQUID "--no-adt" @
@ LIQUID "--exact-data-con" @
@ measure isBool @
@ type Thing = { v: Some Bool | isBool v } @
@ a :: Thing @
@ b :: {v: Some Int | isBool v} @ | # LANGUAGE KindSignatures #
module ExactGADT7 where
data Some a where
SomeBool :: Bool -> Some Bool
SomeInt :: Int -> Some Int
isBool :: Some a -> Bool
isBool (SomeBool _) = True
isBool (SomeInt _) = False
a = SomeBool True
b = SomeInt 5
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.