_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
|
---|---|---|---|---|---|---|---|---|
622650e25752831b27f5d42cb9ba48a64c001fef6cd6827ed00861389a222438 | ekmett/unboxed | Natural.hs | {-# Language MagicHash #-}
module Unboxed.Natural
( Natural#
) where
import Unboxed.Internal.Natural
| null | https://raw.githubusercontent.com/ekmett/unboxed/e4c6ca80fb8946b1abfe595ba1c36587a33931db/src/Unboxed/Natural.hs | haskell | # Language MagicHash # | module Unboxed.Natural
( Natural#
) where
import Unboxed.Internal.Natural
|
f3eb994a5c4f4a38a3d2213397182cf13847923d622bbab87b7aaf8ad591bc7b | acl2/acl2 | parallel.lisp | ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp
Copyright ( C ) 2023 , Regents of the University of Texas
This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright
( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 .
; This program is free software; you can redistribute it and/or modify
; it under the terms of the LICENSE file distributed with ACL2.
; 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
; LICENSE for more details.
Written by : and J Strother Moore
email : and
Department of Computer Science
University of Texas at Austin
Austin , TX 78712 U.S.A.
We thank for contributing an initial version of this file .
(in-package "ACL2")
; Section: To Consider. The following might be good to address as time
; permits.
; Change the piece of work list to an array (perhaps result in a faster
; library because of less garbage.
; Make removing closures from the queue destructive, in particular with
; regard to early termination.
; Recycle locks, perhaps for example in wait-on-condition-variable-lockless.
See this same comment in parallel-raw.lisp .
; Provide a way for the user to modify *core-count*, including inside the
; ACL2 loop. If we allow for changing *core-count*, then we need to think
; about allowing for changing variables that depend on it, e.g.,
; *unassigned-and-active-work-count-limit* (perhaps by changing them to
; zero-ary functions). If you consider making such a change, then think
; about how functions cpu-core-count and cpu-core-count-raw might be
; relevant.
Modify the coefficient ( currently 2 ) in the definition of
; *unassigned-and-active-work-count-limit*. Evaluate such modifications with
; testing, of course.
; End of Section "To Consider".
(defun set-parallel-execution-fn (val ctx state)
(declare (xargs :guard (member-eq val '(t nil :bogus-parallelism-ok))))
(cond
((eq (f-get-global 'parallel-execution-enabled state)
val)
(pprogn (observation ctx
"No change in enabling of parallel execution.")
(value nil)))
(t
#-acl2-par
(er soft ctx
"Parallelism can only be enabled in CCL, threaded SBCL, or Lispworks. ~
~ Additionally, the feature :ACL2-PAR must be set when compiling ~
ACL2 (for example, by using `make' with argument `ACL2_PAR=t'). ~
Either the current Lisp is neither CCL nor threaded SBCL nor ~
Lispworks, or this feature is missing. Consequently, parallelism ~
will remain disabled. Note that you can submit parallelism ~
primitives at the top level when parallel execution is disabled, ~
although they will not result in any parallel execution.~%")
#+acl2-par
(let ((observation-string
(case val
((nil)
"Disabling parallel execution. Parallelism primitives may ~
still be used, but during execution they will degrade to ~
their serial equivalents.")
((t)
"Parallel execution is enabled, but parallelism primitives may ~
only be called within function definitions or macro top-level, ~
not at the top level of the ACL2 read-eval-print loop. See ~
:DOC parallelism-at-the-top-level.")
(otherwise ; :bogus-parallelism-ok
"Parallel execution is enabled. Parallelism primitives may be ~
called directly in the top-level loop, but without use of the ~
macro top-level, they will execute serially. See :DOC ~
parallelism-at-the-top-level."))))
(pprogn
(f-put-global 'parallel-execution-enabled val state)
(observation ctx observation-string)
(value val))))))
(defmacro set-parallel-execution (value)
; Parallelism blemish: cause an error if the user tries to go into a state
; where waterfall-parallelism is enabled but parallel-execution is disabled.
(declare (xargs :guard (member-equal value
'(t 't nil 'nil
:bogus-parallelism-ok
':bogus-parallelism-ok))))
`(let ((val ,value)
(ctx 'set-parallel-execution))
(set-parallel-execution-fn
(cond ((consp val) (cadr val))
(t val))
ctx
state)))
(defun waterfall-printing-value-for-parallelism-value (value)
(declare (xargs :guard (member-eq value *waterfall-parallelism-values*)))
(cond ((eq value nil)
:full)
((eq value :full)
:very-limited)
((eq value :top-level)
:very-limited)
((eq value :resource-based)
:very-limited)
((eq value :resource-and-timing-based)
:very-limited)
(t
(assert$ (eq value :pseudo-parallel)
:very-limited))))
Parallelism wart : figure out if : bdd hints are supported . Given the call of
; error-in-parallelism-mode@par in waterfall-step, it seems that they might not
be ; yet , regressions may have passed with them . One possible outcome : If
; tests fail for contributed book directory books/bdd/, you might just modify
translate - bdd - hint to cause a nice error if waterfall parallelism is enabled ,
; and also mention that (once again) in :doc
unsupported - waterfall - parallelism - features . Note that bdd - clause might be
the function that actually performs the bdd hint , and that bdd - clause does n't
return state . So , aside from the place in waterfall - step , bdd hints might be
; fine.
(defun print-set-waterfall-parallelism-notice (val print-val state)
; Warning: This function should only be called inside the ACL2 loop, because of
; the calls of observation-cw.
(declare (xargs :guard (and (member-eq val *waterfall-parallelism-values*)
(keywordp print-val))))
(let ((str
(case val
((nil)
"Disabling parallel execution of the waterfall.")
(:full
"Parallelizing the proof of every subgoal.")
(:top-level
"Parallelizing the proof of top-level subgoals only.")
(:pseudo-parallel
"Running the version of the waterfall prepared for parallel ~
execution (stateless). However, we will execute this version of ~
the waterfall serially.")
(:resource-and-timing-based
"Parallelizing the proof of every subgoal that was determined to ~
take a non-trivial amount of time in a previous proof attempt.")
(otherwise ; :resource-based
"Parallelizing the proof of every subgoal, as long as CPU core ~
resources are available."))))
; Keep the following ending "~%" in sync with set-waterfall-parallelism.
(observation nil
"~@0 Setting waterfall-parallelism to ~s1. Setting ~
waterfall-printing to ~s2 (see :DOC ~
set-waterfall-printing).~%"
str
(symbol-name val)
(symbol-name print-val))))
(defun check-for-no-override-hints (ctx state)
Although this macro is intended for # + acl2 - par , we need it unconditionally
; because it is called in set-waterfall-parallelism, which might be called
outside ACL2(p ) ; see the note about a call of observation in
; set-waterfall-parallelism-fn.
(let ((wrld (w state)))
(cond
((and (not (cdr (assoc-eq 'hacks-enabled
(table-alist 'waterfall-parallelism-table
wrld))))
(cdr (assoc-eq :override (table-alist 'default-hints-table
wrld))))
(er soft ctx
; Override hints must be removed because set-waterfall-parallelism performs a
; defattach, which spawns some proof effort. If there are override-hints
; available for use during this proof, apply-override-hints will see them and
; attempt to use them. Since override-hints are not permitted without enabling
; waterfall-parallelism-hacks, in this case, we must cause an error.
"Before changing the status of waterfall-parallelism, either (1) ~
override hints must be removed from the default-hints-table or (2) ~
waterfall-parallelism hacks must be enabled. (1) can be achieved ~
by calling ~x0. (2) can be achieved by calling ~x1."
'(set-override-hints nil)
'(set-waterfall-parallelism-hacks-enabled t)))
(t (value nil)))))
(defun set-waterfall-parallelism-fn (val ctx state)
(cond
((eq val (f-get-global 'waterfall-parallelism state))
(pprogn (observation ctx
"Ignoring call to set-waterfall-parallelism since ~
the new value is the same as the current value.~%~%")
(value :ignored)))
(t
(let ((val (if (eq val t) ; t is a alias for :resource-based
:resource-based
val)))
(er-progn
; We check for override hints even when #-acl2-par, to avoid being surprised by
an error when the same proof development is encountered with # + acl2 - par . But
we skip the check if there is no change ( see GitHub Issue # 1171 ) or we are
; turning off waterfall-parallelism.
(cond ((or (null val)
(equal val (f-get-global 'waterfall-parallelism state)))
(value nil))
(t (check-for-no-override-hints ctx state)))
(cond
((member-eq val *waterfall-parallelism-values*)
#+acl2-par
(cond
((null (f-get-global 'parallel-execution-enabled state))
(er soft ctx
"Parallel execution must be enabled before enabling ~
waterfall parallelism. See :DOC set-parallel-execution"))
((and val (f-get-global 'gstackp state))
(er soft ctx
"You must disable brr (e.g., with :BRR NIL) before turning ~
on waterfall-parallelism. See :DOC ~
unsupported-waterfall-parallelism-features."))
(t
; One might be tempted to insert (mf-multiprocessing val) here. However, in
; ACL2(hp) -- which is where this code is run -- we really want to keep
; multiprocessing on, since one can do multithreaded computations (e.g., with
; pand) even with waterfall-parallelism disabled.
(progn$
(and val
; We avoid a possible hard error, e.g. from (mini-proveall), when parallelism
; and accumulated-persistence are both turned on. A corresponding bit of code
; is in accumulated-persistence. We do similarly, just to be safe, for
; forward-chaining-reports; see also set-fc-criteria-fn.
Warning : Keep the following two wormhole - eval calls in sync with the
; definitions of accumulated-persistence and set-fc-criteria-fn.
(prog2$ (wormhole-eval
'accumulated-persistence
'(lambda (whs) (set-wormhole-data whs nil))
nil)
(wormhole-eval
'fc-wormhole
'(lambda (whs)
(set-wormhole-data
whs
(put-assoc-eq :CRITERIA nil
(wormhole-data whs))))
nil)))
#-acl2-loop-only
(funcall ; avoid undefined function warning
'initialize-dmr-interval-used)
(pprogn
(f-put-global 'waterfall-parallelism val state)
(value val)))))
#-acl2-par
; Once upon a time we issued an error here instead of an observation. In
response to feedback from , we have changed it to an observation so
; that users can call set-waterfall-parallelism inside books (presumably via
; make-event) without causing their certification to stop when using #-acl2-par
; builds of ACL2.
(pprogn
(observation ctx
; We make this an observation instead of a warning, because it's probably
; pretty obvious to the user whether they're using an image that was built with
; the acl2-par feature.
"Parallelism can only be enabled in CCL, threaded ~
SBCL, or Lispworks. Additionally, the feature ~
:ACL2-PAR must be set when compiling ACL2 (for ~
example, by using `make' with argument ~
`ACL2_PAR=t'). ~ Either the current Lisp is neither ~
CCL nor threaded SBCL nor Lispworks, or this ~
feature is missing. Consequently, this attempt to ~
set waterfall-parallelism to ~x0 will be ~
ignored.~%~%"
val)
(value :ignored)))
(t (er soft ctx
"Illegal value for set-waterfall-parallelism: ~x0. The legal ~
values are ~&1."
val *waterfall-parallelism-values*))))))))
; Parallelism blemish: make a macro via deflast called
; with-waterfall-parallelism that enables waterfall parallelism for a given
; form, in particular an event form like calls of defun and defthm. It's low
; priority, since it can easily be added as a book later -- though maybe it
; would be nice to have this as an event constructor, like with-output. But
while doing proofs with ACL2(hp ) , would have found this convenient .
(defmacro set-waterfall-parallelism1 (val)
`(let* ((val ,val)
(ctx 'set-waterfall-parallelism))
(er-let* ((val (set-waterfall-parallelism-fn val ctx state)))
(cond ((eq val :ignored)
(value val))
(t (let ((print-val
(waterfall-printing-value-for-parallelism-value
val)))
(pprogn
(print-set-waterfall-parallelism-notice
val print-val state)
(er-progn
(set-waterfall-printing-fn print-val ctx state)
(value (list val print-val))))))))))
(table saved-memoize-table nil nil
:guard
; It is tempting to install a table guard of (memoize-table-chk key val world).
; However, that won't work, for example because it will prohibit adding an
; entry to this table for a function that is currently memoized -- an act that
; is the point of this table! So instead we rely solely on the checks done
; when putting entries in memoize-table.
t)
(defmacro save-memo-table ()
'(with-output
:off (summary event)
(table saved-memoize-table
nil
(table-alist 'memoize-table world)
:clear)))
(defun clear-memo-table-events (alist acc)
(declare (xargs :guard (true-list-listp alist)))
(cond ((endp alist) acc)
(t (clear-memo-table-events
(cdr alist)
(cons `(table memoize-table ',(caar alist) nil)
acc)))))
(defmacro clear-memo-table ()
`(with-output
:off (summary event)
(make-event
(let ((alist (table-alist 'memoize-table (w state))))
(cons 'progn
(clear-memo-table-events alist nil))))))
(defmacro save-and-clear-memoization-settings ()
'(with-output
:off (summary event)
(progn (save-memo-table)
(clear-memo-table))))
(defun set-memo-table-events (alist acc)
(declare (xargs :guard (true-list-listp alist)))
(cond ((endp alist) acc)
(t (set-memo-table-events
(cdr alist)
(cons `(table memoize-table ',(caar alist) ',(cdar alist))
acc)))))
(defmacro restore-memoization-settings ()
`(with-output
:off (summary event)
(make-event
(let ((alist (table-alist 'saved-memoize-table (w state))))
(cons 'progn
(set-memo-table-events alist nil))))))
(defmacro set-waterfall-parallelism (val)
`(with-output
:off (summary event)
(make-event
(er-let*
((new-val (set-waterfall-parallelism1 ,val)))
(value (list 'value-triple (list 'quote new-val)))))))
(defun set-waterfall-printing-fn (val ctx state)
(cond ((member-eq val *waterfall-printing-values*)
#+acl2-par
(pprogn (f-put-global 'waterfall-printing val state)
(value val))
#-acl2-par
; See note about making this an observation instead of an error inside
; set-waterfall-parallelism.
(pprogn (observation ctx
"Customizing waterfall printing only makes ~
sense in the #+acl2-par builds of ACL2. ~
Consequently, this attempt to set ~
waterfall-printing to ~x0 will be ignored.~%~%"
val)
(value :invisible)))
(t (er soft ctx
"Illegal value for set-waterfall-printing: ~x0. The legal ~
values are ~&1."
val *waterfall-printing-values*))))
(defmacro set-waterfall-printing (val)
`(set-waterfall-printing-fn ,val 'set-waterfall-printing state))
(defun set-waterfall-parallelism-hacks-enabled-guard (wrld)
(or (ttag wrld)
(er hard nil
"Using waterfall parallelism hacks requires an active trust-tag. ~
Consider using (set-waterfall-parallelism-hacks-enabled! t). See ~
:DOC set-waterfall-parallelism-hacks-enabled for~ more~ ~
information.")))
(table waterfall-parallelism-table
nil nil :guard (set-waterfall-parallelism-hacks-enabled-guard world))
(defmacro set-waterfall-parallelism-hacks-enabled (val)
; One might consider using a state global to implement
set - waterfall - parallelism - hacks - enabled . But as points out , this
; macro can change whether or not a proof completes. So, we want this macro
; tied into the undoing mechanism; hence we use a table event.
(declare (xargs :guard (or (equal val t) (null val))))
`(table waterfall-parallelism-table 'hacks-enabled ,val))
(defmacro set-waterfall-parallelism-hacks-enabled! (val)
`(encapsulate
()
; Parallelism blemish: the following installation of ttag
; :waterfall-parallelism-hacks should probably be conditionalized upon val
being equal to t. Furthermore , perhaps the installation should also be
; conditionalized upon the non-existence of a prior ttag.
(defttag :waterfall-parallelism-hacks)
(set-waterfall-parallelism-hacks-enabled ,val)))
(defun caar-is-declarep (x)
; Recognizer for expressions x for which (car x) is of the form (declare ...).
(declare (xargs :guard t))
(and (consp x)
(consp (car x))
(eq (caar x) 'declare)))
(defun declare-granularity-p (x)
; We return true when x is of the form (declare (granularity <expr>)).
(declare (xargs :guard t))
(and (true-listp x)
(eql (length x) 2)
(eq (car x) 'declare)
(let ((gran-form (cadr x)))
(and (true-listp gran-form)
(eql (length gran-form) 2)
(eq (car gran-form) 'granularity)))))
(defun check-and-parse-for-granularity-form (x)
; X is a list of forms that may begin with a granularity declaration such as
( declare ( granularity ( < depth 5 ) ) ) . The return signature is ( erp msg
; granularity-form-exists granularity-form remainder-forms). If there is no
; declaration then we return (mv nil nil nil nil x). If there is error then we
; return (mv t an-error-message nil nil x). Otherwise we return (mv nil nil t
granularity - form ) ) .
; It is necessary to return whether the granularity form exists. If we did not
; do so, there would be no mechanism for distinguishing between a non-existent
; granularity form and one that was nil.
; A granularity form declaration is the only acceptable form of declaration.
; Some examples of unaccepted declarations are type and ignore declarations.
; We use this function in both the raw and acl2-loop definitions of plet to
; macroexpand away our granularity form, as part of our effort to ensure that
; pargs is logically the identity function.
(cond ((not (caar-is-declarep x))
(mv nil nil nil nil x))
((declare-granularity-p (car x))
(let* ((granularity-declaration (cadar x))
(granularity-form (cadr granularity-declaration)))
(mv nil nil t granularity-form (cdr x))))
(t
(mv t
"Within a parallelism primitive, a granularity form declaration ~
is the only acceptable form of declaration. Some examples of ~
unaccepted declarations are type and ignore declarations. See ~
:DOC granularity."
nil
nil
x))))
#+(or acl2-loop-only (not acl2-par))
(defmacro pargs (&rest forms)
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'pargs msg))
((or (and (equal (length forms) 1) (not gran-form-exists))
(and (equal (length forms) 2) gran-form-exists))
(let ((function-call (car remainder-forms)))
(if gran-form-exists
`(prog2$ ,gran-form ,function-call)
function-call)))
(t
(er hard 'pargs
"Pargs was passed the wrong number of arguments. Without a ~
granularity declaration, pargs takes one argument. With a ~
granularity declaration, pargs requires two arguments, the ~
first of which must be of the form ~x0. See :DOC pargs."
'(declare (granularity expr)))))))
#+(or acl2-loop-only (not acl2-par))
(defmacro plet (&rest forms)
(mv-let (erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'plet msg))
(gran-form-exists
`(prog2$ ,gran-form
(let ,@remainder-forms)))
(t `(let ,@remainder-forms)))))
(defun binary-pand (x y)
; Booleanized binary and.
(declare (xargs :guard t :mode :logic))
(and x y t))
#+(or acl2-loop-only (not acl2-par))
(defmacro pand (&rest forms)
We Booleanize pand so that it is consistent with por , which must be
; Booleanized (see :DOC por). Another nice thing about this Booleanization is
that it emphasizes that PAND differs from AND logically , which can raise
; awareness of a guard-related difference based on the impact of lazy
; evaluation.
; Since we use &rest, we know forms is a true-list.
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'pand msg))
((atom remainder-forms) t) ; (pand) == t
same as length = = 1
(list 'if (car remainder-forms) t nil)) ; booleanize
(gran-form-exists
(list 'prog2$
gran-form
(xxxjoin 'binary-pand remainder-forms)))
(t (xxxjoin 'binary-pand remainder-forms)))))
(defun binary-por (x y)
; Booleanized binary or.
(declare (xargs :guard t :mode :logic))
(if x t (if y t nil)))
#+(or acl2-loop-only (not acl2-par))
(defmacro por (&rest forms)
; Note that por must be Booleanized if we are to support early termination,
; i.e., so that any non-nil value can cause por to return.
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'por msg))
((atom remainder-forms) nil) ; (por) == nil
same as length = = 1
(list 'if (car remainder-forms) t nil))
(gran-form-exists
(list 'prog2$
gran-form
(xxxjoin 'binary-por remainder-forms)))
(t (xxxjoin 'binary-por remainder-forms)))))
(defun or-list (x)
(declare (xargs :guard (true-listp x) :mode :logic))
(if (endp x)
nil
(if (car x)
t
(or-list (cdr x)))))
(defun and-list (x)
(declare (xargs :guard (true-listp x) :mode :logic))
(if (endp x)
t
(and (car x)
(and-list (cdr x)))))
(defun cpu-core-count (state)
(declare (xargs :stobjs state :guard t))
#+(and (not acl2-loop-only) (not acl2-par))
(when (live-state-p state)
(return-from cpu-core-count
(mv 1 state)))
#+(and (not acl2-loop-only) acl2-par)
(when (live-state-p state)
(return-from cpu-core-count
(mv (if (and (f-boundp-global 'cpu-core-count state)
(posp (f-get-global 'cpu-core-count state)))
(core-count-raw nil (f-get-global 'cpu-core-count
state))
(core-count-raw 'core-count))
state)))
(mv-let (nullp val state)
(read-acl2-oracle state)
(declare (ignore nullp))
(mv val state)))
; Preliminary code for parallelizing the rewriter
; ; We now develop code for parallelizing calls to the arguments of a call of
; ; rewrite.
;
; ; WARNING! We believe that this approach has the following bug. If
; with - prover - time - limit is used , then the main thread ( which is the one
; ; calling waterfall-step) has a catch (implemented by the call there of
; ; catch-time-limit5) that will only catch throws to that tag from the SAME
; ; thread. We will get in trouble if a spawned thread's call of rewrite does
; ; such a throw.
;
; ; Warning: Moreover, if we use this code, consider modifying the
; ; rewrite-constant to store the value of :limit in
; ; rewrite-args-granularity-table. Otherwise, we have to go to the world with a
; ; potentially slow getprop every time we call rewrite-args-par-big-enough.
; ; Maybe that's just noise, but maybe it's expensive.
;
; ; We initially set the value of (the unique key) :limit to nil in
; ; rewrite-args-granularity-table, so that in fact we do not do such
; ; parallelization. But we leave this infrastructure in place (see comment "or
; ; try :limit" below) in case we want to experiment with such parallelization in
; ; the future.
;
# + acl2 - par
; (table rewrite-args-granularity-table nil nil
; :guard (and (eq key :limit)
; (or (null val) (natp val))))
;
# + acl2 - par
( table rewrite - args - granularity - table : limit nil ) ; or try : limit = 10
;
# + acl2 - par
( defun rewrite - args - par - big - enough - rec ( flg x bound acc )
;
; is true when x is a list of terms ; else x is a term . Returns a number by
; accumulating into acc , or t if that number would exceed bound . We assume
; that acc is < = bound .
;
( cond ( flg ; x is a list
; (cond ((null x)
acc )
; (t
; (let ((new-acc (rewrite-args-par-big-enough-rec
; nil (car x) bound acc)))
; (if (eq new-acc t)
; t
; (rewrite-args-par-big-enough-rec
; flg (cdr x) bound new-acc))))))
; ((variablep x)
acc )
; ((fquotep x)
acc )
( ( eql bound acc )
; t)
; ((flambdap (ffn-symb x))
; (let ((new-acc (rewrite-args-par-big-enough-rec
; nil (lambda-body (ffn-symb x)) bound (1+ acc))))
; (if (eq new-acc t)
; t
; (rewrite-args-par-big-enough-rec t (fargs x) bound new-acc))))
; (t (rewrite-args-par-big-enough-rec t (fargs x) bound (1+ acc)))))
;
# + acl2 - par
; (defun rewrite-args-par-big-enough (x wrld)
;
; ; If the limit is set to nil, the function returns nil. This allows the
; ; enabling and disabling of rewriting args in parallel.
;
; (let ((limit (cdr (assoc-eq :limit
; (table-alist
; 'rewrite-args-granularity-table
; wrld)))))
; (and limit (equal t (rewrite-args-par-big-enough-rec nil x limit 0)))))
;
; ; With the additions above, we can contemplate adding something like the
; ; following to the rewrite nest below. If we do that, then replace the call of
; ; rewrite-args in rewrite by the following:
;
; ; #-acl2-par
; ; rewrite-args
; ; #+acl2-par
; ; rewrite-args-par
;
# + acl2 - par
( defun rewrite - args - par ( args alist ; & extra formals
; rdepth
type - alist obj geneqv wrld state fnstack
; ancestors backchain-limit
simplify - clause - pot - lst rcnst )
( let ( ( pair ( rewrite - entry ( rewrite - args - par - rec args alist ) ) ) )
; (mv (car pair) (cdr pair))))
;
# + acl2 - par
( defun rewrite - args - par - rec ( args alist ; & extra formals
; rdepth
type - alist obj geneqv wrld state fnstack
; ancestors backchain-limit
simplify - clause - pot - lst rcnst )
;
; Note : In this function , the extra formal geneqv is actually a list of
; or nil denoting a list of .
;
; ; Unlike rewrite-args, we return (cons rewritten-args ttree) instead of
; ; (mv rewritten-args ttree).
;
( declare ( type ( unsigned - byte 29 ) rdepth ) )
; (cond ((f-big-clock-negative-p state)
( cons ( sublis - var - lst alist args )
; ttree))
; ((null args)
; (cons nil ttree))
; (t (plet
; (declare (granularity t)) ; should call rewrite-args-par-big-enough
( ( pair1
( mv - let ( term )
( rewrite - entry ( rewrite ( car args ) alist )
: ( car geneqv )
; :ttree nil)
( cons term ) ) )
( ( rewrite - entry
; (rewrite-args-par-rec (cdr args) alist (1+ bkptr))
: ( cdr geneqv ) ) ) )
( let * ( ( term ( car pair1 ) )
; (ttree1 (cdr pair1))
( rewritten - args ( car ) )
( ttree2 ( cdr pair2 ) ) )
; (cons (cons term rewritten-args)
; (cons-tag-trees ttree1 ttree2)))))))
; Preliminary code for parallelizing the rewriter.
; Note that the following code treats step-limits a little differently from how
; they are treated in the sequential version. If we keep this treatment, we
; should add a comment here and in decrement-step-limit suggesting that if we
; change either, then we should consider changing the other. Also note the
; commented out declare forms, which would be good to include (especially
important for GCL ) once spec - mv - let accepts them . And finally , note that as
of v6 - 2 , it is necessary to unmemoize the rewriter functions when running the
; rewriter in parallel in ACL2(hp) because memoization is not thread-safe.
; This unmemoization can perhaps be done by issuing a call of (unmemoize-all)
; in raw Lisp).
( defun rewrite - args ( args alist ; & extra formals
; rdepth step-limit
type - alist obj geneqv wrld state fnstack ancestors
; backchain-limit
simplify - clause - pot - lst rcnst )
;
; Note : In this function , the extra formal geneqv is actually a list of
; or nil denoting a list of .
;
( declare ( type ( unsigned - byte 29 ) rdepth )
( type ( signed - byte 30 ) step - limit ) )
; (the-mv
3
( signed - byte 30 )
; (cond ((null args)
; (mv step-limit nil ttree))
; (t (spec-mv-let
; (step-limit1 rewritten-arg ttree1)
; ( declare ( type ( signed - byte 30 ) step - limit1 ) )
( rewrite - entry ( rewrite ( car args ) alist )
: ( car geneqv ) )
; (mv-let
( step - limit2 rewritten - args ttree2 )
; (rewrite-entry (rewrite-args (cdr args) alist (1+ bkptr))
: ( cdr geneqv ) )
; ( declare ( type ( signed - byte 30 ) step - limit2 ) )
; (if t
( mv ( let * ( ( ( - step - limit step - limit1 ) )
( step - limit ( - step - ) ) )
( declare ( type ( signed - byte 30 ) steps1 step - limit ) )
; (cond ((>= step-limit 0)
; step-limit)
; ((step-limit-strictp state)
; (step-limit-error nil))
; (t -1)))
; (cons rewritten-arg rewritten-args)
; (cons-tag-trees ttree1 ttree2))
( mv 0
; nil
; nil))))))))
#+(or acl2-loop-only (not acl2-par))
(defmacro spec-mv-let (&whole spec-mv-let-form outer-vars computation body)
; Warning: Keep this in sync with the raw Lisp #+acl2-par definition of
; spec-mv-let.
; From the documentation, with annotations in brackets [..] showing names used
; in the code below:
; (spec-mv-let
; (v1 ... vn) ; bind distinct variables
; <spec> ; evaluate speculatively; return n values
; (mv-let ; [inner-let] or, use mv?-let if k=1 below
; (w1 ... wk) ; [inner-vars] bind distinct variables
; <eager> ; [evaluate eagerly
; (if <test> ; [test] use results from <spec> if true
; <typical-case> ; [true-branch] may mention v1 ... vn
; <abort-case>))) ; [false-branch] does not mention v1 ... vn
; In the logic, spec-mv-let is just mv?-let where the inner binding is also to
; be done with mv-let, but capture needs to be avoided in the following sense:
; no vi may occur in <test> or <abort-case>, because in the raw Lisp version,
; those values may not be available for those forms.
(case-match body
((inner-let inner-vars inner-body
('if test true-branch false-branch))
(cond
((not (member inner-let '(mv-let mv?-let mv-let@par)
:test 'eq))
(er hard! 'spec-mv-let
"Illegal form (expected inner let to bind with one of ~v0): ~x1. ~ ~
See :doc spec-mv-let."
'(mv-let mv?-let mv-let@par)
spec-mv-let-form))
((or (not (symbol-listp outer-vars))
(not (symbol-listp inner-vars))
(intersectp inner-vars outer-vars
:test 'eq))
(er hard! 'spec-mv-let
"Illegal spec-mv-let form: ~x0. The two bound variable lists ~
must be disjoint true lists of variables, unlike ~x1 and ~x2. ~
See :doc spec-mv-let."
spec-mv-let-form
inner-vars
outer-vars))
(t
`(check-vars-not-free
; Warning: Keep the check for variable name "the-very-obscure-feature" in sync
; with the variable name in the raw Lisp version.
(the-very-obscure-future)
; We lay down code that treats spec-mv-let as mv?-let, augmented by some
; necessary checks. The raw Lisp code has a different shape in order to
; support speculative execution, and possible aborting, of the (speculative)
; computation.
(mv?-let
,outer-vars
,computation
(,inner-let
,inner-vars
,inner-body
(cond ((check-vars-not-free ,outer-vars ,test)
,true-branch)
(t
(check-vars-not-free ,outer-vars ,false-branch)))))))))
(& (er hard! 'spec-mv-let
"Illegal form, ~x0. See :doc spec-mv-let."
spec-mv-let-form))))
; Parallelism wart: when set-verify-guards-eagerness is 0, and there is a guard
; violation in subfunctions that are evaluating in the non-main-thread, we get
; errors that aren't user friendly (the errors occur in the non-main-threads).
; I think that the solution to this problem might necessitate catching the
; errors and re-causing them. Hitting ctrl+c causes the main thread to abort
; waiting on the result from those threads, and allows the interactive session
to resume . says that he may have already fixed this for spec - mv - let ,
; and for the other parallelism primitives, the solution may be for the closure
; to bind *ld-level* to the value inherited from each thread's parent. As of
; this writing (1/13/2012), we can see the unfortunate need for control-c in
; the following example:
; (defun f (x) (declare (xargs :guard (integerp x))) (+ x x))
; (defun g ()
; (declare (xargs :guard t :verify-guards nil))
( plet ( ( a ( f ( car ( make - list 1000000 ) ) ) )
( b ( f ( car ( make - list 1000000 ) ) ) ) )
; (+ a b)))
; (g)
The definition of with - output - lock can be found as ( deflock < comments >
* output - lock * ) in ACL2 source file axioms.lisp .
Parallelism wart : it is still possible in ACL2(p ) to receive an error at the
Lisp - level when CCL can not " create thread " . An example of a user ( Kaufmann )
; encountering this error is shown below, with community book
concurrent - programs / bakery / stutter2 . In March 2012 , Kaufmann 's laptop could
sometimes exhibit this problem ( a 2 - core machine with 4 hardware threads ) .
There are two possible ways to fix this problem . The first is to set the
; default-total-parallelism-work-limit to a lower number so that it never
occurs ( but this costs performance ) . Kaufmann suggests that we should also
; catch this particular Lisp error and instead cause an ACL2 error, similar to
; the error in function not-too-many-futures-already-in-existence. This may be
; harder than one might initially think, because our current mechanism for
; catching errors in child threads involves catching thrown tags and then
; rethrowing them in the thread who is that child's parent.
; The error looks like the following:
;; <snip>
;;
;;.............................................................
;; ***********************************************
* * * * * * * * * * * * ABORTING from raw Lisp * * * * * * * * * * *
;; Error: .Can't create thread
;; ***********************************************
;; The message above might explain the error. If not, and
;; if you didn't cause an explicit interrupt (Control-C),
;; then the root cause may be call of a :program mode
;; function that has the wrong guard specified, or even no
;; guard specified (i.e., an implicit guard of t).
;; See :DOC guards.
;; To enable breaks into the debugger (also see :DOC acl2-customization):
;; (SET-DEBUGGER-ENABLE T)
;; .
;; ***********************************************
* * * * * * * * * * * * ABORTING from raw Lisp * * * * * * * * * * *
;; Error: Can't create thread
;; ***********************************************
;; The message above might explain the error. If not, and
;; if you didn't cause an explicit interrupt (Control-C),
;; then the root cause may be call of a :program mode
;; function that has the wrong guard specified, or even no
;; guard specified (i.e., an implicit guard of t).
;; See :DOC guards.
;; To enable breaks into the debugger (also see :DOC acl2-customization):
;; (SET-DEBUGGER-ENABLE T)
;; ...........................................................
;; ..................Here is the current pstack [see :DOC pstack]:
;; (CLAUSIFY REWRITE-ATM
;; SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
;; REWRITE-ATM SIMPLIFY-CLAUSE REWRITE-ATM
;; PREPROCESS-CLAUSE PREPROCESS-CLAUSE
;; SETUP-SIMPLIFY-CLAUSE-POT-LST
;; SIMPLIFY-CLAUSE
;; EV-FNCALL-META REWRITE-ATM
;; EV-FNCALL-META EV-FNCALL-META
;; EV-FNCALL-META REWRITE-ATM
;; EV-FNCALL EV-FNCALL EV-FNCALL-META
REWRITE - ATM SIMPLIFY - CLAUSE
;; FORWARD-CHAIN1 SIMPLIFY-CLAUSE
;; PREPROCESS-CLAUSE EV-FNCALL-META
REWRITE - ATM REWRITE - ATM
;; FORWARD-CHAIN1 FORWARD-CHAIN1
;; SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
;; SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
;; SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
;; SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
;; REWRITE-ATM PREPROCESS-CLAUSE
;; SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
;; SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
;;
;; <snip>
(defun set-total-parallelism-work-limit-fn (val state)
(declare (xargs :guard (or (equal val :none)
(integerp val))))
(f-put-global 'total-parallelism-work-limit val state))
(defmacro set-total-parallelism-work-limit (val)
(declare (xargs :guard (or (equal val :none)
(integerp val))))
`(set-total-parallelism-work-limit-fn ,val state))
(defun set-total-parallelism-work-limit-error-fn (val state)
(declare (xargs :guard (or (equal val t)
(null val))))
(f-put-global 'total-parallelism-work-limit-error val state))
(defmacro set-total-parallelism-work-limit-error (val)
; Parallelism blemish: explain something about how, unlike
; set-total-parallelism-work-limit, this one only applies to proof (not
; programming).
(declare (xargs :guard (or (equal val t)
(null val))))
`(set-total-parallelism-work-limit-error-fn ,val state))
| null | https://raw.githubusercontent.com/acl2/acl2/65a46d5c1128cbecb9903bfee4192bb5daf7c036/parallel.lisp | lisp | This program is free software; you can redistribute it and/or modify
it under the terms of the LICENSE file distributed with ACL2.
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
LICENSE for more details.
Section: To Consider. The following might be good to address as time
permits.
Change the piece of work list to an array (perhaps result in a faster
library because of less garbage.
Make removing closures from the queue destructive, in particular with
regard to early termination.
Recycle locks, perhaps for example in wait-on-condition-variable-lockless.
Provide a way for the user to modify *core-count*, including inside the
ACL2 loop. If we allow for changing *core-count*, then we need to think
about allowing for changing variables that depend on it, e.g.,
*unassigned-and-active-work-count-limit* (perhaps by changing them to
zero-ary functions). If you consider making such a change, then think
about how functions cpu-core-count and cpu-core-count-raw might be
relevant.
*unassigned-and-active-work-count-limit*. Evaluate such modifications with
testing, of course.
End of Section "To Consider".
:bogus-parallelism-ok
Parallelism blemish: cause an error if the user tries to go into a state
where waterfall-parallelism is enabled but parallel-execution is disabled.
error-in-parallelism-mode@par in waterfall-step, it seems that they might not
yet , regressions may have passed with them . One possible outcome : If
tests fail for contributed book directory books/bdd/, you might just modify
and also mention that (once again) in :doc
fine.
Warning: This function should only be called inside the ACL2 loop, because of
the calls of observation-cw.
:resource-based
Keep the following ending "~%" in sync with set-waterfall-parallelism.
because it is called in set-waterfall-parallelism, which might be called
see the note about a call of observation in
set-waterfall-parallelism-fn.
Override hints must be removed because set-waterfall-parallelism performs a
defattach, which spawns some proof effort. If there are override-hints
available for use during this proof, apply-override-hints will see them and
attempt to use them. Since override-hints are not permitted without enabling
waterfall-parallelism-hacks, in this case, we must cause an error.
t is a alias for :resource-based
We check for override hints even when #-acl2-par, to avoid being surprised by
turning off waterfall-parallelism.
One might be tempted to insert (mf-multiprocessing val) here. However, in
ACL2(hp) -- which is where this code is run -- we really want to keep
multiprocessing on, since one can do multithreaded computations (e.g., with
pand) even with waterfall-parallelism disabled.
We avoid a possible hard error, e.g. from (mini-proveall), when parallelism
and accumulated-persistence are both turned on. A corresponding bit of code
is in accumulated-persistence. We do similarly, just to be safe, for
forward-chaining-reports; see also set-fc-criteria-fn.
definitions of accumulated-persistence and set-fc-criteria-fn.
avoid undefined function warning
Once upon a time we issued an error here instead of an observation. In
that users can call set-waterfall-parallelism inside books (presumably via
make-event) without causing their certification to stop when using #-acl2-par
builds of ACL2.
We make this an observation instead of a warning, because it's probably
pretty obvious to the user whether they're using an image that was built with
the acl2-par feature.
Parallelism blemish: make a macro via deflast called
with-waterfall-parallelism that enables waterfall parallelism for a given
form, in particular an event form like calls of defun and defthm. It's low
priority, since it can easily be added as a book later -- though maybe it
would be nice to have this as an event constructor, like with-output. But
It is tempting to install a table guard of (memoize-table-chk key val world).
However, that won't work, for example because it will prohibit adding an
entry to this table for a function that is currently memoized -- an act that
is the point of this table! So instead we rely solely on the checks done
when putting entries in memoize-table.
See note about making this an observation instead of an error inside
set-waterfall-parallelism.
One might consider using a state global to implement
macro can change whether or not a proof completes. So, we want this macro
tied into the undoing mechanism; hence we use a table event.
Parallelism blemish: the following installation of ttag
:waterfall-parallelism-hacks should probably be conditionalized upon val
conditionalized upon the non-existence of a prior ttag.
Recognizer for expressions x for which (car x) is of the form (declare ...).
We return true when x is of the form (declare (granularity <expr>)).
X is a list of forms that may begin with a granularity declaration such as
granularity-form-exists granularity-form remainder-forms). If there is no
declaration then we return (mv nil nil nil nil x). If there is error then we
return (mv t an-error-message nil nil x). Otherwise we return (mv nil nil t
It is necessary to return whether the granularity form exists. If we did not
do so, there would be no mechanism for distinguishing between a non-existent
granularity form and one that was nil.
A granularity form declaration is the only acceptable form of declaration.
Some examples of unaccepted declarations are type and ignore declarations.
We use this function in both the raw and acl2-loop definitions of plet to
macroexpand away our granularity form, as part of our effort to ensure that
pargs is logically the identity function.
Booleanized binary and.
Booleanized (see :DOC por). Another nice thing about this Booleanization is
awareness of a guard-related difference based on the impact of lazy
evaluation.
Since we use &rest, we know forms is a true-list.
(pand) == t
booleanize
Booleanized binary or.
Note that por must be Booleanized if we are to support early termination,
i.e., so that any non-nil value can cause por to return.
(por) == nil
Preliminary code for parallelizing the rewriter
; We now develop code for parallelizing calls to the arguments of a call of
; rewrite.
; WARNING! We believe that this approach has the following bug. If
with - prover - time - limit is used , then the main thread ( which is the one
; calling waterfall-step) has a catch (implemented by the call there of
; catch-time-limit5) that will only catch throws to that tag from the SAME
; thread. We will get in trouble if a spawned thread's call of rewrite does
; such a throw.
; Warning: Moreover, if we use this code, consider modifying the
; rewrite-constant to store the value of :limit in
; rewrite-args-granularity-table. Otherwise, we have to go to the world with a
; potentially slow getprop every time we call rewrite-args-par-big-enough.
; Maybe that's just noise, but maybe it's expensive.
; We initially set the value of (the unique key) :limit to nil in
; rewrite-args-granularity-table, so that in fact we do not do such
; parallelization. But we leave this infrastructure in place (see comment "or
; try :limit" below) in case we want to experiment with such parallelization in
; the future.
(table rewrite-args-granularity-table nil nil
:guard (and (eq key :limit)
(or (null val) (natp val))))
or try : limit = 10
is true when x is a list of terms ; else x is a term . Returns a number by
accumulating into acc , or t if that number would exceed bound . We assume
that acc is < = bound .
x is a list
(cond ((null x)
(t
(let ((new-acc (rewrite-args-par-big-enough-rec
nil (car x) bound acc)))
(if (eq new-acc t)
t
(rewrite-args-par-big-enough-rec
flg (cdr x) bound new-acc))))))
((variablep x)
((fquotep x)
t)
((flambdap (ffn-symb x))
(let ((new-acc (rewrite-args-par-big-enough-rec
nil (lambda-body (ffn-symb x)) bound (1+ acc))))
(if (eq new-acc t)
t
(rewrite-args-par-big-enough-rec t (fargs x) bound new-acc))))
(t (rewrite-args-par-big-enough-rec t (fargs x) bound (1+ acc)))))
(defun rewrite-args-par-big-enough (x wrld)
; If the limit is set to nil, the function returns nil. This allows the
; enabling and disabling of rewriting args in parallel.
(let ((limit (cdr (assoc-eq :limit
(table-alist
'rewrite-args-granularity-table
wrld)))))
(and limit (equal t (rewrite-args-par-big-enough-rec nil x limit 0)))))
; With the additions above, we can contemplate adding something like the
; following to the rewrite nest below. If we do that, then replace the call of
; rewrite-args in rewrite by the following:
; #-acl2-par
; rewrite-args
; #+acl2-par
; rewrite-args-par
& extra formals
rdepth
ancestors backchain-limit
(mv (car pair) (cdr pair))))
& extra formals
rdepth
ancestors backchain-limit
Note : In this function , the extra formal geneqv is actually a list of
or nil denoting a list of .
; Unlike rewrite-args, we return (cons rewritten-args ttree) instead of
; (mv rewritten-args ttree).
(cond ((f-big-clock-negative-p state)
ttree))
((null args)
(cons nil ttree))
(t (plet
(declare (granularity t)) ; should call rewrite-args-par-big-enough
:ttree nil)
(rewrite-args-par-rec (cdr args) alist (1+ bkptr))
(ttree1 (cdr pair1))
(cons (cons term rewritten-args)
(cons-tag-trees ttree1 ttree2)))))))
Preliminary code for parallelizing the rewriter.
Note that the following code treats step-limits a little differently from how
they are treated in the sequential version. If we keep this treatment, we
should add a comment here and in decrement-step-limit suggesting that if we
change either, then we should consider changing the other. Also note the
commented out declare forms, which would be good to include (especially
rewriter in parallel in ACL2(hp) because memoization is not thread-safe.
This unmemoization can perhaps be done by issuing a call of (unmemoize-all)
in raw Lisp).
& extra formals
rdepth step-limit
backchain-limit
Note : In this function , the extra formal geneqv is actually a list of
or nil denoting a list of .
(the-mv
(cond ((null args)
(mv step-limit nil ttree))
(t (spec-mv-let
(step-limit1 rewritten-arg ttree1)
( declare ( type ( signed - byte 30 ) step - limit1 ) )
(mv-let
(rewrite-entry (rewrite-args (cdr args) alist (1+ bkptr))
( declare ( type ( signed - byte 30 ) step - limit2 ) )
(if t
(cond ((>= step-limit 0)
step-limit)
((step-limit-strictp state)
(step-limit-error nil))
(t -1)))
(cons rewritten-arg rewritten-args)
(cons-tag-trees ttree1 ttree2))
nil
nil))))))))
Warning: Keep this in sync with the raw Lisp #+acl2-par definition of
spec-mv-let.
From the documentation, with annotations in brackets [..] showing names used
in the code below:
(spec-mv-let
(v1 ... vn) ; bind distinct variables
<spec> ; evaluate speculatively; return n values
(mv-let ; [inner-let] or, use mv?-let if k=1 below
(w1 ... wk) ; [inner-vars] bind distinct variables
<eager> ; [evaluate eagerly
(if <test> ; [test] use results from <spec> if true
<typical-case> ; [true-branch] may mention v1 ... vn
<abort-case>))) ; [false-branch] does not mention v1 ... vn
In the logic, spec-mv-let is just mv?-let where the inner binding is also to
be done with mv-let, but capture needs to be avoided in the following sense:
no vi may occur in <test> or <abort-case>, because in the raw Lisp version,
those values may not be available for those forms.
Warning: Keep the check for variable name "the-very-obscure-feature" in sync
with the variable name in the raw Lisp version.
We lay down code that treats spec-mv-let as mv?-let, augmented by some
necessary checks. The raw Lisp code has a different shape in order to
support speculative execution, and possible aborting, of the (speculative)
computation.
Parallelism wart: when set-verify-guards-eagerness is 0, and there is a guard
violation in subfunctions that are evaluating in the non-main-thread, we get
errors that aren't user friendly (the errors occur in the non-main-threads).
I think that the solution to this problem might necessitate catching the
errors and re-causing them. Hitting ctrl+c causes the main thread to abort
waiting on the result from those threads, and allows the interactive session
and for the other parallelism primitives, the solution may be for the closure
to bind *ld-level* to the value inherited from each thread's parent. As of
this writing (1/13/2012), we can see the unfortunate need for control-c in
the following example:
(defun f (x) (declare (xargs :guard (integerp x))) (+ x x))
(defun g ()
(declare (xargs :guard t :verify-guards nil))
(+ a b)))
(g)
encountering this error is shown below, with community book
default-total-parallelism-work-limit to a lower number so that it never
catch this particular Lisp error and instead cause an ACL2 error, similar to
the error in function not-too-many-futures-already-in-existence. This may be
harder than one might initially think, because our current mechanism for
catching errors in child threads involves catching thrown tags and then
rethrowing them in the thread who is that child's parent.
The error looks like the following:
<snip>
.............................................................
***********************************************
Error: .Can't create thread
***********************************************
The message above might explain the error. If not, and
if you didn't cause an explicit interrupt (Control-C),
then the root cause may be call of a :program mode
function that has the wrong guard specified, or even no
guard specified (i.e., an implicit guard of t).
See :DOC guards.
To enable breaks into the debugger (also see :DOC acl2-customization):
(SET-DEBUGGER-ENABLE T)
.
***********************************************
Error: Can't create thread
***********************************************
The message above might explain the error. If not, and
if you didn't cause an explicit interrupt (Control-C),
then the root cause may be call of a :program mode
function that has the wrong guard specified, or even no
guard specified (i.e., an implicit guard of t).
See :DOC guards.
To enable breaks into the debugger (also see :DOC acl2-customization):
(SET-DEBUGGER-ENABLE T)
...........................................................
..................Here is the current pstack [see :DOC pstack]:
(CLAUSIFY REWRITE-ATM
SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
REWRITE-ATM SIMPLIFY-CLAUSE REWRITE-ATM
PREPROCESS-CLAUSE PREPROCESS-CLAUSE
SETUP-SIMPLIFY-CLAUSE-POT-LST
SIMPLIFY-CLAUSE
EV-FNCALL-META REWRITE-ATM
EV-FNCALL-META EV-FNCALL-META
EV-FNCALL-META REWRITE-ATM
EV-FNCALL EV-FNCALL EV-FNCALL-META
FORWARD-CHAIN1 SIMPLIFY-CLAUSE
PREPROCESS-CLAUSE EV-FNCALL-META
FORWARD-CHAIN1 FORWARD-CHAIN1
SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
SIMPLIFY-CLAUSE SIMPLIFY-CLAUSE
REWRITE-ATM PREPROCESS-CLAUSE
SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
SIMPLIFY-CLAUSE PREPROCESS-CLAUSE
<snip>
Parallelism blemish: explain something about how, unlike
set-total-parallelism-work-limit, this one only applies to proof (not
programming). | ACL2 Version 8.5 -- A Computational Logic for Applicative Common Lisp
Copyright ( C ) 2023 , Regents of the University of Texas
This version of ACL2 is a descendent of ACL2 Version 1.9 , Copyright
( C ) 1997 Computational Logic , Inc. See the documentation topic NOTE-2 - 0 .
Written by : and J Strother Moore
email : and
Department of Computer Science
University of Texas at Austin
Austin , TX 78712 U.S.A.
We thank for contributing an initial version of this file .
(in-package "ACL2")
See this same comment in parallel-raw.lisp .
Modify the coefficient ( currently 2 ) in the definition of
(defun set-parallel-execution-fn (val ctx state)
(declare (xargs :guard (member-eq val '(t nil :bogus-parallelism-ok))))
(cond
((eq (f-get-global 'parallel-execution-enabled state)
val)
(pprogn (observation ctx
"No change in enabling of parallel execution.")
(value nil)))
(t
#-acl2-par
(er soft ctx
"Parallelism can only be enabled in CCL, threaded SBCL, or Lispworks. ~
~ Additionally, the feature :ACL2-PAR must be set when compiling ~
ACL2 (for example, by using `make' with argument `ACL2_PAR=t'). ~
Either the current Lisp is neither CCL nor threaded SBCL nor ~
Lispworks, or this feature is missing. Consequently, parallelism ~
will remain disabled. Note that you can submit parallelism ~
primitives at the top level when parallel execution is disabled, ~
although they will not result in any parallel execution.~%")
#+acl2-par
(let ((observation-string
(case val
((nil)
"Disabling parallel execution. Parallelism primitives may ~
still be used, but during execution they will degrade to ~
their serial equivalents.")
((t)
"Parallel execution is enabled, but parallelism primitives may ~
only be called within function definitions or macro top-level, ~
not at the top level of the ACL2 read-eval-print loop. See ~
:DOC parallelism-at-the-top-level.")
"Parallel execution is enabled. Parallelism primitives may be ~
called directly in the top-level loop, but without use of the ~
macro top-level, they will execute serially. See :DOC ~
parallelism-at-the-top-level."))))
(pprogn
(f-put-global 'parallel-execution-enabled val state)
(observation ctx observation-string)
(value val))))))
(defmacro set-parallel-execution (value)
(declare (xargs :guard (member-equal value
'(t 't nil 'nil
:bogus-parallelism-ok
':bogus-parallelism-ok))))
`(let ((val ,value)
(ctx 'set-parallel-execution))
(set-parallel-execution-fn
(cond ((consp val) (cadr val))
(t val))
ctx
state)))
(defun waterfall-printing-value-for-parallelism-value (value)
(declare (xargs :guard (member-eq value *waterfall-parallelism-values*)))
(cond ((eq value nil)
:full)
((eq value :full)
:very-limited)
((eq value :top-level)
:very-limited)
((eq value :resource-based)
:very-limited)
((eq value :resource-and-timing-based)
:very-limited)
(t
(assert$ (eq value :pseudo-parallel)
:very-limited))))
Parallelism wart : figure out if : bdd hints are supported . Given the call of
translate - bdd - hint to cause a nice error if waterfall parallelism is enabled ,
unsupported - waterfall - parallelism - features . Note that bdd - clause might be
the function that actually performs the bdd hint , and that bdd - clause does n't
return state . So , aside from the place in waterfall - step , bdd hints might be
(defun print-set-waterfall-parallelism-notice (val print-val state)
(declare (xargs :guard (and (member-eq val *waterfall-parallelism-values*)
(keywordp print-val))))
(let ((str
(case val
((nil)
"Disabling parallel execution of the waterfall.")
(:full
"Parallelizing the proof of every subgoal.")
(:top-level
"Parallelizing the proof of top-level subgoals only.")
(:pseudo-parallel
"Running the version of the waterfall prepared for parallel ~
execution (stateless). However, we will execute this version of ~
the waterfall serially.")
(:resource-and-timing-based
"Parallelizing the proof of every subgoal that was determined to ~
take a non-trivial amount of time in a previous proof attempt.")
"Parallelizing the proof of every subgoal, as long as CPU core ~
resources are available."))))
(observation nil
"~@0 Setting waterfall-parallelism to ~s1. Setting ~
waterfall-printing to ~s2 (see :DOC ~
set-waterfall-printing).~%"
str
(symbol-name val)
(symbol-name print-val))))
(defun check-for-no-override-hints (ctx state)
Although this macro is intended for # + acl2 - par , we need it unconditionally
(let ((wrld (w state)))
(cond
((and (not (cdr (assoc-eq 'hacks-enabled
(table-alist 'waterfall-parallelism-table
wrld))))
(cdr (assoc-eq :override (table-alist 'default-hints-table
wrld))))
(er soft ctx
"Before changing the status of waterfall-parallelism, either (1) ~
override hints must be removed from the default-hints-table or (2) ~
waterfall-parallelism hacks must be enabled. (1) can be achieved ~
by calling ~x0. (2) can be achieved by calling ~x1."
'(set-override-hints nil)
'(set-waterfall-parallelism-hacks-enabled t)))
(t (value nil)))))
(defun set-waterfall-parallelism-fn (val ctx state)
(cond
((eq val (f-get-global 'waterfall-parallelism state))
(pprogn (observation ctx
"Ignoring call to set-waterfall-parallelism since ~
the new value is the same as the current value.~%~%")
(value :ignored)))
(t
:resource-based
val)))
(er-progn
an error when the same proof development is encountered with # + acl2 - par . But
we skip the check if there is no change ( see GitHub Issue # 1171 ) or we are
(cond ((or (null val)
(equal val (f-get-global 'waterfall-parallelism state)))
(value nil))
(t (check-for-no-override-hints ctx state)))
(cond
((member-eq val *waterfall-parallelism-values*)
#+acl2-par
(cond
((null (f-get-global 'parallel-execution-enabled state))
(er soft ctx
"Parallel execution must be enabled before enabling ~
waterfall parallelism. See :DOC set-parallel-execution"))
((and val (f-get-global 'gstackp state))
(er soft ctx
"You must disable brr (e.g., with :BRR NIL) before turning ~
on waterfall-parallelism. See :DOC ~
unsupported-waterfall-parallelism-features."))
(t
(progn$
(and val
Warning : Keep the following two wormhole - eval calls in sync with the
(prog2$ (wormhole-eval
'accumulated-persistence
'(lambda (whs) (set-wormhole-data whs nil))
nil)
(wormhole-eval
'fc-wormhole
'(lambda (whs)
(set-wormhole-data
whs
(put-assoc-eq :CRITERIA nil
(wormhole-data whs))))
nil)))
#-acl2-loop-only
'initialize-dmr-interval-used)
(pprogn
(f-put-global 'waterfall-parallelism val state)
(value val)))))
#-acl2-par
response to feedback from , we have changed it to an observation so
(pprogn
(observation ctx
"Parallelism can only be enabled in CCL, threaded ~
SBCL, or Lispworks. Additionally, the feature ~
:ACL2-PAR must be set when compiling ACL2 (for ~
example, by using `make' with argument ~
`ACL2_PAR=t'). ~ Either the current Lisp is neither ~
CCL nor threaded SBCL nor Lispworks, or this ~
feature is missing. Consequently, this attempt to ~
set waterfall-parallelism to ~x0 will be ~
ignored.~%~%"
val)
(value :ignored)))
(t (er soft ctx
"Illegal value for set-waterfall-parallelism: ~x0. The legal ~
values are ~&1."
val *waterfall-parallelism-values*))))))))
while doing proofs with ACL2(hp ) , would have found this convenient .
(defmacro set-waterfall-parallelism1 (val)
`(let* ((val ,val)
(ctx 'set-waterfall-parallelism))
(er-let* ((val (set-waterfall-parallelism-fn val ctx state)))
(cond ((eq val :ignored)
(value val))
(t (let ((print-val
(waterfall-printing-value-for-parallelism-value
val)))
(pprogn
(print-set-waterfall-parallelism-notice
val print-val state)
(er-progn
(set-waterfall-printing-fn print-val ctx state)
(value (list val print-val))))))))))
(table saved-memoize-table nil nil
:guard
t)
(defmacro save-memo-table ()
'(with-output
:off (summary event)
(table saved-memoize-table
nil
(table-alist 'memoize-table world)
:clear)))
(defun clear-memo-table-events (alist acc)
(declare (xargs :guard (true-list-listp alist)))
(cond ((endp alist) acc)
(t (clear-memo-table-events
(cdr alist)
(cons `(table memoize-table ',(caar alist) nil)
acc)))))
(defmacro clear-memo-table ()
`(with-output
:off (summary event)
(make-event
(let ((alist (table-alist 'memoize-table (w state))))
(cons 'progn
(clear-memo-table-events alist nil))))))
(defmacro save-and-clear-memoization-settings ()
'(with-output
:off (summary event)
(progn (save-memo-table)
(clear-memo-table))))
(defun set-memo-table-events (alist acc)
(declare (xargs :guard (true-list-listp alist)))
(cond ((endp alist) acc)
(t (set-memo-table-events
(cdr alist)
(cons `(table memoize-table ',(caar alist) ',(cdar alist))
acc)))))
(defmacro restore-memoization-settings ()
`(with-output
:off (summary event)
(make-event
(let ((alist (table-alist 'saved-memoize-table (w state))))
(cons 'progn
(set-memo-table-events alist nil))))))
(defmacro set-waterfall-parallelism (val)
`(with-output
:off (summary event)
(make-event
(er-let*
((new-val (set-waterfall-parallelism1 ,val)))
(value (list 'value-triple (list 'quote new-val)))))))
(defun set-waterfall-printing-fn (val ctx state)
(cond ((member-eq val *waterfall-printing-values*)
#+acl2-par
(pprogn (f-put-global 'waterfall-printing val state)
(value val))
#-acl2-par
(pprogn (observation ctx
"Customizing waterfall printing only makes ~
sense in the #+acl2-par builds of ACL2. ~
Consequently, this attempt to set ~
waterfall-printing to ~x0 will be ignored.~%~%"
val)
(value :invisible)))
(t (er soft ctx
"Illegal value for set-waterfall-printing: ~x0. The legal ~
values are ~&1."
val *waterfall-printing-values*))))
(defmacro set-waterfall-printing (val)
`(set-waterfall-printing-fn ,val 'set-waterfall-printing state))
(defun set-waterfall-parallelism-hacks-enabled-guard (wrld)
(or (ttag wrld)
(er hard nil
"Using waterfall parallelism hacks requires an active trust-tag. ~
Consider using (set-waterfall-parallelism-hacks-enabled! t). See ~
:DOC set-waterfall-parallelism-hacks-enabled for~ more~ ~
information.")))
(table waterfall-parallelism-table
nil nil :guard (set-waterfall-parallelism-hacks-enabled-guard world))
(defmacro set-waterfall-parallelism-hacks-enabled (val)
set - waterfall - parallelism - hacks - enabled . But as points out , this
(declare (xargs :guard (or (equal val t) (null val))))
`(table waterfall-parallelism-table 'hacks-enabled ,val))
(defmacro set-waterfall-parallelism-hacks-enabled! (val)
`(encapsulate
()
being equal to t. Furthermore , perhaps the installation should also be
(defttag :waterfall-parallelism-hacks)
(set-waterfall-parallelism-hacks-enabled ,val)))
(defun caar-is-declarep (x)
(declare (xargs :guard t))
(and (consp x)
(consp (car x))
(eq (caar x) 'declare)))
(defun declare-granularity-p (x)
(declare (xargs :guard t))
(and (true-listp x)
(eql (length x) 2)
(eq (car x) 'declare)
(let ((gran-form (cadr x)))
(and (true-listp gran-form)
(eql (length gran-form) 2)
(eq (car gran-form) 'granularity)))))
(defun check-and-parse-for-granularity-form (x)
( declare ( granularity ( < depth 5 ) ) ) . The return signature is ( erp msg
granularity - form ) ) .
(cond ((not (caar-is-declarep x))
(mv nil nil nil nil x))
((declare-granularity-p (car x))
(let* ((granularity-declaration (cadar x))
(granularity-form (cadr granularity-declaration)))
(mv nil nil t granularity-form (cdr x))))
(t
(mv t
"Within a parallelism primitive, a granularity form declaration ~
is the only acceptable form of declaration. Some examples of ~
unaccepted declarations are type and ignore declarations. See ~
:DOC granularity."
nil
nil
x))))
#+(or acl2-loop-only (not acl2-par))
(defmacro pargs (&rest forms)
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'pargs msg))
((or (and (equal (length forms) 1) (not gran-form-exists))
(and (equal (length forms) 2) gran-form-exists))
(let ((function-call (car remainder-forms)))
(if gran-form-exists
`(prog2$ ,gran-form ,function-call)
function-call)))
(t
(er hard 'pargs
"Pargs was passed the wrong number of arguments. Without a ~
granularity declaration, pargs takes one argument. With a ~
granularity declaration, pargs requires two arguments, the ~
first of which must be of the form ~x0. See :DOC pargs."
'(declare (granularity expr)))))))
#+(or acl2-loop-only (not acl2-par))
(defmacro plet (&rest forms)
(mv-let (erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'plet msg))
(gran-form-exists
`(prog2$ ,gran-form
(let ,@remainder-forms)))
(t `(let ,@remainder-forms)))))
(defun binary-pand (x y)
(declare (xargs :guard t :mode :logic))
(and x y t))
#+(or acl2-loop-only (not acl2-par))
(defmacro pand (&rest forms)
We Booleanize pand so that it is consistent with por , which must be
that it emphasizes that PAND differs from AND logically , which can raise
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'pand msg))
same as length = = 1
(gran-form-exists
(list 'prog2$
gran-form
(xxxjoin 'binary-pand remainder-forms)))
(t (xxxjoin 'binary-pand remainder-forms)))))
(defun binary-por (x y)
(declare (xargs :guard t :mode :logic))
(if x t (if y t nil)))
#+(or acl2-loop-only (not acl2-par))
(defmacro por (&rest forms)
(mv-let
(erp msg gran-form-exists gran-form remainder-forms)
(check-and-parse-for-granularity-form forms)
(cond (erp (er hard 'por msg))
same as length = = 1
(list 'if (car remainder-forms) t nil))
(gran-form-exists
(list 'prog2$
gran-form
(xxxjoin 'binary-por remainder-forms)))
(t (xxxjoin 'binary-por remainder-forms)))))
(defun or-list (x)
(declare (xargs :guard (true-listp x) :mode :logic))
(if (endp x)
nil
(if (car x)
t
(or-list (cdr x)))))
(defun and-list (x)
(declare (xargs :guard (true-listp x) :mode :logic))
(if (endp x)
t
(and (car x)
(and-list (cdr x)))))
(defun cpu-core-count (state)
(declare (xargs :stobjs state :guard t))
#+(and (not acl2-loop-only) (not acl2-par))
(when (live-state-p state)
(return-from cpu-core-count
(mv 1 state)))
#+(and (not acl2-loop-only) acl2-par)
(when (live-state-p state)
(return-from cpu-core-count
(mv (if (and (f-boundp-global 'cpu-core-count state)
(posp (f-get-global 'cpu-core-count state)))
(core-count-raw nil (f-get-global 'cpu-core-count
state))
(core-count-raw 'core-count))
state)))
(mv-let (nullp val state)
(read-acl2-oracle state)
(declare (ignore nullp))
(mv val state)))
# + acl2 - par
# + acl2 - par
# + acl2 - par
( defun rewrite - args - par - big - enough - rec ( flg x bound acc )
acc )
acc )
acc )
( ( eql bound acc )
# + acl2 - par
# + acl2 - par
type - alist obj geneqv wrld state fnstack
simplify - clause - pot - lst rcnst )
( let ( ( pair ( rewrite - entry ( rewrite - args - par - rec args alist ) ) ) )
# + acl2 - par
type - alist obj geneqv wrld state fnstack
simplify - clause - pot - lst rcnst )
( declare ( type ( unsigned - byte 29 ) rdepth ) )
( cons ( sublis - var - lst alist args )
( ( pair1
( mv - let ( term )
( rewrite - entry ( rewrite ( car args ) alist )
: ( car geneqv )
( cons term ) ) )
( ( rewrite - entry
: ( cdr geneqv ) ) ) )
( let * ( ( term ( car pair1 ) )
( rewritten - args ( car ) )
( ttree2 ( cdr pair2 ) ) )
important for GCL ) once spec - mv - let accepts them . And finally , note that as
of v6 - 2 , it is necessary to unmemoize the rewriter functions when running the
type - alist obj geneqv wrld state fnstack ancestors
simplify - clause - pot - lst rcnst )
( declare ( type ( unsigned - byte 29 ) rdepth )
( type ( signed - byte 30 ) step - limit ) )
3
( signed - byte 30 )
( rewrite - entry ( rewrite ( car args ) alist )
: ( car geneqv ) )
( step - limit2 rewritten - args ttree2 )
: ( cdr geneqv ) )
( mv ( let * ( ( ( - step - limit step - limit1 ) )
( step - limit ( - step - ) ) )
( declare ( type ( signed - byte 30 ) steps1 step - limit ) )
( mv 0
#+(or acl2-loop-only (not acl2-par))
(defmacro spec-mv-let (&whole spec-mv-let-form outer-vars computation body)
(case-match body
((inner-let inner-vars inner-body
('if test true-branch false-branch))
(cond
((not (member inner-let '(mv-let mv?-let mv-let@par)
:test 'eq))
(er hard! 'spec-mv-let
"Illegal form (expected inner let to bind with one of ~v0): ~x1. ~ ~
See :doc spec-mv-let."
'(mv-let mv?-let mv-let@par)
spec-mv-let-form))
((or (not (symbol-listp outer-vars))
(not (symbol-listp inner-vars))
(intersectp inner-vars outer-vars
:test 'eq))
(er hard! 'spec-mv-let
"Illegal spec-mv-let form: ~x0. The two bound variable lists ~
must be disjoint true lists of variables, unlike ~x1 and ~x2. ~
See :doc spec-mv-let."
spec-mv-let-form
inner-vars
outer-vars))
(t
`(check-vars-not-free
(the-very-obscure-future)
(mv?-let
,outer-vars
,computation
(,inner-let
,inner-vars
,inner-body
(cond ((check-vars-not-free ,outer-vars ,test)
,true-branch)
(t
(check-vars-not-free ,outer-vars ,false-branch)))))))))
(& (er hard! 'spec-mv-let
"Illegal form, ~x0. See :doc spec-mv-let."
spec-mv-let-form))))
to resume . says that he may have already fixed this for spec - mv - let ,
( plet ( ( a ( f ( car ( make - list 1000000 ) ) ) )
( b ( f ( car ( make - list 1000000 ) ) ) ) )
The definition of with - output - lock can be found as ( deflock < comments >
* output - lock * ) in ACL2 source file axioms.lisp .
Parallelism wart : it is still possible in ACL2(p ) to receive an error at the
Lisp - level when CCL can not " create thread " . An example of a user ( Kaufmann )
concurrent - programs / bakery / stutter2 . In March 2012 , Kaufmann 's laptop could
sometimes exhibit this problem ( a 2 - core machine with 4 hardware threads ) .
There are two possible ways to fix this problem . The first is to set the
occurs ( but this costs performance ) . Kaufmann suggests that we should also
* * * * * * * * * * * * ABORTING from raw Lisp * * * * * * * * * * *
* * * * * * * * * * * * ABORTING from raw Lisp * * * * * * * * * * *
REWRITE - ATM SIMPLIFY - CLAUSE
REWRITE - ATM REWRITE - ATM
(defun set-total-parallelism-work-limit-fn (val state)
(declare (xargs :guard (or (equal val :none)
(integerp val))))
(f-put-global 'total-parallelism-work-limit val state))
(defmacro set-total-parallelism-work-limit (val)
(declare (xargs :guard (or (equal val :none)
(integerp val))))
`(set-total-parallelism-work-limit-fn ,val state))
(defun set-total-parallelism-work-limit-error-fn (val state)
(declare (xargs :guard (or (equal val t)
(null val))))
(f-put-global 'total-parallelism-work-limit-error val state))
(defmacro set-total-parallelism-work-limit-error (val)
(declare (xargs :guard (or (equal val t)
(null val))))
`(set-total-parallelism-work-limit-error-fn ,val state))
|
0999f476b033d57af7b28588de81925467de37fca34966755175db7d35bcf342 | MaartenFaddegon/Hoed | Subtype.hs | module Subtype (subtype) where
import Control.Monad
import Data.Map (Map)
import Data.Map ((!))
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.List as List
import Types
import TypeUtils
import TypedAst
data Variance
= Positive
| Negative
| Top
| Bottom
lub :: Variance -> Variance -> Variance
lub Positive Positive = Positive
lub Negative Negative = Negative
lub v Bottom = v
lub Bottom v = v
lub _ _ = Top
lubs :: [Variance] -> Variance
lubs = List.foldr lub Bottom
invert :: Variance -> Variance
invert Positive = Negative
invert Negative = Positive
invert v = v
maxNumberOfUnrolls = 100
variance :: Env -> ArgOrd -> Type -> String -> Variance
variance env argOrd t s =
let var trace v (Name s' tys)
| Set.member s' trace = v
| otherwise =
case Map.lookup s' env of
Just ty ->
let order = argOrd ! s'
names = List.map (order !) [0..]
ty' = instansiates ty (Map.fromList (List.zip names tys))
in var (Set.insert s' trace) v ty'
Nothing
| s == s' -> lub v Positive
| otherwise -> v
var trace v (Arrow t1 t2) =
lub (invert (var trace v t1)) (var trace v t2)
var trace v (Forall u ty) = var trace v ty
var trace v (Union t1 t2) = lub (var trace v t1) (var trace v t2)
var trace v (Tuple ts) = lubs (List.map (var trace v) ts)
var trace v (Record b fields) = lubs (List.map (var trace v . snd) fields)
var trace v (Array ty) = var trace v ty
var trace v (Intersect t1 t2) = lubs (List.map (var trace v) [t1, t2])
var trace v _ = v
in var Set.empty Bottom t
subtype :: Type -> Type -> Env -> ArgOrd -> Substitution -> IO (Bool, Substitution)
subtype t1 t2 env argOrd subst =
let
lookup bind env s = Map.findWithDefault (bind ! s) s env
updateOrElse f def k map =
case Map.lookup k map of
Just a -> Map.insert k (f a) map
Nothing -> Map.insert k def map
sub trace bind1 bind2 assum subst (Forall u t1) t2 =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 (Forall u t2) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 t2@(TypeVar u) =
case follow subst t2 of
TypeVar u -> return (True, Map.insert u t1 subst)
ty -> sub trace bind1 bind2 assum subst t1 ty
sub trace bind1 bind2 assum subst t1@(TypeVar u) t2 =
case follow subst t1 of
TypeVar u -> return (True, Map.insert u t2 subst)
ty -> sub trace bind1 bind2 assum subst ty t2
sub trace bind1 bind2 assum subst (Name s1 tys1) (Name s2 tys2) =
case Map.lookup (s1, s2) assum of
Just (tys1', tys2') -> do
let ty1 = lookup bind1 env s1
ty2 = lookup bind2 env s2
vars1 = List.map (variance env argOrd ty1) (Map.keys bind1)
vars2 = List.map (variance env argOrd ty2) (Map.keys bind2)
(b1, subst') <- foldM f (True, subst) (List.zip3 tys1 tys1' vars1)
foldM f (b1, subst') (List.zip3 tys1 tys1' vars1)
Nothing
| s1 == s2 && Map.notMember s1 bind1 && Map.notMember s2 bind2 ->
let ty = env ! s1
vars = List.map (variance env argOrd ty) (Map.keys bind1)
in foldM f (True, subst) (List.zip3 tys1 tys2 vars)
| otherwise ->
let t1 = lookup bind1 env s1
t2 = lookup bind2 env s2
assum' = Map.insert (s1, s2) (tys1, tys2) assum
in sub trace bind1 bind2 assum' subst t1 t2
where f (True, subst) (t1, t2, Top) = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 t2
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 t1
return (b1 && b2, subst'')
f (True, subst) (t1, t2, Positive) = sub trace bind1 bind2 assum subst t1 t2
f (True, subst) (t1, t2, Negative) = sub trace bind1 bind2 assum subst t2 t1
f (True, subst) (t1, t2, Bottom) = return (True, subst)
f (False, subst) _ = return (False, subst)
sub trace bind1 bind2 assum subst (Name s tys) ty =
case Map.lookup s trace of
Just n -> return (n < maxNumberOfUnrolls, subst)
Nothing -> sub (updateOrElse (+1) 0 s trace) bind1' bind2 assum subst (lookup bind1 env s) ty
where bind1' = makeBindings argOrd s tys
sub trace bind1 bind2 assum subst ty (Name s tys) =
case Map.lookup s trace of
Just n -> return (n < maxNumberOfUnrolls, subst)
Nothing -> sub (updateOrElse (+1) 0 s trace) bind1 bind2' assum subst ty (lookup bind2 env s)
where bind2' = makeBindings argOrd s tys
sub trace bind1 bind2 assum subst (Union t11 t12) (Union t21 t22) = do
(b1121, subst1121) <- sub trace bind1 bind2 assum subst t11 t21
(b1221, subst1221) <- sub trace bind1 bind2 assum subst1121 t12 t21
(b1222, subst1222) <- sub trace bind1 bind2 assum subst1121 t12 t22
(b1122, subst1122) <- sub trace bind1 bind2 assum subst t11 t22
(b1221', subst1221') <- sub trace bind1 bind2 assum subst1122 t12 t21
(b1222', subst1222') <- sub trace bind1 bind2 assum subst1122 t12 t22
if b1121 && b1221 then return (True, subst1221)
else if b1121 && b1222 then return (True, subst1222)
else if b1122 && b1221' then return (True, subst1221')
else if b1122 && b1222' then return (True, subst1222')
else return (False, subst)
sub trace bind1 bind2 assum subst (Union t1 t2) ty = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 ty
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 ty
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst ty (Union t1 t2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst ty t1
(b2, subst'') <- sub trace bind1 bind2 assum subst' ty t2
return (b1 || b2, subst'')
sub trace bind1 bind2 assum subst (Arrow tDom1 tCod1) (Arrow tDom2 tCod2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst tDom2 tDom1
(b2, subst'') <- sub trace bind1 bind2 assum subst' tCod1 tCod2
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst (Tuple [t1]) t2 =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 (Tuple [t2]) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst (Tuple tys1) (Tuple tys2) =
if List.length tys1 == List.length tys2 then
foldM f (True, subst) (List.zip tys1 tys2)
else return (False, subst)
where f (True, subst) (t1, t2) = sub trace bind1 bind2 assum subst t1 t2
f (False, subst) _ = return (False, subst)
sub trace bind1 bind2 assum subst (Array t1) (Array t2) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst (Record _ fields1) (Record b fields2) =
foldM f (True, subst) fields1
where f :: (Bool, Substitution) -> (String, Type) -> IO (Bool, Substitution)
f (b, subst) (name, ty) =
case List.lookup name fields2 of
Just ty' -> sub trace bind1 bind2 assum subst ty ty'
Nothing -> return (False, subst)
sub trace bind1 bind2 assum subst (Intersect t1 t2) ty = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 ty
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 ty
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst ty (Intersect t1 t2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst ty t1
(b2, subst'') <- sub trace bind1 bind2 assum subst' ty t2
return (b1 || b2, subst'')
sub trace bind1 bind2 _ subst IntType IntType = return (True, subst)
sub trace bind1 bind2 _ subst IntType RealType = return (True, subst)
sub trace bind1 bind2 _ subst RealType RealType = return (True, subst)
sub trace bind1 bind2 _ subst BoolType BoolType = return (True, subst)
sub trace bind1 bind2 _ subst StringType StringType = return (True, subst)
sub trace bind1 bind2 _ _ _ _ = return (False, subst)
in sub Map.empty Map.empty Map.empty Map.empty subst t1 t2 | null | https://raw.githubusercontent.com/MaartenFaddegon/Hoed/8769d69e309928aab439b22bc3f3dbf5452acc77/examples/ZLang/1/Subtype.hs | haskell | module Subtype (subtype) where
import Control.Monad
import Data.Map (Map)
import Data.Map ((!))
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import qualified Data.List as List
import Types
import TypeUtils
import TypedAst
data Variance
= Positive
| Negative
| Top
| Bottom
lub :: Variance -> Variance -> Variance
lub Positive Positive = Positive
lub Negative Negative = Negative
lub v Bottom = v
lub Bottom v = v
lub _ _ = Top
lubs :: [Variance] -> Variance
lubs = List.foldr lub Bottom
invert :: Variance -> Variance
invert Positive = Negative
invert Negative = Positive
invert v = v
maxNumberOfUnrolls = 100
variance :: Env -> ArgOrd -> Type -> String -> Variance
variance env argOrd t s =
let var trace v (Name s' tys)
| Set.member s' trace = v
| otherwise =
case Map.lookup s' env of
Just ty ->
let order = argOrd ! s'
names = List.map (order !) [0..]
ty' = instansiates ty (Map.fromList (List.zip names tys))
in var (Set.insert s' trace) v ty'
Nothing
| s == s' -> lub v Positive
| otherwise -> v
var trace v (Arrow t1 t2) =
lub (invert (var trace v t1)) (var trace v t2)
var trace v (Forall u ty) = var trace v ty
var trace v (Union t1 t2) = lub (var trace v t1) (var trace v t2)
var trace v (Tuple ts) = lubs (List.map (var trace v) ts)
var trace v (Record b fields) = lubs (List.map (var trace v . snd) fields)
var trace v (Array ty) = var trace v ty
var trace v (Intersect t1 t2) = lubs (List.map (var trace v) [t1, t2])
var trace v _ = v
in var Set.empty Bottom t
subtype :: Type -> Type -> Env -> ArgOrd -> Substitution -> IO (Bool, Substitution)
subtype t1 t2 env argOrd subst =
let
lookup bind env s = Map.findWithDefault (bind ! s) s env
updateOrElse f def k map =
case Map.lookup k map of
Just a -> Map.insert k (f a) map
Nothing -> Map.insert k def map
sub trace bind1 bind2 assum subst (Forall u t1) t2 =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 (Forall u t2) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 t2@(TypeVar u) =
case follow subst t2 of
TypeVar u -> return (True, Map.insert u t1 subst)
ty -> sub trace bind1 bind2 assum subst t1 ty
sub trace bind1 bind2 assum subst t1@(TypeVar u) t2 =
case follow subst t1 of
TypeVar u -> return (True, Map.insert u t2 subst)
ty -> sub trace bind1 bind2 assum subst ty t2
sub trace bind1 bind2 assum subst (Name s1 tys1) (Name s2 tys2) =
case Map.lookup (s1, s2) assum of
Just (tys1', tys2') -> do
let ty1 = lookup bind1 env s1
ty2 = lookup bind2 env s2
vars1 = List.map (variance env argOrd ty1) (Map.keys bind1)
vars2 = List.map (variance env argOrd ty2) (Map.keys bind2)
(b1, subst') <- foldM f (True, subst) (List.zip3 tys1 tys1' vars1)
foldM f (b1, subst') (List.zip3 tys1 tys1' vars1)
Nothing
| s1 == s2 && Map.notMember s1 bind1 && Map.notMember s2 bind2 ->
let ty = env ! s1
vars = List.map (variance env argOrd ty) (Map.keys bind1)
in foldM f (True, subst) (List.zip3 tys1 tys2 vars)
| otherwise ->
let t1 = lookup bind1 env s1
t2 = lookup bind2 env s2
assum' = Map.insert (s1, s2) (tys1, tys2) assum
in sub trace bind1 bind2 assum' subst t1 t2
where f (True, subst) (t1, t2, Top) = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 t2
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 t1
return (b1 && b2, subst'')
f (True, subst) (t1, t2, Positive) = sub trace bind1 bind2 assum subst t1 t2
f (True, subst) (t1, t2, Negative) = sub trace bind1 bind2 assum subst t2 t1
f (True, subst) (t1, t2, Bottom) = return (True, subst)
f (False, subst) _ = return (False, subst)
sub trace bind1 bind2 assum subst (Name s tys) ty =
case Map.lookup s trace of
Just n -> return (n < maxNumberOfUnrolls, subst)
Nothing -> sub (updateOrElse (+1) 0 s trace) bind1' bind2 assum subst (lookup bind1 env s) ty
where bind1' = makeBindings argOrd s tys
sub trace bind1 bind2 assum subst ty (Name s tys) =
case Map.lookup s trace of
Just n -> return (n < maxNumberOfUnrolls, subst)
Nothing -> sub (updateOrElse (+1) 0 s trace) bind1 bind2' assum subst ty (lookup bind2 env s)
where bind2' = makeBindings argOrd s tys
sub trace bind1 bind2 assum subst (Union t11 t12) (Union t21 t22) = do
(b1121, subst1121) <- sub trace bind1 bind2 assum subst t11 t21
(b1221, subst1221) <- sub trace bind1 bind2 assum subst1121 t12 t21
(b1222, subst1222) <- sub trace bind1 bind2 assum subst1121 t12 t22
(b1122, subst1122) <- sub trace bind1 bind2 assum subst t11 t22
(b1221', subst1221') <- sub trace bind1 bind2 assum subst1122 t12 t21
(b1222', subst1222') <- sub trace bind1 bind2 assum subst1122 t12 t22
if b1121 && b1221 then return (True, subst1221)
else if b1121 && b1222 then return (True, subst1222)
else if b1122 && b1221' then return (True, subst1221')
else if b1122 && b1222' then return (True, subst1222')
else return (False, subst)
sub trace bind1 bind2 assum subst (Union t1 t2) ty = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 ty
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 ty
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst ty (Union t1 t2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst ty t1
(b2, subst'') <- sub trace bind1 bind2 assum subst' ty t2
return (b1 || b2, subst'')
sub trace bind1 bind2 assum subst (Arrow tDom1 tCod1) (Arrow tDom2 tCod2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst tDom2 tDom1
(b2, subst'') <- sub trace bind1 bind2 assum subst' tCod1 tCod2
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst (Tuple [t1]) t2 =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst t1 (Tuple [t2]) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst (Tuple tys1) (Tuple tys2) =
if List.length tys1 == List.length tys2 then
foldM f (True, subst) (List.zip tys1 tys2)
else return (False, subst)
where f (True, subst) (t1, t2) = sub trace bind1 bind2 assum subst t1 t2
f (False, subst) _ = return (False, subst)
sub trace bind1 bind2 assum subst (Array t1) (Array t2) =
sub trace bind1 bind2 assum subst t1 t2
sub trace bind1 bind2 assum subst (Record _ fields1) (Record b fields2) =
foldM f (True, subst) fields1
where f :: (Bool, Substitution) -> (String, Type) -> IO (Bool, Substitution)
f (b, subst) (name, ty) =
case List.lookup name fields2 of
Just ty' -> sub trace bind1 bind2 assum subst ty ty'
Nothing -> return (False, subst)
sub trace bind1 bind2 assum subst (Intersect t1 t2) ty = do
(b1, subst') <- sub trace bind1 bind2 assum subst t1 ty
(b2, subst'') <- sub trace bind1 bind2 assum subst' t2 ty
return (b1 && b2, subst'')
sub trace bind1 bind2 assum subst ty (Intersect t1 t2) = do
(b1, subst') <- sub trace bind1 bind2 assum subst ty t1
(b2, subst'') <- sub trace bind1 bind2 assum subst' ty t2
return (b1 || b2, subst'')
sub trace bind1 bind2 _ subst IntType IntType = return (True, subst)
sub trace bind1 bind2 _ subst IntType RealType = return (True, subst)
sub trace bind1 bind2 _ subst RealType RealType = return (True, subst)
sub trace bind1 bind2 _ subst BoolType BoolType = return (True, subst)
sub trace bind1 bind2 _ subst StringType StringType = return (True, subst)
sub trace bind1 bind2 _ _ _ _ = return (False, subst)
in sub Map.empty Map.empty Map.empty Map.empty subst t1 t2 |
|
9d93f45d35927dd8618b7368675a079f60635bc76a5e28da99b19f272eae5175 | degree9/uikit-hl | dotnav.cljs | (ns uikit-hl.dotnav
(:require [hoplon.core :as h]))
(defmulti uk-dotnav! h/kw-dispatcher :default ::default)
(defmethod h/do! ::default
[elem key val]
(uk-dotnav! elem key val))
(defn- format-dotnav [dotnav]
(str "uk-dotnav-" dotnav))
(defmethod uk-dotnav! ::default
[elem kw v]
(h/do! elem :class {(format-dotnav (name kw)) v}))
(defmethod uk-dotnav! ::dotnav
[elem kw v]
(h/do! elem :class {:uk-dotnav v}))
(defmethod uk-dotnav! ::active
[elem kw v]
(h/do! elem :class {:uk-active v}))
(h/defelem dotnav [{:keys [vertical] :as attr} kids]
(h/ul
(dissoc attr :vertical)
::dotnav true
::vertical vertical
kids))
(h/defelem item [attr kids]
(h/li attr kids))
| null | https://raw.githubusercontent.com/degree9/uikit-hl/b226b1429ea50f8e9a6c1d12c082a3be504dda33/src/uikit_hl/dotnav.cljs | clojure | (ns uikit-hl.dotnav
(:require [hoplon.core :as h]))
(defmulti uk-dotnav! h/kw-dispatcher :default ::default)
(defmethod h/do! ::default
[elem key val]
(uk-dotnav! elem key val))
(defn- format-dotnav [dotnav]
(str "uk-dotnav-" dotnav))
(defmethod uk-dotnav! ::default
[elem kw v]
(h/do! elem :class {(format-dotnav (name kw)) v}))
(defmethod uk-dotnav! ::dotnav
[elem kw v]
(h/do! elem :class {:uk-dotnav v}))
(defmethod uk-dotnav! ::active
[elem kw v]
(h/do! elem :class {:uk-active v}))
(h/defelem dotnav [{:keys [vertical] :as attr} kids]
(h/ul
(dissoc attr :vertical)
::dotnav true
::vertical vertical
kids))
(h/defelem item [attr kids]
(h/li attr kids))
|
|
ad576c9e9c75d74ca5690f55cee94adf64a97344916bd611cf19135446c5a42a | ghc/packages-base | Function.hs | {-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Function
Copyright : 2006
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
-- Simple combinators working solely on and with functions.
--
-----------------------------------------------------------------------------
module Data.Function
* " Prelude " re - exports
id, const, (.), flip, ($)
-- * Other combinators
, fix
, on
) where
import Prelude
infixl 0 `on`
| @'fix ' f@ is the least fixed point of the function @f@ ,
-- i.e. the least defined @x@ such that @f x = x@.
fix :: (a -> a) -> a
fix f = let x = f x in x
-- | @(*) \`on\` f = \\x y -> f x * f y@.
--
Typical usage : @'Data . ' ( ' compare ' \`on\ ` ' fst')@.
--
Algebraic properties :
--
-- * @(*) \`on\` 'id' = (*)@ (if @(*) ∉ {⊥, 'const' ⊥}@)
--
-- * @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@
--
* @'flip ' on f . ' flip ' on = ' flip ' on ( g . f)@
-- Proofs (so that I don't have to edit the test-suite):
-- (*) `on` id
-- =
-- \x y -> id x * id y
-- =
-- \x y -> x * y
-- = { If (*) /= _|_ or const _|_. }
-- (*)
-- (*) `on` f `on` g
-- =
-- ((*) `on` f) `on` g
-- =
-- \x y -> ((*) `on` f) (g x) (g y)
-- =
\x y - > ( \x y - > f x * f y ) ( g x ) ( g y )
-- =
-- \x y -> f (g x) * f (g y)
-- =
\x y - > ( f . ) x * ( f . ) y
-- =
( * ) ` on ` ( f . )
-- =
( * ) ` on ` f .
-- flip on f . flip on g
-- =
-- (\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g
-- =
-- (\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)
-- =
-- \(*) -> (*) `on` g `on` f
-- = { See above. }
-- \(*) -> (*) `on` g . f
-- =
-- (\h (*) -> (*) `on` h) (g . f)
-- =
-- flip on (g . f)
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y
| null | https://raw.githubusercontent.com/ghc/packages-base/52c0b09036c36f1ed928663abb2f295fd36a88bb/Data/Function.hs | haskell | # LANGUAGE Safe #
---------------------------------------------------------------------------
|
Module : Data.Function
License : BSD-style (see the LICENSE file in the distribution)
Maintainer :
Stability : experimental
Portability : portable
Simple combinators working solely on and with functions.
---------------------------------------------------------------------------
* Other combinators
i.e. the least defined @x@ such that @f x = x@.
| @(*) \`on\` f = \\x y -> f x * f y@.
* @(*) \`on\` 'id' = (*)@ (if @(*) ∉ {⊥, 'const' ⊥}@)
* @((*) \`on\` f) \`on\` g = (*) \`on\` (f . g)@
Proofs (so that I don't have to edit the test-suite):
(*) `on` id
=
\x y -> id x * id y
=
\x y -> x * y
= { If (*) /= _|_ or const _|_. }
(*)
(*) `on` f `on` g
=
((*) `on` f) `on` g
=
\x y -> ((*) `on` f) (g x) (g y)
=
=
\x y -> f (g x) * f (g y)
=
=
=
flip on f . flip on g
=
(\h (*) -> (*) `on` h) f . (\h (*) -> (*) `on` h) g
=
(\(*) -> (*) `on` f) . (\(*) -> (*) `on` g)
=
\(*) -> (*) `on` g `on` f
= { See above. }
\(*) -> (*) `on` g . f
=
(\h (*) -> (*) `on` h) (g . f)
=
flip on (g . f) |
Copyright : 2006
module Data.Function
* " Prelude " re - exports
id, const, (.), flip, ($)
, fix
, on
) where
import Prelude
infixl 0 `on`
| @'fix ' f@ is the least fixed point of the function @f@ ,
fix :: (a -> a) -> a
fix f = let x = f x in x
Typical usage : @'Data . ' ( ' compare ' \`on\ ` ' fst')@.
Algebraic properties :
* @'flip ' on f . ' flip ' on = ' flip ' on ( g . f)@
\x y - > ( \x y - > f x * f y ) ( g x ) ( g y )
\x y - > ( f . ) x * ( f . ) y
( * ) ` on ` ( f . )
( * ) ` on ` f .
on :: (b -> b -> c) -> (a -> b) -> a -> a -> c
(.*.) `on` f = \x y -> f x .*. f y
|
d2b4d903f2ef40ca229bb28faff65e420d16128535a834e4055960f24e70f941 | ijvcms/chuanqi_dev | goods_type_config.erl | %%%-------------------------------------------------------------------
@author zhengsiying
%%% @doc
%%% 自动生成文件,不要手动修改
%%% @end
Created : 2016/10/12
%%%-------------------------------------------------------------------
-module(goods_type_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list() ->
[{4,3}, {4,2}, {4,5}].
get({4,3}) ->
#goods_type_conf{
key = 1,
type = 4,
sub_type = 3,
cd_time = 2
};
get({4,2}) ->
#goods_type_conf{
key = 2,
type = 4,
sub_type = 2,
cd_time = 1
};
get({4,5}) ->
#goods_type_conf{
key = 3,
type = 4,
sub_type = 5,
cd_time = 2
};
get(_Key) ->
?ERR("undefined key from goods_type_config ~p", [_Key]). | null | https://raw.githubusercontent.com/ijvcms/chuanqi_dev/7742184bded15f25be761c4f2d78834249d78097/server/trunk/server/src/config/goods_type_config.erl | erlang | -------------------------------------------------------------------
@doc
自动生成文件,不要手动修改
@end
------------------------------------------------------------------- | @author zhengsiying
Created : 2016/10/12
-module(goods_type_config).
-include("common.hrl").
-include("config.hrl").
-compile([export_all]).
get_list() ->
[{4,3}, {4,2}, {4,5}].
get({4,3}) ->
#goods_type_conf{
key = 1,
type = 4,
sub_type = 3,
cd_time = 2
};
get({4,2}) ->
#goods_type_conf{
key = 2,
type = 4,
sub_type = 2,
cd_time = 1
};
get({4,5}) ->
#goods_type_conf{
key = 3,
type = 4,
sub_type = 5,
cd_time = 2
};
get(_Key) ->
?ERR("undefined key from goods_type_config ~p", [_Key]). |
9629250279568d2356e88955c6ec5c56a733b06ca1f4bcba60b7ae6444cabc9d | argp/bap | batHashcons.mli |
* Hashcons -- a hashconsing library
* Copyright ( C ) 2011 Batteries Included Development Team
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Hashcons -- a hashconsing library
* Copyright (C) 2011 Batteries Included Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
(** Hash consing of data structures *)
(** The type [t hobj] represents hashed objects of type [t]. A hashed
object contains a unique tag and a hash code. *)
type 'a hobj = private {
obj : 'a ;
tag : int ; (** Unique id for this object *)
hcode : int ; (** Hash code for this object *)
}
type 'a t = 'a hobj
(** A synonym for convenience *)
val compare : 'a hobj -> 'a hobj -> int
(** Comparison on the tags *)
(** Hashcons tables *)
module type Table = sig
type key
(** type of objects in the table *)
type t
(** type of the table *)
val create : int -> t
(** [create n] creates a table with at least [n] cells. *)
val clear : t -> unit
(** [clear tab] removes all entries from the table [tab]. *)
val hashcons : t -> key -> key hobj
(** [hashcons tab k] returns either [k], adding it to the table
[tab] as a side effect, or if [k] is already in the table then
it returns the hashed object corresponding to that entry.
@raise Failure if number of objects with the same hash reaches system limit of array size *)
val iter : (key hobj -> unit) -> t -> unit
(** [iter f tab] applies [f] to every live hashed object in the
table [tab]. *)
val fold : (key hobj -> 'a -> 'a) -> t -> 'a -> 'a
* [ fold f tab ] folds [ f ] across every live hashed object in
the table [ tab ] , starting with value [ x0 ]
the table [tab], starting with value [x0] *)
val count : t -> int
* [ count tab ] returns a count of how many live objects are in
[ tab ] . This can decrease whenever the GC runs , even during
execution , so consider the returned value as an upper - bound .
[tab]. This can decrease whenever the GC runs, even during
execution, so consider the returned value as an upper-bound. *)
end
module MakeTable (HT : BatHashtbl.HashedType)
: Table with type key = HT.t
(** Hashing utilities *)
module H : sig
val hc0_ : int -> int
* [ hc0 _ h ] corresponds to the hashcode of a first constructor
applied to an object of hashcode [ h ]
applied to an object of hashcode [h] *)
val hc0 : 'a hobj -> int
* [ hc0 ho ] is the hashcode of a first constructor applied to the
hashed object [ ho ]
hashed object [ho] *)
val hc1_ : int -> int -> int
(** [hc1_ h k] corresponds to the hashcode of the [k]th
constructor applied to an object of hashcode [h]. *)
val hc1 : 'a hobj -> int -> int
(** [hc1 ho k] corresponds to the hashcode of the [k]th
constructor applied to the hashed object [ho]. *)
end
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/src/batHashcons.mli | ocaml | * Hash consing of data structures
* The type [t hobj] represents hashed objects of type [t]. A hashed
object contains a unique tag and a hash code.
* Unique id for this object
* Hash code for this object
* A synonym for convenience
* Comparison on the tags
* Hashcons tables
* type of objects in the table
* type of the table
* [create n] creates a table with at least [n] cells.
* [clear tab] removes all entries from the table [tab].
* [hashcons tab k] returns either [k], adding it to the table
[tab] as a side effect, or if [k] is already in the table then
it returns the hashed object corresponding to that entry.
@raise Failure if number of objects with the same hash reaches system limit of array size
* [iter f tab] applies [f] to every live hashed object in the
table [tab].
* Hashing utilities
* [hc1_ h k] corresponds to the hashcode of the [k]th
constructor applied to an object of hashcode [h].
* [hc1 ho k] corresponds to the hashcode of the [k]th
constructor applied to the hashed object [ho]. |
* Hashcons -- a hashconsing library
* Copyright ( C ) 2011 Batteries Included Development Team
*
* This library is free software ; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation ; either
* version 2.1 of the License , or ( at your option ) any later version ,
* with the special exception on linking described in file LICENSE .
*
* This library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA
* Hashcons -- a hashconsing library
* Copyright (C) 2011 Batteries Included Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)
type 'a hobj = private {
obj : 'a ;
}
type 'a t = 'a hobj
val compare : 'a hobj -> 'a hobj -> int
module type Table = sig
type key
type t
val create : int -> t
val clear : t -> unit
val hashcons : t -> key -> key hobj
val iter : (key hobj -> unit) -> t -> unit
val fold : (key hobj -> 'a -> 'a) -> t -> 'a -> 'a
* [ fold f tab ] folds [ f ] across every live hashed object in
the table [ tab ] , starting with value [ x0 ]
the table [tab], starting with value [x0] *)
val count : t -> int
* [ count tab ] returns a count of how many live objects are in
[ tab ] . This can decrease whenever the GC runs , even during
execution , so consider the returned value as an upper - bound .
[tab]. This can decrease whenever the GC runs, even during
execution, so consider the returned value as an upper-bound. *)
end
module MakeTable (HT : BatHashtbl.HashedType)
: Table with type key = HT.t
module H : sig
val hc0_ : int -> int
* [ hc0 _ h ] corresponds to the hashcode of a first constructor
applied to an object of hashcode [ h ]
applied to an object of hashcode [h] *)
val hc0 : 'a hobj -> int
* [ hc0 ho ] is the hashcode of a first constructor applied to the
hashed object [ ho ]
hashed object [ho] *)
val hc1_ : int -> int -> int
val hc1 : 'a hobj -> int -> int
end
|
fc49acb2c2c2708ea7d67c0efcf7d2ae8252598d643135548cf670a67aca84ac | anuragsoni/poll | epoll_poll.ml | [%%import "config.h"]
[%%if defined POLL_CONF_LINUX]
let available = true
let fd_of_int : int -> Unix.file_descr = Obj.magic
module Ffi = struct
external epoll_create1 : unit -> Unix.file_descr = "poll_stub_epoll_create1"
external epoll_in : unit -> int = "poll_stub_epollin"
external epoll_rdhup : unit -> int = "poll_stub_epollrdhup"
external epoll_hup : unit -> int = "poll_stub_epollhup"
external epoll_err : unit -> int = "poll_stub_epollerr"
external epoll_pri : unit -> int = "poll_stub_epollpri"
external epoll_out : unit -> int = "poll_stub_epollout"
external epoll_oneshot : unit -> int = "poll_stub_epolloneshot"
external epoll_event_sizeof : unit -> int = "poll_stub_epoll_event_sizeout"
external epoll_fd_offset : unit -> int = "poll_stub_epoll_fd_offset"
external epoll_flag_offset : unit -> int = "poll_stub_epoll_flag_offset"
external epoll_ctl_add
: Unix.file_descr
-> Unix.file_descr
-> int
-> unit
= "poll_stub_epoll_ctl_add"
external epoll_ctl_mod
: Unix.file_descr
-> Unix.file_descr
-> int
-> unit
= "poll_stub_epoll_ctl_mod"
external epoll_ctl_del
: Unix.file_descr
-> Unix.file_descr
-> unit
= "poll_stub_epoll_ctl_del"
let epoll_event_sizeof = epoll_event_sizeof ()
let epoll_fd_offset = epoll_fd_offset ()
let epoll_flag_offset = epoll_flag_offset ()
let epoll_in = epoll_in ()
let epoll_rdhup = epoll_rdhup ()
let epoll_hup = epoll_hup ()
let epoll_err = epoll_err ()
let epoll_oneshot = epoll_oneshot ()
let epoll_pri = epoll_pri ()
let epoll_out = epoll_out ()
let flag_read = epoll_in lor epoll_rdhup lor epoll_hup lor epoll_err lor epoll_pri
let flag_write = epoll_out lor epoll_hup lor epoll_err
external epoll_wait
: Unix.file_descr
-> Bigstring.t
-> int
-> int
= "poll_stub_epoll_wait"
end
type t =
{ epoll_fd : Unix.file_descr
; mutable ready_events : int
; events : Bigstring.t
; mutable closed : bool
; flags : (Unix.file_descr, int) Hashtbl.t
}
let ensure_open t = if t.closed then failwith "Attempting to use a closed epoll fd"
let backend = Backend.Epoll
let create ?(num_events = 256) () =
if num_events < 1 then invalid_arg "Number of events cannot be less than 1";
{ epoll_fd = Ffi.epoll_create1 ()
; ready_events = 0
; events = Bigstring.create (num_events * Ffi.epoll_event_sizeof)
; closed = false
; flags = Hashtbl.create 65536
}
;;
let clear t =
ensure_open t;
t.ready_events <- 0
;;
let close t =
if not t.closed
then (
t.closed <- true;
Unix.close t.epoll_fd)
;;
let set t fd event =
ensure_open t;
let current_flags = Hashtbl.find_opt t.flags fd in
let new_flags =
match event.Event.readable, event.Event.writable with
| false, false -> None
| true, false -> Some (Ffi.epoll_oneshot lor Ffi.flag_read)
| false, true -> Some (Ffi.epoll_oneshot lor Ffi.flag_write)
| true, true -> Some Ffi.(epoll_oneshot lor flag_read lor flag_write)
in
match current_flags, new_flags with
| None, None -> ()
| None, Some f ->
Ffi.epoll_ctl_add t.epoll_fd fd f;
Hashtbl.replace t.flags fd f
| Some _, None ->
Ffi.epoll_ctl_del t.epoll_fd fd;
Hashtbl.remove t.flags fd
| Some _, Some b ->
Ffi.epoll_ctl_mod t.epoll_fd fd b;
Hashtbl.replace t.flags fd b
;;
let wait t timeout =
let timeout =
match timeout with
| Timeout.Immediate -> 0
| Never -> -1
| After x -> Int64.to_int (Int64.div x 1_000_000L)
in
ensure_open t;
t.ready_events <- 0;
t.ready_events <- Ffi.epoll_wait t.epoll_fd t.events timeout;
if t.ready_events = 0 then `Timeout else `Ok
;;
let get_fd_at buf idx =
fd_of_int
(Bigstring.unsafe_get_int32_le
buf
~pos:((idx * Ffi.epoll_event_sizeof) + Ffi.epoll_fd_offset))
;;
let get_flags_at buf idx =
Bigstring.unsafe_get_int32_le
buf
~pos:((idx * Ffi.epoll_event_sizeof) + Ffi.epoll_flag_offset)
;;
let iter_ready t ~f =
ensure_open t;
for i = 0 to t.ready_events - 1 do
let fd = get_fd_at t.events i in
let flags = get_flags_at t.events i in
let readable = flags land Ffi.flag_read <> 0 in
let writable = flags land Ffi.flag_write <> 0 in
f fd { Event.readable; writable }
done
;;
[%%else]
include Empty_poll
let available = false
[%%endif]
| null | https://raw.githubusercontent.com/anuragsoni/poll/a9a496cfd1a7db0df9bab0551d6f1e3fdecc627a/src/epoll_poll.ml | ocaml | [%%import "config.h"]
[%%if defined POLL_CONF_LINUX]
let available = true
let fd_of_int : int -> Unix.file_descr = Obj.magic
module Ffi = struct
external epoll_create1 : unit -> Unix.file_descr = "poll_stub_epoll_create1"
external epoll_in : unit -> int = "poll_stub_epollin"
external epoll_rdhup : unit -> int = "poll_stub_epollrdhup"
external epoll_hup : unit -> int = "poll_stub_epollhup"
external epoll_err : unit -> int = "poll_stub_epollerr"
external epoll_pri : unit -> int = "poll_stub_epollpri"
external epoll_out : unit -> int = "poll_stub_epollout"
external epoll_oneshot : unit -> int = "poll_stub_epolloneshot"
external epoll_event_sizeof : unit -> int = "poll_stub_epoll_event_sizeout"
external epoll_fd_offset : unit -> int = "poll_stub_epoll_fd_offset"
external epoll_flag_offset : unit -> int = "poll_stub_epoll_flag_offset"
external epoll_ctl_add
: Unix.file_descr
-> Unix.file_descr
-> int
-> unit
= "poll_stub_epoll_ctl_add"
external epoll_ctl_mod
: Unix.file_descr
-> Unix.file_descr
-> int
-> unit
= "poll_stub_epoll_ctl_mod"
external epoll_ctl_del
: Unix.file_descr
-> Unix.file_descr
-> unit
= "poll_stub_epoll_ctl_del"
let epoll_event_sizeof = epoll_event_sizeof ()
let epoll_fd_offset = epoll_fd_offset ()
let epoll_flag_offset = epoll_flag_offset ()
let epoll_in = epoll_in ()
let epoll_rdhup = epoll_rdhup ()
let epoll_hup = epoll_hup ()
let epoll_err = epoll_err ()
let epoll_oneshot = epoll_oneshot ()
let epoll_pri = epoll_pri ()
let epoll_out = epoll_out ()
let flag_read = epoll_in lor epoll_rdhup lor epoll_hup lor epoll_err lor epoll_pri
let flag_write = epoll_out lor epoll_hup lor epoll_err
external epoll_wait
: Unix.file_descr
-> Bigstring.t
-> int
-> int
= "poll_stub_epoll_wait"
end
type t =
{ epoll_fd : Unix.file_descr
; mutable ready_events : int
; events : Bigstring.t
; mutable closed : bool
; flags : (Unix.file_descr, int) Hashtbl.t
}
let ensure_open t = if t.closed then failwith "Attempting to use a closed epoll fd"
let backend = Backend.Epoll
let create ?(num_events = 256) () =
if num_events < 1 then invalid_arg "Number of events cannot be less than 1";
{ epoll_fd = Ffi.epoll_create1 ()
; ready_events = 0
; events = Bigstring.create (num_events * Ffi.epoll_event_sizeof)
; closed = false
; flags = Hashtbl.create 65536
}
;;
let clear t =
ensure_open t;
t.ready_events <- 0
;;
let close t =
if not t.closed
then (
t.closed <- true;
Unix.close t.epoll_fd)
;;
let set t fd event =
ensure_open t;
let current_flags = Hashtbl.find_opt t.flags fd in
let new_flags =
match event.Event.readable, event.Event.writable with
| false, false -> None
| true, false -> Some (Ffi.epoll_oneshot lor Ffi.flag_read)
| false, true -> Some (Ffi.epoll_oneshot lor Ffi.flag_write)
| true, true -> Some Ffi.(epoll_oneshot lor flag_read lor flag_write)
in
match current_flags, new_flags with
| None, None -> ()
| None, Some f ->
Ffi.epoll_ctl_add t.epoll_fd fd f;
Hashtbl.replace t.flags fd f
| Some _, None ->
Ffi.epoll_ctl_del t.epoll_fd fd;
Hashtbl.remove t.flags fd
| Some _, Some b ->
Ffi.epoll_ctl_mod t.epoll_fd fd b;
Hashtbl.replace t.flags fd b
;;
let wait t timeout =
let timeout =
match timeout with
| Timeout.Immediate -> 0
| Never -> -1
| After x -> Int64.to_int (Int64.div x 1_000_000L)
in
ensure_open t;
t.ready_events <- 0;
t.ready_events <- Ffi.epoll_wait t.epoll_fd t.events timeout;
if t.ready_events = 0 then `Timeout else `Ok
;;
let get_fd_at buf idx =
fd_of_int
(Bigstring.unsafe_get_int32_le
buf
~pos:((idx * Ffi.epoll_event_sizeof) + Ffi.epoll_fd_offset))
;;
let get_flags_at buf idx =
Bigstring.unsafe_get_int32_le
buf
~pos:((idx * Ffi.epoll_event_sizeof) + Ffi.epoll_flag_offset)
;;
let iter_ready t ~f =
ensure_open t;
for i = 0 to t.ready_events - 1 do
let fd = get_fd_at t.events i in
let flags = get_flags_at t.events i in
let readable = flags land Ffi.flag_read <> 0 in
let writable = flags land Ffi.flag_write <> 0 in
f fd { Event.readable; writable }
done
;;
[%%else]
include Empty_poll
let available = false
[%%endif]
|
|
93d8a1cd4504dbfbddb0e71ab330176502f2257b0ceb645fc402e09b041176b3 | ucsd-progsys/nate | compact.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ I d : compact.ml , v 1.7 2002/10/28 16:46:49 maranget Exp $
(* Compaction of an automata *)
open Lexgen
(* Code for memory actions *)
let code = Table.create 0
instructions are 2 8 - bits integers , a 0xff byte means return
let emit_int i = Table.emit code i
let ins_mem i c = match i with
| Copy (dst, src) -> dst::src::c
| Set dst -> dst::0xff::c
let ins_tag i c = match i with
| SetTag (dst, src) -> dst::src::c
| EraseTag dst -> dst::0xff::c
let do_emit_code c =
let r = Table.size code in
List.iter emit_int c ;
emit_int 0xff ;
r
let memory = Hashtbl.create 101
let mem_emit_code c =
try Hashtbl.find memory c with
| Not_found ->
let r = do_emit_code c in
Hashtbl.add memory c r ;
r
(* Code address 0 is the empty code (ie do nothing) *)
let _ = mem_emit_code []
let emit_tag_code c = mem_emit_code (List.fold_right ins_tag c [])
and emit_mem_code c =mem_emit_code (List.fold_right ins_mem c [])
(*******************************************)
(* Compact the transition and check arrays *)
(*******************************************)
(* Determine the integer occurring most frequently in an array *)
let most_frequent_elt v =
let frequencies = Hashtbl.create 17 in
let max_freq = ref 0 in
let most_freq = ref (v.(0)) in
for i = 0 to Array.length v - 1 do
let e = v.(i) in
let r =
try
Hashtbl.find frequencies e
with Not_found ->
let r = ref 1 in Hashtbl.add frequencies e r; r in
incr r;
if !r > !max_freq then begin max_freq := !r; most_freq := e end
done;
!most_freq
(* Transform an array into a list of (position, non-default element) *)
let non_default_elements def v =
let rec nondef i =
if i >= Array.length v then [] else begin
let e = v.(i) in
if e = def then nondef(i+1) else (i, e) :: nondef(i+1)
end in
nondef 0
type t_compact =
{mutable c_trans : int array ;
mutable c_check : int array ;
mutable c_last_used : int ; }
let create_compact () =
{ c_trans = Array.create 1024 0 ;
c_check = Array.create 1024 (-1) ;
c_last_used = 0 ; }
let reset_compact c =
c.c_trans <- Array.create 1024 0 ;
c.c_check <- Array.create 1024 (-1) ;
c.c_last_used <- 0
One compacted table for transitions , one other for memory actions
let trans = create_compact ()
and moves = create_compact ()
let grow_compact c =
let old_trans = c.c_trans
and old_check = c.c_check in
let n = Array.length old_trans in
c.c_trans <- Array.create (2*n) 0;
Array.blit old_trans 0 c.c_trans 0 c.c_last_used;
c.c_check <- Array.create (2*n) (-1);
Array.blit old_check 0 c.c_check 0 c.c_last_used
let do_pack state_num orig compact =
let default = most_frequent_elt orig in
let nondef = non_default_elements default orig in
let rec pack_from b =
while
b + 257 > Array.length compact.c_trans
do
grow_compact compact
done;
let rec try_pack = function
[] -> b
| (pos, v) :: rem ->
if compact.c_check.(b + pos) = -1 then
try_pack rem
else pack_from (b+1) in
try_pack nondef in
let base = pack_from 0 in
List.iter
(fun (pos, v) ->
compact.c_trans.(base + pos) <- v;
compact.c_check.(base + pos) <- state_num)
nondef;
if base + 257 > compact.c_last_used then
compact.c_last_used <- base + 257;
(base, default)
let pack_moves state_num move_t =
let move_v = Array.create 257 0
and move_m = Array.create 257 0 in
for i = 0 to 256 do
let act,c = move_t.(i) in
move_v.(i) <- (match act with Backtrack -> -1 | Goto n -> n) ;
move_m.(i) <- emit_mem_code c
done ;
let pk_trans = do_pack state_num move_v trans
and pk_moves = do_pack state_num move_m moves in
pk_trans, pk_moves
(* Build the tables *)
type lex_tables =
{ tbl_base: int array; (* Perform / Shift *)
tbl_backtrk: int array; (* No_remember / Remember *)
tbl_default: int array; (* Default transition *)
Transitions ( compacted )
tbl_check: int array; (* Check (compacted) *)
(* code addresses are managed in a similar fashion as transitions *)
code ptr / base for Shift
tbl_backtrk_code : int array; (* nothing / code when Remember *)
(* moves to execute before transitions (compacted) *)
tbl_default_code : int array;
tbl_trans_code : int array;
tbl_check_code : int array;
(* byte code itself *)
tbl_code: int array;}
let compact_tables state_v =
let n = Array.length state_v in
let base = Array.create n 0
and backtrk = Array.create n (-1)
and default = Array.create n 0
and base_code = Array.create n 0
and backtrk_code = Array.create n 0
and default_code = Array.create n 0 in
for i = 0 to n - 1 do
match state_v.(i) with
| Perform (n,c) ->
base.(i) <- -(n+1) ;
base_code.(i) <- emit_tag_code c
| Shift(trans, move) ->
begin match trans with
| No_remember -> ()
| Remember (n,c) ->
backtrk.(i) <- n ;
backtrk_code.(i) <- emit_tag_code c
end;
let (b_trans, d_trans),(b_moves,d_moves) = pack_moves i move in
base.(i) <- b_trans; default.(i) <- d_trans ;
base_code.(i) <- b_moves; default_code.(i) <- d_moves ;
done;
let code = Table.trim code in
let tables =
if Array.length code > 1 then
{ tbl_base = base;
tbl_backtrk = backtrk;
tbl_default = default;
tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
tbl_base_code = base_code ;
tbl_backtrk_code = backtrk_code;
tbl_default_code = default_code;
tbl_trans_code = Array.sub moves.c_trans 0 moves.c_last_used;
tbl_check_code = Array.sub moves.c_check 0 moves.c_last_used;
tbl_code = code}
else (* when no memory moves, do not emit related tables *)
{ tbl_base = base;
tbl_backtrk = backtrk;
tbl_default = default;
tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
tbl_base_code = [||] ;
tbl_backtrk_code = [||];
tbl_default_code = [||];
tbl_trans_code = [||];
tbl_check_code = [||];
tbl_code = [||]}
in
reset_compact trans ;
reset_compact moves ;
tables
| null | https://raw.githubusercontent.com/ucsd-progsys/nate/8b1267cd8b10283d8bc239d16a28c654a4cb8942/eval/sherrloc/easyocaml%2B%2B/lex/compact.ml | ocaml | *********************************************************************
Objective Caml
*********************************************************************
Compaction of an automata
Code for memory actions
Code address 0 is the empty code (ie do nothing)
*****************************************
Compact the transition and check arrays
*****************************************
Determine the integer occurring most frequently in an array
Transform an array into a list of (position, non-default element)
Build the tables
Perform / Shift
No_remember / Remember
Default transition
Check (compacted)
code addresses are managed in a similar fashion as transitions
nothing / code when Remember
moves to execute before transitions (compacted)
byte code itself
when no memory moves, do not emit related tables | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ I d : compact.ml , v 1.7 2002/10/28 16:46:49 maranget Exp $
open Lexgen
let code = Table.create 0
instructions are 2 8 - bits integers , a 0xff byte means return
let emit_int i = Table.emit code i
let ins_mem i c = match i with
| Copy (dst, src) -> dst::src::c
| Set dst -> dst::0xff::c
let ins_tag i c = match i with
| SetTag (dst, src) -> dst::src::c
| EraseTag dst -> dst::0xff::c
let do_emit_code c =
let r = Table.size code in
List.iter emit_int c ;
emit_int 0xff ;
r
let memory = Hashtbl.create 101
let mem_emit_code c =
try Hashtbl.find memory c with
| Not_found ->
let r = do_emit_code c in
Hashtbl.add memory c r ;
r
let _ = mem_emit_code []
let emit_tag_code c = mem_emit_code (List.fold_right ins_tag c [])
and emit_mem_code c =mem_emit_code (List.fold_right ins_mem c [])
let most_frequent_elt v =
let frequencies = Hashtbl.create 17 in
let max_freq = ref 0 in
let most_freq = ref (v.(0)) in
for i = 0 to Array.length v - 1 do
let e = v.(i) in
let r =
try
Hashtbl.find frequencies e
with Not_found ->
let r = ref 1 in Hashtbl.add frequencies e r; r in
incr r;
if !r > !max_freq then begin max_freq := !r; most_freq := e end
done;
!most_freq
let non_default_elements def v =
let rec nondef i =
if i >= Array.length v then [] else begin
let e = v.(i) in
if e = def then nondef(i+1) else (i, e) :: nondef(i+1)
end in
nondef 0
type t_compact =
{mutable c_trans : int array ;
mutable c_check : int array ;
mutable c_last_used : int ; }
let create_compact () =
{ c_trans = Array.create 1024 0 ;
c_check = Array.create 1024 (-1) ;
c_last_used = 0 ; }
let reset_compact c =
c.c_trans <- Array.create 1024 0 ;
c.c_check <- Array.create 1024 (-1) ;
c.c_last_used <- 0
One compacted table for transitions , one other for memory actions
let trans = create_compact ()
and moves = create_compact ()
let grow_compact c =
let old_trans = c.c_trans
and old_check = c.c_check in
let n = Array.length old_trans in
c.c_trans <- Array.create (2*n) 0;
Array.blit old_trans 0 c.c_trans 0 c.c_last_used;
c.c_check <- Array.create (2*n) (-1);
Array.blit old_check 0 c.c_check 0 c.c_last_used
let do_pack state_num orig compact =
let default = most_frequent_elt orig in
let nondef = non_default_elements default orig in
let rec pack_from b =
while
b + 257 > Array.length compact.c_trans
do
grow_compact compact
done;
let rec try_pack = function
[] -> b
| (pos, v) :: rem ->
if compact.c_check.(b + pos) = -1 then
try_pack rem
else pack_from (b+1) in
try_pack nondef in
let base = pack_from 0 in
List.iter
(fun (pos, v) ->
compact.c_trans.(base + pos) <- v;
compact.c_check.(base + pos) <- state_num)
nondef;
if base + 257 > compact.c_last_used then
compact.c_last_used <- base + 257;
(base, default)
let pack_moves state_num move_t =
let move_v = Array.create 257 0
and move_m = Array.create 257 0 in
for i = 0 to 256 do
let act,c = move_t.(i) in
move_v.(i) <- (match act with Backtrack -> -1 | Goto n -> n) ;
move_m.(i) <- emit_mem_code c
done ;
let pk_trans = do_pack state_num move_v trans
and pk_moves = do_pack state_num move_m moves in
pk_trans, pk_moves
type lex_tables =
Transitions ( compacted )
code ptr / base for Shift
tbl_default_code : int array;
tbl_trans_code : int array;
tbl_check_code : int array;
tbl_code: int array;}
let compact_tables state_v =
let n = Array.length state_v in
let base = Array.create n 0
and backtrk = Array.create n (-1)
and default = Array.create n 0
and base_code = Array.create n 0
and backtrk_code = Array.create n 0
and default_code = Array.create n 0 in
for i = 0 to n - 1 do
match state_v.(i) with
| Perform (n,c) ->
base.(i) <- -(n+1) ;
base_code.(i) <- emit_tag_code c
| Shift(trans, move) ->
begin match trans with
| No_remember -> ()
| Remember (n,c) ->
backtrk.(i) <- n ;
backtrk_code.(i) <- emit_tag_code c
end;
let (b_trans, d_trans),(b_moves,d_moves) = pack_moves i move in
base.(i) <- b_trans; default.(i) <- d_trans ;
base_code.(i) <- b_moves; default_code.(i) <- d_moves ;
done;
let code = Table.trim code in
let tables =
if Array.length code > 1 then
{ tbl_base = base;
tbl_backtrk = backtrk;
tbl_default = default;
tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
tbl_base_code = base_code ;
tbl_backtrk_code = backtrk_code;
tbl_default_code = default_code;
tbl_trans_code = Array.sub moves.c_trans 0 moves.c_last_used;
tbl_check_code = Array.sub moves.c_check 0 moves.c_last_used;
tbl_code = code}
{ tbl_base = base;
tbl_backtrk = backtrk;
tbl_default = default;
tbl_trans = Array.sub trans.c_trans 0 trans.c_last_used;
tbl_check = Array.sub trans.c_check 0 trans.c_last_used;
tbl_base_code = [||] ;
tbl_backtrk_code = [||];
tbl_default_code = [||];
tbl_trans_code = [||];
tbl_check_code = [||];
tbl_code = [||]}
in
reset_compact trans ;
reset_compact moves ;
tables
|
a66e0c024ac8c3539d43867072859f6df9d9abff0906dac3948d005cf7455149 | spechub/Hets | OWL22CASL.hs | # LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE TypeSynonymInstances #-}
# LANGUAGE FlexibleInstances #
|
Module : $ Header$
Description : Comorphism from OWL 2 to CASL_Dl
Copyright : ( c ) , : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( via Logic . Logic )
Module : $Header$
Description : Comorphism from OWL 2 to CASL_Dl
Copyright : (c) Francisc-Nicolae Bungiu, Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (via Logic.Logic)
-}
module OWL2.OWL22CASL (OWL22CASL (..)) where
import Logic.Logic as Logic
import Logic.Comorphism
import Common.AS_Annotation
import Common.Result
import Common.Id
import Common.IRI
import Control.Monad
import qualified Control.Monad.Fail as Fail
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Common.Lib.MapSet as MapSet
import qualified Common.Lib.Rel as Rel
the DL with the initial signature for OWL
import CASL_DL.PredefinedCASLAxioms
OWL = domain
import OWL2.Logic_OWL2
import OWL2.AS as AS
import OWL2.Parse
import OWL2.Print
import OWL2.ProfilesAndSublogics
import OWL2.ManchesterPrint ()
import OWL2.Morphism
import OWL2.Symbols
import qualified OWL2.Sign as OS
import qualified OWL2.Sublogic as SL
-- CASL_DL = codomain
import CASL.Logic_CASL
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.Morphism
import CASL.Induction
import CASL.Sublogic
import OWL2.ManchesterParser
import Common.ProofTree
import Data.Maybe
import Text.ParserCombinators.Parsec
data OWL22CASL = OWL22CASL deriving Show
instance Language OWL22CASL
instance Comorphism
OWL22CASL -- comorphism
OWL2 -- lid domain
ProfSub -- sublogics domain
OntologyDocument -- Basic spec domain
Axiom -- sentence domain
SymbItems -- symbol items domain
SymbMapItems -- symbol map items domain
OS.Sign -- signature domain
OWLMorphism -- morphism domain
Entity -- symbol domain
RawSymb -- rawsymbol domain
ProofTree -- proof tree codomain
CASL -- lid codomain
CASL_Sublogics -- sublogics codomain
CASLBasicSpec -- Basic spec codomain
CASLFORMULA -- sentence codomain
SYMB_ITEMS -- symbol items codomain
SYMB_MAP_ITEMS -- symbol map items codomain
CASLSign -- signature codomain
CASLMor -- morphism codomain
Symbol -- symbol codomain
RawSymbol -- rawsymbol codomain
ProofTree -- proof tree domain
where
sourceLogic OWL22CASL = OWL2
sourceSublogic OWL22CASL = topS
targetLogic OWL22CASL = CASL
mapSublogic OWL22CASL _ = Just $ cFol
{ cons_features = emptyMapConsFeature }
map_theory OWL22CASL = mapTheory
map_morphism OWL22CASL = mapMorphism
map_symbol OWL22CASL _ = mapSymbol
isInclusionComorphism OWL22CASL = True
has_model_expansion OWL22CASL = True
-- s = emptySign ()
objectPropPred :: PredType
objectPropPred = PredType [thing, thing]
dataPropPred :: PredType
dataPropPred = PredType [thing, dataS]
indiConst :: OpType
indiConst = OpType Total [] thing
uriToIdM :: IRI -> Result Id
uriToIdM = return . uriToCaslId
tokDecl :: Token -> VAR_DECL
tokDecl = flip mkVarDecl thing
tokDataDecl :: Token -> VAR_DECL
tokDataDecl = flip mkVarDecl dataS
nameDecl :: Int -> SORT -> VAR_DECL
nameDecl = mkVarDecl . mkNName
thingDecl :: Int -> VAR_DECL
thingDecl = flip nameDecl thing
dataDecl :: Int -> VAR_DECL
dataDecl = flip nameDecl dataS
qualThing :: Int -> TERM f
qualThing = toQualVar . thingDecl
qualData :: Int -> TERM f
qualData = toQualVar . dataDecl
implConj :: [FORMULA f] -> FORMULA f -> FORMULA f
implConj = mkImpl . conjunct
mkNC :: [FORMULA f] -> FORMULA f
mkNC = mkNeg . conjunct
mkEqVar :: VAR_DECL -> TERM f -> FORMULA f
mkEqVar = mkStEq . toQualVar
mkFEI :: [VAR_DECL] -> [VAR_DECL] -> FORMULA f -> FORMULA f -> FORMULA f
mkFEI l1 l2 f = mkForall l1 . mkExist l2 . mkImpl f
mkFIE :: [Int] -> [FORMULA f] -> Int -> Int -> FORMULA f
mkFIE l1 l2 x y = mkVDecl l1 $ implConj l2 $ mkEqVar (thingDecl x) $ qualThing y
mkFI :: [VAR_DECL] -> [VAR_DECL] -> FORMULA f -> FORMULA f -> FORMULA f
mkFI l1 l2 f1 = (mkForall l1) . (mkImpl (mkExist l2 f1))
mkRI :: [Int] -> Int -> FORMULA f -> FORMULA f
mkRI l x so = mkVDecl l $ mkImpl (mkMember (qualThing x) thing) so
mkThingVar :: VAR -> TERM f
mkThingVar v = Qual_var v thing nullRange
mkEqDecl :: Int -> TERM f -> FORMULA f
mkEqDecl i = mkEqVar (thingDecl i)
mkVDecl :: [Int] -> FORMULA f -> FORMULA f
mkVDecl = mkForall . map thingDecl
mkVDataDecl :: [Int] -> FORMULA f -> FORMULA f
mkVDataDecl = mkForall . map dataDecl
mk1VDecl :: FORMULA f -> FORMULA f
mk1VDecl = mkVDecl [1]
mkPred :: PredType -> [TERM f] -> PRED_NAME -> FORMULA f
mkPred c tl u = mkPredication (mkQualPred u $ toPRED_TYPE c) tl
mkMember :: TERM f -> SORT -> FORMULA f
mkMember t s = Membership t s nullRange
-- | Get all distinct pairs for commutative operations
comPairs :: [t] -> [t1] -> [(t, t1)]
comPairs [] [] = []
comPairs _ [] = []
comPairs [] _ = []
comPairs (a : as) (_ : bs) = mkPairs a bs ++ comPairs as bs
mkPairs :: t -> [s] -> [(t, s)]
mkPairs a = map (\ b -> (a, b))
data VarOrIndi = OVar Int | OIndi IRI
deriving (Show, Eq, Ord)
-- | Mapping of OWL morphisms to CASL morphisms
mapMorphism :: OWLMorphism -> Result CASLMor
mapMorphism oMor = do
cdm <- mapSign $ osource oMor
ccd <- mapSign $ otarget oMor
let emap = mmaps oMor
preds = Map.foldrWithKey (\ (Entity _ ty u1) u2 -> let
i1 = uriToCaslId u1
i2 = uriToCaslId u2
in case ty of
Class -> Map.insert (i1, conceptPred) i2
ObjectProperty -> Map.insert (i1, objectPropPred) i2
DataProperty -> Map.insert (i1, dataPropPred) i2
_ -> id) Map.empty emap
ops = Map.foldrWithKey (\ (Entity _ ty u1) u2 -> case ty of
NamedIndividual -> Map.insert (uriToCaslId u1, indiConst)
(uriToCaslId u2, Total)
_ -> id) Map.empty emap
return (embedMorphism () cdm ccd)
{ op_map = ops
, pred_map = preds }
mapSymbol :: Entity -> Set.Set Symbol
mapSymbol (Entity _ ty iRi) = let
syN = Set.singleton . Symbol (uriToCaslId iRi)
in case ty of
Class -> syN $ PredAsItemType conceptPred
ObjectProperty -> syN $ PredAsItemType objectPropPred
DataProperty -> syN $ PredAsItemType dataPropPred
NamedIndividual -> syN $ OpAsItemType indiConst
AnnotationProperty -> Set.empty
Datatype -> Set.empty
mapSign :: OS.Sign -> Result CASLSign
mapSign sig =
let conc = OS.concepts sig
cvrt = map uriToCaslId . Set.toList
tMp k = MapSet.fromList . map (\ u -> (u, [k]))
cPreds = thing : nothing : cvrt conc
oPreds = cvrt $ OS.objectProperties sig
dPreds = cvrt $ OS.dataProperties sig
aPreds = foldr MapSet.union MapSet.empty
[ tMp conceptPred cPreds
, tMp objectPropPred oPreds
, tMp dataPropPred dPreds ]
in return $ uniteCASLSign predefSign2
(emptySign ())
{ predMap = aPreds
, opMap = tMp indiConst . cvrt $ OS.individuals sig
}
loadDataInformation :: ProfSub -> CASLSign
loadDataInformation sl = let
dts = Set.map uriToCaslId $ SL.datatype $ sublogic sl
eSig x = (emptySign ()) { sortRel =
Rel.fromList [(x, dataS)]}
sigs = Set.toList $
Set.map (\x -> Map.findWithDefault (eSig x) x datatypeSigns) dts
in foldl uniteCASLSign (emptySign ()) sigs
mapTheory :: (OS.Sign, [Named Axiom]) -> Result (CASLSign, [Named CASLFORMULA])
mapTheory (owlSig, owlSens) = let
sl = sublogicOfTheo OWL2 (owlSig, map sentence owlSens)
in do
cSig <- mapSign owlSig
let pSig = loadDataInformation sl
dTypes = ( emptySign ( ) ) { sortRel = Rel.transClosure . Rel.fromSet
. Set.map ( \ d - > ( uriToCaslId d , dataS ) )
. Set.union owlSig }
. Set.map (\ d -> (uriToCaslId d, dataS))
. Set.union predefIRIs $ OS.datatypes owlSig} -}
(cSens, nSigs) <- foldM (\ (x, y) z -> do
(sen, y') <- mapSentence z
return (sen ++ x, y ++ y')) -- uniteCASLSign sig y))
([], []) owlSens
return (foldl1 uniteCASLSign $ [cSig,pSig] ++ nSigs, -- , dTypes],
predefinedAxioms ++ (reverse cSens))
| mapping of OWL to CASL_DL formulae
mapSentence :: Named Axiom -> Result ([Named CASLFORMULA], [CASLSign])
mapSentence inSen = do
(outAx, outSigs) <- mapAxioms $ sentence inSen
return (map (flip mapNamed inSen . const) outAx, outSigs)
mapVar :: VarOrIndi -> Result (TERM ())
mapVar v = case v of
OVar n -> return $ qualThing n
OIndi i -> mapIndivURI i
-- | Mapping of Class URIs
mapClassURI :: Class -> Token -> Result CASLFORMULA
mapClassURI c t = fmap (mkPred conceptPred [mkThingVar t]) $ uriToIdM c
-- | Mapping of Individual URIs
mapIndivURI :: Individual -> Result (TERM ())
mapIndivURI uriI = do
ur <- uriToIdM uriI
return $ mkAppl (mkQualOp ur (Op_type Total [] thing nullRange)) []
mapNNInt :: NNInt -> TERM ()
mapNNInt int = let NNInt uInt = int in foldr1 joinDigits $ map mkDigit uInt
mapIntLit :: IntLit -> TERM ()
mapIntLit int =
let cInt = mapNNInt $ absInt int
in if isNegInt int then negateInt $ upcast cInt integer
else upcast cInt integer
mapDecLit :: DecLit -> TERM ()
mapDecLit dec =
let ip = truncDec dec
np = absInt ip
fp = fracDec dec
n = mkDecimal (mapNNInt np) (mapNNInt fp)
in if isNegInt ip then negateFloat n else n
mapFloatLit :: FloatLit -> TERM ()
mapFloatLit f =
let fb = floatBase f
ex = floatExp f
in mkFloat (mapDecLit fb) (mapIntLit ex)
mapNrLit :: Literal -> TERM ()
mapNrLit l = case l of
NumberLit f
| isFloatInt f -> mapIntLit $ truncDec $ floatBase f
| isFloatDec f -> mapDecLit $ floatBase f
| otherwise -> mapFloatLit f
_ -> error "not number literal"
mapLiteral :: Literal -> Result (TERM ())
mapLiteral lit = return $ case lit of
Literal l ty -> Sorted_term (case ty of
Untyped _ -> foldr consChar emptyStringTerm l
Typed dt -> case getDatatypeCat dt of
OWL2Number -> let p = parse literal "" l in case p of
Right nr -> mapNrLit nr
_ -> error "cannot parse number literal"
OWL2Bool -> case l of
"true" -> trueT
_ -> falseT
_ -> foldr consChar emptyStringTerm l) dataS nullRange
_ -> mapNrLit lit
-- | Mapping of data properties
mapDataProp :: DataPropertyExpression -> Int -> Int
-> Result CASLFORMULA
mapDataProp dp a b = fmap (mkPred dataPropPred [qualThing a, qualData b])
$ uriToIdM dp
-- | Mapping of obj props
mapObjProp :: ObjectPropertyExpression -> Int -> Int
-> Result CASLFORMULA
mapObjProp ob a b = case ob of
ObjectProp u -> fmap (mkPred objectPropPred $ map qualThing [a, b])
$ uriToIdM u
ObjectInverseOf u -> mapObjProp u b a
-- | Mapping of obj props with Individuals
mapObjPropI :: ObjectPropertyExpression -> VarOrIndi -> VarOrIndi
-> Result CASLFORMULA
mapObjPropI ob lP rP = case ob of
ObjectProp u -> do
l <- mapVar lP
r <- mapVar rP
fmap (mkPred objectPropPred [l, r]) $ uriToIdM u
ObjectInverseOf u -> mapObjPropI u rP lP
-- | mapping of individual list
mapComIndivList :: SameOrDifferent -> Maybe Individual
-> [Individual] -> Result [CASLFORMULA]
mapComIndivList sod mol inds = do
fs <- mapM mapIndivURI inds
tps <- case mol of
Nothing -> return $ comPairs fs fs
Just ol -> do
f <- mapIndivURI ol
return $ mkPairs f fs
return $ map (\ (x, y) -> case sod of
Same -> mkStEq x y
Different -> mkNeg $ mkStEq x y) tps
{- | Mapping along DataPropsList for creation of pairs for commutative
operations. -}
mapComDataPropsList :: Maybe DataPropertyExpression
-> [DataPropertyExpression] -> Int -> Int
-> Result [(CASLFORMULA, CASLFORMULA)]
mapComDataPropsList md props a b = do
fs <- mapM (\ x -> mapDataProp x a b) props
case md of
Nothing -> return $ comPairs fs fs
Just dp -> fmap (`mkPairs` fs) $ mapDataProp dp a b
{- | Mapping along ObjectPropsList for creation of pairs for commutative
operations. -}
mapComObjectPropsList :: Maybe ObjectPropertyExpression
-> [ObjectPropertyExpression] -> Int -> Int
-> Result [(CASLFORMULA, CASLFORMULA)]
mapComObjectPropsList mol props a b = do
fs <- mapM (\ x -> mapObjProp x a b) props
case mol of
Nothing -> return $ comPairs fs fs
Just ol -> fmap (`mkPairs` fs) $ mapObjProp ol a b
mapDataRangeAux :: DataRange -> CASLTERM -> Result (CASLFORMULA, [CASLSign])
mapDataRangeAux dr i = case dr of
DataType d fl -> do
let dt = mkMember i $ uriToCaslId d
(sens, s) <- mapAndUnzipM (mapFacet i) fl
return (conjunct $ dt : sens, concat s)
DataComplementOf drc -> do
(sens, s) <- mapDataRangeAux drc i
return (mkNeg sens, s)
DataJunction jt drl -> do
(jl, sl) <- mapAndUnzipM ((\ v r -> mapDataRangeAux r v) i) drl
--let usig = uniteL sl
return $ case jt of
IntersectionOf -> (conjunct jl, concat sl)
UnionOf -> (disjunct jl, concat sl)
DataOneOf cs -> do
ls <- mapM mapLiteral cs
return (disjunct $ map (mkStEq i) ls, [])
| mapping of Data Range
mapDataRange :: DataRange -> Int -> Result (CASLFORMULA, [CASLSign])
mapDataRange dr = mapDataRangeAux dr . qualData
mkFacetPred :: TERM f -> ConstrainingFacet -> TERM f -> (FORMULA f, Id)
mkFacetPred lit f var =
let cf = mkInfix $ fromCF f
in (mkPred dataPred [var, lit] cf, cf)
mapFacet :: CASLTERM -> (ConstrainingFacet, RestrictionValue)
-> Result (CASLFORMULA, [CASLSign])
mapFacet var (f, r) = do
con <- mapLiteral r
let (fp, cf) = mkFacetPred con f var
return (fp,
[(emptySign ()) {predMap = MapSet.fromList [(cf, [dataPred])]}])
cardProps :: Bool
-> Either ObjectPropertyExpression DataPropertyExpression -> Int
-> [Int] -> Result [CASLFORMULA]
cardProps b prop var vLst =
if b then let Left ope = prop in mapM (mapObjProp ope var) vLst
else let Right dpe = prop in mapM (mapDataProp dpe var) vLst
mapCard :: Bool -> CardinalityType -> Int
-> Either ObjectPropertyExpression DataPropertyExpression
-> Maybe (Either ClassExpression DataRange) -> Int
-> Result (FORMULA (), [CASLSign])
mapCard b ct n prop d var = do
let vlst = map (var +) [1 .. n]
vlstM = vlst ++ [n + var + 1]
vlstE = [n + var + 1]
(dOut, s) <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlst
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlst
(eOut, s') <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlstM
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlstM
(fOut, s'') <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlstE
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlstE
let dlst = map (\ (x, y) -> mkNeg $ mkStEq (qualThing x) $ qualThing y)
$ comPairs vlst vlst
dlstM = map (\ (x, y) -> mkStEq (qualThing x) $ qualThing y)
$ comPairs vlstM vlstM
qVars = map thingDecl vlst
qVarsM = map thingDecl vlstM
qVarsE = map thingDecl vlstE
oProps <- cardProps b prop var vlst
oPropsM <- cardProps b prop var vlstM
oPropsE <- cardProps b prop var vlstE
let minLst = conjunct $ dlst ++ oProps ++ dOut
maxLst = mkImpl (conjunct $ oPropsM ++ eOut)
$ disjunct dlstM
exactLst' = mkImpl (conjunct $ oPropsE ++ fOut) $ disjunct dlstM
senAux = conjunct [minLst, mkForall qVarsE exactLst']
exactLst = if null qVars then senAux else mkExist qVars senAux
ts = concat $ s ++ s' ++ s''
return $ case ct of
MinCardinality -> (mkExist qVars minLst, ts)
MaxCardinality -> (mkForall qVarsM maxLst, ts)
ExactCardinality -> (exactLst, ts)
-- | mapping of OWL2 Descriptions
mapDescription :: ClassExpression -> Int ->
Result (CASLFORMULA, [CASLSign])
mapDescription desc var = case desc of
Expression u -> do
c <- mapClassURI u $ mkNName var
return (c, [])
ObjectJunction ty ds -> do
(els, s) <- mapAndUnzipM (flip mapDescription var) ds
return ((case ty of
UnionOf -> disjunct
IntersectionOf -> conjunct)
els, concat s)
ObjectComplementOf d -> do
(els, s) <- mapDescription d var
return (mkNeg els, s)
ObjectOneOf is -> do
il <- mapM mapIndivURI is
return (disjunct $ map (mkStEq $ qualThing var) il, [])
ObjectValuesFrom ty o d -> let n = var + 1 in do
oprop0 <- mapObjProp o var n
(desc0, s) <- mapDescription d n
return $ case ty of
SomeValuesFrom -> (mkExist [thingDecl n] $ conjunct [oprop0, desc0],
s)
AllValuesFrom -> (mkVDecl [n] $ mkImpl oprop0 desc0,
s)
ObjectHasSelf o -> do
op <- mapObjProp o var var
return (op, [])
ObjectHasValue o i -> do
op <- mapObjPropI o (OVar var) (OIndi i)
return (op, [])
ObjectCardinality (Cardinality ct n oprop d) -> mapCard True ct n
(Left oprop) (fmap Left d) var
DataValuesFrom ty dpe dr -> let n = var + 1 in do
oprop0 <- mapDataProp (head dpe) var n
(desc0, s) <- mapDataRange dr n
let ts = niteCASLSign s
return $ case ty of
SomeValuesFrom -> (mkExist [dataDecl n] $ conjunct [oprop0, desc0],
s)
AllValuesFrom -> (mkVDataDecl [n] $ mkImpl oprop0 desc0, s)
DataHasValue dpe c -> do
con <- mapLiteral c
return (mkPred dataPropPred [qualThing var, con]
$ uriToCaslId dpe, [])
DataCardinality (Cardinality ct n dpe dr) -> mapCard False ct n
(Right dpe) (fmap Right dr) var
-- | Mapping of a list of descriptions
mapDescriptionList :: Int -> [ClassExpression]
-> Result ([CASLFORMULA], [CASLSign])
mapDescriptionList n lst = do
(els, s) <- mapAndUnzipM (uncurry $ mapDescription)
$ zip lst $ replicate (length lst) n
return (els, concat s)
-- | Mapping of a list of pairs of descriptions
mapDescriptionListP :: Int -> [(ClassExpression, ClassExpression)]
-> Result ([(CASLFORMULA, CASLFORMULA)], [CASLSign])
mapDescriptionListP n lst = do
let (l, r) = unzip lst
([lls, rls], s) <- mapAndUnzipM (mapDescriptionList n) [l, r]
return (zip lls rls, concat s)
mapCharact :: ObjectPropertyExpression -> Character
-> Result CASLFORMULA
mapCharact ope c = case c of
Functional -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 1 3
return $ mkFIE [1, 2, 3] [so1, so2] 2 3
InverseFunctional -> do
so1 <- mapObjProp ope 1 3
so2 <- mapObjProp ope 2 3
return $ mkFIE [1, 2, 3] [so1, so2] 1 2
Reflexive -> do
so <- mapObjProp ope 1 1
return $ mkRI [1] 1 so
Irreflexive -> do
so <- mapObjProp ope 1 1
return $ mkRI [1] 1 $ mkNeg so
Symmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkVDecl [1, 2] $ mkImpl so1 so2
Asymmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkVDecl [1, 2] $ mkImpl so1 $ mkNeg so2
Antisymmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkFIE [1, 2] [so1, so2] 1 2
Transitive -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 3
so3 <- mapObjProp ope 1 3
return $ mkVDecl [1, 2, 3] $ implConj [so1, so2] so3
-- | Mapping of ObjectSubPropertyChain
mapSubObjPropChain :: [ObjectPropertyExpression]
-> ObjectPropertyExpression -> Result CASLFORMULA
mapSubObjPropChain props oP = do
let (_, vars) = unzip $ zip (oP:props) [1 ..]
-- because we need n+1 vars for a chain of n roles
oProps <- mapM (\ (z, x) -> mapObjProp z x (x+1)) $
zip props vars
ooP <- mapObjProp oP 1 (head $ reverse vars)
return $ mkVDecl vars $ implConj oProps ooP
-- | Mapping of subobj properties
mapSubObjProp :: ObjectPropertyExpression
-> ObjectPropertyExpression -> Int -> Result CASLFORMULA
mapSubObjProp e1 e2 a = do
let b = a + 1
l <- mapObjProp e1 a b
r <- mapObjProp e2 a b
return $ mkForallRange (map thingDecl [a, b]) (mkImpl l r) nullRange
mkEDPairs :: [Int] -> Maybe AS.Relation -> [(FORMULA f, FORMULA f)]
-> Result ([FORMULA f], [CASLSign])
mkEDPairs il mr pairs = do
let ls = map (\ (x, y) -> mkVDecl il
$ case fromMaybe (error "expected EDRelation") mr of
EDRelation Equivalent -> mkEqv x y
EDRelation Disjoint -> mkNC [x, y]
_ -> error "expected EDRelation") pairs
return (ls, [])
mkEDPairs' :: [Int] -> Maybe AS.Relation -> [(FORMULA f, FORMULA f)]
-> Result ([FORMULA f], [CASLSign])
mkEDPairs' [i1, i2] mr pairs = do
let ls = map (\ (x, y) -> mkVDecl [i1] $ mkVDataDecl [i2]
$ case fromMaybe (error "expected EDRelation") mr of
EDRelation Equivalent -> mkEqv x y
EDRelation Disjoint -> mkNC [x, y]
_ -> error "expected EDRelation") pairs
return (ls, [])
mkEDPairs' _ _ _ = error "wrong call of mkEDPairs'"
keyDecl :: Int -> [Int] -> [VAR_DECL]
keyDecl h il = map thingDecl (take h il) ++ map dataDecl (drop h il)
mapKey :: ClassExpression -> [FORMULA ()] -> [FORMULA ()]
-> Int -> [Int] -> Int -> Result (FORMULA (), [CASLSign])
mapKey ce pl npl p i h = do
(nce, s) <- mapDescription ce 1
(c3, _) <- mapDescription ce p
let un = mkForall [thingDecl p] $ implConj (c3 : npl)
$ mkStEq (qualThing p) $ qualThing 1
return (mkForall [thingDecl 1] $ mkImpl nce
$ mkExist (keyDecl h i) $ conjunct $ pl ++ [un], s)
-- mapAxioms :: Axiom -> Result ([CASLFORMULA], [CASLSign])
-- mapAxioms (PlainAxiom ex fb) = case fb of
ListFrameBit rel lfb - > mapListFrameBit ex rel
-- AnnFrameBit ans afb -> mapAnnFrameBit ex ans afb
swrlVariableToVar :: IRI -> VAR_DECL
swrlVariableToVar iri = (flip mkVarDecl) thing $
case List.stripPrefix "urn:swrl#" (showIRI iri) of
Nothing -> idToSimpleId . uriToCaslId $ iri
Just var -> genToken var
mapAxioms :: Axiom -> Result([CASLFORMULA], [CASLSign])
mapAxioms axiom = case axiom of
Declaration _ _ -> return ([], [])
ClassAxiom clAxiom -> case clAxiom of
SubClassOf _ sub sup -> do
(domT, s1) <- mapDescription sub 1
(codT, s2) <- mapDescriptionList 1 [sup]
return (map (mk1VDecl . mkImpl domT) codT,
s1 ++ s2)
EquivalentClasses _ cel -> do
(els, _) <- mapDescriptionListP 1 $ comPairs cel cel
mkEDPairs [1] (Just $ EDRelation Equivalent) els
DisjointClasses _ cel -> do
(els, _) <- mapDescriptionListP 1 $ comPairs cel cel
mkEDPairs [1] (Just $ EDRelation Disjoint) els
DisjointUnion _ clIri clsl -> do
(decrs, s1) <- mapDescriptionList 1 clsl
(decrsS, s2) <- mapDescriptionListP 1 $ comPairs clsl clsl
let decrsP = map (\ (x, y) -> conjunct [x, y]) decrsS
mcls <- mapClassURI clIri $ mkNName 1
return ([mk1VDecl $ mkEqv mcls $ conjunct
[disjunct decrs, mkNC decrsP]], s1 ++ s2)
ObjectPropertyAxiom opAxiom -> case opAxiom of
SubObjectPropertyOf _ subOpExpr supOpExpr -> case subOpExpr of
SubObjPropExpr_obj opExpr -> do
os <- mapM (\ (o1, o2) -> mapSubObjProp o1 o2 3)
$ mkPairs opExpr [supOpExpr]
return (os, [])
SubObjPropExpr_exprchain opExprs -> do
os <- mapSubObjPropChain opExprs supOpExpr
return ([os], [])
EquivalentObjectProperties _ opExprs -> do
pairs <- mapComObjectPropsList Nothing opExprs 1 2
mkEDPairs [1, 2] (Just $ EDRelation Equivalent) pairs
DisjointObjectProperties _ opExprs -> do
pairs <- mapComObjectPropsList Nothing opExprs 1 2
mkEDPairs [1, 2] (Just $ EDRelation Disjoint) pairs
InverseObjectProperties _ opExpr1 opExpr2 -> do
os1 <- mapM (\o1 -> mapObjProp o1 1 2) [opExpr2]
o2 <- mapObjProp opExpr1 2 1
return (map (mkVDecl [1, 2] . mkEqv o2) os1, [])
ObjectPropertyDomain _ opExpr clExpr -> do
tobjP <- mapObjProp opExpr 1 2
(tdsc, s) <- mapAndUnzipM (\c -> mapDescription c 1) [clExpr]
let vars = (mkNName 1, mkNName 2)
return (map (mkFI [tokDecl $ fst vars] [tokDecl $ snd vars] tobjP) tdsc,
concat s)
ObjectPropertyRange _ opExpr clExpr -> do
tobjP <- mapObjProp opExpr 1 2
(tdsc, s) <- mapAndUnzipM (\c -> mapDescription c 2) [clExpr]
let vars = (mkNName 2, mkNName 1)
return (map (mkFI [tokDecl $ fst vars] [tokDecl $ snd vars] tobjP) tdsc,
concat s)
FunctionalObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Functional]
return (cl, [])
InverseFunctionalObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [InverseFunctional]
return (cl, [])
ReflexiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Reflexive]
return (cl, [])
IrreflexiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Irreflexive]
return (cl, [])
SymmetricObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Symmetric]
return (cl, [])
AsymmetricObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Asymmetric]
return (cl, [])
TransitiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Transitive]
return (cl, [])
DataPropertyAxiom dpAxiom -> case dpAxiom of
SubDataPropertyOf _ subDpExpr supDpExpr -> do
os1 <- mapM (\ o1 -> mapDataProp o1 1 2) [supDpExpr]
was 2 1
return (map (mkForall [thingDecl 1, dataDecl 2]
. mkImpl o2) os1, [])
EquivalentDataProperties _ dpExprs -> do
pairs <- mapComDataPropsList Nothing dpExprs 1 2
mkEDPairs' [1, 2] (Just $ EDRelation Equivalent) pairs
DisjointDataProperties _ dpExprs -> do
pairs <- mapComDataPropsList Nothing dpExprs 1 2
mkEDPairs' [1, 2] (Just $ EDRelation Disjoint) pairs
DataPropertyDomain _ dpExpr clExpr -> do
(els, s) <- mapAndUnzipM (\ c -> mapDescription c 1) [clExpr]
oEx <- mapDataProp dpExpr 1 2
let vars = (mkNName 1, mkNName 2)
return (map (mkFI [tokDecl $ fst vars]
[mkVarDecl (snd vars) dataS] oEx) els, concat s)
DataPropertyRange _ dpExpr dr -> do
oEx <- mapDataProp dpExpr 1 2
(odes, s) <- mapAndUnzipM (\r -> mapDataRange r 2) [dr]
let vars = (mkNName 1, mkNName 2)
return (map (mkFEI [tokDecl $ fst vars]
[tokDataDecl $ snd vars] oEx) odes, concat s)
FunctionalDataProperty _ dpExpr -> do
so1 <- mapDataProp dpExpr 1 2
so2 <- mapDataProp dpExpr 1 3
return ([mkForall (thingDecl 1 : map dataDecl [2, 3]) $ implConj
[so1, so2] $ mkEqVar (dataDecl 2) $ qualData 3], [])
DatatypeDefinition _ dt dr -> do
(odes, s) <- mapDataRange dr 2
return ([mkVDataDecl [2] $ mkEqv odes $ mkMember
(qualData 2) $ uriToCaslId dt], s)
HasKey _ ce opl dpl -> do
let lo = length opl
ld = length dpl
uptoOP = [2 .. lo + 1]
uptoDP = [lo + 2 .. lo + ld + 1]
tl = lo + ld + 2
ol <- mapM (\ (n, o) -> mapObjProp o 1 n) $ zip uptoOP opl
nol <- mapM (\ (n, o) -> mapObjProp o tl n) $ zip uptoOP opl
dl <- mapM (\ (n, d) -> mapDataProp d 1 n) $ zip uptoDP dpl
ndl <- mapM (\ (n, d) -> mapDataProp d tl n) $ zip uptoDP dpl
(keys, s) <-
mapKey ce (ol ++ dl) (nol ++ ndl) tl (uptoOP ++ uptoDP) lo
return ([keys], s)
Assertion assertion -> case assertion of
SameIndividual _ inds -> do
let (mi, rest) = case inds of
(iri:r) -> (Just iri, r)
_ -> (Nothing, inds)
fs <- mapComIndivList Same mi rest
return (fs, [])
DifferentIndividuals _ inds -> do
let (mi, rest) = case inds of
(iri:r) -> (Just iri, r)
_ -> (Nothing, inds)
fs <- mapComIndivList Different mi rest
return (fs, [])
ClassAssertion _ ce iIri -> do
(els, s) <- mapAndUnzipM (\c -> mapDescription c 1) [ce]
inD <- mapIndivURI iIri
let els' = map (substitute (mkNName 1) thing inD) els
return ( els', concat s)
ObjectPropertyAssertion _ op si ti -> do
oPropH <- mapObjPropI op (OIndi si) (OIndi ti)
return ([oPropH], [])
NegativeObjectPropertyAssertion _ op si ti -> do
oPropH <- mapObjPropI op (OIndi si) (OIndi ti)
let oProp = Negation oPropH nullRange
return ([oProp], [])
DataPropertyAssertion _ dp si tv -> do
inS <- mapIndivURI si
inT <- mapLiteral tv
oProp <- mapDataProp dp 1 2
return ([mkForall [thingDecl 1, dataDecl 2] $ implConj
[mkEqDecl 1 inS, mkEqVar (dataDecl 2) $ upcast inT dataS] oProp],
[])
NegativeDataPropertyAssertion _ dp si tv -> do
inS <- mapIndivURI si
inT <- mapLiteral tv
oPropH <- mapDataProp dp 1 2
let oProp = Negation oPropH nullRange
return ([mkForall [thingDecl 1, dataDecl 2] $ implConj
[mkEqDecl 1 inS, mkEqVar (dataDecl 2) $ upcast inT dataS] oProp],
[])
AnnotationAxiom _ -> return ([], [])
Rule rule -> case rule of
DLSafeRule _ b h ->
let vars = Set.toList . Set.unions $ getVariablesFromAtom <$> (b ++ h)
names = swrlVariableToVar <$> vars
f (s, sig, startVal) at = do
(sentences', sig', offsetValue) <- atomToSentence startVal at
return (s ++ sentences', sig ++ sig', offsetValue)
g startVal atoms = foldM f ([], [], startVal) atoms
in do
(antecedentSen, sig1, offsetValue) <- g 1 b
let antecedent = conjunct antecedentSen
(consequentSen, sig2, lastVar) <- g offsetValue h
let consequent = conjunct consequentSen
let impl = mkImpl antecedent consequent
return $ ([mkForall (names ++ map thingDecl [1..lastVar - 1]) impl], sig1 ++ sig2)
DGRule _ _ _ -> Fail.fail "Translating DGRules is not supported yet!"
DGAxiom _ _ _ _ _ -> Fail.fail "Translating DGAxioms is not supported yet!"
iArgToTerm :: IndividualArg -> Result(TERM ())
iArgToTerm arg = case arg of
IVar v -> return . toQualVar . swrlVariableToVar $ v
IArg iri -> mapIndivURI iri
iArgToVarOrIndi :: IndividualArg -> VarOrIndi
iArgToVarOrIndi arg = case arg of
IVar v -> OIndi v
IArg iri -> OIndi iri
iArgToIRI :: IndividualArg -> IRI
iArgToIRI arg = case arg of
IVar var -> var
IArg ind -> ind
dArgToTerm :: DataArg -> Result (TERM ())
dArgToTerm arg = case arg of
DVar var -> return . toQualVar . tokDataDecl . uriToTok $ var
DArg lit -> mapLiteral lit
atomToSentence :: Int -> Atom -> Result ([CASLFORMULA], [CASLSign], Int)
atomToSentence startVar atom = case atom of
ClassAtom clExpr iarg -> do
(el, sigs) <- mapDescription clExpr startVar
inD <- iArgToTerm iarg
let el' = substitute (mkNName startVar) thing inD el
return ([el'], sigs, startVar)
DataRangeAtom dr darg -> do
dt <- dArgToTerm darg
(odes, s) <- mapDataRangeAux dr dt
return ([substitute (mkNName 1) thing dt odes], s, startVar)
ObjectPropertyAtom opExpr iarg1 iarg2 -> do
let si = iArgToVarOrIndi iarg1
ti = iArgToVarOrIndi iarg2
oPropH <- mapObjPropI opExpr si ti
return ([oPropH], [], startVar)
DataPropertyAtom dpExpr iarg darg -> do
let a = 1
b = 2
inS <- iArgToTerm iarg
inT <- dArgToTerm darg
oProp <- mapDataProp dpExpr a b
return ([mkForall [thingDecl a, dataDecl b] $ implConj
[mkEqDecl a inS, mkEqVar (dataDecl b) $ upcast inT dataS] oProp],
[], startVar)
BuiltInAtom iri args -> do
prdArgs <- mapM dArgToTerm args
let predtype = PredType $ map (const thing) args
prd = mkPred predtype prdArgs (uriToId iri)
return ([prd], [], startVar)
SameIndividualAtom iarg1 iarg2 -> do
fs <- mapComIndivList Same (Just $ iArgToIRI iarg1) [iArgToIRI iarg2]
return (fs, [], startVar)
DifferentIndividualsAtom iarg1 iarg2 -> do
fs <- mapComIndivList Different (Just $ iArgToIRI iarg1) [iArgToIRI iarg2]
return (fs, [], startVar)
_ -> Fail.fail $ "Couldn't translate unknown atom '" ++ show atom ++ "'!"
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/OWL2/OWL22CASL.hs | haskell | # LANGUAGE TypeSynonymInstances #
CASL_DL = codomain
comorphism
lid domain
sublogics domain
Basic spec domain
sentence domain
symbol items domain
symbol map items domain
signature domain
morphism domain
symbol domain
rawsymbol domain
proof tree codomain
lid codomain
sublogics codomain
Basic spec codomain
sentence codomain
symbol items codomain
symbol map items codomain
signature codomain
morphism codomain
symbol codomain
rawsymbol codomain
proof tree domain
s = emptySign ()
| Get all distinct pairs for commutative operations
| Mapping of OWL morphisms to CASL morphisms
uniteCASLSign sig y))
, dTypes],
| Mapping of Class URIs
| Mapping of Individual URIs
| Mapping of data properties
| Mapping of obj props
| Mapping of obj props with Individuals
| mapping of individual list
| Mapping along DataPropsList for creation of pairs for commutative
operations.
| Mapping along ObjectPropsList for creation of pairs for commutative
operations.
let usig = uniteL sl
| mapping of OWL2 Descriptions
| Mapping of a list of descriptions
| Mapping of a list of pairs of descriptions
| Mapping of ObjectSubPropertyChain
because we need n+1 vars for a chain of n roles
| Mapping of subobj properties
mapAxioms :: Axiom -> Result ([CASLFORMULA], [CASLSign])
mapAxioms (PlainAxiom ex fb) = case fb of
AnnFrameBit ans afb -> mapAnnFrameBit ex ans afb | # LANGUAGE MultiParamTypeClasses #
# LANGUAGE FlexibleInstances #
|
Module : $ Header$
Description : Comorphism from OWL 2 to CASL_Dl
Copyright : ( c ) , : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non - portable ( via Logic . Logic )
Module : $Header$
Description : Comorphism from OWL 2 to CASL_Dl
Copyright : (c) Francisc-Nicolae Bungiu, Felix Gabriel Mance
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : non-portable (via Logic.Logic)
-}
module OWL2.OWL22CASL (OWL22CASL (..)) where
import Logic.Logic as Logic
import Logic.Comorphism
import Common.AS_Annotation
import Common.Result
import Common.Id
import Common.IRI
import Control.Monad
import qualified Control.Monad.Fail as Fail
import qualified Data.Set as Set
import qualified Data.Map as Map
import qualified Data.List as List
import qualified Common.Lib.MapSet as MapSet
import qualified Common.Lib.Rel as Rel
the DL with the initial signature for OWL
import CASL_DL.PredefinedCASLAxioms
OWL = domain
import OWL2.Logic_OWL2
import OWL2.AS as AS
import OWL2.Parse
import OWL2.Print
import OWL2.ProfilesAndSublogics
import OWL2.ManchesterPrint ()
import OWL2.Morphism
import OWL2.Symbols
import qualified OWL2.Sign as OS
import qualified OWL2.Sublogic as SL
import CASL.Logic_CASL
import CASL.AS_Basic_CASL
import CASL.Sign
import CASL.Morphism
import CASL.Induction
import CASL.Sublogic
import OWL2.ManchesterParser
import Common.ProofTree
import Data.Maybe
import Text.ParserCombinators.Parsec
data OWL22CASL = OWL22CASL deriving Show
instance Language OWL22CASL
instance Comorphism
where
sourceLogic OWL22CASL = OWL2
sourceSublogic OWL22CASL = topS
targetLogic OWL22CASL = CASL
mapSublogic OWL22CASL _ = Just $ cFol
{ cons_features = emptyMapConsFeature }
map_theory OWL22CASL = mapTheory
map_morphism OWL22CASL = mapMorphism
map_symbol OWL22CASL _ = mapSymbol
isInclusionComorphism OWL22CASL = True
has_model_expansion OWL22CASL = True
objectPropPred :: PredType
objectPropPred = PredType [thing, thing]
dataPropPred :: PredType
dataPropPred = PredType [thing, dataS]
indiConst :: OpType
indiConst = OpType Total [] thing
uriToIdM :: IRI -> Result Id
uriToIdM = return . uriToCaslId
tokDecl :: Token -> VAR_DECL
tokDecl = flip mkVarDecl thing
tokDataDecl :: Token -> VAR_DECL
tokDataDecl = flip mkVarDecl dataS
nameDecl :: Int -> SORT -> VAR_DECL
nameDecl = mkVarDecl . mkNName
thingDecl :: Int -> VAR_DECL
thingDecl = flip nameDecl thing
dataDecl :: Int -> VAR_DECL
dataDecl = flip nameDecl dataS
qualThing :: Int -> TERM f
qualThing = toQualVar . thingDecl
qualData :: Int -> TERM f
qualData = toQualVar . dataDecl
implConj :: [FORMULA f] -> FORMULA f -> FORMULA f
implConj = mkImpl . conjunct
mkNC :: [FORMULA f] -> FORMULA f
mkNC = mkNeg . conjunct
mkEqVar :: VAR_DECL -> TERM f -> FORMULA f
mkEqVar = mkStEq . toQualVar
mkFEI :: [VAR_DECL] -> [VAR_DECL] -> FORMULA f -> FORMULA f -> FORMULA f
mkFEI l1 l2 f = mkForall l1 . mkExist l2 . mkImpl f
mkFIE :: [Int] -> [FORMULA f] -> Int -> Int -> FORMULA f
mkFIE l1 l2 x y = mkVDecl l1 $ implConj l2 $ mkEqVar (thingDecl x) $ qualThing y
mkFI :: [VAR_DECL] -> [VAR_DECL] -> FORMULA f -> FORMULA f -> FORMULA f
mkFI l1 l2 f1 = (mkForall l1) . (mkImpl (mkExist l2 f1))
mkRI :: [Int] -> Int -> FORMULA f -> FORMULA f
mkRI l x so = mkVDecl l $ mkImpl (mkMember (qualThing x) thing) so
mkThingVar :: VAR -> TERM f
mkThingVar v = Qual_var v thing nullRange
mkEqDecl :: Int -> TERM f -> FORMULA f
mkEqDecl i = mkEqVar (thingDecl i)
mkVDecl :: [Int] -> FORMULA f -> FORMULA f
mkVDecl = mkForall . map thingDecl
mkVDataDecl :: [Int] -> FORMULA f -> FORMULA f
mkVDataDecl = mkForall . map dataDecl
mk1VDecl :: FORMULA f -> FORMULA f
mk1VDecl = mkVDecl [1]
mkPred :: PredType -> [TERM f] -> PRED_NAME -> FORMULA f
mkPred c tl u = mkPredication (mkQualPred u $ toPRED_TYPE c) tl
mkMember :: TERM f -> SORT -> FORMULA f
mkMember t s = Membership t s nullRange
comPairs :: [t] -> [t1] -> [(t, t1)]
comPairs [] [] = []
comPairs _ [] = []
comPairs [] _ = []
comPairs (a : as) (_ : bs) = mkPairs a bs ++ comPairs as bs
mkPairs :: t -> [s] -> [(t, s)]
mkPairs a = map (\ b -> (a, b))
data VarOrIndi = OVar Int | OIndi IRI
deriving (Show, Eq, Ord)
mapMorphism :: OWLMorphism -> Result CASLMor
mapMorphism oMor = do
cdm <- mapSign $ osource oMor
ccd <- mapSign $ otarget oMor
let emap = mmaps oMor
preds = Map.foldrWithKey (\ (Entity _ ty u1) u2 -> let
i1 = uriToCaslId u1
i2 = uriToCaslId u2
in case ty of
Class -> Map.insert (i1, conceptPred) i2
ObjectProperty -> Map.insert (i1, objectPropPred) i2
DataProperty -> Map.insert (i1, dataPropPred) i2
_ -> id) Map.empty emap
ops = Map.foldrWithKey (\ (Entity _ ty u1) u2 -> case ty of
NamedIndividual -> Map.insert (uriToCaslId u1, indiConst)
(uriToCaslId u2, Total)
_ -> id) Map.empty emap
return (embedMorphism () cdm ccd)
{ op_map = ops
, pred_map = preds }
mapSymbol :: Entity -> Set.Set Symbol
mapSymbol (Entity _ ty iRi) = let
syN = Set.singleton . Symbol (uriToCaslId iRi)
in case ty of
Class -> syN $ PredAsItemType conceptPred
ObjectProperty -> syN $ PredAsItemType objectPropPred
DataProperty -> syN $ PredAsItemType dataPropPred
NamedIndividual -> syN $ OpAsItemType indiConst
AnnotationProperty -> Set.empty
Datatype -> Set.empty
mapSign :: OS.Sign -> Result CASLSign
mapSign sig =
let conc = OS.concepts sig
cvrt = map uriToCaslId . Set.toList
tMp k = MapSet.fromList . map (\ u -> (u, [k]))
cPreds = thing : nothing : cvrt conc
oPreds = cvrt $ OS.objectProperties sig
dPreds = cvrt $ OS.dataProperties sig
aPreds = foldr MapSet.union MapSet.empty
[ tMp conceptPred cPreds
, tMp objectPropPred oPreds
, tMp dataPropPred dPreds ]
in return $ uniteCASLSign predefSign2
(emptySign ())
{ predMap = aPreds
, opMap = tMp indiConst . cvrt $ OS.individuals sig
}
loadDataInformation :: ProfSub -> CASLSign
loadDataInformation sl = let
dts = Set.map uriToCaslId $ SL.datatype $ sublogic sl
eSig x = (emptySign ()) { sortRel =
Rel.fromList [(x, dataS)]}
sigs = Set.toList $
Set.map (\x -> Map.findWithDefault (eSig x) x datatypeSigns) dts
in foldl uniteCASLSign (emptySign ()) sigs
mapTheory :: (OS.Sign, [Named Axiom]) -> Result (CASLSign, [Named CASLFORMULA])
mapTheory (owlSig, owlSens) = let
sl = sublogicOfTheo OWL2 (owlSig, map sentence owlSens)
in do
cSig <- mapSign owlSig
let pSig = loadDataInformation sl
dTypes = ( emptySign ( ) ) { sortRel = Rel.transClosure . Rel.fromSet
. Set.map ( \ d - > ( uriToCaslId d , dataS ) )
. Set.union owlSig }
. Set.map (\ d -> (uriToCaslId d, dataS))
. Set.union predefIRIs $ OS.datatypes owlSig} -}
(cSens, nSigs) <- foldM (\ (x, y) z -> do
(sen, y') <- mapSentence z
([], []) owlSens
predefinedAxioms ++ (reverse cSens))
| mapping of OWL to CASL_DL formulae
mapSentence :: Named Axiom -> Result ([Named CASLFORMULA], [CASLSign])
mapSentence inSen = do
(outAx, outSigs) <- mapAxioms $ sentence inSen
return (map (flip mapNamed inSen . const) outAx, outSigs)
mapVar :: VarOrIndi -> Result (TERM ())
mapVar v = case v of
OVar n -> return $ qualThing n
OIndi i -> mapIndivURI i
mapClassURI :: Class -> Token -> Result CASLFORMULA
mapClassURI c t = fmap (mkPred conceptPred [mkThingVar t]) $ uriToIdM c
mapIndivURI :: Individual -> Result (TERM ())
mapIndivURI uriI = do
ur <- uriToIdM uriI
return $ mkAppl (mkQualOp ur (Op_type Total [] thing nullRange)) []
mapNNInt :: NNInt -> TERM ()
mapNNInt int = let NNInt uInt = int in foldr1 joinDigits $ map mkDigit uInt
mapIntLit :: IntLit -> TERM ()
mapIntLit int =
let cInt = mapNNInt $ absInt int
in if isNegInt int then negateInt $ upcast cInt integer
else upcast cInt integer
mapDecLit :: DecLit -> TERM ()
mapDecLit dec =
let ip = truncDec dec
np = absInt ip
fp = fracDec dec
n = mkDecimal (mapNNInt np) (mapNNInt fp)
in if isNegInt ip then negateFloat n else n
mapFloatLit :: FloatLit -> TERM ()
mapFloatLit f =
let fb = floatBase f
ex = floatExp f
in mkFloat (mapDecLit fb) (mapIntLit ex)
mapNrLit :: Literal -> TERM ()
mapNrLit l = case l of
NumberLit f
| isFloatInt f -> mapIntLit $ truncDec $ floatBase f
| isFloatDec f -> mapDecLit $ floatBase f
| otherwise -> mapFloatLit f
_ -> error "not number literal"
mapLiteral :: Literal -> Result (TERM ())
mapLiteral lit = return $ case lit of
Literal l ty -> Sorted_term (case ty of
Untyped _ -> foldr consChar emptyStringTerm l
Typed dt -> case getDatatypeCat dt of
OWL2Number -> let p = parse literal "" l in case p of
Right nr -> mapNrLit nr
_ -> error "cannot parse number literal"
OWL2Bool -> case l of
"true" -> trueT
_ -> falseT
_ -> foldr consChar emptyStringTerm l) dataS nullRange
_ -> mapNrLit lit
mapDataProp :: DataPropertyExpression -> Int -> Int
-> Result CASLFORMULA
mapDataProp dp a b = fmap (mkPred dataPropPred [qualThing a, qualData b])
$ uriToIdM dp
mapObjProp :: ObjectPropertyExpression -> Int -> Int
-> Result CASLFORMULA
mapObjProp ob a b = case ob of
ObjectProp u -> fmap (mkPred objectPropPred $ map qualThing [a, b])
$ uriToIdM u
ObjectInverseOf u -> mapObjProp u b a
mapObjPropI :: ObjectPropertyExpression -> VarOrIndi -> VarOrIndi
-> Result CASLFORMULA
mapObjPropI ob lP rP = case ob of
ObjectProp u -> do
l <- mapVar lP
r <- mapVar rP
fmap (mkPred objectPropPred [l, r]) $ uriToIdM u
ObjectInverseOf u -> mapObjPropI u rP lP
mapComIndivList :: SameOrDifferent -> Maybe Individual
-> [Individual] -> Result [CASLFORMULA]
mapComIndivList sod mol inds = do
fs <- mapM mapIndivURI inds
tps <- case mol of
Nothing -> return $ comPairs fs fs
Just ol -> do
f <- mapIndivURI ol
return $ mkPairs f fs
return $ map (\ (x, y) -> case sod of
Same -> mkStEq x y
Different -> mkNeg $ mkStEq x y) tps
mapComDataPropsList :: Maybe DataPropertyExpression
-> [DataPropertyExpression] -> Int -> Int
-> Result [(CASLFORMULA, CASLFORMULA)]
mapComDataPropsList md props a b = do
fs <- mapM (\ x -> mapDataProp x a b) props
case md of
Nothing -> return $ comPairs fs fs
Just dp -> fmap (`mkPairs` fs) $ mapDataProp dp a b
mapComObjectPropsList :: Maybe ObjectPropertyExpression
-> [ObjectPropertyExpression] -> Int -> Int
-> Result [(CASLFORMULA, CASLFORMULA)]
mapComObjectPropsList mol props a b = do
fs <- mapM (\ x -> mapObjProp x a b) props
case mol of
Nothing -> return $ comPairs fs fs
Just ol -> fmap (`mkPairs` fs) $ mapObjProp ol a b
mapDataRangeAux :: DataRange -> CASLTERM -> Result (CASLFORMULA, [CASLSign])
mapDataRangeAux dr i = case dr of
DataType d fl -> do
let dt = mkMember i $ uriToCaslId d
(sens, s) <- mapAndUnzipM (mapFacet i) fl
return (conjunct $ dt : sens, concat s)
DataComplementOf drc -> do
(sens, s) <- mapDataRangeAux drc i
return (mkNeg sens, s)
DataJunction jt drl -> do
(jl, sl) <- mapAndUnzipM ((\ v r -> mapDataRangeAux r v) i) drl
return $ case jt of
IntersectionOf -> (conjunct jl, concat sl)
UnionOf -> (disjunct jl, concat sl)
DataOneOf cs -> do
ls <- mapM mapLiteral cs
return (disjunct $ map (mkStEq i) ls, [])
| mapping of Data Range
mapDataRange :: DataRange -> Int -> Result (CASLFORMULA, [CASLSign])
mapDataRange dr = mapDataRangeAux dr . qualData
mkFacetPred :: TERM f -> ConstrainingFacet -> TERM f -> (FORMULA f, Id)
mkFacetPred lit f var =
let cf = mkInfix $ fromCF f
in (mkPred dataPred [var, lit] cf, cf)
mapFacet :: CASLTERM -> (ConstrainingFacet, RestrictionValue)
-> Result (CASLFORMULA, [CASLSign])
mapFacet var (f, r) = do
con <- mapLiteral r
let (fp, cf) = mkFacetPred con f var
return (fp,
[(emptySign ()) {predMap = MapSet.fromList [(cf, [dataPred])]}])
cardProps :: Bool
-> Either ObjectPropertyExpression DataPropertyExpression -> Int
-> [Int] -> Result [CASLFORMULA]
cardProps b prop var vLst =
if b then let Left ope = prop in mapM (mapObjProp ope var) vLst
else let Right dpe = prop in mapM (mapDataProp dpe var) vLst
mapCard :: Bool -> CardinalityType -> Int
-> Either ObjectPropertyExpression DataPropertyExpression
-> Maybe (Either ClassExpression DataRange) -> Int
-> Result (FORMULA (), [CASLSign])
mapCard b ct n prop d var = do
let vlst = map (var +) [1 .. n]
vlstM = vlst ++ [n + var + 1]
vlstE = [n + var + 1]
(dOut, s) <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlst
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlst
(eOut, s') <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlstM
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlstM
(fOut, s'') <- case d of
Nothing -> return ([], [])
Just y ->
if b then let Left ce = y in mapAndUnzipM
(mapDescription ce) vlstE
else let Right dr = y in mapAndUnzipM (mapDataRange dr) vlstE
let dlst = map (\ (x, y) -> mkNeg $ mkStEq (qualThing x) $ qualThing y)
$ comPairs vlst vlst
dlstM = map (\ (x, y) -> mkStEq (qualThing x) $ qualThing y)
$ comPairs vlstM vlstM
qVars = map thingDecl vlst
qVarsM = map thingDecl vlstM
qVarsE = map thingDecl vlstE
oProps <- cardProps b prop var vlst
oPropsM <- cardProps b prop var vlstM
oPropsE <- cardProps b prop var vlstE
let minLst = conjunct $ dlst ++ oProps ++ dOut
maxLst = mkImpl (conjunct $ oPropsM ++ eOut)
$ disjunct dlstM
exactLst' = mkImpl (conjunct $ oPropsE ++ fOut) $ disjunct dlstM
senAux = conjunct [minLst, mkForall qVarsE exactLst']
exactLst = if null qVars then senAux else mkExist qVars senAux
ts = concat $ s ++ s' ++ s''
return $ case ct of
MinCardinality -> (mkExist qVars minLst, ts)
MaxCardinality -> (mkForall qVarsM maxLst, ts)
ExactCardinality -> (exactLst, ts)
mapDescription :: ClassExpression -> Int ->
Result (CASLFORMULA, [CASLSign])
mapDescription desc var = case desc of
Expression u -> do
c <- mapClassURI u $ mkNName var
return (c, [])
ObjectJunction ty ds -> do
(els, s) <- mapAndUnzipM (flip mapDescription var) ds
return ((case ty of
UnionOf -> disjunct
IntersectionOf -> conjunct)
els, concat s)
ObjectComplementOf d -> do
(els, s) <- mapDescription d var
return (mkNeg els, s)
ObjectOneOf is -> do
il <- mapM mapIndivURI is
return (disjunct $ map (mkStEq $ qualThing var) il, [])
ObjectValuesFrom ty o d -> let n = var + 1 in do
oprop0 <- mapObjProp o var n
(desc0, s) <- mapDescription d n
return $ case ty of
SomeValuesFrom -> (mkExist [thingDecl n] $ conjunct [oprop0, desc0],
s)
AllValuesFrom -> (mkVDecl [n] $ mkImpl oprop0 desc0,
s)
ObjectHasSelf o -> do
op <- mapObjProp o var var
return (op, [])
ObjectHasValue o i -> do
op <- mapObjPropI o (OVar var) (OIndi i)
return (op, [])
ObjectCardinality (Cardinality ct n oprop d) -> mapCard True ct n
(Left oprop) (fmap Left d) var
DataValuesFrom ty dpe dr -> let n = var + 1 in do
oprop0 <- mapDataProp (head dpe) var n
(desc0, s) <- mapDataRange dr n
let ts = niteCASLSign s
return $ case ty of
SomeValuesFrom -> (mkExist [dataDecl n] $ conjunct [oprop0, desc0],
s)
AllValuesFrom -> (mkVDataDecl [n] $ mkImpl oprop0 desc0, s)
DataHasValue dpe c -> do
con <- mapLiteral c
return (mkPred dataPropPred [qualThing var, con]
$ uriToCaslId dpe, [])
DataCardinality (Cardinality ct n dpe dr) -> mapCard False ct n
(Right dpe) (fmap Right dr) var
mapDescriptionList :: Int -> [ClassExpression]
-> Result ([CASLFORMULA], [CASLSign])
mapDescriptionList n lst = do
(els, s) <- mapAndUnzipM (uncurry $ mapDescription)
$ zip lst $ replicate (length lst) n
return (els, concat s)
mapDescriptionListP :: Int -> [(ClassExpression, ClassExpression)]
-> Result ([(CASLFORMULA, CASLFORMULA)], [CASLSign])
mapDescriptionListP n lst = do
let (l, r) = unzip lst
([lls, rls], s) <- mapAndUnzipM (mapDescriptionList n) [l, r]
return (zip lls rls, concat s)
mapCharact :: ObjectPropertyExpression -> Character
-> Result CASLFORMULA
mapCharact ope c = case c of
Functional -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 1 3
return $ mkFIE [1, 2, 3] [so1, so2] 2 3
InverseFunctional -> do
so1 <- mapObjProp ope 1 3
so2 <- mapObjProp ope 2 3
return $ mkFIE [1, 2, 3] [so1, so2] 1 2
Reflexive -> do
so <- mapObjProp ope 1 1
return $ mkRI [1] 1 so
Irreflexive -> do
so <- mapObjProp ope 1 1
return $ mkRI [1] 1 $ mkNeg so
Symmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkVDecl [1, 2] $ mkImpl so1 so2
Asymmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkVDecl [1, 2] $ mkImpl so1 $ mkNeg so2
Antisymmetric -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 1
return $ mkFIE [1, 2] [so1, so2] 1 2
Transitive -> do
so1 <- mapObjProp ope 1 2
so2 <- mapObjProp ope 2 3
so3 <- mapObjProp ope 1 3
return $ mkVDecl [1, 2, 3] $ implConj [so1, so2] so3
mapSubObjPropChain :: [ObjectPropertyExpression]
-> ObjectPropertyExpression -> Result CASLFORMULA
mapSubObjPropChain props oP = do
let (_, vars) = unzip $ zip (oP:props) [1 ..]
oProps <- mapM (\ (z, x) -> mapObjProp z x (x+1)) $
zip props vars
ooP <- mapObjProp oP 1 (head $ reverse vars)
return $ mkVDecl vars $ implConj oProps ooP
mapSubObjProp :: ObjectPropertyExpression
-> ObjectPropertyExpression -> Int -> Result CASLFORMULA
mapSubObjProp e1 e2 a = do
let b = a + 1
l <- mapObjProp e1 a b
r <- mapObjProp e2 a b
return $ mkForallRange (map thingDecl [a, b]) (mkImpl l r) nullRange
mkEDPairs :: [Int] -> Maybe AS.Relation -> [(FORMULA f, FORMULA f)]
-> Result ([FORMULA f], [CASLSign])
mkEDPairs il mr pairs = do
let ls = map (\ (x, y) -> mkVDecl il
$ case fromMaybe (error "expected EDRelation") mr of
EDRelation Equivalent -> mkEqv x y
EDRelation Disjoint -> mkNC [x, y]
_ -> error "expected EDRelation") pairs
return (ls, [])
mkEDPairs' :: [Int] -> Maybe AS.Relation -> [(FORMULA f, FORMULA f)]
-> Result ([FORMULA f], [CASLSign])
mkEDPairs' [i1, i2] mr pairs = do
let ls = map (\ (x, y) -> mkVDecl [i1] $ mkVDataDecl [i2]
$ case fromMaybe (error "expected EDRelation") mr of
EDRelation Equivalent -> mkEqv x y
EDRelation Disjoint -> mkNC [x, y]
_ -> error "expected EDRelation") pairs
return (ls, [])
mkEDPairs' _ _ _ = error "wrong call of mkEDPairs'"
keyDecl :: Int -> [Int] -> [VAR_DECL]
keyDecl h il = map thingDecl (take h il) ++ map dataDecl (drop h il)
mapKey :: ClassExpression -> [FORMULA ()] -> [FORMULA ()]
-> Int -> [Int] -> Int -> Result (FORMULA (), [CASLSign])
mapKey ce pl npl p i h = do
(nce, s) <- mapDescription ce 1
(c3, _) <- mapDescription ce p
let un = mkForall [thingDecl p] $ implConj (c3 : npl)
$ mkStEq (qualThing p) $ qualThing 1
return (mkForall [thingDecl 1] $ mkImpl nce
$ mkExist (keyDecl h i) $ conjunct $ pl ++ [un], s)
ListFrameBit rel lfb - > mapListFrameBit ex rel
swrlVariableToVar :: IRI -> VAR_DECL
swrlVariableToVar iri = (flip mkVarDecl) thing $
case List.stripPrefix "urn:swrl#" (showIRI iri) of
Nothing -> idToSimpleId . uriToCaslId $ iri
Just var -> genToken var
mapAxioms :: Axiom -> Result([CASLFORMULA], [CASLSign])
mapAxioms axiom = case axiom of
Declaration _ _ -> return ([], [])
ClassAxiom clAxiom -> case clAxiom of
SubClassOf _ sub sup -> do
(domT, s1) <- mapDescription sub 1
(codT, s2) <- mapDescriptionList 1 [sup]
return (map (mk1VDecl . mkImpl domT) codT,
s1 ++ s2)
EquivalentClasses _ cel -> do
(els, _) <- mapDescriptionListP 1 $ comPairs cel cel
mkEDPairs [1] (Just $ EDRelation Equivalent) els
DisjointClasses _ cel -> do
(els, _) <- mapDescriptionListP 1 $ comPairs cel cel
mkEDPairs [1] (Just $ EDRelation Disjoint) els
DisjointUnion _ clIri clsl -> do
(decrs, s1) <- mapDescriptionList 1 clsl
(decrsS, s2) <- mapDescriptionListP 1 $ comPairs clsl clsl
let decrsP = map (\ (x, y) -> conjunct [x, y]) decrsS
mcls <- mapClassURI clIri $ mkNName 1
return ([mk1VDecl $ mkEqv mcls $ conjunct
[disjunct decrs, mkNC decrsP]], s1 ++ s2)
ObjectPropertyAxiom opAxiom -> case opAxiom of
SubObjectPropertyOf _ subOpExpr supOpExpr -> case subOpExpr of
SubObjPropExpr_obj opExpr -> do
os <- mapM (\ (o1, o2) -> mapSubObjProp o1 o2 3)
$ mkPairs opExpr [supOpExpr]
return (os, [])
SubObjPropExpr_exprchain opExprs -> do
os <- mapSubObjPropChain opExprs supOpExpr
return ([os], [])
EquivalentObjectProperties _ opExprs -> do
pairs <- mapComObjectPropsList Nothing opExprs 1 2
mkEDPairs [1, 2] (Just $ EDRelation Equivalent) pairs
DisjointObjectProperties _ opExprs -> do
pairs <- mapComObjectPropsList Nothing opExprs 1 2
mkEDPairs [1, 2] (Just $ EDRelation Disjoint) pairs
InverseObjectProperties _ opExpr1 opExpr2 -> do
os1 <- mapM (\o1 -> mapObjProp o1 1 2) [opExpr2]
o2 <- mapObjProp opExpr1 2 1
return (map (mkVDecl [1, 2] . mkEqv o2) os1, [])
ObjectPropertyDomain _ opExpr clExpr -> do
tobjP <- mapObjProp opExpr 1 2
(tdsc, s) <- mapAndUnzipM (\c -> mapDescription c 1) [clExpr]
let vars = (mkNName 1, mkNName 2)
return (map (mkFI [tokDecl $ fst vars] [tokDecl $ snd vars] tobjP) tdsc,
concat s)
ObjectPropertyRange _ opExpr clExpr -> do
tobjP <- mapObjProp opExpr 1 2
(tdsc, s) <- mapAndUnzipM (\c -> mapDescription c 2) [clExpr]
let vars = (mkNName 2, mkNName 1)
return (map (mkFI [tokDecl $ fst vars] [tokDecl $ snd vars] tobjP) tdsc,
concat s)
FunctionalObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Functional]
return (cl, [])
InverseFunctionalObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [InverseFunctional]
return (cl, [])
ReflexiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Reflexive]
return (cl, [])
IrreflexiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Irreflexive]
return (cl, [])
SymmetricObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Symmetric]
return (cl, [])
AsymmetricObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Asymmetric]
return (cl, [])
TransitiveObjectProperty _ opExpr -> do
cl <- mapM (mapCharact opExpr) [Transitive]
return (cl, [])
DataPropertyAxiom dpAxiom -> case dpAxiom of
SubDataPropertyOf _ subDpExpr supDpExpr -> do
os1 <- mapM (\ o1 -> mapDataProp o1 1 2) [supDpExpr]
was 2 1
return (map (mkForall [thingDecl 1, dataDecl 2]
. mkImpl o2) os1, [])
EquivalentDataProperties _ dpExprs -> do
pairs <- mapComDataPropsList Nothing dpExprs 1 2
mkEDPairs' [1, 2] (Just $ EDRelation Equivalent) pairs
DisjointDataProperties _ dpExprs -> do
pairs <- mapComDataPropsList Nothing dpExprs 1 2
mkEDPairs' [1, 2] (Just $ EDRelation Disjoint) pairs
DataPropertyDomain _ dpExpr clExpr -> do
(els, s) <- mapAndUnzipM (\ c -> mapDescription c 1) [clExpr]
oEx <- mapDataProp dpExpr 1 2
let vars = (mkNName 1, mkNName 2)
return (map (mkFI [tokDecl $ fst vars]
[mkVarDecl (snd vars) dataS] oEx) els, concat s)
DataPropertyRange _ dpExpr dr -> do
oEx <- mapDataProp dpExpr 1 2
(odes, s) <- mapAndUnzipM (\r -> mapDataRange r 2) [dr]
let vars = (mkNName 1, mkNName 2)
return (map (mkFEI [tokDecl $ fst vars]
[tokDataDecl $ snd vars] oEx) odes, concat s)
FunctionalDataProperty _ dpExpr -> do
so1 <- mapDataProp dpExpr 1 2
so2 <- mapDataProp dpExpr 1 3
return ([mkForall (thingDecl 1 : map dataDecl [2, 3]) $ implConj
[so1, so2] $ mkEqVar (dataDecl 2) $ qualData 3], [])
DatatypeDefinition _ dt dr -> do
(odes, s) <- mapDataRange dr 2
return ([mkVDataDecl [2] $ mkEqv odes $ mkMember
(qualData 2) $ uriToCaslId dt], s)
HasKey _ ce opl dpl -> do
let lo = length opl
ld = length dpl
uptoOP = [2 .. lo + 1]
uptoDP = [lo + 2 .. lo + ld + 1]
tl = lo + ld + 2
ol <- mapM (\ (n, o) -> mapObjProp o 1 n) $ zip uptoOP opl
nol <- mapM (\ (n, o) -> mapObjProp o tl n) $ zip uptoOP opl
dl <- mapM (\ (n, d) -> mapDataProp d 1 n) $ zip uptoDP dpl
ndl <- mapM (\ (n, d) -> mapDataProp d tl n) $ zip uptoDP dpl
(keys, s) <-
mapKey ce (ol ++ dl) (nol ++ ndl) tl (uptoOP ++ uptoDP) lo
return ([keys], s)
Assertion assertion -> case assertion of
SameIndividual _ inds -> do
let (mi, rest) = case inds of
(iri:r) -> (Just iri, r)
_ -> (Nothing, inds)
fs <- mapComIndivList Same mi rest
return (fs, [])
DifferentIndividuals _ inds -> do
let (mi, rest) = case inds of
(iri:r) -> (Just iri, r)
_ -> (Nothing, inds)
fs <- mapComIndivList Different mi rest
return (fs, [])
ClassAssertion _ ce iIri -> do
(els, s) <- mapAndUnzipM (\c -> mapDescription c 1) [ce]
inD <- mapIndivURI iIri
let els' = map (substitute (mkNName 1) thing inD) els
return ( els', concat s)
ObjectPropertyAssertion _ op si ti -> do
oPropH <- mapObjPropI op (OIndi si) (OIndi ti)
return ([oPropH], [])
NegativeObjectPropertyAssertion _ op si ti -> do
oPropH <- mapObjPropI op (OIndi si) (OIndi ti)
let oProp = Negation oPropH nullRange
return ([oProp], [])
DataPropertyAssertion _ dp si tv -> do
inS <- mapIndivURI si
inT <- mapLiteral tv
oProp <- mapDataProp dp 1 2
return ([mkForall [thingDecl 1, dataDecl 2] $ implConj
[mkEqDecl 1 inS, mkEqVar (dataDecl 2) $ upcast inT dataS] oProp],
[])
NegativeDataPropertyAssertion _ dp si tv -> do
inS <- mapIndivURI si
inT <- mapLiteral tv
oPropH <- mapDataProp dp 1 2
let oProp = Negation oPropH nullRange
return ([mkForall [thingDecl 1, dataDecl 2] $ implConj
[mkEqDecl 1 inS, mkEqVar (dataDecl 2) $ upcast inT dataS] oProp],
[])
AnnotationAxiom _ -> return ([], [])
Rule rule -> case rule of
DLSafeRule _ b h ->
let vars = Set.toList . Set.unions $ getVariablesFromAtom <$> (b ++ h)
names = swrlVariableToVar <$> vars
f (s, sig, startVal) at = do
(sentences', sig', offsetValue) <- atomToSentence startVal at
return (s ++ sentences', sig ++ sig', offsetValue)
g startVal atoms = foldM f ([], [], startVal) atoms
in do
(antecedentSen, sig1, offsetValue) <- g 1 b
let antecedent = conjunct antecedentSen
(consequentSen, sig2, lastVar) <- g offsetValue h
let consequent = conjunct consequentSen
let impl = mkImpl antecedent consequent
return $ ([mkForall (names ++ map thingDecl [1..lastVar - 1]) impl], sig1 ++ sig2)
DGRule _ _ _ -> Fail.fail "Translating DGRules is not supported yet!"
DGAxiom _ _ _ _ _ -> Fail.fail "Translating DGAxioms is not supported yet!"
iArgToTerm :: IndividualArg -> Result(TERM ())
iArgToTerm arg = case arg of
IVar v -> return . toQualVar . swrlVariableToVar $ v
IArg iri -> mapIndivURI iri
iArgToVarOrIndi :: IndividualArg -> VarOrIndi
iArgToVarOrIndi arg = case arg of
IVar v -> OIndi v
IArg iri -> OIndi iri
iArgToIRI :: IndividualArg -> IRI
iArgToIRI arg = case arg of
IVar var -> var
IArg ind -> ind
dArgToTerm :: DataArg -> Result (TERM ())
dArgToTerm arg = case arg of
DVar var -> return . toQualVar . tokDataDecl . uriToTok $ var
DArg lit -> mapLiteral lit
atomToSentence :: Int -> Atom -> Result ([CASLFORMULA], [CASLSign], Int)
atomToSentence startVar atom = case atom of
ClassAtom clExpr iarg -> do
(el, sigs) <- mapDescription clExpr startVar
inD <- iArgToTerm iarg
let el' = substitute (mkNName startVar) thing inD el
return ([el'], sigs, startVar)
DataRangeAtom dr darg -> do
dt <- dArgToTerm darg
(odes, s) <- mapDataRangeAux dr dt
return ([substitute (mkNName 1) thing dt odes], s, startVar)
ObjectPropertyAtom opExpr iarg1 iarg2 -> do
let si = iArgToVarOrIndi iarg1
ti = iArgToVarOrIndi iarg2
oPropH <- mapObjPropI opExpr si ti
return ([oPropH], [], startVar)
DataPropertyAtom dpExpr iarg darg -> do
let a = 1
b = 2
inS <- iArgToTerm iarg
inT <- dArgToTerm darg
oProp <- mapDataProp dpExpr a b
return ([mkForall [thingDecl a, dataDecl b] $ implConj
[mkEqDecl a inS, mkEqVar (dataDecl b) $ upcast inT dataS] oProp],
[], startVar)
BuiltInAtom iri args -> do
prdArgs <- mapM dArgToTerm args
let predtype = PredType $ map (const thing) args
prd = mkPred predtype prdArgs (uriToId iri)
return ([prd], [], startVar)
SameIndividualAtom iarg1 iarg2 -> do
fs <- mapComIndivList Same (Just $ iArgToIRI iarg1) [iArgToIRI iarg2]
return (fs, [], startVar)
DifferentIndividualsAtom iarg1 iarg2 -> do
fs <- mapComIndivList Different (Just $ iArgToIRI iarg1) [iArgToIRI iarg2]
return (fs, [], startVar)
_ -> Fail.fail $ "Couldn't translate unknown atom '" ++ show atom ++ "'!"
|
905f429610b1d01e9187bdd777ec2ce42e39a6a22d2c77a98c50e3452525e501 | rabbitmq/ra | ra_bench.erl | 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 /.
%%
Copyright ( c ) 2017 - 2022 VMware , Inc. or its affiliates . All rights reserved .
%%
%% @hidden
-module(ra_bench).
-behaviour(ra_machine).
-compile(inline_list_funcs).
-compile(inline).
-compile({no_auto_import, [apply/3]}).
-include_lib("eunit/include/eunit.hrl").
-define(PIPE_SIZE, 500).
-define(DATA_SIZE, 256).
-export([
init/1,
apply/3,
% profile/0,
% stop_profile/0
prepare/0,
run/3,
run/2,
run/1,
run/0,
print_metrics/1
]).
init(#{}) ->
undefined.
% msg_ids are scoped per customer
% ra_indexes holds all raft indexes for enqueues currently on queue
apply(#{index := I}, {noop, _}, State) ->
case I rem 100000 of
0 ->
{State, ok, {release_cursor, I, State}};
_ ->
{State, ok}
end.
run(Name, Nodes) ->
run(Name, Nodes, ?PIPE_SIZE).
run(Name, Nodes, Pipe)
when is_atom(Name)
andalso is_list(Nodes) ->
run(#{name => Name,
seconds => 30,
commands / sec
degree => 5,
pipe => Pipe,
nodes => Nodes}).
run() ->
run(#{name => noop,
seconds => 10,
commands / sec
degree => 5,
nodes => [node() | nodes()]}).
print_counter(Last, Counter) ->
V = counters:get(Counter, 1),
io:format("ops/sec: ~b~n", [ V - Last]),
timer:sleep(1000),
print_counter(V, Counter).
run(Nodes) when is_list(Nodes) ->
run(#{name => noop,
seconds => 30,
commands / sec
degree => 5,
nodes => Nodes});
run(#{name := Name,
seconds := Secs,
target := Target,
nodes := Nodes,
degree := Degree} = Conf) ->
Pipe = maps:get(pipe, Conf, ?PIPE_SIZE),
io:format("running ra benchmark config: ~p~n", [Conf]),
io:format("starting servers on ~w~n", [Nodes]),
{ok, ServerIds, []} = start(Name, Nodes),
{ok, _, Leader} = ra:members(hd(ServerIds)),
TotalOps = Secs * Target,
Each = max(Pipe, TotalOps div Degree),
DataSize = maps:get(data_size, Conf, ?DATA_SIZE),
Counter = counters:new(1, [write_concurrency]),
Pids = [spawn_client(self(), Leader, Each, DataSize, Pipe, Counter)
|| _ <- lists:seq(1, Degree)],
io:format("running bench mark...~n", []),
Start = erlang:system_time(millisecond),
[P ! go || P <- Pids],
CounterPrinter = spawn(fun () ->
print_counter(counters:get(Counter, 1), Counter)
end),
%% wait for each pid
Wait = ((Secs * 10000) * 4),
[begin
receive
{done, P} ->
io:format("~w is done ", [P]),
ok
after Wait ->
exit({timeout, P})
end
end || P <- Pids],
End = erlang:system_time(millisecond),
Taken = End - Start,
exit(CounterPrinter, kill),
io:format("benchmark completed: ~b ops in ~bms rate ~.2f ops/sec~n",
[TotalOps, Taken, TotalOps / (Taken / 1000)]),
BName = atom_to_binary(Name, utf8),
_ = [rpc:call(N, ?MODULE, print_metrics, [BName])
|| N <- Nodes],
_ = ra:delete_cluster(ServerIds),
%%
ok.
start(Name, Nodes) when is_atom(Name) ->
ServerIds = [{Name, N} || N <- Nodes],
Configs = [begin
rpc:call(N, ?MODULE, prepare, []),
Id = {Name, N},
UId = ra:new_uid(ra_lib:to_binary(Name)),
#{id => Id,
uid => UId,
cluster_name => Name,
metrics_key => atom_to_binary(Name, utf8),
log_init_args => #{uid => UId},
initial_members => ServerIds,
machine => {module, ?MODULE, #{}}}
end || N <- Nodes],
ra:start_cluster(default, Configs).
prepare() ->
_ = application:ensure_all_started(ra),
_ = ra_system:start_default(),
% error_logger:logfile(filename:join(ra_env:data_dir(), "log.log")),
ok.
send_n(_, _Data, 0, _Counter) -> ok;
send_n(Leader, Data, N, Counter) ->
ra:pipeline_command(Leader, {noop, Data}, make_ref(), low),
counters:add(Counter, 1, 1),
send_n(Leader, Data, N-1, Counter).
client_loop(0, 0, _Leader, _Data, _Counter) ->
ok;
client_loop(Num, Sent, _Leader, Data, Counter) ->
receive
{ra_event, Leader, {applied, Applied}} ->
N = length(Applied),
ToSend = min(Sent, N),
send_n(Leader, Data, ToSend, Counter),
client_loop(Num - N, Sent - ToSend, Leader, Data, Counter);
{ra_event, _, {rejected, {not_leader, NewLeader, _}}} ->
io:format("new leader ~w~n", [NewLeader]),
send_n(NewLeader, Data, 1, Counter),
client_loop(Num, Sent, NewLeader, Data, Counter);
{ra_event, Leader, Evt} ->
io:format("unexpected ra_event ~w~n", [Evt]),
client_loop(Num, Sent, Leader, Data, Counter)
end.
spawn_client(Parent, Leader, Num, DataSize, Pipe, Counter) ->
Data = crypto:strong_rand_bytes(DataSize),
spawn_link(
fun () ->
first send one 1000 noop commands
%% then top up as they are applied
receive
go ->
send_n(Leader, Data, Pipe, Counter),
ok = client_loop(Num, Num - Pipe, Leader, Data, Counter),
Parent ! {done, self()}
end
end).
print_metrics(Name) ->
io:format("Node: ~w~n", [node()]),
io:format("metrics ~p~n", [ets:lookup(ra_metrics, Name)]),
io:format("counters ~p~n", [ra_counters:overview()]).
% profile() ->
GzFile = atom_to_list(node ( ) ) + + " " ,
lg : trace([noop , ra_server , ra_server_proc , ra_snapshot , ra_machine ,
ra_log , ra_flru , ra_machine , ra_log_meta , ra_log_segment ] ,
% lg_file_tracer,
% GzFile, #{running => false, mode => profile}),
% ok.
% stop_profile() ->
% lg:stop(),
% Base = atom_to_list(node()),
% GzFile = Base ++ ".gz.*",
% lg_callgrind:profile_many(GzFile, Base ++ ".out",#{}),
% ok.
| null | https://raw.githubusercontent.com/rabbitmq/ra/f81fa41b86fdc044afc0cf832355806a9edfeb81/src/ra_bench.erl | erlang |
@hidden
profile/0,
stop_profile/0
msg_ids are scoped per customer
ra_indexes holds all raft indexes for enqueues currently on queue
wait for each pid
error_logger:logfile(filename:join(ra_env:data_dir(), "log.log")),
then top up as they are applied
profile() ->
lg_file_tracer,
GzFile, #{running => false, mode => profile}),
ok.
stop_profile() ->
lg:stop(),
Base = atom_to_list(node()),
GzFile = Base ++ ".gz.*",
lg_callgrind:profile_many(GzFile, Base ++ ".out",#{}),
ok. | 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 /.
Copyright ( c ) 2017 - 2022 VMware , Inc. or its affiliates . All rights reserved .
-module(ra_bench).
-behaviour(ra_machine).
-compile(inline_list_funcs).
-compile(inline).
-compile({no_auto_import, [apply/3]}).
-include_lib("eunit/include/eunit.hrl").
-define(PIPE_SIZE, 500).
-define(DATA_SIZE, 256).
-export([
init/1,
apply/3,
prepare/0,
run/3,
run/2,
run/1,
run/0,
print_metrics/1
]).
init(#{}) ->
undefined.
apply(#{index := I}, {noop, _}, State) ->
case I rem 100000 of
0 ->
{State, ok, {release_cursor, I, State}};
_ ->
{State, ok}
end.
run(Name, Nodes) ->
run(Name, Nodes, ?PIPE_SIZE).
run(Name, Nodes, Pipe)
when is_atom(Name)
andalso is_list(Nodes) ->
run(#{name => Name,
seconds => 30,
commands / sec
degree => 5,
pipe => Pipe,
nodes => Nodes}).
run() ->
run(#{name => noop,
seconds => 10,
commands / sec
degree => 5,
nodes => [node() | nodes()]}).
print_counter(Last, Counter) ->
V = counters:get(Counter, 1),
io:format("ops/sec: ~b~n", [ V - Last]),
timer:sleep(1000),
print_counter(V, Counter).
run(Nodes) when is_list(Nodes) ->
run(#{name => noop,
seconds => 30,
commands / sec
degree => 5,
nodes => Nodes});
run(#{name := Name,
seconds := Secs,
target := Target,
nodes := Nodes,
degree := Degree} = Conf) ->
Pipe = maps:get(pipe, Conf, ?PIPE_SIZE),
io:format("running ra benchmark config: ~p~n", [Conf]),
io:format("starting servers on ~w~n", [Nodes]),
{ok, ServerIds, []} = start(Name, Nodes),
{ok, _, Leader} = ra:members(hd(ServerIds)),
TotalOps = Secs * Target,
Each = max(Pipe, TotalOps div Degree),
DataSize = maps:get(data_size, Conf, ?DATA_SIZE),
Counter = counters:new(1, [write_concurrency]),
Pids = [spawn_client(self(), Leader, Each, DataSize, Pipe, Counter)
|| _ <- lists:seq(1, Degree)],
io:format("running bench mark...~n", []),
Start = erlang:system_time(millisecond),
[P ! go || P <- Pids],
CounterPrinter = spawn(fun () ->
print_counter(counters:get(Counter, 1), Counter)
end),
Wait = ((Secs * 10000) * 4),
[begin
receive
{done, P} ->
io:format("~w is done ", [P]),
ok
after Wait ->
exit({timeout, P})
end
end || P <- Pids],
End = erlang:system_time(millisecond),
Taken = End - Start,
exit(CounterPrinter, kill),
io:format("benchmark completed: ~b ops in ~bms rate ~.2f ops/sec~n",
[TotalOps, Taken, TotalOps / (Taken / 1000)]),
BName = atom_to_binary(Name, utf8),
_ = [rpc:call(N, ?MODULE, print_metrics, [BName])
|| N <- Nodes],
_ = ra:delete_cluster(ServerIds),
ok.
start(Name, Nodes) when is_atom(Name) ->
ServerIds = [{Name, N} || N <- Nodes],
Configs = [begin
rpc:call(N, ?MODULE, prepare, []),
Id = {Name, N},
UId = ra:new_uid(ra_lib:to_binary(Name)),
#{id => Id,
uid => UId,
cluster_name => Name,
metrics_key => atom_to_binary(Name, utf8),
log_init_args => #{uid => UId},
initial_members => ServerIds,
machine => {module, ?MODULE, #{}}}
end || N <- Nodes],
ra:start_cluster(default, Configs).
prepare() ->
_ = application:ensure_all_started(ra),
_ = ra_system:start_default(),
ok.
send_n(_, _Data, 0, _Counter) -> ok;
send_n(Leader, Data, N, Counter) ->
ra:pipeline_command(Leader, {noop, Data}, make_ref(), low),
counters:add(Counter, 1, 1),
send_n(Leader, Data, N-1, Counter).
client_loop(0, 0, _Leader, _Data, _Counter) ->
ok;
client_loop(Num, Sent, _Leader, Data, Counter) ->
receive
{ra_event, Leader, {applied, Applied}} ->
N = length(Applied),
ToSend = min(Sent, N),
send_n(Leader, Data, ToSend, Counter),
client_loop(Num - N, Sent - ToSend, Leader, Data, Counter);
{ra_event, _, {rejected, {not_leader, NewLeader, _}}} ->
io:format("new leader ~w~n", [NewLeader]),
send_n(NewLeader, Data, 1, Counter),
client_loop(Num, Sent, NewLeader, Data, Counter);
{ra_event, Leader, Evt} ->
io:format("unexpected ra_event ~w~n", [Evt]),
client_loop(Num, Sent, Leader, Data, Counter)
end.
spawn_client(Parent, Leader, Num, DataSize, Pipe, Counter) ->
Data = crypto:strong_rand_bytes(DataSize),
spawn_link(
fun () ->
first send one 1000 noop commands
receive
go ->
send_n(Leader, Data, Pipe, Counter),
ok = client_loop(Num, Num - Pipe, Leader, Data, Counter),
Parent ! {done, self()}
end
end).
print_metrics(Name) ->
io:format("Node: ~w~n", [node()]),
io:format("metrics ~p~n", [ets:lookup(ra_metrics, Name)]),
io:format("counters ~p~n", [ra_counters:overview()]).
GzFile = atom_to_list(node ( ) ) + + " " ,
lg : trace([noop , ra_server , ra_server_proc , ra_snapshot , ra_machine ,
ra_log , ra_flru , ra_machine , ra_log_meta , ra_log_segment ] ,
|
81bc4cf54821002feb0d712914f15ee4f5550cd42e5b3026c170bf5f76c4edf0 | dextroamphetamine/nuko | Text.hs | module Nuko.Report.Text (
Color(..),
Mode(..),
Piece(..),
colorlessFromFormat,
DetailedDiagnosticInfo(..),
PrettyDiagnostic(..),
Severity(..),
Annotation(..),
mkBasicDiagnostic,
) where
import Relude
import Nuko.Report.Range (Range)
data Severity
= Warning
| Error
| Information
| Hint
data Color
= Fst
| Snd
| Thr
| For
newtype Mode
= Words [Piece]
data Piece
= Raw Text
| Marked Color Text
| Quoted Piece
data Annotation
= Ann Color Mode Range
| NoAnn Color Range
data DetailedDiagnosticInfo = DetailedDiagnosticInfo
{ code :: Int
, title :: Mode
, subtitles :: [(Color, Mode)]
, hints :: [Mode]
, positions :: [Annotation]
}
mkBasicDiagnostic :: Int -> [Piece] -> [Annotation] -> DetailedDiagnosticInfo
mkBasicDiagnostic code' diagTitle = DetailedDiagnosticInfo code' (Words diagTitle) [] []
class PrettyDiagnostic a where
prettyDiagnostic :: a -> DetailedDiagnosticInfo
getPieceText :: Piece -> Text
getPieceText (Raw t) = t
getPieceText (Marked _ t) = t
getPieceText (Quoted t) = "'" <> getPieceText t <> "'"
colorlessFromFormat :: Mode -> Text
colorlessFromFormat = \case
(Words pieces) -> unwords (fmap getPieceText pieces)
| null | https://raw.githubusercontent.com/dextroamphetamine/nuko/1b6f960eeeebbfcbfb5700279c39758f82e7df28/src/Nuko/Report/Text.hs | haskell | module Nuko.Report.Text (
Color(..),
Mode(..),
Piece(..),
colorlessFromFormat,
DetailedDiagnosticInfo(..),
PrettyDiagnostic(..),
Severity(..),
Annotation(..),
mkBasicDiagnostic,
) where
import Relude
import Nuko.Report.Range (Range)
data Severity
= Warning
| Error
| Information
| Hint
data Color
= Fst
| Snd
| Thr
| For
newtype Mode
= Words [Piece]
data Piece
= Raw Text
| Marked Color Text
| Quoted Piece
data Annotation
= Ann Color Mode Range
| NoAnn Color Range
data DetailedDiagnosticInfo = DetailedDiagnosticInfo
{ code :: Int
, title :: Mode
, subtitles :: [(Color, Mode)]
, hints :: [Mode]
, positions :: [Annotation]
}
mkBasicDiagnostic :: Int -> [Piece] -> [Annotation] -> DetailedDiagnosticInfo
mkBasicDiagnostic code' diagTitle = DetailedDiagnosticInfo code' (Words diagTitle) [] []
class PrettyDiagnostic a where
prettyDiagnostic :: a -> DetailedDiagnosticInfo
getPieceText :: Piece -> Text
getPieceText (Raw t) = t
getPieceText (Marked _ t) = t
getPieceText (Quoted t) = "'" <> getPieceText t <> "'"
colorlessFromFormat :: Mode -> Text
colorlessFromFormat = \case
(Words pieces) -> unwords (fmap getPieceText pieces)
|
|
01bcdad5e4e40d7dbc12c4a2d70a7ccbbafda97be740996fe34f076da5fe3018 | vlstill/hsExprTest | wrap-err.1.nok.hs | f = True
t = True
| null | https://raw.githubusercontent.com/vlstill/hsExprTest/391fc823c1684ec248ac8f76412fefeffb791865/test/wrap-err.1.nok.hs | haskell | f = True
t = True
|
|
c7b10eac34a3325da3b30fbfb9b17876164e5e98b1615b0872b7ff93baf9fb9a | benoitc/cbt | cbt_stream_tests.erl | 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(cbt_stream_tests).
-include("cbt_tests.hrl").
setup() ->
{ok, Fd} = cbt_file:open(?tempfile(), [create, overwrite]),
{ok, Stream} = cbt_stream:open(Fd),
{Fd, Stream}.
teardown({Fd, _}) ->
ok = cbt_file:close(Fd).
stream_test_() ->
{
"CBT stream tests",
{
foreach,
fun setup/0, fun teardown/1,
[
fun should_write/1,
fun should_write_consecutive/1,
fun should_write_empty_binary/1,
fun should_return_file_pointers_on_close/1,
fun should_return_stream_size_on_close/1,
fun should_return_valid_pointers/1,
fun should_recall_last_pointer_position/1,
fun should_stream_more_with_4K_chunk_size/1
]
}
}.
should_write({_, Stream}) ->
?_assertEqual(ok, cbt_stream:write(Stream, <<"food">>)).
should_write_consecutive({_, Stream}) ->
cbt_stream:write(Stream, <<"food">>),
?_assertEqual(ok, cbt_stream:write(Stream, <<"foob">>)).
should_write_empty_binary({_, Stream}) ->
?_assertEqual(ok, cbt_stream:write(Stream, <<>>)).
should_return_file_pointers_on_close({_, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{Ptrs, _, _, _, _} = cbt_stream:close(Stream),
?_assertEqual([{0, 8}], Ptrs).
should_return_stream_size_on_close({_, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{_, Length, _, _, _} = cbt_stream:close(Stream),
?_assertEqual(8, Length).
should_return_valid_pointers({Fd, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{Ptrs, _, _, _, _} = cbt_stream:close(Stream),
?_assertEqual(<<"foodfoob">>, read_all(Fd, Ptrs)).
should_recall_last_pointer_position({Fd, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{_, _, _, _, _} = cbt_stream:close(Stream),
{ok, ExpPtr} = cbt_file:bytes(Fd),
{ok, Stream2} = cbt_stream:open(Fd),
ZeroBits = <<0:(8 * 10)>>,
OneBits = <<1:(8 * 10)>>,
ok = cbt_stream:write(Stream2, OneBits),
ok = cbt_stream:write(Stream2, ZeroBits),
{Ptrs, 20, _, _, _} = cbt_stream:close(Stream2),
[{ExpPtr, 20}] = Ptrs,
AllBits = iolist_to_binary([OneBits, ZeroBits]),
?_assertEqual(AllBits, read_all(Fd, Ptrs)).
should_stream_more_with_4K_chunk_size({Fd, _}) ->
{ok, Stream} = cbt_stream:open(Fd, [{buffer_size, 4096}]),
lists:foldl(
fun(_, Acc) ->
Data = <<"a1b2c">>,
cbt_stream:write(Stream, Data),
[Data | Acc]
end, [], lists:seq(1, 1024)),
?_assertMatch({[{0, 4100}, {4106, 1020}], 5120, _, _, _},
cbt_stream:close(Stream)).
read_all(Fd, PosList) ->
Data = cbt_stream:foldl(Fd, PosList, fun(Bin, Acc) -> [Bin, Acc] end, []),
iolist_to_binary(Data).
| null | https://raw.githubusercontent.com/benoitc/cbt/49b99e56f406f918739adde152e8a4908e755521/test/cbt_stream_tests.erl | erlang | 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
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations under
the License. | Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may not
distributed under the License is distributed on an " AS IS " BASIS , WITHOUT
-module(cbt_stream_tests).
-include("cbt_tests.hrl").
setup() ->
{ok, Fd} = cbt_file:open(?tempfile(), [create, overwrite]),
{ok, Stream} = cbt_stream:open(Fd),
{Fd, Stream}.
teardown({Fd, _}) ->
ok = cbt_file:close(Fd).
stream_test_() ->
{
"CBT stream tests",
{
foreach,
fun setup/0, fun teardown/1,
[
fun should_write/1,
fun should_write_consecutive/1,
fun should_write_empty_binary/1,
fun should_return_file_pointers_on_close/1,
fun should_return_stream_size_on_close/1,
fun should_return_valid_pointers/1,
fun should_recall_last_pointer_position/1,
fun should_stream_more_with_4K_chunk_size/1
]
}
}.
should_write({_, Stream}) ->
?_assertEqual(ok, cbt_stream:write(Stream, <<"food">>)).
should_write_consecutive({_, Stream}) ->
cbt_stream:write(Stream, <<"food">>),
?_assertEqual(ok, cbt_stream:write(Stream, <<"foob">>)).
should_write_empty_binary({_, Stream}) ->
?_assertEqual(ok, cbt_stream:write(Stream, <<>>)).
should_return_file_pointers_on_close({_, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{Ptrs, _, _, _, _} = cbt_stream:close(Stream),
?_assertEqual([{0, 8}], Ptrs).
should_return_stream_size_on_close({_, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{_, Length, _, _, _} = cbt_stream:close(Stream),
?_assertEqual(8, Length).
should_return_valid_pointers({Fd, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{Ptrs, _, _, _, _} = cbt_stream:close(Stream),
?_assertEqual(<<"foodfoob">>, read_all(Fd, Ptrs)).
should_recall_last_pointer_position({Fd, Stream}) ->
cbt_stream:write(Stream, <<"foodfoob">>),
{_, _, _, _, _} = cbt_stream:close(Stream),
{ok, ExpPtr} = cbt_file:bytes(Fd),
{ok, Stream2} = cbt_stream:open(Fd),
ZeroBits = <<0:(8 * 10)>>,
OneBits = <<1:(8 * 10)>>,
ok = cbt_stream:write(Stream2, OneBits),
ok = cbt_stream:write(Stream2, ZeroBits),
{Ptrs, 20, _, _, _} = cbt_stream:close(Stream2),
[{ExpPtr, 20}] = Ptrs,
AllBits = iolist_to_binary([OneBits, ZeroBits]),
?_assertEqual(AllBits, read_all(Fd, Ptrs)).
should_stream_more_with_4K_chunk_size({Fd, _}) ->
{ok, Stream} = cbt_stream:open(Fd, [{buffer_size, 4096}]),
lists:foldl(
fun(_, Acc) ->
Data = <<"a1b2c">>,
cbt_stream:write(Stream, Data),
[Data | Acc]
end, [], lists:seq(1, 1024)),
?_assertMatch({[{0, 4100}, {4106, 1020}], 5120, _, _, _},
cbt_stream:close(Stream)).
read_all(Fd, PosList) ->
Data = cbt_stream:foldl(Fd, PosList, fun(Bin, Acc) -> [Bin, Acc] end, []),
iolist_to_binary(Data).
|
e043a6b03a5578d559244c26c633b2ad6fdf1b7a3092c5203f387db1d9a046de | dongcarl/guix | substitute.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2013 , 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < >
Copyright © 2014 < >
Copyright © 2018 < >
Copyright © 2020 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix scripts substitute)
#:use-module (guix ui)
#:use-module (guix scripts)
#:use-module (guix narinfo)
#:use-module (guix store)
#:use-module (guix substitutes)
#:use-module (guix utils)
#:use-module (guix combinators)
#:use-module (guix config)
#:use-module (guix records)
#:use-module (guix diagnostics)
#:use-module (guix i18n)
#:use-module ((guix serialization) #:select (restore-file dump-file))
#:autoload (guix store deduplication) (dump-file/deduplicate)
#:autoload (guix scripts discover) (read-substitute-urls)
#:use-module (gcrypt hash)
#:use-module (guix base32)
#:use-module (guix base64)
#:use-module (guix cache)
#:use-module (gcrypt pk-crypto)
#:use-module (guix pki)
#:use-module ((guix build utils) #:select (mkdir-p))
#:use-module ((guix build download)
#:select (uri-abbreviation nar-uri-abbreviation
(open-connection-for-uri
. guix:open-connection-for-uri)))
#:autoload (gnutls) (error/invalid-session error/again error/interrupted)
#:use-module (guix progress)
#:use-module ((guix build syscalls)
#:select (set-thread-name))
#:use-module (ice-9 rdelim)
#:use-module (ice-9 match)
#:use-module (ice-9 format)
#:use-module (ice-9 ftw)
#:use-module (rnrs bytevectors)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (web uri)
#:use-module (guix http-client)
#:export (%allow-unauthenticated-substitutes?
%reply-file-descriptor
substitute-urls
guix-substitute))
;;; Comment:
;;;
;;; This is the "binary substituter". It is invoked by the daemon do check
;;; for the existence of available "substitutes" (pre-built binaries), and to
;;; actually use them as a substitute to building things locally.
;;;
;;; If possible, substitute a binary for the requested store path, using a Nix
;;; "binary cache". This program implements the Nix "substituter" protocol.
;;;
;;; Code:
(define %narinfo-expired-cache-entry-removal-delay
;; How often we want to remove files corresponding to expired cache entries.
(* 7 24 3600))
(define (warn-about-missing-authentication)
(warning (G_ "authentication and authorization of substitutes \
disabled!~%"))
#t)
(define %allow-unauthenticated-substitutes?
;; Whether to allow unchecked substitutes. This is useful for testing
;; purposes, and should be avoided otherwise.
(make-parameter
(and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES")
(cut string-ci=? <> "yes"))))
(define %fetch-timeout
;; Number of seconds after which networking is considered "slow".
5)
(define %random-state
(seed->random-state (+ (ash (cdr (gettimeofday)) 32) (getpid))))
(define-syntax-rule (with-timeout duration handler body ...)
when DURATION seconds have expired , call HANDLER , and run BODY
again."
(begin
(sigaction SIGALRM
(lambda (signum)
(sigaction SIGALRM SIG_DFL)
handler))
(alarm duration)
(call-with-values
(lambda ()
(let try ()
(catch 'system-error
(lambda ()
body ...)
(lambda args
Before 39 - gfe51c7b , the SIGALRM triggers
;; because of the bug at
;; <-devel/2013-06/msg00050.html>.
When that happens , try again . Note : can not be
;; used because of <>.
(if (= EINTR (system-error-errno args))
(begin
;; Wait a little to avoid bursts.
(usleep (random 3000000 %random-state))
(try))
(apply throw args))))))
(lambda result
(alarm 0)
(sigaction SIGALRM SIG_DFL)
(apply values result)))))
(define (at-most max-length lst)
"If LST is shorter than MAX-LENGTH, return it and the empty list; otherwise
return its MAX-LENGTH first elements and its tail."
(let loop ((len 0)
(lst lst)
(result '()))
(match lst
(()
(values (reverse result) '()))
((head . tail)
(if (>= len max-length)
(values (reverse result) lst)
(loop (+ 1 len) tail (cons head result)))))))
(define (narinfo-from-file file url)
"Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f
if file doesn't exist, and the narinfo otherwise."
(catch 'system-error
(lambda ()
(call-with-input-file file
(cut read-narinfo <> url)))
(lambda args
(if (= ENOENT (system-error-errno args))
#f
(apply throw args)))))
(define (lookup-narinfo caches path authorized?)
"Return the narinfo for PATH in CACHES, or #f when no substitute for PATH
was found."
(match (lookup-narinfos/diverse
caches (list path) authorized?
#:open-connection open-connection-for-uri/cached)
((answer) answer)
(_ #f)))
(define (cached-narinfo-expiration-time file)
"Return the expiration time for FILE, which is a cached narinfo."
(catch 'system-error
(lambda ()
(call-with-input-file file
(lambda (port)
(match (read port)
(('narinfo ('version 2) ('cache-uri uri)
('date date) ('ttl ttl) ('value #f))
(+ date ttl))
(('narinfo ('version 2) ('cache-uri uri)
('date date) ('ttl ttl) ('value value))
(+ date ttl))
(x
0)))))
(lambda args
;; FILE may have been deleted.
0)))
(define (narinfo-cache-directories directory)
"Return the list of narinfo cache directories (one per cache URL.)"
(map (cut string-append directory "/" <>)
(scandir %narinfo-cache-directory
(lambda (item)
(and (not (member item '("." "..")))
(file-is-directory?
(string-append %narinfo-cache-directory
"/" item)))))))
(define* (cached-narinfo-files #:optional
(directory %narinfo-cache-directory))
"Return the list of cached narinfo files under DIRECTORY."
(append-map (lambda (directory)
(map (cut string-append directory "/" <>)
(scandir directory
(lambda (file)
(= (string-length file) 32)))))
(narinfo-cache-directories directory)))
(define-syntax with-networking
(syntax-rules ()
"Catch DNS lookup errors and TLS errors and gracefully exit."
Note : no attempt is made to catch other networking errors , because DNS
lookup errors are typically the first one , and because other errors are
;; a subset of `system-error', which is harder to filter.
((_ exp ...)
;; Use a pre-unwind handler so that re-throwing preserves useful
backtraces . ' with - throw - handler ' works for 2.2 and 3.0 .
(with-throw-handler #t
(lambda () exp ...)
(match-lambda*
(('getaddrinfo-error error)
(leave (G_ "host name lookup error: ~a~%")
(gai-strerror error)))
(('gnutls-error error proc . rest)
(let ((error->string (module-ref (resolve-interface '(gnutls))
'error->string)))
(leave (G_ "TLS error in procedure '~a': ~a~%")
proc (error->string error))))
(args
(apply throw args)))))))
;;;
;;; Help.
;;;
(define (show-help)
(display (G_ "Usage: guix substitute [OPTION]...
Internal tool to substitute a pre-built binary to a local build.\n"))
(display (G_ "
--query report on the availability of substitutes for the
store file names passed on the standard input"))
(display (G_ "
--substitute STORE-FILE DESTINATION
download STORE-FILE and store it as a Nar in file
DESTINATION"))
(newline)
(display (G_ "
-h, --help display this help and exit"))
(display (G_ "
-V, --version display version information and exit"))
(newline)
(show-bug-report-information))
;;;
;;; Daemon/substituter protocol.
;;;
(define %prefer-fast-decompression?
;; Whether to prefer fast decompression over good compression ratios. This
serves in particular to choose between lzip ( high compression ratio but
low decompression throughput ) and zstd ( lower compression ratio but high
;; decompression throughput).
#f)
(define (call-with-cpu-usage-monitoring proc)
(let ((before (times)))
(proc)
(let ((after (times)))
(if (= (tms:clock after) (tms:clock before))
0
(/ (- (tms:utime after) (tms:utime before))
(- (tms:clock after) (tms:clock before))
1.)))))
(define-syntax-rule (with-cpu-usage-monitoring exp ...)
"Evaluate EXP... Return its CPU usage as a fraction between 0 and 1."
(call-with-cpu-usage-monitoring (lambda () exp ...)))
(define (display-narinfo-data port narinfo)
"Write to PORT the contents of NARINFO in the format expected by the
daemon."
(format port "~a\n~a\n~a\n"
(narinfo-path narinfo)
(or (and=> (narinfo-deriver narinfo)
(cute string-append (%store-prefix) "/" <>))
"")
(length (narinfo-references narinfo)))
(for-each (cute format port "~a/~a~%" (%store-prefix) <>)
(narinfo-references narinfo))
(let-values (((uri compression file-size)
(narinfo-best-uri narinfo
#:fast-decompression?
%prefer-fast-decompression?)))
(format port "~a\n~a\n"
(or file-size 0)
(or (narinfo-size narinfo) 0))))
(define* (process-query port command
#:key cache-urls acl)
"Reply on PORT to COMMAND, a query as written by the daemon to this process's
standard input. Use ACL as the access-control list against which to check
authorized substitutes."
(define valid?
(if (%allow-unauthenticated-substitutes?)
(begin
(warn-about-missing-authentication)
(const #t))
(lambda (obj)
(valid-narinfo? obj acl))))
(define* (make-progress-reporter total #:key url)
(define done 0)
(define (report-progress)
(erase-current-line (current-error-port)) ;erase current line
(force-output (current-error-port))
(format (current-error-port)
(G_ "updating substitutes from '~a'... ~5,1f%")
url (* 100. (/ done total)))
(set! done (+ 1 done)))
(progress-reporter
(start report-progress)
(report report-progress)
(stop (lambda ()
(newline (current-error-port))))))
(match (string-tokenize command)
(("have" paths ..1)
;; Return the subset of PATHS available in CACHE-URLS.
(let ((substitutable (lookup-narinfos/diverse
cache-urls paths valid?
#:open-connection open-connection-for-uri/cached
#:make-progress-reporter make-progress-reporter)))
(for-each (lambda (narinfo)
(format port "~a~%" (narinfo-path narinfo)))
substitutable)
(newline port)))
(("info" paths ..1)
;; Reply info about PATHS if it's in CACHE-URLS.
(let ((substitutable (lookup-narinfos/diverse
cache-urls paths valid?
#:open-connection open-connection-for-uri/cached
#:make-progress-reporter make-progress-reporter)))
(for-each (cut display-narinfo-data port <>) substitutable)
(newline port)))
(wtf
(error "unknown `--query' command" wtf))))
(define %max-cached-connections
;; Maximum number of connections kept in cache by
;; 'open-connection-for-uri/cached'.
16)
(define open-connection-for-uri/cached
(let ((cache '()))
(lambda* (uri #:key fresh? (timeout %fetch-timeout) verify-certificate?)
"Return a connection for URI, possibly reusing a cached connection.
When FRESH? is true, delete any cached connections for URI and open a new one.
Return #f if URI's scheme is 'file' or #f.
When true, TIMEOUT is the maximum number of milliseconds to wait for
connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS
server certificates."
(define host (uri-host uri))
(define scheme (uri-scheme uri))
(define key (list host scheme (uri-port uri)))
(and (not (memq scheme '(file #f)))
(match (assoc-ref cache key)
(#f
Open a new connection to URI and evict old entries from
;; CACHE, if any.
(let-values (((socket)
(guix:open-connection-for-uri
uri
#:verify-certificate? verify-certificate?
#:timeout timeout))
((new-cache evicted)
(at-most (- %max-cached-connections 1) cache)))
(for-each (match-lambda
((_ . port)
(false-if-exception (close-port port))))
evicted)
(set! cache (alist-cons key socket new-cache))
socket))
(socket
(if (or fresh? (port-closed? socket))
(begin
(false-if-exception (close-port socket))
(set! cache (alist-delete key cache))
(open-connection-for-uri/cached uri #:timeout timeout
#:verify-certificate?
verify-certificate?))
(begin
;; Drain input left from the previous use.
(drain-input socket)
socket))))))))
(define (call-with-cached-connection uri proc)
(let ((port (open-connection-for-uri/cached uri
#:verify-certificate? #f)))
(catch #t
(lambda ()
(proc port))
(lambda (key . args)
;; If PORT was cached and the server closed the connection in the
;; meantime, we get EPIPE. In that case, open a fresh connection
;; and retry. We might also get 'bad-response or a similar
;; exception from (web response) later on, once we've sent the
request , or a ERROR / INVALID - SESSION from GnuTLS .
(if (or (and (eq? key 'system-error)
(= EPIPE (system-error-errno `(,key ,@args))))
(and (eq? key 'gnutls-error)
(memq (first args)
(list error/invalid-session
XXX : These two are not properly handled in
GnuTLS < 3.7.3 , in
;; 'write_to_session_record_port'; see
;; <>.
error/again error/interrupted)))
(memq key '(bad-response bad-header bad-header-component)))
(proc (open-connection-for-uri/cached uri
#:verify-certificate? #f
#:fresh? #t))
(apply throw key args))))))
(define-syntax-rule (with-cached-connection uri port exp ...)
"Bind PORT with EXP... to a socket connected to URI."
(call-with-cached-connection uri (lambda (port) exp ...)))
(define* (process-substitution port store-item destination
#:key cache-urls acl
deduplicate? print-build-trace?)
"Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
DESTINATION as a nar file. Verify the substitute against ACL, and verify its
hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
DESTINATION is in the store, deduplicate its files. Print a status line to
PORT."
(define narinfo
(lookup-narinfo cache-urls store-item
(if (%allow-unauthenticated-substitutes?)
(const #t)
(cut valid-narinfo? <> acl))))
(define destination-in-store?
(string-prefix? (string-append (%store-prefix) "/")
destination))
(define (dump-file/deduplicate* . args)
;; Make sure deduplication looks at the right store (necessary in test
;; environments).
(apply dump-file/deduplicate
(append args (list #:store (%store-prefix)))))
(define (fetch uri)
(case (uri-scheme uri)
((file)
(let ((port (open-file (uri-path uri) "r0b")))
(values port (stat:size (stat port)))))
((http https)
(guard (c ((http-get-error? c)
(leave (G_ "download from '~a' failed: ~a, ~s~%")
(uri->string (http-get-error-uri c))
(http-get-error-code c)
(http-get-error-reason c))))
;; Test this with:
sudo tc qdisc add dev eth0 root netem delay
;; and then cancel with:
;; sudo tc qdisc del dev eth0 root
(with-timeout %fetch-timeout
(begin
(warning (G_ "while fetching ~a: server is somewhat slow~%")
(uri->string uri))
(warning (G_ "try `--no-substitutes' if the problem persists~%")))
(with-cached-connection uri port
(http-fetch uri #:text? #f
#:port port
#:keep-alive? #t
#:buffered? #f)))))
(else
(leave (G_ "unsupported substitute URI scheme: ~a~%")
(uri->string uri)))))
(unless narinfo
(leave (G_ "no valid substitute for '~a'~%")
store-item))
(let-values (((uri compression file-size)
(narinfo-best-uri narinfo
#:fast-decompression?
%prefer-fast-decompression?)))
(unless print-build-trace?
(format (current-error-port)
(G_ "Downloading ~a...~%") (uri->string uri)))
(let*-values (((raw download-size)
;; 'guix publish' without '--cache' doesn't specify a
;; Content-Length, so DOWNLOAD-SIZE is #f in this case.
(fetch uri))
((progress)
(let* ((dl-size (or download-size
(and (equal? compression "none")
(narinfo-size narinfo))))
(reporter (if print-build-trace?
(progress-reporter/trace
destination
(uri->string uri) dl-size
(current-error-port))
(progress-reporter/file
(uri->string uri) dl-size
(current-error-port)
#:abbreviation nar-uri-abbreviation))))
;; Keep RAW open upon completion so we can later reuse
;; the underlying connection. Pass the download size so
that this procedure wo n't block reading from RAW .
(progress-report-port reporter raw
#:close? #f
#:download-size dl-size)))
((input pids)
;; NOTE: This 'progress' port of current process will be
;; closed here, while the child process doing the
;; reporting will close it upon exit.
(decompressed-port (string->symbol compression)
progress))
Compute the actual nar hash as we read it .
((algorithm expected)
(narinfo-hash-algorithm+value narinfo))
((hashed get-hash)
(open-hash-input-port algorithm input)))
Unpack the Nar at INPUT into DESTINATION .
(define cpu-usage
(with-cpu-usage-monitoring
(restore-file hashed destination
#:dump-file (if (and destination-in-store?
deduplicate?)
dump-file/deduplicate*
dump-file))))
;; Create a hysteresis: depending on CPU usage, favor compression
methods with faster decompression ( like ) or methods with better
compression ratios ( like lzip ) . This stems from the observation that
;; substitution can be CPU-bound when high-speed networks are used:
;; <-devel/2020-12/msg00177.html>.
;; To simulate "slow" networking or changing conditions, run:
sudo tc qdisc add dev eno1 root tbf rate 512kbit latency 50ms burst 1540
;; and then cancel with:
;; sudo tc qdisc del dev eno1 root
(when (> cpu-usage .8)
(set! %prefer-fast-decompression? #t))
(when (< cpu-usage .2)
(set! %prefer-fast-decompression? #f))
(close-port hashed)
(close-port input)
;; Wait for the reporter to finish.
(every (compose zero? cdr waitpid) pids)
;; Skip a line after what 'progress-reporter/file' printed, and another
;; one to visually separate substitutions. When PRINT-BUILD-TRACE? is
;; true, leave it up to (guix status) to prettify things.
(newline (current-error-port))
(unless print-build-trace?
(newline (current-error-port)))
;; Check whether we got the data announced in NARINFO.
(let ((actual (get-hash)))
(if (bytevector=? actual expected)
;; Tell the daemon that we're done.
(format port "success ~a ~a~%"
(narinfo-hash narinfo) (narinfo-size narinfo))
;; The actual data has a different hash than that in NARINFO.
(format port "hash-mismatch ~a ~a ~a~%"
(hash-algorithm-name algorithm)
(bytevector->nix-base32-string expected)
(bytevector->nix-base32-string actual)))))))
;;;
;;; Entry point.
;;;
(define (check-acl-initialized)
"Warn if the ACL is uninitialized."
(define (singleton? acl)
;; True if ACL contains just the user's public key.
(and (file-exists? %public-key-file)
(let ((key (call-with-input-file %public-key-file
(compose string->canonical-sexp
read-string))))
(match acl
((thing)
(equal? (canonical-sexp->string thing)
(canonical-sexp->string key)))
(_
#f)))))
(let ((acl (acl->public-keys (current-acl))))
(when (or (null? acl) (singleton? acl))
(warning (G_ "ACL for archive imports seems to be uninitialized, \
substitutes may be unavailable\n")))))
(define (daemon-options)
"Return a list of name/value pairs denoting build daemon options."
(define %not-newline
(char-set-complement (char-set #\newline)))
(match (getenv "_NIX_OPTIONS")
(#f ;should not happen when called by the daemon
'())
(newline-separated
;; Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
(filter-map (lambda (option=value)
(match (string-index option=value #\=)
(#f ;invalid option setting
#f)
(equal-sign
(cons (string-take option=value equal-sign)
(string-drop option=value (+ 1 equal-sign))))))
(string-tokenize newline-separated %not-newline)))))
(define (find-daemon-option option)
"Return the value of build daemon option OPTION, or #f if it could not be
found."
(assoc-ref (daemon-options) option))
(define %default-substitute-urls
(match (and=> (or (find-daemon-option "untrusted-substitute-urls") ;client
(find-daemon-option "substitute-urls")) ;admin
string-tokenize)
((urls ...)
urls)
(#f
;; This can only happen when this script is not invoked by the
;; daemon.
'(""
""))))
;; In order to prevent using large number of discovered local substitute
;; servers, limit the local substitute urls list size.
(define %max-substitute-urls 50)
(define* (randomize-substitute-urls urls
#:key
(max %max-substitute-urls))
"Return a list containing MAX urls from URLS, picked randomly. If URLS list
is shorter than MAX elements, then it is directly returned."
(define (random-item list)
(list-ref list (random (length list))))
(if (<= (length urls) max)
urls
(let loop ((res '())
(urls urls))
(if (eq? (length res) max)
res
(let ((url (random-item urls)))
(loop (cons url res) (delete url urls)))))))
(define %local-substitute-urls
;; If the following option is passed to the daemon, use the substitutes list
;; provided by "guix discover" process.
(let* ((option (find-daemon-option "discover"))
(discover? (and option (string=? option "true"))))
(if discover?
(randomize-substitute-urls (read-substitute-urls))
'())))
(define substitute-urls
;; List of substitute URLs.
(make-parameter (append %local-substitute-urls
%default-substitute-urls)))
(define (client-terminal-columns)
"Return the number of columns in the client's terminal, if it is known, or a
default value."
(or (and=> (or (find-daemon-option "untrusted-terminal-columns")
(find-daemon-option "terminal-columns"))
(lambda (str)
(let ((number (string->number str)))
(and number (max 20 (- number 1))))))
80))
(define (validate-uri uri)
(unless (string->uri uri)
(leave (G_ "~a: invalid URI~%") uri)))
(define %reply-file-descriptor
The file descriptor where replies to the daemon must be sent , or # f to
;; use the current output port instead.
(make-parameter 4))
(define-command (guix-substitute . args)
(category internal)
(synopsis "implement the build daemon's substituter protocol")
(define print-build-trace?
(match (or (find-daemon-option "untrusted-print-extended-build-trace")
(find-daemon-option "print-extended-build-trace"))
(#f #f)
((= string->number number) (> number 0))
(_ #f)))
(define deduplicate?
(find-daemon-option "deduplicate"))
(define reply-port
;; Port used to reply to the daemon.
(if (%reply-file-descriptor)
(fdopen (%reply-file-descriptor) "wl")
(current-output-port)))
(mkdir-p %narinfo-cache-directory)
(maybe-remove-expired-cache-entries %narinfo-cache-directory
cached-narinfo-files
#:entry-expiration
cached-narinfo-expiration-time
#:cleanup-period
%narinfo-expired-cache-entry-removal-delay)
(check-acl-initialized)
;; Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
;; message.
(for-each validate-uri (substitute-urls))
;; Attempt to install the client's locale so that messages are suitably
translated . LC_CTYPE must be a UTF-8 locale ; it 's the case by default
;; so don't change it.
(match (or (find-daemon-option "untrusted-locale")
(find-daemon-option "locale"))
(#f #f)
(locale (false-if-exception (setlocale LC_MESSAGES locale))))
(catch 'system-error
(lambda ()
(set-thread-name "guix substitute"))
GNU / lacks ' prctl '
(with-networking
(with-error-handling ; for signature errors
(match args
(("--query")
(let ((acl (current-acl)))
(let loop ((command (read-line)))
(or (eof-object? command)
(begin
(process-query reply-port command
#:cache-urls (substitute-urls)
#:acl acl)
(loop (read-line)))))))
(("--substitute")
;; Download STORE-PATH and store it as a Nar in file DESTINATION.
;; Specify the number of columns of the terminal so the progress
;; report displays nicely.
(parameterize ((current-terminal-columns (client-terminal-columns)))
(let loop ()
(match (read-line)
((? eof-object?)
#t)
((= string-tokenize ("substitute" store-path destination))
(process-substitution reply-port store-path destination
#:cache-urls (substitute-urls)
#:acl (current-acl)
#:deduplicate? deduplicate?
#:print-build-trace?
print-build-trace?)
(loop))))))
((or ("-V") ("--version"))
(show-version-and-exit "guix substitute"))
(("--help")
(show-help))
(opts
(leave (G_ "~a: unrecognized options~%") opts))))))
;;; Local Variables:
eval : ( put ' with - timeout ' scheme - indent - function 1 )
;;; eval: (put 'with-redirected-error-port 'scheme-indent-function 0)
eval : ( put ' with - cached - connection ' scheme - indent - function 2 )
eval : ( put ' call - with - cached - connection ' scheme - indent - function 1 )
;;; End:
;;; substitute.scm ends here
| null | https://raw.githubusercontent.com/dongcarl/guix/d2b30db788f1743f9f8738cb1de977b77748567f/guix/scripts/substitute.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Comment:
This is the "binary substituter". It is invoked by the daemon do check
for the existence of available "substitutes" (pre-built binaries), and to
actually use them as a substitute to building things locally.
If possible, substitute a binary for the requested store path, using a Nix
"binary cache". This program implements the Nix "substituter" protocol.
Code:
How often we want to remove files corresponding to expired cache entries.
Whether to allow unchecked substitutes. This is useful for testing
purposes, and should be avoided otherwise.
Number of seconds after which networking is considered "slow".
because of the bug at
<-devel/2013-06/msg00050.html>.
used because of <>.
Wait a little to avoid bursts.
otherwise
FILE may have been deleted.
a subset of `system-error', which is harder to filter.
Use a pre-unwind handler so that re-throwing preserves useful
Help.
Daemon/substituter protocol.
Whether to prefer fast decompression over good compression ratios. This
decompression throughput).
erase current line
Return the subset of PATHS available in CACHE-URLS.
Reply info about PATHS if it's in CACHE-URLS.
Maximum number of connections kept in cache by
'open-connection-for-uri/cached'.
CACHE, if any.
Drain input left from the previous use.
If PORT was cached and the server closed the connection in the
meantime, we get EPIPE. In that case, open a fresh connection
and retry. We might also get 'bad-response or a similar
exception from (web response) later on, once we've sent the
'write_to_session_record_port'; see
<>.
Make sure deduplication looks at the right store (necessary in test
environments).
Test this with:
and then cancel with:
sudo tc qdisc del dev eth0 root
'guix publish' without '--cache' doesn't specify a
Content-Length, so DOWNLOAD-SIZE is #f in this case.
Keep RAW open upon completion so we can later reuse
the underlying connection. Pass the download size so
NOTE: This 'progress' port of current process will be
closed here, while the child process doing the
reporting will close it upon exit.
Create a hysteresis: depending on CPU usage, favor compression
substitution can be CPU-bound when high-speed networks are used:
<-devel/2020-12/msg00177.html>.
To simulate "slow" networking or changing conditions, run:
and then cancel with:
sudo tc qdisc del dev eno1 root
Wait for the reporter to finish.
Skip a line after what 'progress-reporter/file' printed, and another
one to visually separate substitutions. When PRINT-BUILD-TRACE? is
true, leave it up to (guix status) to prettify things.
Check whether we got the data announced in NARINFO.
Tell the daemon that we're done.
The actual data has a different hash than that in NARINFO.
Entry point.
True if ACL contains just the user's public key.
should not happen when called by the daemon
Here we get something of the form "OPTION1=VALUE1\nOPTION2=VALUE2\n".
invalid option setting
client
admin
This can only happen when this script is not invoked by the
daemon.
In order to prevent using large number of discovered local substitute
servers, limit the local substitute urls list size.
If the following option is passed to the daemon, use the substitutes list
provided by "guix discover" process.
List of substitute URLs.
use the current output port instead.
Port used to reply to the daemon.
Sanity-check SUBSTITUTE-URLS so we can provide a meaningful error
message.
Attempt to install the client's locale so that messages are suitably
it 's the case by default
so don't change it.
for signature errors
Download STORE-PATH and store it as a Nar in file DESTINATION.
Specify the number of columns of the terminal so the progress
report displays nicely.
Local Variables:
eval: (put 'with-redirected-error-port 'scheme-indent-function 0)
End:
substitute.scm ends here | Copyright © 2013 , 2014 , 2015 , 2016 , 2017 , 2018 , 2019 , 2020 , 2021 < >
Copyright © 2014 < >
Copyright © 2018 < >
Copyright © 2020 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (guix scripts substitute)
#:use-module (guix ui)
#:use-module (guix scripts)
#:use-module (guix narinfo)
#:use-module (guix store)
#:use-module (guix substitutes)
#:use-module (guix utils)
#:use-module (guix combinators)
#:use-module (guix config)
#:use-module (guix records)
#:use-module (guix diagnostics)
#:use-module (guix i18n)
#:use-module ((guix serialization) #:select (restore-file dump-file))
#:autoload (guix store deduplication) (dump-file/deduplicate)
#:autoload (guix scripts discover) (read-substitute-urls)
#:use-module (gcrypt hash)
#:use-module (guix base32)
#:use-module (guix base64)
#:use-module (guix cache)
#:use-module (gcrypt pk-crypto)
#:use-module (guix pki)
#:use-module ((guix build utils) #:select (mkdir-p))
#:use-module ((guix build download)
#:select (uri-abbreviation nar-uri-abbreviation
(open-connection-for-uri
. guix:open-connection-for-uri)))
#:autoload (gnutls) (error/invalid-session error/again error/interrupted)
#:use-module (guix progress)
#:use-module ((guix build syscalls)
#:select (set-thread-name))
#:use-module (ice-9 rdelim)
#:use-module (ice-9 match)
#:use-module (ice-9 format)
#:use-module (ice-9 ftw)
#:use-module (rnrs bytevectors)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-11)
#:use-module (srfi srfi-19)
#:use-module (srfi srfi-26)
#:use-module (srfi srfi-34)
#:use-module (srfi srfi-35)
#:use-module (web uri)
#:use-module (guix http-client)
#:export (%allow-unauthenticated-substitutes?
%reply-file-descriptor
substitute-urls
guix-substitute))
(define %narinfo-expired-cache-entry-removal-delay
(* 7 24 3600))
(define (warn-about-missing-authentication)
(warning (G_ "authentication and authorization of substitutes \
disabled!~%"))
#t)
(define %allow-unauthenticated-substitutes?
(make-parameter
(and=> (getenv "GUIX_ALLOW_UNAUTHENTICATED_SUBSTITUTES")
(cut string-ci=? <> "yes"))))
(define %fetch-timeout
5)
(define %random-state
(seed->random-state (+ (ash (cdr (gettimeofday)) 32) (getpid))))
(define-syntax-rule (with-timeout duration handler body ...)
when DURATION seconds have expired , call HANDLER , and run BODY
again."
(begin
(sigaction SIGALRM
(lambda (signum)
(sigaction SIGALRM SIG_DFL)
handler))
(alarm duration)
(call-with-values
(lambda ()
(let try ()
(catch 'system-error
(lambda ()
body ...)
(lambda args
Before 39 - gfe51c7b , the SIGALRM triggers
When that happens , try again . Note : can not be
(if (= EINTR (system-error-errno args))
(begin
(usleep (random 3000000 %random-state))
(try))
(apply throw args))))))
(lambda result
(alarm 0)
(sigaction SIGALRM SIG_DFL)
(apply values result)))))
(define (at-most max-length lst)
return its MAX-LENGTH first elements and its tail."
(let loop ((len 0)
(lst lst)
(result '()))
(match lst
(()
(values (reverse result) '()))
((head . tail)
(if (>= len max-length)
(values (reverse result) lst)
(loop (+ 1 len) tail (cons head result)))))))
(define (narinfo-from-file file url)
"Attempt to read a narinfo from FILE, using URL as the cache URL. Return #f
if file doesn't exist, and the narinfo otherwise."
(catch 'system-error
(lambda ()
(call-with-input-file file
(cut read-narinfo <> url)))
(lambda args
(if (= ENOENT (system-error-errno args))
#f
(apply throw args)))))
(define (lookup-narinfo caches path authorized?)
"Return the narinfo for PATH in CACHES, or #f when no substitute for PATH
was found."
(match (lookup-narinfos/diverse
caches (list path) authorized?
#:open-connection open-connection-for-uri/cached)
((answer) answer)
(_ #f)))
(define (cached-narinfo-expiration-time file)
"Return the expiration time for FILE, which is a cached narinfo."
(catch 'system-error
(lambda ()
(call-with-input-file file
(lambda (port)
(match (read port)
(('narinfo ('version 2) ('cache-uri uri)
('date date) ('ttl ttl) ('value #f))
(+ date ttl))
(('narinfo ('version 2) ('cache-uri uri)
('date date) ('ttl ttl) ('value value))
(+ date ttl))
(x
0)))))
(lambda args
0)))
(define (narinfo-cache-directories directory)
"Return the list of narinfo cache directories (one per cache URL.)"
(map (cut string-append directory "/" <>)
(scandir %narinfo-cache-directory
(lambda (item)
(and (not (member item '("." "..")))
(file-is-directory?
(string-append %narinfo-cache-directory
"/" item)))))))
(define* (cached-narinfo-files #:optional
(directory %narinfo-cache-directory))
"Return the list of cached narinfo files under DIRECTORY."
(append-map (lambda (directory)
(map (cut string-append directory "/" <>)
(scandir directory
(lambda (file)
(= (string-length file) 32)))))
(narinfo-cache-directories directory)))
(define-syntax with-networking
(syntax-rules ()
"Catch DNS lookup errors and TLS errors and gracefully exit."
Note : no attempt is made to catch other networking errors , because DNS
lookup errors are typically the first one , and because other errors are
((_ exp ...)
backtraces . ' with - throw - handler ' works for 2.2 and 3.0 .
(with-throw-handler #t
(lambda () exp ...)
(match-lambda*
(('getaddrinfo-error error)
(leave (G_ "host name lookup error: ~a~%")
(gai-strerror error)))
(('gnutls-error error proc . rest)
(let ((error->string (module-ref (resolve-interface '(gnutls))
'error->string)))
(leave (G_ "TLS error in procedure '~a': ~a~%")
proc (error->string error))))
(args
(apply throw args)))))))
(define (show-help)
(display (G_ "Usage: guix substitute [OPTION]...
Internal tool to substitute a pre-built binary to a local build.\n"))
(display (G_ "
--query report on the availability of substitutes for the
store file names passed on the standard input"))
(display (G_ "
--substitute STORE-FILE DESTINATION
download STORE-FILE and store it as a Nar in file
DESTINATION"))
(newline)
(display (G_ "
-h, --help display this help and exit"))
(display (G_ "
-V, --version display version information and exit"))
(newline)
(show-bug-report-information))
(define %prefer-fast-decompression?
serves in particular to choose between lzip ( high compression ratio but
low decompression throughput ) and zstd ( lower compression ratio but high
#f)
(define (call-with-cpu-usage-monitoring proc)
(let ((before (times)))
(proc)
(let ((after (times)))
(if (= (tms:clock after) (tms:clock before))
0
(/ (- (tms:utime after) (tms:utime before))
(- (tms:clock after) (tms:clock before))
1.)))))
(define-syntax-rule (with-cpu-usage-monitoring exp ...)
"Evaluate EXP... Return its CPU usage as a fraction between 0 and 1."
(call-with-cpu-usage-monitoring (lambda () exp ...)))
(define (display-narinfo-data port narinfo)
"Write to PORT the contents of NARINFO in the format expected by the
daemon."
(format port "~a\n~a\n~a\n"
(narinfo-path narinfo)
(or (and=> (narinfo-deriver narinfo)
(cute string-append (%store-prefix) "/" <>))
"")
(length (narinfo-references narinfo)))
(for-each (cute format port "~a/~a~%" (%store-prefix) <>)
(narinfo-references narinfo))
(let-values (((uri compression file-size)
(narinfo-best-uri narinfo
#:fast-decompression?
%prefer-fast-decompression?)))
(format port "~a\n~a\n"
(or file-size 0)
(or (narinfo-size narinfo) 0))))
(define* (process-query port command
#:key cache-urls acl)
"Reply on PORT to COMMAND, a query as written by the daemon to this process's
standard input. Use ACL as the access-control list against which to check
authorized substitutes."
(define valid?
(if (%allow-unauthenticated-substitutes?)
(begin
(warn-about-missing-authentication)
(const #t))
(lambda (obj)
(valid-narinfo? obj acl))))
(define* (make-progress-reporter total #:key url)
(define done 0)
(define (report-progress)
(force-output (current-error-port))
(format (current-error-port)
(G_ "updating substitutes from '~a'... ~5,1f%")
url (* 100. (/ done total)))
(set! done (+ 1 done)))
(progress-reporter
(start report-progress)
(report report-progress)
(stop (lambda ()
(newline (current-error-port))))))
(match (string-tokenize command)
(("have" paths ..1)
(let ((substitutable (lookup-narinfos/diverse
cache-urls paths valid?
#:open-connection open-connection-for-uri/cached
#:make-progress-reporter make-progress-reporter)))
(for-each (lambda (narinfo)
(format port "~a~%" (narinfo-path narinfo)))
substitutable)
(newline port)))
(("info" paths ..1)
(let ((substitutable (lookup-narinfos/diverse
cache-urls paths valid?
#:open-connection open-connection-for-uri/cached
#:make-progress-reporter make-progress-reporter)))
(for-each (cut display-narinfo-data port <>) substitutable)
(newline port)))
(wtf
(error "unknown `--query' command" wtf))))
(define %max-cached-connections
16)
(define open-connection-for-uri/cached
(let ((cache '()))
(lambda* (uri #:key fresh? (timeout %fetch-timeout) verify-certificate?)
"Return a connection for URI, possibly reusing a cached connection.
When FRESH? is true, delete any cached connections for URI and open a new one.
Return #f if URI's scheme is 'file' or #f.
When true, TIMEOUT is the maximum number of milliseconds to wait for
connection establishment. When VERIFY-CERTIFICATE? is true, verify HTTPS
server certificates."
(define host (uri-host uri))
(define scheme (uri-scheme uri))
(define key (list host scheme (uri-port uri)))
(and (not (memq scheme '(file #f)))
(match (assoc-ref cache key)
(#f
Open a new connection to URI and evict old entries from
(let-values (((socket)
(guix:open-connection-for-uri
uri
#:verify-certificate? verify-certificate?
#:timeout timeout))
((new-cache evicted)
(at-most (- %max-cached-connections 1) cache)))
(for-each (match-lambda
((_ . port)
(false-if-exception (close-port port))))
evicted)
(set! cache (alist-cons key socket new-cache))
socket))
(socket
(if (or fresh? (port-closed? socket))
(begin
(false-if-exception (close-port socket))
(set! cache (alist-delete key cache))
(open-connection-for-uri/cached uri #:timeout timeout
#:verify-certificate?
verify-certificate?))
(begin
(drain-input socket)
socket))))))))
(define (call-with-cached-connection uri proc)
(let ((port (open-connection-for-uri/cached uri
#:verify-certificate? #f)))
(catch #t
(lambda ()
(proc port))
(lambda (key . args)
request , or a ERROR / INVALID - SESSION from GnuTLS .
(if (or (and (eq? key 'system-error)
(= EPIPE (system-error-errno `(,key ,@args))))
(and (eq? key 'gnutls-error)
(memq (first args)
(list error/invalid-session
XXX : These two are not properly handled in
GnuTLS < 3.7.3 , in
error/again error/interrupted)))
(memq key '(bad-response bad-header bad-header-component)))
(proc (open-connection-for-uri/cached uri
#:verify-certificate? #f
#:fresh? #t))
(apply throw key args))))))
(define-syntax-rule (with-cached-connection uri port exp ...)
"Bind PORT with EXP... to a socket connected to URI."
(call-with-cached-connection uri (lambda (port) exp ...)))
(define* (process-substitution port store-item destination
#:key cache-urls acl
deduplicate? print-build-trace?)
"Substitute STORE-ITEM (a store file name) from CACHE-URLS, and write it to
DESTINATION as a nar file. Verify the substitute against ACL, and verify its
hash against what appears in the narinfo. When DEDUPLICATE? is true, and if
DESTINATION is in the store, deduplicate its files. Print a status line to
PORT."
(define narinfo
(lookup-narinfo cache-urls store-item
(if (%allow-unauthenticated-substitutes?)
(const #t)
(cut valid-narinfo? <> acl))))
(define destination-in-store?
(string-prefix? (string-append (%store-prefix) "/")
destination))
(define (dump-file/deduplicate* . args)
(apply dump-file/deduplicate
(append args (list #:store (%store-prefix)))))
(define (fetch uri)
(case (uri-scheme uri)
((file)
(let ((port (open-file (uri-path uri) "r0b")))
(values port (stat:size (stat port)))))
((http https)
(guard (c ((http-get-error? c)
(leave (G_ "download from '~a' failed: ~a, ~s~%")
(uri->string (http-get-error-uri c))
(http-get-error-code c)
(http-get-error-reason c))))
sudo tc qdisc add dev eth0 root netem delay
(with-timeout %fetch-timeout
(begin
(warning (G_ "while fetching ~a: server is somewhat slow~%")
(uri->string uri))
(warning (G_ "try `--no-substitutes' if the problem persists~%")))
(with-cached-connection uri port
(http-fetch uri #:text? #f
#:port port
#:keep-alive? #t
#:buffered? #f)))))
(else
(leave (G_ "unsupported substitute URI scheme: ~a~%")
(uri->string uri)))))
(unless narinfo
(leave (G_ "no valid substitute for '~a'~%")
store-item))
(let-values (((uri compression file-size)
(narinfo-best-uri narinfo
#:fast-decompression?
%prefer-fast-decompression?)))
(unless print-build-trace?
(format (current-error-port)
(G_ "Downloading ~a...~%") (uri->string uri)))
(let*-values (((raw download-size)
(fetch uri))
((progress)
(let* ((dl-size (or download-size
(and (equal? compression "none")
(narinfo-size narinfo))))
(reporter (if print-build-trace?
(progress-reporter/trace
destination
(uri->string uri) dl-size
(current-error-port))
(progress-reporter/file
(uri->string uri) dl-size
(current-error-port)
#:abbreviation nar-uri-abbreviation))))
that this procedure wo n't block reading from RAW .
(progress-report-port reporter raw
#:close? #f
#:download-size dl-size)))
((input pids)
(decompressed-port (string->symbol compression)
progress))
Compute the actual nar hash as we read it .
((algorithm expected)
(narinfo-hash-algorithm+value narinfo))
((hashed get-hash)
(open-hash-input-port algorithm input)))
Unpack the Nar at INPUT into DESTINATION .
(define cpu-usage
(with-cpu-usage-monitoring
(restore-file hashed destination
#:dump-file (if (and destination-in-store?
deduplicate?)
dump-file/deduplicate*
dump-file))))
methods with faster decompression ( like ) or methods with better
compression ratios ( like lzip ) . This stems from the observation that
sudo tc qdisc add dev eno1 root tbf rate 512kbit latency 50ms burst 1540
(when (> cpu-usage .8)
(set! %prefer-fast-decompression? #t))
(when (< cpu-usage .2)
(set! %prefer-fast-decompression? #f))
(close-port hashed)
(close-port input)
(every (compose zero? cdr waitpid) pids)
(newline (current-error-port))
(unless print-build-trace?
(newline (current-error-port)))
(let ((actual (get-hash)))
(if (bytevector=? actual expected)
(format port "success ~a ~a~%"
(narinfo-hash narinfo) (narinfo-size narinfo))
(format port "hash-mismatch ~a ~a ~a~%"
(hash-algorithm-name algorithm)
(bytevector->nix-base32-string expected)
(bytevector->nix-base32-string actual)))))))
(define (check-acl-initialized)
"Warn if the ACL is uninitialized."
(define (singleton? acl)
(and (file-exists? %public-key-file)
(let ((key (call-with-input-file %public-key-file
(compose string->canonical-sexp
read-string))))
(match acl
((thing)
(equal? (canonical-sexp->string thing)
(canonical-sexp->string key)))
(_
#f)))))
(let ((acl (acl->public-keys (current-acl))))
(when (or (null? acl) (singleton? acl))
(warning (G_ "ACL for archive imports seems to be uninitialized, \
substitutes may be unavailable\n")))))
(define (daemon-options)
"Return a list of name/value pairs denoting build daemon options."
(define %not-newline
(char-set-complement (char-set #\newline)))
(match (getenv "_NIX_OPTIONS")
'())
(newline-separated
(filter-map (lambda (option=value)
(match (string-index option=value #\=)
#f)
(equal-sign
(cons (string-take option=value equal-sign)
(string-drop option=value (+ 1 equal-sign))))))
(string-tokenize newline-separated %not-newline)))))
(define (find-daemon-option option)
"Return the value of build daemon option OPTION, or #f if it could not be
found."
(assoc-ref (daemon-options) option))
(define %default-substitute-urls
string-tokenize)
((urls ...)
urls)
(#f
'(""
""))))
(define %max-substitute-urls 50)
(define* (randomize-substitute-urls urls
#:key
(max %max-substitute-urls))
"Return a list containing MAX urls from URLS, picked randomly. If URLS list
is shorter than MAX elements, then it is directly returned."
(define (random-item list)
(list-ref list (random (length list))))
(if (<= (length urls) max)
urls
(let loop ((res '())
(urls urls))
(if (eq? (length res) max)
res
(let ((url (random-item urls)))
(loop (cons url res) (delete url urls)))))))
(define %local-substitute-urls
(let* ((option (find-daemon-option "discover"))
(discover? (and option (string=? option "true"))))
(if discover?
(randomize-substitute-urls (read-substitute-urls))
'())))
(define substitute-urls
(make-parameter (append %local-substitute-urls
%default-substitute-urls)))
(define (client-terminal-columns)
"Return the number of columns in the client's terminal, if it is known, or a
default value."
(or (and=> (or (find-daemon-option "untrusted-terminal-columns")
(find-daemon-option "terminal-columns"))
(lambda (str)
(let ((number (string->number str)))
(and number (max 20 (- number 1))))))
80))
(define (validate-uri uri)
(unless (string->uri uri)
(leave (G_ "~a: invalid URI~%") uri)))
(define %reply-file-descriptor
The file descriptor where replies to the daemon must be sent , or # f to
(make-parameter 4))
(define-command (guix-substitute . args)
(category internal)
(synopsis "implement the build daemon's substituter protocol")
(define print-build-trace?
(match (or (find-daemon-option "untrusted-print-extended-build-trace")
(find-daemon-option "print-extended-build-trace"))
(#f #f)
((= string->number number) (> number 0))
(_ #f)))
(define deduplicate?
(find-daemon-option "deduplicate"))
(define reply-port
(if (%reply-file-descriptor)
(fdopen (%reply-file-descriptor) "wl")
(current-output-port)))
(mkdir-p %narinfo-cache-directory)
(maybe-remove-expired-cache-entries %narinfo-cache-directory
cached-narinfo-files
#:entry-expiration
cached-narinfo-expiration-time
#:cleanup-period
%narinfo-expired-cache-entry-removal-delay)
(check-acl-initialized)
(for-each validate-uri (substitute-urls))
(match (or (find-daemon-option "untrusted-locale")
(find-daemon-option "locale"))
(#f #f)
(locale (false-if-exception (setlocale LC_MESSAGES locale))))
(catch 'system-error
(lambda ()
(set-thread-name "guix substitute"))
GNU / lacks ' prctl '
(with-networking
(match args
(("--query")
(let ((acl (current-acl)))
(let loop ((command (read-line)))
(or (eof-object? command)
(begin
(process-query reply-port command
#:cache-urls (substitute-urls)
#:acl acl)
(loop (read-line)))))))
(("--substitute")
(parameterize ((current-terminal-columns (client-terminal-columns)))
(let loop ()
(match (read-line)
((? eof-object?)
#t)
((= string-tokenize ("substitute" store-path destination))
(process-substitution reply-port store-path destination
#:cache-urls (substitute-urls)
#:acl (current-acl)
#:deduplicate? deduplicate?
#:print-build-trace?
print-build-trace?)
(loop))))))
((or ("-V") ("--version"))
(show-version-and-exit "guix substitute"))
(("--help")
(show-help))
(opts
(leave (G_ "~a: unrecognized options~%") opts))))))
eval : ( put ' with - timeout ' scheme - indent - function 1 )
eval : ( put ' with - cached - connection ' scheme - indent - function 2 )
eval : ( put ' call - with - cached - connection ' scheme - indent - function 1 )
|
92803b68120952072fb2aa125cbdc7fa138ffc933ba73f5b3a8e560a5faf119d | ocaml-multicore/tezos | script_typed_ir.ml | (*****************************************************************************)
(* *)
(* Open Source License *)
Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
Copyright ( c ) 2021 - 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 Alpha_context
open Script_int
The step function of the interpreter is parametrized by a bunch of values called the step constants .
These values are indeed constants during the call of a smart contract with the notable exception of
the IView instruction which modifies ` source ` , ` self ` , and ` amount ` and the KView_exit continuation
which restores them .
= = = = = = = = = = = = = = = = = = = = = =
The step function of the interpreter is parametrized by a bunch of values called the step constants.
These values are indeed constants during the call of a smart contract with the notable exception of
the IView instruction which modifies `source`, `self`, and `amount` and the KView_exit continuation
which restores them.
======================
*)
type step_constants = {
source : Contract.t;
(** The address calling this contract, as returned by SENDER. *)
payer : Contract.t;
(** The address of the implicit account that initiated the chain of contract calls, as returned by SOURCE. *)
self : Contract.t;
* The address of the contract being executed , as returned by SELF and SELF_ADDRESS .
Also used :
- as ticketer in TICKET
- as caller in VIEW , TRANSFER_TOKENS , and CREATE_CONTRACT
Also used:
- as ticketer in TICKET
- as caller in VIEW, TRANSFER_TOKENS, and CREATE_CONTRACT *)
amount : Tez.t;
(** The amount of the current transaction, as returned by AMOUNT. *)
balance : Tez.t; (** The balance of the contract as returned by BALANCE. *)
chain_id : Chain_id.t;
* The chain i d of the chain , as returned by CHAIN_ID .
now : Script_timestamp.t;
(** The earliest time at which the current block could have been timestamped, as returned by NOW. *)
level : Script_int.n Script_int.num;
(** The level of the current block, as returned by LEVEL. *)
}
(* Preliminary definitions. *)
type never = |
type address = {destination : Destination.t; entrypoint : Entrypoint.t}
module Script_signature = struct
type t = Signature_tag of signature [@@ocaml.unboxed]
let make s = Signature_tag s
let get (Signature_tag s) = s
let encoding =
Data_encoding.conv
(fun (Signature_tag x) -> x)
(fun x -> Signature_tag x)
Signature.encoding
let of_b58check_opt x = Option.map make (Signature.of_b58check_opt x)
let check ?watermark pub_key (Signature_tag s) bytes =
Signature.check ?watermark pub_key s bytes
let compare (Signature_tag x) (Signature_tag y) = Signature.compare x y
let size = Signature.size
end
type signature = Script_signature.t
type ('a, 'b) pair = 'a * 'b
type ('a, 'b) union = L of 'a | R of 'b
type operation = {
piop : packed_internal_operation;
lazy_storage_diff : Lazy_storage.diffs option;
}
module Script_chain_id = struct
type t = Chain_id_tag of Chain_id.t [@@ocaml.unboxed]
let make x = Chain_id_tag x
let compare (Chain_id_tag x) (Chain_id_tag y) = Chain_id.compare x y
let size = Chain_id.size
let encoding =
Data_encoding.conv (fun (Chain_id_tag x) -> x) make Chain_id.encoding
let to_b58check (Chain_id_tag x) = Chain_id.to_b58check x
let of_b58check_opt x = Option.map make (Chain_id.of_b58check_opt x)
end
module Script_bls = struct
module type S = sig
type t
type fr
val add : t -> t -> t
val mul : t -> fr -> t
val negate : t -> t
val of_bytes_opt : Bytes.t -> t option
val to_bytes : t -> Bytes.t
end
module Fr = struct
type t = Fr_tag of Bls12_381.Fr.t [@@ocaml.unboxed]
open Bls12_381.Fr
let add (Fr_tag x) (Fr_tag y) = Fr_tag (add x y)
let mul (Fr_tag x) (Fr_tag y) = Fr_tag (mul x y)
let negate (Fr_tag x) = Fr_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> Fr_tag x) (of_bytes_opt bytes)
let to_bytes (Fr_tag x) = to_bytes x
let of_z z = Fr_tag (of_z z)
let to_z (Fr_tag x) = to_z x
end
module G1 = struct
type t = G1_tag of Bls12_381.G1.t [@@ocaml.unboxed]
open Bls12_381.G1
let add (G1_tag x) (G1_tag y) = G1_tag (add x y)
let mul (G1_tag x) (Fr.Fr_tag y) = G1_tag (mul x y)
let negate (G1_tag x) = G1_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> G1_tag x) (of_bytes_opt bytes)
let to_bytes (G1_tag x) = to_bytes x
end
module G2 = struct
type t = G2_tag of Bls12_381.G2.t [@@ocaml.unboxed]
open Bls12_381.G2
let add (G2_tag x) (G2_tag y) = G2_tag (add x y)
let mul (G2_tag x) (Fr.Fr_tag y) = G2_tag (mul x y)
let negate (G2_tag x) = G2_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> G2_tag x) (of_bytes_opt bytes)
let to_bytes (G2_tag x) = to_bytes x
end
let pairing_check l =
let l = List.map (fun (G1.G1_tag x, G2.G2_tag y) -> (x, y)) l in
Bls12_381.pairing_check l
end
module Script_timelock = struct
type chest_key = Chest_key_tag of Timelock.chest_key [@@ocaml.unboxed]
let make_chest_key chest_key = Chest_key_tag chest_key
let chest_key_encoding =
Data_encoding.conv
(fun (Chest_key_tag x) -> x)
(fun x -> Chest_key_tag x)
Timelock.chest_key_encoding
type chest = Chest_tag of Timelock.chest [@@ocaml.unboxed]
let make_chest chest = Chest_tag chest
let chest_encoding =
Data_encoding.conv
(fun (Chest_tag x) -> x)
(fun x -> Chest_tag x)
Timelock.chest_encoding
let open_chest (Chest_tag chest) (Chest_key_tag chest_key) ~time =
Timelock.open_chest chest chest_key ~time
let get_plaintext_size (Chest_tag x) = Timelock.get_plaintext_size x
end
type 'a ticket = {ticketer : Contract.t; contents : 'a; amount : n num}
module type TYPE_SIZE = sig
A type size represents the size of its type parameter .
This constraint is enforced inside this module ( Script_type_ir ) , hence there
should be no way to construct a type size outside of it .
It allows keeping type metadata and types non - private .
This module is here because we want three levels of visibility over this
code :
- inside this submodule , we have [ type ' a t = int ]
- outside of [ Script_typed_ir ] , the [ ' a t ] type is abstract and we have
the invariant that whenever [ x : ' a t ] we have that [ x ] is exactly
the size of [ ' a ] .
- in - between ( inside [ Script_typed_ir ] but outside the [ Type_size ]
submodule ) , the type is abstract but we have access to unsafe
constructors that can break the invariant .
This constraint is enforced inside this module (Script_type_ir), hence there
should be no way to construct a type size outside of it.
It allows keeping type metadata and types non-private.
This module is here because we want three levels of visibility over this
code:
- inside this submodule, we have [type 'a t = int]
- outside of [Script_typed_ir], the ['a t] type is abstract and we have
the invariant that whenever [x : 'a t] we have that [x] is exactly
the size of ['a].
- in-between (inside [Script_typed_ir] but outside the [Type_size]
submodule), the type is abstract but we have access to unsafe
constructors that can break the invariant.
*)
type 'a t
val merge :
error_details:'error_trace Script_tc_errors.error_details ->
'a t ->
'b t ->
('a t, 'error_trace) result
val to_int : 'a t -> Saturation_repr.mul_safe Saturation_repr.t
(* Unsafe constructors, to be used only safely and inside this module *)
val one : _ t
val two : _ t
val three : _ t
val four : (_, _) pair option t
val compound1 : Script.location -> _ t -> _ t tzresult
val compound2 : Script.location -> _ t -> _ t -> _ t tzresult
end
module Type_size : TYPE_SIZE = struct
type 'a t = int
let () =
(* static-like check that all [t] values fit in a [mul_safe] *)
let (_ : Saturation_repr.mul_safe Saturation_repr.t) =
Saturation_repr.mul_safe_of_int_exn Constants.michelson_maximum_type_size
in
()
let to_int = Saturation_repr.mul_safe_of_int_exn
let one = 1
let two = 2
let three = 3
let four = 4
let merge :
type a b error_trace.
error_details:error_trace Script_tc_errors.error_details ->
a t ->
b t ->
(a t, error_trace) result =
fun ~error_details x y ->
if Compare.Int.(x = y) then ok x
else
Error
(match error_details with
| Fast -> Inconsistent_types_fast
| Informative ->
trace_of_error @@ Script_tc_errors.Inconsistent_type_sizes (x, y))
let of_int loc size =
let max_size = Constants.michelson_maximum_type_size in
if Compare.Int.(size <= max_size) then ok size
else error (Script_tc_errors.Type_too_large (loc, max_size))
let compound1 loc size = of_int loc (1 + size)
let compound2 loc size1 size2 = of_int loc (1 + size1 + size2)
end
type empty_cell = EmptyCell
type end_of_stack = empty_cell * empty_cell
type 'a ty_metadata = {size : 'a Type_size.t} [@@unboxed]
type _ comparable_ty =
| Unit_key : unit comparable_ty
| Never_key : never comparable_ty
| Int_key : z num comparable_ty
| Nat_key : n num comparable_ty
| Signature_key : signature comparable_ty
| String_key : Script_string.t comparable_ty
| Bytes_key : Bytes.t comparable_ty
| Mutez_key : Tez.t comparable_ty
| Bool_key : bool comparable_ty
| Key_hash_key : public_key_hash comparable_ty
| Key_key : public_key comparable_ty
| Timestamp_key : Script_timestamp.t comparable_ty
| Chain_id_key : Script_chain_id.t comparable_ty
| Address_key : address comparable_ty
| Pair_key :
'a comparable_ty * 'b comparable_ty * ('a, 'b) pair ty_metadata
-> ('a, 'b) pair comparable_ty
| Union_key :
'a comparable_ty * 'b comparable_ty * ('a, 'b) union ty_metadata
-> ('a, 'b) union comparable_ty
| Option_key :
'v comparable_ty * 'v option ty_metadata
-> 'v option comparable_ty
let meta_basic = {size = Type_size.one}
let comparable_ty_metadata : type a. a comparable_ty -> a ty_metadata = function
| Unit_key | Never_key | Int_key | Nat_key | Signature_key | String_key
| Bytes_key | Mutez_key | Bool_key | Key_hash_key | Key_key | Timestamp_key
| Chain_id_key | Address_key ->
meta_basic
| Pair_key (_, _, meta) -> meta
| Union_key (_, _, meta) -> meta
| Option_key (_, meta) -> meta
let comparable_ty_size t = (comparable_ty_metadata t).size
let unit_key = Unit_key
let never_key = Never_key
let int_key = Int_key
let nat_key = Nat_key
let signature_key = Signature_key
let string_key = String_key
let bytes_key = Bytes_key
let mutez_key = Mutez_key
let bool_key = Bool_key
let key_hash_key = Key_hash_key
let key_key = Key_key
let timestamp_key = Timestamp_key
let chain_id_key = Chain_id_key
let address_key = Address_key
let pair_key loc l r =
Type_size.compound2 loc (comparable_ty_size l) (comparable_ty_size r)
>|? fun size -> Pair_key (l, r, {size})
let pair_3_key loc l m r = pair_key loc m r >>? fun r -> pair_key loc l r
let union_key loc l r =
Type_size.compound2 loc (comparable_ty_size l) (comparable_ty_size r)
>|? fun size -> Union_key (l, r, {size})
let option_key loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Option_key (t, {size})
This signature contains the exact set of functions used in the
protocol . We do not include all [ Set . S ] because this would
increase the size of the first class modules used to represent
[ boxed_set ] .
Warning : for any change in this signature , there must be a
change in [ Script_typed_ir_size.value_size ] which updates
[ boxing_space ] in the case for sets .
This signature contains the exact set of functions used in the
protocol. We do not include all [Set.S] because this would
increase the size of the first class modules used to represent
[boxed_set].
Warning: for any change in this signature, there must be a
change in [Script_typed_ir_size.value_size] which updates
[boxing_space] in the case for sets.
*)
module type Boxed_set_OPS = sig
type t
type elt
val empty : t
val add : elt -> t -> t
val mem : elt -> t -> bool
val remove : elt -> t -> t
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
end
module type Boxed_set = sig
type elt
val elt_ty : elt comparable_ty
module OPS : Boxed_set_OPS with type elt = elt
val boxed : OPS.t
val size : int
end
type 'elt set = Set_tag of (module Boxed_set with type elt = 'elt)
[@@ocaml.unboxed]
(*
Same remark as for [Boxed_set_OPS]. (See below.)
*)
module type Boxed_map_OPS = sig
type t
type key
type value
val empty : t
val add : key -> value -> t -> t
val remove : key -> t -> t
val find : key -> t -> value option
val fold : (key -> value -> 'a -> 'a) -> t -> 'a -> 'a
end
module type Boxed_map = sig
type key
type value
val key_ty : key comparable_ty
module OPS : Boxed_map_OPS with type key = key and type value = value
val boxed : OPS.t
val size : int
end
type ('key, 'value) map =
| Map_tag of (module Boxed_map with type key = 'key and type value = 'value)
[@@ocaml.unboxed]
module Big_map_overlay = Map.Make (struct
type t = Script_expr_hash.t
let compare = Script_expr_hash.compare
end)
type ('key, 'value) big_map_overlay = {
map : ('key * 'value option) Big_map_overlay.t;
size : int;
}
type 'elt boxed_list = {elements : 'elt list; length : int}
module SMap = Map.Make (Script_string)
type view = {
input_ty : Script.node;
output_ty : Script.node;
view_code : Script.node;
}
type 'arg entrypoints = {
name : Entrypoint.t option;
nested : 'arg nested_entrypoints;
}
and 'arg nested_entrypoints =
| Entrypoints_Union : {
left : 'l entrypoints;
right : 'r entrypoints;
}
-> ('l, 'r) union nested_entrypoints
| Entrypoints_None : _ nested_entrypoints
let no_entrypoints = {name = None; nested = Entrypoints_None}
type ('arg, 'storage) script = {
code : (('arg, 'storage) pair, (operation boxed_list, 'storage) pair) lambda;
arg_type : 'arg ty;
storage : 'storage;
storage_type : 'storage ty;
views : view SMap.t;
entrypoints : 'arg entrypoints;
code_size : Cache_memory_helpers.sint;
(* This is an over-approximation of the value size in memory, in
bytes, of the contract's static part, that is its source
code. This includes the code of the contract as well as the code
of the views. The storage size is not taken into account by this
field as it has a dynamic size. *)
}
(* ---- Instructions --------------------------------------------------------*)
and ('before_top, 'before, 'result_top, 'result) kinstr =
(*
Stack
-----
*)
| IDrop :
('a, 'b * 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDup :
('a, 's) kinfo * ('a, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISwap :
('a, 'b * 's) kinfo * ('b, 'a * 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IConst :
('a, 's) kinfo * 'ty * ('ty, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
(*
Pairs
-----
*)
| ICons_pair :
('a, 'b * 's) kinfo * ('a * 'b, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| ICar :
('a * 'b, 's) kinfo * ('a, 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
| ICdr :
('a * 'b, 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
| IUnpair :
('a * 'b, 's) kinfo * ('a, 'b * 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
(*
Options
-------
*)
| ICons_some :
('v, 's) kinfo * ('v option, 's, 'r, 'f) kinstr
-> ('v, 's, 'r, 'f) kinstr
| ICons_none :
('a, 's) kinfo * ('b option, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IIf_none : {
kinfo : ('a option, 'b * 's) kinfo;
branch_if_none : ('b, 's, 'c, 't) kinstr;
branch_if_some : ('a, 'b * 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> ('a option, 'b * 's, 'r, 'f) kinstr
| IOpt_map : {
kinfo : ('a option, 's) kinfo;
body : ('a, 's, 'b, 's) kinstr;
k : ('b option, 's, 'c, 't) kinstr;
}
-> ('a option, 's, 'c, 't) kinstr
(*
Unions
------
*)
| ICons_left :
('a, 's) kinfo * (('a, 'b) union, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ICons_right :
('b, 's) kinfo * (('a, 'b) union, 's, 'r, 'f) kinstr
-> ('b, 's, 'r, 'f) kinstr
| IIf_left : {
kinfo : (('a, 'b) union, 's) kinfo;
branch_if_left : ('a, 's, 'c, 't) kinstr;
branch_if_right : ('b, 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> (('a, 'b) union, 's, 'r, 'f) kinstr
(*
Lists
-----
*)
| ICons_list :
('a, 'a boxed_list * 's) kinfo * ('a boxed_list, 's, 'r, 'f) kinstr
-> ('a, 'a boxed_list * 's, 'r, 'f) kinstr
| INil :
('a, 's) kinfo * ('b boxed_list, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IIf_cons : {
kinfo : ('a boxed_list, 'b * 's) kinfo;
branch_if_cons : ('a, 'a boxed_list * ('b * 's), 'c, 't) kinstr;
branch_if_nil : ('b, 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> ('a boxed_list, 'b * 's, 'r, 'f) kinstr
| IList_map :
('a boxed_list, 'c * 's) kinfo
* ('a, 'c * 's, 'b, 'c * 's) kinstr
* ('b boxed_list, 'c * 's, 'r, 'f) kinstr
-> ('a boxed_list, 'c * 's, 'r, 'f) kinstr
| IList_iter :
('a boxed_list, 'b * 's) kinfo
* ('a, 'b * 's, 'b, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> ('a boxed_list, 'b * 's, 'r, 'f) kinstr
| IList_size :
('a boxed_list, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> ('a boxed_list, 's, 'r, 'f) kinstr
(*
Sets
----
*)
| IEmpty_set :
('a, 's) kinfo * 'b comparable_ty * ('b set, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISet_iter :
('a set, 'b * 's) kinfo
* ('a, 'b * 's, 'b, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> ('a set, 'b * 's, 'r, 'f) kinstr
| ISet_mem :
('a, 'a set * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, 'a set * 's, 'r, 'f) kinstr
| ISet_update :
('a, bool * ('a set * 's)) kinfo * ('a set, 's, 'r, 'f) kinstr
-> ('a, bool * ('a set * 's), 'r, 'f) kinstr
| ISet_size :
('a set, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> ('a set, 's, 'r, 'f) kinstr
(*
Maps
----
*)
| IEmpty_map :
('a, 's) kinfo * 'b comparable_ty * (('b, 'c) map, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IMap_map :
(('a, 'b) map, 'd * 's) kinfo
* ('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* (('a, 'c) map, 'd * 's, 'r, 'f) kinstr
-> (('a, 'b) map, 'd * 's, 'r, 'f) kinstr
| IMap_iter :
(('a, 'b) map, 'c * 's) kinfo
* ('a * 'b, 'c * 's, 'c, 's) kinstr
* ('c, 's, 'r, 'f) kinstr
-> (('a, 'b) map, 'c * 's, 'r, 'f) kinstr
| IMap_mem :
('a, ('a, 'b) map * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) map * 's, 'r, 'f) kinstr
| IMap_get :
('a, ('a, 'b) map * 's) kinfo * ('b option, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) map * 's, 'r, 'f) kinstr
| IMap_update :
('a, 'b option * (('a, 'b) map * 's)) kinfo
* (('a, 'b) map, 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) map * 's), 'r, 'f) kinstr
| IMap_get_and_update :
('a, 'b option * (('a, 'b) map * 's)) kinfo
* ('b option, ('a, 'b) map * 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) map * 's), 'r, 'f) kinstr
| IMap_size :
(('a, 'b) map, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (('a, 'b) map, 's, 'r, 'f) kinstr
(*
Big maps
--------
*)
| IEmpty_big_map :
('a, 's) kinfo
* 'b comparable_ty
* 'c ty
* (('b, 'c) big_map, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IBig_map_mem :
('a, ('a, 'b) big_map * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) big_map * 's, 'r, 'f) kinstr
| IBig_map_get :
('a, ('a, 'b) big_map * 's) kinfo * ('b option, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) big_map * 's, 'r, 'f) kinstr
| IBig_map_update :
('a, 'b option * (('a, 'b) big_map * 's)) kinfo
* (('a, 'b) big_map, 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) big_map * 's), 'r, 'f) kinstr
| IBig_map_get_and_update :
('a, 'b option * (('a, 'b) big_map * 's)) kinfo
* ('b option, ('a, 'b) big_map * 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) big_map * 's), 'r, 'f) kinstr
(*
Strings
-------
*)
| IConcat_string :
(Script_string.t boxed_list, 's) kinfo
* (Script_string.t, 's, 'r, 'f) kinstr
-> (Script_string.t boxed_list, 's, 'r, 'f) kinstr
| IConcat_string_pair :
(Script_string.t, Script_string.t * 's) kinfo
* (Script_string.t, 's, 'r, 'f) kinstr
-> (Script_string.t, Script_string.t * 's, 'r, 'f) kinstr
| ISlice_string :
(n num, n num * (Script_string.t * 's)) kinfo
* (Script_string.t option, 's, 'r, 'f) kinstr
-> (n num, n num * (Script_string.t * 's), 'r, 'f) kinstr
| IString_size :
(Script_string.t, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (Script_string.t, 's, 'r, 'f) kinstr
(*
Bytes
-----
*)
| IConcat_bytes :
(bytes boxed_list, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes boxed_list, 's, 'r, 'f) kinstr
| IConcat_bytes_pair :
(bytes, bytes * 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, bytes * 's, 'r, 'f) kinstr
| ISlice_bytes :
(n num, n num * (bytes * 's)) kinfo * (bytes option, 's, 'r, 'f) kinstr
-> (n num, n num * (bytes * 's), 'r, 'f) kinstr
| IBytes_size :
(bytes, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
(*
Timestamps
----------
*)
| IAdd_seconds_to_timestamp :
(z num, Script_timestamp.t * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (z num, Script_timestamp.t * 's, 'r, 'f) kinstr
| IAdd_timestamp_to_seconds :
(Script_timestamp.t, z num * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, z num * 's, 'r, 'f) kinstr
| ISub_timestamp_seconds :
(Script_timestamp.t, z num * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, z num * 's, 'r, 'f) kinstr
| IDiff_timestamps :
(Script_timestamp.t, Script_timestamp.t * 's) kinfo
* (z num, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, Script_timestamp.t * 's, 'r, 'f) kinstr
Tez
---
Tez
---
*)
| IAdd_tez :
(Tez.t, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| ISub_tez :
(Tez.t, Tez.t * 's) kinfo * (Tez.t option, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| ISub_tez_legacy :
(Tez.t, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| IMul_teznat :
(Tez.t, n num * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, n num * 's, 'r, 'f) kinstr
| IMul_nattez :
(n num, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (n num, Tez.t * 's, 'r, 'f) kinstr
| IEdiv_teznat :
(Tez.t, n num * 's) kinfo
* ((Tez.t, Tez.t) pair option, 's, 'r, 'f) kinstr
-> (Tez.t, n num * 's, 'r, 'f) kinstr
| IEdiv_tez :
(Tez.t, Tez.t * 's) kinfo
* ((n num, Tez.t) pair option, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
Booleans
--------
Booleans
--------
*)
| IOr :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| IAnd :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| IXor :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| INot :
(bool, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, 's, 'r, 'f) kinstr
(*
Integers
--------
*)
| IIs_nat :
(z num, 's) kinfo * (n num option, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| INeg :
('a num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 's, 'r, 'f) kinstr
| IAbs_int :
(z num, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IInt_nat :
(n num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> (n num, 's, 'r, 'f) kinstr
| IAdd_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IAdd_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| ISub_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IMul_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IMul_nat :
(n num, 'a num * 's) kinfo * ('a num, 's, 'r, 'f) kinstr
-> (n num, 'a num * 's, 'r, 'f) kinstr
| IEdiv_int :
('a num, 'b num * 's) kinfo
* ((z num, n num) pair option, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IEdiv_nat :
(n num, 'a num * 's) kinfo
* (('a num, n num) pair option, 's, 'r, 'f) kinstr
-> (n num, 'a num * 's, 'r, 'f) kinstr
| ILsl_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| ILsr_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| IOr_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
(* Even though `IAnd_nat` and `IAnd_int_nat` could be merged into a single
instruction from both the type and behavior point of views, their gas costs
differ too much (see `cost_N_IAnd_nat` and `cost_N_IAnd_int_nat` in
`Michelson_v1_gas.Cost_of.Generated_costs`), so we keep them separated. *)
| IAnd_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| IAnd_int_nat :
(z num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (z num, n num * 's, 'r, 'f) kinstr
| IXor_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| INot_int :
('a num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 's, 'r, 'f) kinstr
(*
Control
-------
*)
| IIf : {
kinfo : (bool, 'a * 's) kinfo;
branch_if_true : ('a, 's, 'b, 'u) kinstr;
branch_if_false : ('a, 's, 'b, 'u) kinstr;
k : ('b, 'u, 'r, 'f) kinstr;
}
-> (bool, 'a * 's, 'r, 'f) kinstr
| ILoop :
(bool, 'a * 's) kinfo
* ('a, 's, bool, 'a * 's) kinstr
* ('a, 's, 'r, 'f) kinstr
-> (bool, 'a * 's, 'r, 'f) kinstr
| ILoop_left :
(('a, 'b) union, 's) kinfo
* ('a, 's, ('a, 'b) union, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> (('a, 'b) union, 's, 'r, 'f) kinstr
| IDip :
('a, 'b * 's) kinfo
* ('b, 's, 'c, 't) kinstr
* ('a, 'c * 't, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IExec :
('a, ('a, 'b) lambda * 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) lambda * 's, 'r, 'f) kinstr
| IApply :
('a, ('a * 'b, 'c) lambda * 's) kinfo
* 'a ty
* (('b, 'c) lambda, 's, 'r, 'f) kinstr
-> ('a, ('a * 'b, 'c) lambda * 's, 'r, 'f) kinstr
| ILambda :
('a, 's) kinfo
* ('b, 'c) lambda
* (('b, 'c) lambda, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IFailwith :
('a, 's) kinfo * Script.location * 'a ty
-> ('a, 's, 'r, 'f) kinstr
(*
Comparison
----------
*)
| ICompare :
('a, 'a * 's) kinfo * 'a comparable_ty * (z num, 's, 'r, 'f) kinstr
-> ('a, 'a * 's, 'r, 'f) kinstr
(*
Comparators
-----------
*)
| IEq :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| INeq :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| ILt :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IGt :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| ILe :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IGe :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
(*
Protocol
--------
*)
| IAddress :
('a typed_contract, 's) kinfo * (address, 's, 'r, 'f) kinstr
-> ('a typed_contract, 's, 'r, 'f) kinstr
| IContract :
(address, 's) kinfo
* 'a ty
* Entrypoint.t
* ('a typed_contract option, 's, 'r, 'f) kinstr
-> (address, 's, 'r, 'f) kinstr
| IView :
('a, address * 's) kinfo
* ('a, 'b) view_signature
* ('b option, 's, 'r, 'f) kinstr
-> ('a, address * 's, 'r, 'f) kinstr
| ITransfer_tokens :
('a, Tez.t * ('a typed_contract * 's)) kinfo
* (operation, 's, 'r, 'f) kinstr
-> ('a, Tez.t * ('a typed_contract * 's), 'r, 'f) kinstr
| IImplicit_account :
(public_key_hash, 's) kinfo * (unit typed_contract, 's, 'r, 'f) kinstr
-> (public_key_hash, 's, 'r, 'f) kinstr
| ICreate_contract : {
kinfo : (public_key_hash option, Tez.t * ('a * 's)) kinfo;
storage_type : 'a ty;
arg_type : 'b ty;
lambda : ('b * 'a, operation boxed_list * 'a) lambda;
views : view SMap.t;
entrypoints : 'b entrypoints;
k : (operation, address * 's, 'r, 'f) kinstr;
}
-> (public_key_hash option, Tez.t * ('a * 's), 'r, 'f) kinstr
| ISet_delegate :
(public_key_hash option, 's) kinfo * (operation, 's, 'r, 'f) kinstr
-> (public_key_hash option, 's, 'r, 'f) kinstr
| INow :
('a, 's) kinfo * (Script_timestamp.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IBalance :
('a, 's) kinfo * (Tez.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ILevel :
('a, 's) kinfo * (n num, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ICheck_signature :
(public_key, signature * (bytes * 's)) kinfo * (bool, 's, 'r, 'f) kinstr
-> (public_key, signature * (bytes * 's), 'r, 'f) kinstr
| IHash_key :
(public_key, 's) kinfo * (public_key_hash, 's, 'r, 'f) kinstr
-> (public_key, 's, 'r, 'f) kinstr
| IPack :
('a, 's) kinfo * 'a ty * (bytes, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IUnpack :
(bytes, 's) kinfo * 'a ty * ('a option, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| IBlake2b :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha256 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha512 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISource :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISender :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISelf :
('a, 's) kinfo
* 'b ty
* Entrypoint.t
* ('b typed_contract, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISelf_address :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IAmount :
('a, 's) kinfo * (Tez.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISapling_empty_state :
('a, 's) kinfo
* Sapling.Memo_size.t
* (Sapling.state, 'a * 's, 'b, 'f) kinstr
-> ('a, 's, 'b, 'f) kinstr
| ISapling_verify_update :
(Sapling.transaction, Sapling.state * 's) kinfo
* ((z num, Sapling.state) pair option, 's, 'r, 'f) kinstr
-> (Sapling.transaction, Sapling.state * 's, 'r, 'f) kinstr
| IDig :
('a, 's) kinfo
* int
* ('b, 'c * 't, 'c, 't, 'a, 's, 'd, 'u) stack_prefix_preservation_witness
* ('b, 'd * 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IDug :
('a, 'b * 's) kinfo
* int
* ('c, 't, 'a, 'c * 't, 'b, 's, 'd, 'u) stack_prefix_preservation_witness
* ('d, 'u, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDipn :
('a, 's) kinfo
* int
* ('c, 't, 'd, 'v, 'a, 's, 'b, 'u) stack_prefix_preservation_witness
* ('c, 't, 'd, 'v) kinstr
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IDropn :
('a, 's) kinfo
* int
* ('b, 'u, 'b, 'u, 'a, 's, 'a, 's) stack_prefix_preservation_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IChainId :
('a, 's) kinfo * (Script_chain_id.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| INever : (never, 's) kinfo -> (never, 's, 'r, 'f) kinstr
| IVoting_power :
(public_key_hash, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (public_key_hash, 's, 'r, 'f) kinstr
| ITotal_voting_power :
('a, 's) kinfo * (n num, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IKeccak :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha3 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| IAdd_bls12_381_g1 :
(Script_bls.G1.t, Script_bls.G1.t * 's) kinfo
* (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, Script_bls.G1.t * 's, 'r, 'f) kinstr
| IAdd_bls12_381_g2 :
(Script_bls.G2.t, Script_bls.G2.t * 's) kinfo
* (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, Script_bls.G2.t * 's, 'r, 'f) kinstr
| IAdd_bls12_381_fr :
(Script_bls.Fr.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_g1 :
(Script_bls.G1.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_g2 :
(Script_bls.G2.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_fr :
(Script_bls.Fr.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_z_fr :
(Script_bls.Fr.t, 'a num * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 'a num * 's, 'r, 'f) kinstr
| IMul_bls12_381_fr_z :
('a num, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> ('a num, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IInt_bls12_381_fr :
(Script_bls.Fr.t, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_g1 :
(Script_bls.G1.t, 's) kinfo * (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_g2 :
(Script_bls.G2.t, 's) kinfo * (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_fr :
(Script_bls.Fr.t, 's) kinfo * (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 's, 'r, 'f) kinstr
| IPairing_check_bls12_381 :
((Script_bls.G1.t, Script_bls.G2.t) pair boxed_list, 's) kinfo
* (bool, 's, 'r, 'f) kinstr
-> ((Script_bls.G1.t, Script_bls.G2.t) pair boxed_list, 's, 'r, 'f) kinstr
| IComb :
('a, 's) kinfo
* int
* ('a * 's, 'b * 'u) comb_gadt_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IUncomb :
('a, 's) kinfo
* int
* ('a * 's, 'b * 'u) uncomb_gadt_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IComb_get :
('t, 's) kinfo
* int
* ('t, 'v) comb_get_gadt_witness
* ('v, 's, 'r, 'f) kinstr
-> ('t, 's, 'r, 'f) kinstr
| IComb_set :
('a, 'b * 's) kinfo
* int
* ('a, 'b, 'c) comb_set_gadt_witness
* ('c, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDup_n :
('a, 's) kinfo
* int
* ('a * 's, 't) dup_n_gadt_witness
* ('t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ITicket :
('a, n num * 's) kinfo * ('a ticket, 's, 'r, 'f) kinstr
-> ('a, n num * 's, 'r, 'f) kinstr
| IRead_ticket :
('a ticket, 's) kinfo
* (address * ('a * n num), 'a ticket * 's, 'r, 'f) kinstr
-> ('a ticket, 's, 'r, 'f) kinstr
| ISplit_ticket :
('a ticket, (n num * n num) * 's) kinfo
* (('a ticket * 'a ticket) option, 's, 'r, 'f) kinstr
-> ('a ticket, (n num * n num) * 's, 'r, 'f) kinstr
| IJoin_tickets :
('a ticket * 'a ticket, 's) kinfo
* 'a comparable_ty
* ('a ticket option, 's, 'r, 'f) kinstr
-> ('a ticket * 'a ticket, 's, 'r, 'f) kinstr
| IOpen_chest :
(Script_timelock.chest_key, Script_timelock.chest * (n num * 's)) kinfo
* ((bytes, bool) union, 's, 'r, 'f) kinstr
-> ( Script_timelock.chest_key,
Script_timelock.chest * (n num * 's),
'r,
'f )
kinstr
(*
Internal control instructions
-----------------------------
*)
| IHalt : ('a, 's) kinfo -> ('a, 's, 'a, 's) kinstr
| ILog :
('a, 's) kinfo * logging_event * logger * ('a, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
and logging_event =
| LogEntry : logging_event
| LogExit : ('b, 'u) kinfo -> logging_event
and ('arg, 'ret) lambda =
| Lam :
('arg, end_of_stack, 'ret, end_of_stack) kdescr * Script.node
-> ('arg, 'ret) lambda
[@@coq_force_gadt]
and 'arg typed_contract = {arg_ty : 'arg ty; address : address}
and (_, _, _, _) continuation =
| KNil : ('r, 'f, 'r, 'f) continuation
| KCons :
('a, 's, 'b, 't) kinstr * ('b, 't, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KReturn :
's * ('a, 's, 'r, 'f) continuation
-> ('a, end_of_stack, 'r, 'f) continuation
| KMap_head :
('a -> 'b) * ('b, 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KUndip :
'b * ('b, 'a * 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KLoop_in :
('a, 's, bool, 'a * 's) kinstr * ('a, 's, 'r, 'f) continuation
-> (bool, 'a * 's, 'r, 'f) continuation
| KLoop_in_left :
('a, 's, ('a, 'b) union, 's) kinstr * ('b, 's, 'r, 'f) continuation
-> (('a, 'b) union, 's, 'r, 'f) continuation
| KIter :
('a, 'b * 's, 'b, 's) kinstr * 'a list * ('b, 's, 'r, 'f) continuation
-> ('b, 's, 'r, 'f) continuation
| KList_enter_body :
('a, 'c * 's, 'b, 'c * 's) kinstr
* 'a list
* 'b list
* int
* ('b boxed_list, 'c * 's, 'r, 'f) continuation
-> ('c, 's, 'r, 'f) continuation
| KList_exit_body :
('a, 'c * 's, 'b, 'c * 's) kinstr
* 'a list
* 'b list
* int
* ('b boxed_list, 'c * 's, 'r, 'f) continuation
-> ('b, 'c * 's, 'r, 'f) continuation
| KMap_enter_body :
('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* ('a * 'b) list
* ('a, 'c) map
* (('a, 'c) map, 'd * 's, 'r, 'f) continuation
-> ('d, 's, 'r, 'f) continuation
| KMap_exit_body :
('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* ('a * 'b) list
* ('a, 'c) map
* 'a
* (('a, 'c) map, 'd * 's, 'r, 'f) continuation
-> ('c, 'd * 's, 'r, 'f) continuation
| KView_exit :
step_constants * ('a, 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KLog :
('a, 's, 'r, 'f) continuation * logger
-> ('a, 's, 'r, 'f) continuation
and ('a, 's, 'b, 'f, 'c, 'u) logging_function =
('a, 's, 'b, 'f) kinstr ->
context ->
Script.location ->
('c, 'u) stack_ty ->
'c * 'u ->
unit
and execution_trace = (Script.location * Gas.t * Script.expr list) list
and logger = {
log_interp : 'a 's 'b 'f 'c 'u. ('a, 's, 'b, 'f, 'c, 'u) logging_function;
log_entry : 'a 's 'b 'f. ('a, 's, 'b, 'f, 'a, 's) logging_function;
log_control : 'a 's 'b 'f. ('a, 's, 'b, 'f) continuation -> unit;
log_exit : 'a 's 'b 'f 'c 'u. ('a, 's, 'b, 'f, 'c, 'u) logging_function;
get_log : unit -> execution_trace option tzresult Lwt.t;
}
(* ---- Auxiliary types -----------------------------------------------------*)
and 'ty ty =
| Unit_t : unit ty
| Int_t : z num ty
| Nat_t : n num ty
| Signature_t : signature ty
| String_t : Script_string.t ty
| Bytes_t : bytes ty
| Mutez_t : Tez.t ty
| Key_hash_t : public_key_hash ty
| Key_t : public_key ty
| Timestamp_t : Script_timestamp.t ty
| Address_t : address ty
| Bool_t : bool ty
| Pair_t : 'a ty * 'b ty * ('a, 'b) pair ty_metadata -> ('a, 'b) pair ty
| Union_t : 'a ty * 'b ty * ('a, 'b) union ty_metadata -> ('a, 'b) union ty
| Lambda_t :
'arg ty * 'ret ty * ('arg, 'ret) lambda ty_metadata
-> ('arg, 'ret) lambda ty
| Option_t : 'v ty * 'v option ty_metadata -> 'v option ty
| List_t : 'v ty * 'v boxed_list ty_metadata -> 'v boxed_list ty
| Set_t : 'v comparable_ty * 'v set ty_metadata -> 'v set ty
| Map_t :
'k comparable_ty * 'v ty * ('k, 'v) map ty_metadata
-> ('k, 'v) map ty
| Big_map_t :
'k comparable_ty * 'v ty * ('k, 'v) big_map ty_metadata
-> ('k, 'v) big_map ty
| Contract_t :
'arg ty * 'arg typed_contract ty_metadata
-> 'arg typed_contract ty
| Sapling_transaction_t : Sapling.Memo_size.t -> Sapling.transaction ty
| Sapling_state_t : Sapling.Memo_size.t -> Sapling.state ty
| Operation_t : operation ty
| Chain_id_t : Script_chain_id.t ty
| Never_t : never ty
| Bls12_381_g1_t : Script_bls.G1.t ty
| Bls12_381_g2_t : Script_bls.G2.t ty
| Bls12_381_fr_t : Script_bls.Fr.t ty
| Ticket_t : 'a comparable_ty * 'a ticket ty_metadata -> 'a ticket ty
| Chest_key_t : Script_timelock.chest_key ty
| Chest_t : Script_timelock.chest ty
and ('top_ty, 'resty) stack_ty =
| Item_t : 'ty ty * ('ty2, 'rest) stack_ty -> ('ty, 'ty2 * 'rest) stack_ty
| Bot_t : (empty_cell, empty_cell) stack_ty
and ('key, 'value) big_map = {
id : Big_map.Id.t option;
diff : ('key, 'value) big_map_overlay;
key_type : 'key comparable_ty;
value_type : 'value ty;
}
and ('a, 's, 'r, 'f) kdescr = {
kloc : Script.location;
kbef : ('a, 's) stack_ty;
kaft : ('r, 'f) stack_ty;
kinstr : ('a, 's, 'r, 'f) kinstr;
}
and ('a, 's) kinfo = {iloc : Script.location; kstack_ty : ('a, 's) stack_ty}
and (_, _, _, _, _, _, _, _) stack_prefix_preservation_witness =
| KPrefix :
('y, 'u) kinfo
* ('c, 'v, 'd, 'w, 'x, 's, 'y, 'u) stack_prefix_preservation_witness
-> ( 'c,
'v,
'd,
'w,
'a,
'x * 's,
'a,
'y * 'u )
stack_prefix_preservation_witness
| KRest : ('a, 's, 'b, 'u, 'a, 's, 'b, 'u) stack_prefix_preservation_witness
and ('before, 'after) comb_gadt_witness =
| Comb_one : ('a * ('x * 'before), 'a * ('x * 'before)) comb_gadt_witness
| Comb_succ :
('before, 'b * 'after) comb_gadt_witness
-> ('a * 'before, ('a * 'b) * 'after) comb_gadt_witness
and ('before, 'after) uncomb_gadt_witness =
| Uncomb_one : ('rest, 'rest) uncomb_gadt_witness
| Uncomb_succ :
('b * 'before, 'after) uncomb_gadt_witness
-> (('a * 'b) * 'before, 'a * 'after) uncomb_gadt_witness
and ('before, 'after) comb_get_gadt_witness =
| Comb_get_zero : ('b, 'b) comb_get_gadt_witness
| Comb_get_one : ('a * 'b, 'a) comb_get_gadt_witness
| Comb_get_plus_two :
('before, 'after) comb_get_gadt_witness
-> ('a * 'before, 'after) comb_get_gadt_witness
and ('value, 'before, 'after) comb_set_gadt_witness =
| Comb_set_zero : ('value, _, 'value) comb_set_gadt_witness
| Comb_set_one : ('value, 'hd * 'tl, 'value * 'tl) comb_set_gadt_witness
| Comb_set_plus_two :
('value, 'before, 'after) comb_set_gadt_witness
-> ('value, 'a * 'before, 'a * 'after) comb_set_gadt_witness
[@@coq_force_gadt]
and (_, _) dup_n_gadt_witness =
| Dup_n_zero : ('a * 'rest, 'a) dup_n_gadt_witness
| Dup_n_succ :
('stack, 'b) dup_n_gadt_witness
-> ('a * 'stack, 'b) dup_n_gadt_witness
and ('a, 'b) view_signature =
| View_signature of {
name : Script_string.t;
input_ty : 'a ty;
output_ty : 'b ty;
}
let kinfo_of_kinstr : type a s b f. (a, s, b, f) kinstr -> (a, s) kinfo =
fun i ->
match i with
| IDrop (kinfo, _) -> kinfo
| IDup (kinfo, _) -> kinfo
| ISwap (kinfo, _) -> kinfo
| IConst (kinfo, _, _) -> kinfo
| ICons_pair (kinfo, _) -> kinfo
| ICar (kinfo, _) -> kinfo
| ICdr (kinfo, _) -> kinfo
| IUnpair (kinfo, _) -> kinfo
| ICons_some (kinfo, _) -> kinfo
| ICons_none (kinfo, _) -> kinfo
| IIf_none {kinfo; _} -> kinfo
| IOpt_map {kinfo; _} -> kinfo
| ICons_left (kinfo, _) -> kinfo
| ICons_right (kinfo, _) -> kinfo
| IIf_left {kinfo; _} -> kinfo
| ICons_list (kinfo, _) -> kinfo
| INil (kinfo, _) -> kinfo
| IIf_cons {kinfo; _} -> kinfo
| IList_map (kinfo, _, _) -> kinfo
| IList_iter (kinfo, _, _) -> kinfo
| IList_size (kinfo, _) -> kinfo
| IEmpty_set (kinfo, _, _) -> kinfo
| ISet_iter (kinfo, _, _) -> kinfo
| ISet_mem (kinfo, _) -> kinfo
| ISet_update (kinfo, _) -> kinfo
| ISet_size (kinfo, _) -> kinfo
| IEmpty_map (kinfo, _, _) -> kinfo
| IMap_map (kinfo, _, _) -> kinfo
| IMap_iter (kinfo, _, _) -> kinfo
| IMap_mem (kinfo, _) -> kinfo
| IMap_get (kinfo, _) -> kinfo
| IMap_update (kinfo, _) -> kinfo
| IMap_get_and_update (kinfo, _) -> kinfo
| IMap_size (kinfo, _) -> kinfo
| IEmpty_big_map (kinfo, _, _, _) -> kinfo
| IBig_map_mem (kinfo, _) -> kinfo
| IBig_map_get (kinfo, _) -> kinfo
| IBig_map_update (kinfo, _) -> kinfo
| IBig_map_get_and_update (kinfo, _) -> kinfo
| IConcat_string (kinfo, _) -> kinfo
| IConcat_string_pair (kinfo, _) -> kinfo
| ISlice_string (kinfo, _) -> kinfo
| IString_size (kinfo, _) -> kinfo
| IConcat_bytes (kinfo, _) -> kinfo
| IConcat_bytes_pair (kinfo, _) -> kinfo
| ISlice_bytes (kinfo, _) -> kinfo
| IBytes_size (kinfo, _) -> kinfo
| IAdd_seconds_to_timestamp (kinfo, _) -> kinfo
| IAdd_timestamp_to_seconds (kinfo, _) -> kinfo
| ISub_timestamp_seconds (kinfo, _) -> kinfo
| IDiff_timestamps (kinfo, _) -> kinfo
| IAdd_tez (kinfo, _) -> kinfo
| ISub_tez (kinfo, _) -> kinfo
| ISub_tez_legacy (kinfo, _) -> kinfo
| IMul_teznat (kinfo, _) -> kinfo
| IMul_nattez (kinfo, _) -> kinfo
| IEdiv_teznat (kinfo, _) -> kinfo
| IEdiv_tez (kinfo, _) -> kinfo
| IOr (kinfo, _) -> kinfo
| IAnd (kinfo, _) -> kinfo
| IXor (kinfo, _) -> kinfo
| INot (kinfo, _) -> kinfo
| IIs_nat (kinfo, _) -> kinfo
| INeg (kinfo, _) -> kinfo
| IAbs_int (kinfo, _) -> kinfo
| IInt_nat (kinfo, _) -> kinfo
| IAdd_int (kinfo, _) -> kinfo
| IAdd_nat (kinfo, _) -> kinfo
| ISub_int (kinfo, _) -> kinfo
| IMul_int (kinfo, _) -> kinfo
| IMul_nat (kinfo, _) -> kinfo
| IEdiv_int (kinfo, _) -> kinfo
| IEdiv_nat (kinfo, _) -> kinfo
| ILsl_nat (kinfo, _) -> kinfo
| ILsr_nat (kinfo, _) -> kinfo
| IOr_nat (kinfo, _) -> kinfo
| IAnd_nat (kinfo, _) -> kinfo
| IAnd_int_nat (kinfo, _) -> kinfo
| IXor_nat (kinfo, _) -> kinfo
| INot_int (kinfo, _) -> kinfo
| IIf {kinfo; _} -> kinfo
| ILoop (kinfo, _, _) -> kinfo
| ILoop_left (kinfo, _, _) -> kinfo
| IDip (kinfo, _, _) -> kinfo
| IExec (kinfo, _) -> kinfo
| IApply (kinfo, _, _) -> kinfo
| ILambda (kinfo, _, _) -> kinfo
| IFailwith (kinfo, _, _) -> kinfo
| ICompare (kinfo, _, _) -> kinfo
| IEq (kinfo, _) -> kinfo
| INeq (kinfo, _) -> kinfo
| ILt (kinfo, _) -> kinfo
| IGt (kinfo, _) -> kinfo
| ILe (kinfo, _) -> kinfo
| IGe (kinfo, _) -> kinfo
| IAddress (kinfo, _) -> kinfo
| IContract (kinfo, _, _, _) -> kinfo
| ITransfer_tokens (kinfo, _) -> kinfo
| IView (kinfo, _, _) -> kinfo
| IImplicit_account (kinfo, _) -> kinfo
| ICreate_contract {kinfo; _} -> kinfo
| ISet_delegate (kinfo, _) -> kinfo
| INow (kinfo, _) -> kinfo
| IBalance (kinfo, _) -> kinfo
| ILevel (kinfo, _) -> kinfo
| ICheck_signature (kinfo, _) -> kinfo
| IHash_key (kinfo, _) -> kinfo
| IPack (kinfo, _, _) -> kinfo
| IUnpack (kinfo, _, _) -> kinfo
| IBlake2b (kinfo, _) -> kinfo
| ISha256 (kinfo, _) -> kinfo
| ISha512 (kinfo, _) -> kinfo
| ISource (kinfo, _) -> kinfo
| ISender (kinfo, _) -> kinfo
| ISelf (kinfo, _, _, _) -> kinfo
| ISelf_address (kinfo, _) -> kinfo
| IAmount (kinfo, _) -> kinfo
| ISapling_empty_state (kinfo, _, _) -> kinfo
| ISapling_verify_update (kinfo, _) -> kinfo
| IDig (kinfo, _, _, _) -> kinfo
| IDug (kinfo, _, _, _) -> kinfo
| IDipn (kinfo, _, _, _, _) -> kinfo
| IDropn (kinfo, _, _, _) -> kinfo
| IChainId (kinfo, _) -> kinfo
| INever kinfo -> kinfo
| IVoting_power (kinfo, _) -> kinfo
| ITotal_voting_power (kinfo, _) -> kinfo
| IKeccak (kinfo, _) -> kinfo
| ISha3 (kinfo, _) -> kinfo
| IAdd_bls12_381_g1 (kinfo, _) -> kinfo
| IAdd_bls12_381_g2 (kinfo, _) -> kinfo
| IAdd_bls12_381_fr (kinfo, _) -> kinfo
| IMul_bls12_381_g1 (kinfo, _) -> kinfo
| IMul_bls12_381_g2 (kinfo, _) -> kinfo
| IMul_bls12_381_fr (kinfo, _) -> kinfo
| IMul_bls12_381_z_fr (kinfo, _) -> kinfo
| IMul_bls12_381_fr_z (kinfo, _) -> kinfo
| IInt_bls12_381_fr (kinfo, _) -> kinfo
| INeg_bls12_381_g1 (kinfo, _) -> kinfo
| INeg_bls12_381_g2 (kinfo, _) -> kinfo
| INeg_bls12_381_fr (kinfo, _) -> kinfo
| IPairing_check_bls12_381 (kinfo, _) -> kinfo
| IComb (kinfo, _, _, _) -> kinfo
| IUncomb (kinfo, _, _, _) -> kinfo
| IComb_get (kinfo, _, _, _) -> kinfo
| IComb_set (kinfo, _, _, _) -> kinfo
| IDup_n (kinfo, _, _, _) -> kinfo
| ITicket (kinfo, _) -> kinfo
| IRead_ticket (kinfo, _) -> kinfo
| ISplit_ticket (kinfo, _) -> kinfo
| IJoin_tickets (kinfo, _, _) -> kinfo
| IHalt kinfo -> kinfo
| ILog (kinfo, _, _, _) -> kinfo
| IOpen_chest (kinfo, _) -> kinfo
type kinstr_rewritek = {
apply : 'b 'u 'r 'f. ('b, 'u, 'r, 'f) kinstr -> ('b, 'u, 'r, 'f) kinstr;
}
let kinstr_rewritek :
type a s r f. (a, s, r, f) kinstr -> kinstr_rewritek -> (a, s, r, f) kinstr
=
fun i f ->
match i with
| IDrop (kinfo, k) -> IDrop (kinfo, f.apply k)
| IDup (kinfo, k) -> IDup (kinfo, f.apply k)
| ISwap (kinfo, k) -> ISwap (kinfo, f.apply k)
| IConst (kinfo, x, k) -> IConst (kinfo, x, f.apply k)
| ICons_pair (kinfo, k) -> ICons_pair (kinfo, f.apply k)
| ICar (kinfo, k) -> ICar (kinfo, f.apply k)
| ICdr (kinfo, k) -> ICdr (kinfo, f.apply k)
| IUnpair (kinfo, k) -> IUnpair (kinfo, f.apply k)
| ICons_some (kinfo, k) -> ICons_some (kinfo, f.apply k)
| ICons_none (kinfo, k) -> ICons_none (kinfo, f.apply k)
| IIf_none {kinfo; branch_if_none; branch_if_some; k} ->
IIf_none
{
kinfo;
branch_if_none = f.apply branch_if_none;
branch_if_some = f.apply branch_if_some;
k = f.apply k;
}
| IOpt_map {kinfo; body; k} ->
let body = f.apply body in
let k = f.apply k in
IOpt_map {kinfo; body; k}
| ICons_left (kinfo, k) -> ICons_left (kinfo, f.apply k)
| ICons_right (kinfo, k) -> ICons_right (kinfo, f.apply k)
| IIf_left {kinfo; branch_if_left; branch_if_right; k} ->
IIf_left
{
kinfo;
branch_if_left = f.apply branch_if_left;
branch_if_right = f.apply branch_if_right;
k = f.apply k;
}
| ICons_list (kinfo, k) -> ICons_list (kinfo, f.apply k)
| INil (kinfo, k) -> INil (kinfo, f.apply k)
| IIf_cons {kinfo; branch_if_cons; branch_if_nil; k} ->
IIf_cons
{
kinfo;
branch_if_cons = f.apply branch_if_cons;
branch_if_nil = f.apply branch_if_nil;
k = f.apply k;
}
| IList_map (kinfo, body, k) -> IList_map (kinfo, f.apply body, f.apply k)
| IList_iter (kinfo, body, k) -> IList_iter (kinfo, f.apply body, f.apply k)
| IList_size (kinfo, k) -> IList_size (kinfo, f.apply k)
| IEmpty_set (kinfo, ty, k) -> IEmpty_set (kinfo, ty, f.apply k)
| ISet_iter (kinfo, body, k) -> ISet_iter (kinfo, f.apply body, f.apply k)
| ISet_mem (kinfo, k) -> ISet_mem (kinfo, f.apply k)
| ISet_update (kinfo, k) -> ISet_update (kinfo, f.apply k)
| ISet_size (kinfo, k) -> ISet_size (kinfo, f.apply k)
| IEmpty_map (kinfo, cty, k) -> IEmpty_map (kinfo, cty, f.apply k)
| IMap_map (kinfo, body, k) -> IMap_map (kinfo, f.apply body, f.apply k)
| IMap_iter (kinfo, body, k) -> IMap_iter (kinfo, f.apply body, f.apply k)
| IMap_mem (kinfo, k) -> IMap_mem (kinfo, f.apply k)
| IMap_get (kinfo, k) -> IMap_get (kinfo, f.apply k)
| IMap_update (kinfo, k) -> IMap_update (kinfo, f.apply k)
| IMap_get_and_update (kinfo, k) -> IMap_get_and_update (kinfo, f.apply k)
| IMap_size (kinfo, k) -> IMap_size (kinfo, f.apply k)
| IEmpty_big_map (kinfo, cty, ty, k) ->
IEmpty_big_map (kinfo, cty, ty, f.apply k)
| IBig_map_mem (kinfo, k) -> IBig_map_mem (kinfo, f.apply k)
| IBig_map_get (kinfo, k) -> IBig_map_get (kinfo, f.apply k)
| IBig_map_update (kinfo, k) -> IBig_map_update (kinfo, f.apply k)
| IBig_map_get_and_update (kinfo, k) ->
IBig_map_get_and_update (kinfo, f.apply k)
| IConcat_string (kinfo, k) -> IConcat_string (kinfo, f.apply k)
| IConcat_string_pair (kinfo, k) -> IConcat_string_pair (kinfo, f.apply k)
| ISlice_string (kinfo, k) -> ISlice_string (kinfo, f.apply k)
| IString_size (kinfo, k) -> IString_size (kinfo, f.apply k)
| IConcat_bytes (kinfo, k) -> IConcat_bytes (kinfo, f.apply k)
| IConcat_bytes_pair (kinfo, k) -> IConcat_bytes_pair (kinfo, f.apply k)
| ISlice_bytes (kinfo, k) -> ISlice_bytes (kinfo, f.apply k)
| IBytes_size (kinfo, k) -> IBytes_size (kinfo, f.apply k)
| IAdd_seconds_to_timestamp (kinfo, k) ->
IAdd_seconds_to_timestamp (kinfo, f.apply k)
| IAdd_timestamp_to_seconds (kinfo, k) ->
IAdd_timestamp_to_seconds (kinfo, f.apply k)
| ISub_timestamp_seconds (kinfo, k) ->
ISub_timestamp_seconds (kinfo, f.apply k)
| IDiff_timestamps (kinfo, k) -> IDiff_timestamps (kinfo, f.apply k)
| IAdd_tez (kinfo, k) -> IAdd_tez (kinfo, f.apply k)
| ISub_tez (kinfo, k) -> ISub_tez (kinfo, f.apply k)
| ISub_tez_legacy (kinfo, k) -> ISub_tez_legacy (kinfo, f.apply k)
| IMul_teznat (kinfo, k) -> IMul_teznat (kinfo, f.apply k)
| IMul_nattez (kinfo, k) -> IMul_nattez (kinfo, f.apply k)
| IEdiv_teznat (kinfo, k) -> IEdiv_teznat (kinfo, f.apply k)
| IEdiv_tez (kinfo, k) -> IEdiv_tez (kinfo, f.apply k)
| IOr (kinfo, k) -> IOr (kinfo, f.apply k)
| IAnd (kinfo, k) -> IAnd (kinfo, f.apply k)
| IXor (kinfo, k) -> IXor (kinfo, f.apply k)
| INot (kinfo, k) -> INot (kinfo, f.apply k)
| IIs_nat (kinfo, k) -> IIs_nat (kinfo, f.apply k)
| INeg (kinfo, k) -> INeg (kinfo, f.apply k)
| IAbs_int (kinfo, k) -> IAbs_int (kinfo, f.apply k)
| IInt_nat (kinfo, k) -> IInt_nat (kinfo, f.apply k)
| IAdd_int (kinfo, k) -> IAdd_int (kinfo, f.apply k)
| IAdd_nat (kinfo, k) -> IAdd_nat (kinfo, f.apply k)
| ISub_int (kinfo, k) -> ISub_int (kinfo, f.apply k)
| IMul_int (kinfo, k) -> IMul_int (kinfo, f.apply k)
| IMul_nat (kinfo, k) -> IMul_nat (kinfo, f.apply k)
| IEdiv_int (kinfo, k) -> IEdiv_int (kinfo, f.apply k)
| IEdiv_nat (kinfo, k) -> IEdiv_nat (kinfo, f.apply k)
| ILsl_nat (kinfo, k) -> ILsl_nat (kinfo, f.apply k)
| ILsr_nat (kinfo, k) -> ILsr_nat (kinfo, f.apply k)
| IOr_nat (kinfo, k) -> IOr_nat (kinfo, f.apply k)
| IAnd_nat (kinfo, k) -> IAnd_nat (kinfo, f.apply k)
| IAnd_int_nat (kinfo, k) -> IAnd_int_nat (kinfo, f.apply k)
| IXor_nat (kinfo, k) -> IXor_nat (kinfo, f.apply k)
| INot_int (kinfo, k) -> INot_int (kinfo, f.apply k)
| IIf {kinfo; branch_if_true; branch_if_false; k} ->
IIf
{
kinfo;
branch_if_true = f.apply branch_if_true;
branch_if_false = f.apply branch_if_false;
k = f.apply k;
}
| ILoop (kinfo, kbody, k) -> ILoop (kinfo, f.apply kbody, f.apply k)
| ILoop_left (kinfo, kl, kr) -> ILoop_left (kinfo, f.apply kl, f.apply kr)
| IDip (kinfo, body, k) -> IDip (kinfo, f.apply body, f.apply k)
| IExec (kinfo, k) -> IExec (kinfo, f.apply k)
| IApply (kinfo, ty, k) -> IApply (kinfo, ty, f.apply k)
| ILambda (kinfo, l, k) -> ILambda (kinfo, l, f.apply k)
| IFailwith (kinfo, i, ty) -> IFailwith (kinfo, i, ty)
| ICompare (kinfo, ty, k) -> ICompare (kinfo, ty, f.apply k)
| IEq (kinfo, k) -> IEq (kinfo, f.apply k)
| INeq (kinfo, k) -> INeq (kinfo, f.apply k)
| ILt (kinfo, k) -> ILt (kinfo, f.apply k)
| IGt (kinfo, k) -> IGt (kinfo, f.apply k)
| ILe (kinfo, k) -> ILe (kinfo, f.apply k)
| IGe (kinfo, k) -> IGe (kinfo, f.apply k)
| IAddress (kinfo, k) -> IAddress (kinfo, f.apply k)
| IContract (kinfo, ty, code, k) -> IContract (kinfo, ty, code, f.apply k)
| ITransfer_tokens (kinfo, k) -> ITransfer_tokens (kinfo, f.apply k)
| IView (kinfo, view_signature, k) -> IView (kinfo, view_signature, f.apply k)
| IImplicit_account (kinfo, k) -> IImplicit_account (kinfo, f.apply k)
| ICreate_contract
{kinfo; storage_type; arg_type; lambda; views; entrypoints; k} ->
let k = f.apply k in
ICreate_contract
{kinfo; storage_type; arg_type; lambda; views; entrypoints; k}
| ISet_delegate (kinfo, k) -> ISet_delegate (kinfo, f.apply k)
| INow (kinfo, k) -> INow (kinfo, f.apply k)
| IBalance (kinfo, k) -> IBalance (kinfo, f.apply k)
| ILevel (kinfo, k) -> ILevel (kinfo, f.apply k)
| ICheck_signature (kinfo, k) -> ICheck_signature (kinfo, f.apply k)
| IHash_key (kinfo, k) -> IHash_key (kinfo, f.apply k)
| IPack (kinfo, ty, k) -> IPack (kinfo, ty, f.apply k)
| IUnpack (kinfo, ty, k) -> IUnpack (kinfo, ty, f.apply k)
| IBlake2b (kinfo, k) -> IBlake2b (kinfo, f.apply k)
| ISha256 (kinfo, k) -> ISha256 (kinfo, f.apply k)
| ISha512 (kinfo, k) -> ISha512 (kinfo, f.apply k)
| ISource (kinfo, k) -> ISource (kinfo, f.apply k)
| ISender (kinfo, k) -> ISender (kinfo, f.apply k)
| ISelf (kinfo, ty, s, k) -> ISelf (kinfo, ty, s, f.apply k)
| ISelf_address (kinfo, k) -> ISelf_address (kinfo, f.apply k)
| IAmount (kinfo, k) -> IAmount (kinfo, f.apply k)
| ISapling_empty_state (kinfo, s, k) ->
ISapling_empty_state (kinfo, s, f.apply k)
| ISapling_verify_update (kinfo, k) ->
ISapling_verify_update (kinfo, f.apply k)
| IDig (kinfo, n, p, k) -> IDig (kinfo, n, p, f.apply k)
| IDug (kinfo, n, p, k) -> IDug (kinfo, n, p, f.apply k)
| IDipn (kinfo, n, p, k1, k2) -> IDipn (kinfo, n, p, f.apply k1, f.apply k2)
| IDropn (kinfo, n, p, k) -> IDropn (kinfo, n, p, f.apply k)
| IChainId (kinfo, k) -> IChainId (kinfo, f.apply k)
| INever kinfo -> INever kinfo
| IVoting_power (kinfo, k) -> IVoting_power (kinfo, f.apply k)
| ITotal_voting_power (kinfo, k) -> ITotal_voting_power (kinfo, f.apply k)
| IKeccak (kinfo, k) -> IKeccak (kinfo, f.apply k)
| ISha3 (kinfo, k) -> ISha3 (kinfo, f.apply k)
| IAdd_bls12_381_g1 (kinfo, k) -> IAdd_bls12_381_g1 (kinfo, f.apply k)
| IAdd_bls12_381_g2 (kinfo, k) -> IAdd_bls12_381_g2 (kinfo, f.apply k)
| IAdd_bls12_381_fr (kinfo, k) -> IAdd_bls12_381_fr (kinfo, f.apply k)
| IMul_bls12_381_g1 (kinfo, k) -> IMul_bls12_381_g1 (kinfo, f.apply k)
| IMul_bls12_381_g2 (kinfo, k) -> IMul_bls12_381_g2 (kinfo, f.apply k)
| IMul_bls12_381_fr (kinfo, k) -> IMul_bls12_381_fr (kinfo, f.apply k)
| IMul_bls12_381_z_fr (kinfo, k) -> IMul_bls12_381_z_fr (kinfo, f.apply k)
| IMul_bls12_381_fr_z (kinfo, k) -> IMul_bls12_381_fr_z (kinfo, f.apply k)
| IInt_bls12_381_fr (kinfo, k) -> IInt_bls12_381_fr (kinfo, f.apply k)
| INeg_bls12_381_g1 (kinfo, k) -> INeg_bls12_381_g1 (kinfo, f.apply k)
| INeg_bls12_381_g2 (kinfo, k) -> INeg_bls12_381_g2 (kinfo, f.apply k)
| INeg_bls12_381_fr (kinfo, k) -> INeg_bls12_381_fr (kinfo, f.apply k)
| IPairing_check_bls12_381 (kinfo, k) ->
IPairing_check_bls12_381 (kinfo, f.apply k)
| IComb (kinfo, n, p, k) -> IComb (kinfo, n, p, f.apply k)
| IUncomb (kinfo, n, p, k) -> IUncomb (kinfo, n, p, f.apply k)
| IComb_get (kinfo, n, p, k) -> IComb_get (kinfo, n, p, f.apply k)
| IComb_set (kinfo, n, p, k) -> IComb_set (kinfo, n, p, f.apply k)
| IDup_n (kinfo, n, p, k) -> IDup_n (kinfo, n, p, f.apply k)
| ITicket (kinfo, k) -> ITicket (kinfo, f.apply k)
| IRead_ticket (kinfo, k) -> IRead_ticket (kinfo, f.apply k)
| ISplit_ticket (kinfo, k) -> ISplit_ticket (kinfo, f.apply k)
| IJoin_tickets (kinfo, ty, k) -> IJoin_tickets (kinfo, ty, f.apply k)
| IHalt kinfo -> IHalt kinfo
| ILog (kinfo, event, logger, k) -> ILog (kinfo, event, logger, k)
| IOpen_chest (kinfo, k) -> IOpen_chest (kinfo, f.apply k)
let ty_metadata : type a. a ty -> a ty_metadata = function
| Unit_t | Never_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t
| Mutez_t | Bool_t | Key_hash_t | Key_t | Timestamp_t | Chain_id_t | Address_t
->
meta_basic
| Pair_t (_, _, meta) -> meta
| Union_t (_, _, meta) -> meta
| Option_t (_, meta) -> meta
| Lambda_t (_, _, meta) -> meta
| List_t (_, meta) -> meta
| Set_t (_, meta) -> meta
| Map_t (_, _, meta) -> meta
| Big_map_t (_, _, meta) -> meta
| Ticket_t (_, meta) -> meta
| Contract_t (_, meta) -> meta
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Bls12_381_g1_t
| Bls12_381_g2_t | Bls12_381_fr_t | Chest_t | Chest_key_t ->
meta_basic
let ty_size t = (ty_metadata t).size
let unit_t = Unit_t
let int_t = Int_t
let nat_t = Nat_t
let signature_t = Signature_t
let string_t = String_t
let bytes_t = Bytes_t
let mutez_t = Mutez_t
let key_hash_t = Key_hash_t
let key_t = Key_t
let timestamp_t = Timestamp_t
let address_t = Address_t
let bool_t = Bool_t
let pair_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Pair_t (l, r, {size})
let union_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Union_t (l, r, {size})
let union_bytes_bool_t = Union_t (bytes_t, bool_t, {size = Type_size.three})
let lambda_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Lambda_t (l, r, {size})
let option_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> Option_t (t, {size})
let option_mutez_t = Option_t (mutez_t, {size = Type_size.two})
let option_string_t = Option_t (string_t, {size = Type_size.two})
let option_bytes_t = Option_t (bytes_t, {size = Type_size.two})
let option_nat_t = Option_t (nat_t, {size = Type_size.two})
let option_pair_nat_nat_t =
Option_t
(Pair_t (nat_t, nat_t, {size = Type_size.three}), {size = Type_size.four})
let option_pair_nat_mutez_t =
Option_t
(Pair_t (nat_t, mutez_t, {size = Type_size.three}), {size = Type_size.four})
let option_pair_mutez_mutez_t =
Option_t
( Pair_t (mutez_t, mutez_t, {size = Type_size.three}),
{size = Type_size.four} )
let option_pair_int_nat_t =
Option_t
(Pair_t (int_t, nat_t, {size = Type_size.three}), {size = Type_size.four})
let list_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> List_t (t, {size})
let operation_t = Operation_t
let list_operation_t = List_t (operation_t, {size = Type_size.two})
let set_t loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Set_t (t, {size})
let map_t loc l r =
Type_size.compound2 loc (comparable_ty_size l) (ty_size r) >|? fun size ->
Map_t (l, r, {size})
let big_map_t loc l r =
Type_size.compound2 loc (comparable_ty_size l) (ty_size r) >|? fun size ->
Big_map_t (l, r, {size})
let contract_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> Contract_t (t, {size})
let contract_unit_t = Contract_t (unit_t, {size = Type_size.two})
let sapling_transaction_t ~memo_size = Sapling_transaction_t memo_size
let sapling_state_t ~memo_size = Sapling_state_t memo_size
let chain_id_t = Chain_id_t
let never_t = Never_t
let bls12_381_g1_t = Bls12_381_g1_t
let bls12_381_g2_t = Bls12_381_g2_t
let bls12_381_fr_t = Bls12_381_fr_t
let ticket_t loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Ticket_t (t, {size})
let chest_key_t = Chest_key_t
let chest_t = Chest_t
type 'a kinstr_traverse = {
apply : 'b 'u 'r 'f. 'a -> ('b, 'u, 'r, 'f) kinstr -> 'a;
}
let kinstr_traverse i init f =
let rec aux :
type ret a s r f. 'accu -> (a, s, r, f) kinstr -> ('accu -> ret) -> ret =
fun accu t continue ->
let accu = f.apply accu t in
let next k =
(aux [@ocaml.tailcall]) accu k @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next2 k1 k2 =
(aux [@ocaml.tailcall]) accu k1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next3 k1 k2 k3 =
(aux [@ocaml.tailcall]) accu k1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k2 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k3 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match t with
| IDrop (_, k) -> (next [@ocaml.tailcall]) k
| IDup (_, k) -> (next [@ocaml.tailcall]) k
| ISwap (_, k) -> (next [@ocaml.tailcall]) k
| IConst (_, _, k) -> (next [@ocaml.tailcall]) k
| ICons_pair (_, k) -> (next [@ocaml.tailcall]) k
| ICar (_, k) -> (next [@ocaml.tailcall]) k
| ICdr (_, k) -> (next [@ocaml.tailcall]) k
| IUnpair (_, k) -> (next [@ocaml.tailcall]) k
| ICons_some (_, k) -> (next [@ocaml.tailcall]) k
| ICons_none (_, k) -> (next [@ocaml.tailcall]) k
| IIf_none {kinfo = _; branch_if_none = k1; branch_if_some = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| IOpt_map {kinfo = _; body; k} -> (next2 [@ocaml.tailcall]) body k
| ICons_left (_, k) -> (next [@ocaml.tailcall]) k
| ICons_right (_, k) -> (next [@ocaml.tailcall]) k
| IIf_left {kinfo = _; branch_if_left = k1; branch_if_right = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| ICons_list (_, k) -> (next [@ocaml.tailcall]) k
| INil (_, k) -> (next [@ocaml.tailcall]) k
| IIf_cons {kinfo = _; branch_if_nil = k1; branch_if_cons = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| IList_map (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IList_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IList_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_set (_, _, k) -> (next [@ocaml.tailcall]) k
| ISet_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| ISet_mem (_, k) -> (next [@ocaml.tailcall]) k
| ISet_update (_, k) -> (next [@ocaml.tailcall]) k
| ISet_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_map (_, _, k) -> (next [@ocaml.tailcall]) k
| IMap_map (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IMap_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IMap_mem (_, k) -> (next [@ocaml.tailcall]) k
| IMap_get (_, k) -> (next [@ocaml.tailcall]) k
| IMap_update (_, k) -> (next [@ocaml.tailcall]) k
| IMap_get_and_update (_, k) -> (next [@ocaml.tailcall]) k
| IMap_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_big_map (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IBig_map_mem (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_get (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_update (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_get_and_update (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_string (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_string_pair (_, k) -> (next [@ocaml.tailcall]) k
| ISlice_string (_, k) -> (next [@ocaml.tailcall]) k
| IString_size (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_bytes (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_bytes_pair (_, k) -> (next [@ocaml.tailcall]) k
| ISlice_bytes (_, k) -> (next [@ocaml.tailcall]) k
| IBytes_size (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_seconds_to_timestamp (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_timestamp_to_seconds (_, k) -> (next [@ocaml.tailcall]) k
| ISub_timestamp_seconds (_, k) -> (next [@ocaml.tailcall]) k
| IDiff_timestamps (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_tez (_, k) -> (next [@ocaml.tailcall]) k
| ISub_tez (_, k) -> (next [@ocaml.tailcall]) k
| ISub_tez_legacy (_, k) -> (next [@ocaml.tailcall]) k
| IMul_teznat (_, k) -> (next [@ocaml.tailcall]) k
| IMul_nattez (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_teznat (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_tez (_, k) -> (next [@ocaml.tailcall]) k
| IOr (_, k) -> (next [@ocaml.tailcall]) k
| IAnd (_, k) -> (next [@ocaml.tailcall]) k
| IXor (_, k) -> (next [@ocaml.tailcall]) k
| INot (_, k) -> (next [@ocaml.tailcall]) k
| IIs_nat (_, k) -> (next [@ocaml.tailcall]) k
| INeg (_, k) -> (next [@ocaml.tailcall]) k
| IAbs_int (_, k) -> (next [@ocaml.tailcall]) k
| IInt_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_int (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_nat (_, k) -> (next [@ocaml.tailcall]) k
| ISub_int (_, k) -> (next [@ocaml.tailcall]) k
| IMul_int (_, k) -> (next [@ocaml.tailcall]) k
| IMul_nat (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_int (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_nat (_, k) -> (next [@ocaml.tailcall]) k
| ILsl_nat (_, k) -> (next [@ocaml.tailcall]) k
| ILsr_nat (_, k) -> (next [@ocaml.tailcall]) k
| IOr_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAnd_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAnd_int_nat (_, k) -> (next [@ocaml.tailcall]) k
| IXor_nat (_, k) -> (next [@ocaml.tailcall]) k
| INot_int (_, k) -> (next [@ocaml.tailcall]) k
| IIf {kinfo = _; branch_if_true = k1; branch_if_false = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| ILoop (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| ILoop_left (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IDip (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IExec (_, k) -> (next [@ocaml.tailcall]) k
| IApply (_, _, k) -> (next [@ocaml.tailcall]) k
| ILambda (_, _, k) -> (next [@ocaml.tailcall]) k
| IFailwith (_, _, _) -> (return [@ocaml.tailcall]) ()
| ICompare (_, _, k) -> (next [@ocaml.tailcall]) k
| IEq (_, k) -> (next [@ocaml.tailcall]) k
| INeq (_, k) -> (next [@ocaml.tailcall]) k
| ILt (_, k) -> (next [@ocaml.tailcall]) k
| IGt (_, k) -> (next [@ocaml.tailcall]) k
| ILe (_, k) -> (next [@ocaml.tailcall]) k
| IGe (_, k) -> (next [@ocaml.tailcall]) k
| IAddress (_, k) -> (next [@ocaml.tailcall]) k
| IContract (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IView (_, _, k) -> (next [@ocaml.tailcall]) k
| ITransfer_tokens (_, k) -> (next [@ocaml.tailcall]) k
| IImplicit_account (_, k) -> (next [@ocaml.tailcall]) k
| ICreate_contract {k; _} -> (next [@ocaml.tailcall]) k
| ISet_delegate (_, k) -> (next [@ocaml.tailcall]) k
| INow (_, k) -> (next [@ocaml.tailcall]) k
| IBalance (_, k) -> (next [@ocaml.tailcall]) k
| ILevel (_, k) -> (next [@ocaml.tailcall]) k
| ICheck_signature (_, k) -> (next [@ocaml.tailcall]) k
| IHash_key (_, k) -> (next [@ocaml.tailcall]) k
| IPack (_, _, k) -> (next [@ocaml.tailcall]) k
| IUnpack (_, _, k) -> (next [@ocaml.tailcall]) k
| IBlake2b (_, k) -> (next [@ocaml.tailcall]) k
| ISha256 (_, k) -> (next [@ocaml.tailcall]) k
| ISha512 (_, k) -> (next [@ocaml.tailcall]) k
| ISource (_, k) -> (next [@ocaml.tailcall]) k
| ISender (_, k) -> (next [@ocaml.tailcall]) k
| ISelf (_, _, _, k) -> (next [@ocaml.tailcall]) k
| ISelf_address (_, k) -> (next [@ocaml.tailcall]) k
| IAmount (_, k) -> (next [@ocaml.tailcall]) k
| ISapling_empty_state (_, _, k) -> (next [@ocaml.tailcall]) k
| ISapling_verify_update (_, k) -> (next [@ocaml.tailcall]) k
| IDig (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDug (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDipn (_, _, _, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IDropn (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IChainId (_, k) -> (next [@ocaml.tailcall]) k
| INever _ -> (return [@ocaml.tailcall]) ()
| IVoting_power (_, k) -> (next [@ocaml.tailcall]) k
| ITotal_voting_power (_, k) -> (next [@ocaml.tailcall]) k
| IKeccak (_, k) -> (next [@ocaml.tailcall]) k
| ISha3 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_z_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_fr_z (_, k) -> (next [@ocaml.tailcall]) k
| IInt_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IPairing_check_bls12_381 (_, k) -> (next [@ocaml.tailcall]) k
| IComb (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IUncomb (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IComb_get (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IComb_set (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDup_n (_, _, _, k) -> (next [@ocaml.tailcall]) k
| ITicket (_, k) -> (next [@ocaml.tailcall]) k
| IRead_ticket (_, k) -> (next [@ocaml.tailcall]) k
| ISplit_ticket (_, k) -> (next [@ocaml.tailcall]) k
| IJoin_tickets (_, _, k) -> (next [@ocaml.tailcall]) k
| IOpen_chest (_, k) -> (next [@ocaml.tailcall]) k
| IHalt _ -> (return [@ocaml.tailcall]) ()
| ILog (_, _, _, k) -> (next [@ocaml.tailcall]) k
in
aux init i (fun accu -> accu)
type 'a ty_traverse = {
apply : 't. 'a -> 't ty -> 'a;
apply_comparable : 't. 'a -> 't comparable_ty -> 'a;
}
let (ty_traverse, comparable_ty_traverse) =
let rec aux :
type t ret accu.
accu ty_traverse -> accu -> t comparable_ty -> (accu -> ret) -> ret =
fun f accu ty continue ->
let accu = f.apply_comparable accu ty in
let next2 ty1 ty2 =
(aux [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(aux [@ocaml.tailcall]) f accu ty2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 =
(aux [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match ty with
| Unit_key | Int_key | Nat_key | Signature_key | String_key | Bytes_key
| Mutez_key | Key_hash_key | Key_key | Timestamp_key | Address_key
| Bool_key | Chain_id_key | Never_key ->
(return [@ocaml.tailcall]) ()
| Pair_key (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2
| Union_key (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2
| Option_key (ty, _) -> (next [@ocaml.tailcall]) ty
and aux' :
type ret t accu. accu ty_traverse -> accu -> t ty -> (accu -> ret) -> ret
=
fun f accu ty continue ->
let accu = f.apply accu ty in
match (ty : t ty) with
| Unit_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t | Mutez_t
| Key_hash_t | Key_t | Timestamp_t | Address_t | Bool_t
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Chain_id_t
| Never_t | Bls12_381_g1_t | Bls12_381_g2_t | Bls12_381_fr_t ->
(continue [@ocaml.tailcall]) accu
| Ticket_t (cty, _) -> aux f accu cty continue
| Chest_key_t | Chest_t -> (continue [@ocaml.tailcall]) accu
| Pair_t (ty1, ty2, _) -> (next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Union_t (ty1, ty2, _) ->
(next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Lambda_t (ty1, ty2, _) ->
(next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Option_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
| List_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
| Set_t (cty, _) -> (aux [@ocaml.tailcall]) f accu cty @@ continue
| Map_t (cty, ty1, _) ->
(aux [@ocaml.tailcall]) f accu cty @@ fun accu ->
(next' [@ocaml.tailcall]) f accu ty1 continue
| Big_map_t (cty, ty1, _) ->
(aux [@ocaml.tailcall]) f accu cty @@ fun accu ->
(next' [@ocaml.tailcall]) f accu ty1 continue
| Contract_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
and next2' :
type a b ret accu.
accu ty_traverse -> accu -> a ty -> b ty -> (accu -> ret) -> ret =
fun f accu ty1 ty2 continue ->
(aux' [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(aux' [@ocaml.tailcall]) f accu ty2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
and next' :
type a ret accu. accu ty_traverse -> accu -> a ty -> (accu -> ret) -> ret
=
fun f accu ty1 continue ->
(aux' [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
( (fun ty init f -> aux' f init ty (fun accu -> accu)),
fun cty init f -> aux f init cty (fun accu -> accu) )
type 'accu stack_ty_traverse = {
apply : 'ty 's. 'accu -> ('ty, 's) stack_ty -> 'accu;
}
let stack_ty_traverse (type a t) (sty : (a, t) stack_ty) init f =
let rec aux : type b u. 'accu -> (b, u) stack_ty -> 'accu =
fun accu sty ->
match sty with
| Bot_t -> f.apply accu sty
| Item_t (_, sty') -> aux (f.apply accu sty) sty'
in
aux init sty
type 'a value_traverse = {
apply : 't. 'a -> 't ty -> 't -> 'a;
apply_comparable : 't. 'a -> 't comparable_ty -> 't -> 'a;
}
let value_traverse (type t) (ty : (t ty, t comparable_ty) union) (x : t) init f
=
let rec aux : type ret t. 'accu -> t ty -> t -> ('accu -> ret) -> ret =
fun accu ty x continue ->
let accu = f.apply accu ty x in
let next2 ty1 ty2 x1 x2 =
(aux [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu ty2 x2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 x1 =
(aux [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
let rec on_list ty' accu = function
| [] -> (continue [@ocaml.tailcall]) accu
| x :: xs ->
(aux [@ocaml.tailcall]) accu ty' x @@ fun accu ->
(on_list [@ocaml.tailcall]) ty' accu xs
in
match ty with
| Unit_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t | Mutez_t
| Key_hash_t | Key_t | Timestamp_t | Address_t | Bool_t
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Chain_id_t
| Never_t | Bls12_381_g1_t | Bls12_381_g2_t | Bls12_381_fr_t | Chest_key_t
| Chest_t
| Lambda_t (_, _, _) ->
(return [@ocaml.tailcall]) ()
| Pair_t (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2 (fst x) (snd x)
| Union_t (ty1, ty2, _) -> (
match x with
| L l -> (next [@ocaml.tailcall]) ty1 l
| R r -> (next [@ocaml.tailcall]) ty2 r)
| Option_t (ty, _) -> (
match x with
| None -> return ()
| Some v -> (next [@ocaml.tailcall]) ty v)
| Ticket_t (cty, _) -> (aux' [@ocaml.tailcall]) accu cty x.contents continue
| List_t (ty', _) -> on_list ty' accu x.elements
| Map_t (kty, ty', _) ->
let (Map_tag (module M)) = x in
let bindings = M.OPS.fold (fun k v bs -> (k, v) :: bs) M.boxed [] in
on_bindings accu kty ty' continue bindings
| Set_t (ty', _) ->
let (Set_tag (module M)) = x in
let elements = M.OPS.fold (fun x s -> x :: s) M.boxed [] in
on_list' accu ty' elements continue
| Big_map_t (_, _, _) ->
(* For big maps, there is no obvious recursion scheme so we
delegate this case to the client. *)
(return [@ocaml.tailcall]) ()
| Contract_t (_, _) -> (return [@ocaml.tailcall]) ()
and on_list' :
type ret t. 'accu -> t comparable_ty -> t list -> ('accu -> ret) -> ret =
fun accu ty' xs continue ->
match xs with
| [] -> (continue [@ocaml.tailcall]) accu
| x :: xs ->
(aux' [@ocaml.tailcall]) accu ty' x @@ fun accu ->
(on_list' [@ocaml.tailcall]) accu ty' xs continue
and on_bindings :
type ret k v.
'accu -> k comparable_ty -> v ty -> ('accu -> ret) -> (k * v) list -> ret
=
fun accu kty ty' continue xs ->
match xs with
| [] -> (continue [@ocaml.tailcall]) accu
| (k, v) :: xs ->
(aux' [@ocaml.tailcall]) accu kty k @@ fun accu ->
(aux [@ocaml.tailcall]) accu ty' v @@ fun accu ->
(on_bindings [@ocaml.tailcall]) accu kty ty' continue xs
and aux' : type ret t. 'accu -> t comparable_ty -> t -> ('accu -> ret) -> ret
=
fun accu ty x continue ->
let accu = f.apply_comparable accu ty x in
let next2 ty1 ty2 x1 x2 =
(aux' [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(aux' [@ocaml.tailcall]) accu ty2 x2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 x1 =
(aux' [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match ty with
| Unit_key | Int_key | Nat_key | Signature_key | String_key | Bytes_key
| Mutez_key | Key_hash_key | Key_key | Timestamp_key | Address_key
| Bool_key | Chain_id_key | Never_key ->
(return [@ocaml.tailcall]) ()
| Pair_key (ty1, ty2, _) ->
(next2 [@ocaml.tailcall]) ty1 ty2 (fst x) (snd x)
| Union_key (ty1, ty2, _) -> (
match x with
| L l -> (next [@ocaml.tailcall]) ty1 l
| R r -> (next [@ocaml.tailcall]) ty2 r)
| Option_key (ty, _) -> (
match x with
| None -> (return [@ocaml.tailcall]) ()
| Some v -> (next [@ocaml.tailcall]) ty v)
in
match ty with
| L ty -> aux init ty x (fun accu -> accu)
| R cty -> aux' init cty x (fun accu -> accu)
[@@coq_axiom_with_reason "local mutually recursive definition not handled"]
let stack_top_ty : type a b s. (a, b * s) stack_ty -> a ty = function
| Item_t (ty, _) -> ty
| null | https://raw.githubusercontent.com/ocaml-multicore/tezos/e4fd21a1cb02d194b3162ab42d512b7c985ee8a9/src/proto_alpha/lib_protocol/script_typed_ir.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.
***************************************************************************
* The address calling this contract, as returned by SENDER.
* The address of the implicit account that initiated the chain of contract calls, as returned by SOURCE.
* The amount of the current transaction, as returned by AMOUNT.
* The balance of the contract as returned by BALANCE.
* The earliest time at which the current block could have been timestamped, as returned by NOW.
* The level of the current block, as returned by LEVEL.
Preliminary definitions.
Unsafe constructors, to be used only safely and inside this module
static-like check that all [t] values fit in a [mul_safe]
Same remark as for [Boxed_set_OPS]. (See below.)
This is an over-approximation of the value size in memory, in
bytes, of the contract's static part, that is its source
code. This includes the code of the contract as well as the code
of the views. The storage size is not taken into account by this
field as it has a dynamic size.
---- Instructions --------------------------------------------------------
Stack
-----
Pairs
-----
Options
-------
Unions
------
Lists
-----
Sets
----
Maps
----
Big maps
--------
Strings
-------
Bytes
-----
Timestamps
----------
Integers
--------
Even though `IAnd_nat` and `IAnd_int_nat` could be merged into a single
instruction from both the type and behavior point of views, their gas costs
differ too much (see `cost_N_IAnd_nat` and `cost_N_IAnd_int_nat` in
`Michelson_v1_gas.Cost_of.Generated_costs`), so we keep them separated.
Control
-------
Comparison
----------
Comparators
-----------
Protocol
--------
Internal control instructions
-----------------------------
---- Auxiliary types -----------------------------------------------------
For big maps, there is no obvious recursion scheme so we
delegate this case to the client. | Copyright ( c ) 2018 Dynamic Ledger Solutions , Inc. < >
Copyright ( c ) 2020 Metastate AG < >
Copyright ( c ) 2021 - 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 Alpha_context
open Script_int
The step function of the interpreter is parametrized by a bunch of values called the step constants .
These values are indeed constants during the call of a smart contract with the notable exception of
the IView instruction which modifies ` source ` , ` self ` , and ` amount ` and the KView_exit continuation
which restores them .
= = = = = = = = = = = = = = = = = = = = = =
The step function of the interpreter is parametrized by a bunch of values called the step constants.
These values are indeed constants during the call of a smart contract with the notable exception of
the IView instruction which modifies `source`, `self`, and `amount` and the KView_exit continuation
which restores them.
======================
*)
type step_constants = {
source : Contract.t;
payer : Contract.t;
self : Contract.t;
* The address of the contract being executed , as returned by SELF and SELF_ADDRESS .
Also used :
- as ticketer in TICKET
- as caller in VIEW , TRANSFER_TOKENS , and CREATE_CONTRACT
Also used:
- as ticketer in TICKET
- as caller in VIEW, TRANSFER_TOKENS, and CREATE_CONTRACT *)
amount : Tez.t;
chain_id : Chain_id.t;
* The chain i d of the chain , as returned by CHAIN_ID .
now : Script_timestamp.t;
level : Script_int.n Script_int.num;
}
type never = |
type address = {destination : Destination.t; entrypoint : Entrypoint.t}
module Script_signature = struct
type t = Signature_tag of signature [@@ocaml.unboxed]
let make s = Signature_tag s
let get (Signature_tag s) = s
let encoding =
Data_encoding.conv
(fun (Signature_tag x) -> x)
(fun x -> Signature_tag x)
Signature.encoding
let of_b58check_opt x = Option.map make (Signature.of_b58check_opt x)
let check ?watermark pub_key (Signature_tag s) bytes =
Signature.check ?watermark pub_key s bytes
let compare (Signature_tag x) (Signature_tag y) = Signature.compare x y
let size = Signature.size
end
type signature = Script_signature.t
type ('a, 'b) pair = 'a * 'b
type ('a, 'b) union = L of 'a | R of 'b
type operation = {
piop : packed_internal_operation;
lazy_storage_diff : Lazy_storage.diffs option;
}
module Script_chain_id = struct
type t = Chain_id_tag of Chain_id.t [@@ocaml.unboxed]
let make x = Chain_id_tag x
let compare (Chain_id_tag x) (Chain_id_tag y) = Chain_id.compare x y
let size = Chain_id.size
let encoding =
Data_encoding.conv (fun (Chain_id_tag x) -> x) make Chain_id.encoding
let to_b58check (Chain_id_tag x) = Chain_id.to_b58check x
let of_b58check_opt x = Option.map make (Chain_id.of_b58check_opt x)
end
module Script_bls = struct
module type S = sig
type t
type fr
val add : t -> t -> t
val mul : t -> fr -> t
val negate : t -> t
val of_bytes_opt : Bytes.t -> t option
val to_bytes : t -> Bytes.t
end
module Fr = struct
type t = Fr_tag of Bls12_381.Fr.t [@@ocaml.unboxed]
open Bls12_381.Fr
let add (Fr_tag x) (Fr_tag y) = Fr_tag (add x y)
let mul (Fr_tag x) (Fr_tag y) = Fr_tag (mul x y)
let negate (Fr_tag x) = Fr_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> Fr_tag x) (of_bytes_opt bytes)
let to_bytes (Fr_tag x) = to_bytes x
let of_z z = Fr_tag (of_z z)
let to_z (Fr_tag x) = to_z x
end
module G1 = struct
type t = G1_tag of Bls12_381.G1.t [@@ocaml.unboxed]
open Bls12_381.G1
let add (G1_tag x) (G1_tag y) = G1_tag (add x y)
let mul (G1_tag x) (Fr.Fr_tag y) = G1_tag (mul x y)
let negate (G1_tag x) = G1_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> G1_tag x) (of_bytes_opt bytes)
let to_bytes (G1_tag x) = to_bytes x
end
module G2 = struct
type t = G2_tag of Bls12_381.G2.t [@@ocaml.unboxed]
open Bls12_381.G2
let add (G2_tag x) (G2_tag y) = G2_tag (add x y)
let mul (G2_tag x) (Fr.Fr_tag y) = G2_tag (mul x y)
let negate (G2_tag x) = G2_tag (negate x)
let of_bytes_opt bytes = Option.map (fun x -> G2_tag x) (of_bytes_opt bytes)
let to_bytes (G2_tag x) = to_bytes x
end
let pairing_check l =
let l = List.map (fun (G1.G1_tag x, G2.G2_tag y) -> (x, y)) l in
Bls12_381.pairing_check l
end
module Script_timelock = struct
type chest_key = Chest_key_tag of Timelock.chest_key [@@ocaml.unboxed]
let make_chest_key chest_key = Chest_key_tag chest_key
let chest_key_encoding =
Data_encoding.conv
(fun (Chest_key_tag x) -> x)
(fun x -> Chest_key_tag x)
Timelock.chest_key_encoding
type chest = Chest_tag of Timelock.chest [@@ocaml.unboxed]
let make_chest chest = Chest_tag chest
let chest_encoding =
Data_encoding.conv
(fun (Chest_tag x) -> x)
(fun x -> Chest_tag x)
Timelock.chest_encoding
let open_chest (Chest_tag chest) (Chest_key_tag chest_key) ~time =
Timelock.open_chest chest chest_key ~time
let get_plaintext_size (Chest_tag x) = Timelock.get_plaintext_size x
end
type 'a ticket = {ticketer : Contract.t; contents : 'a; amount : n num}
module type TYPE_SIZE = sig
A type size represents the size of its type parameter .
This constraint is enforced inside this module ( Script_type_ir ) , hence there
should be no way to construct a type size outside of it .
It allows keeping type metadata and types non - private .
This module is here because we want three levels of visibility over this
code :
- inside this submodule , we have [ type ' a t = int ]
- outside of [ Script_typed_ir ] , the [ ' a t ] type is abstract and we have
the invariant that whenever [ x : ' a t ] we have that [ x ] is exactly
the size of [ ' a ] .
- in - between ( inside [ Script_typed_ir ] but outside the [ Type_size ]
submodule ) , the type is abstract but we have access to unsafe
constructors that can break the invariant .
This constraint is enforced inside this module (Script_type_ir), hence there
should be no way to construct a type size outside of it.
It allows keeping type metadata and types non-private.
This module is here because we want three levels of visibility over this
code:
- inside this submodule, we have [type 'a t = int]
- outside of [Script_typed_ir], the ['a t] type is abstract and we have
the invariant that whenever [x : 'a t] we have that [x] is exactly
the size of ['a].
- in-between (inside [Script_typed_ir] but outside the [Type_size]
submodule), the type is abstract but we have access to unsafe
constructors that can break the invariant.
*)
type 'a t
val merge :
error_details:'error_trace Script_tc_errors.error_details ->
'a t ->
'b t ->
('a t, 'error_trace) result
val to_int : 'a t -> Saturation_repr.mul_safe Saturation_repr.t
val one : _ t
val two : _ t
val three : _ t
val four : (_, _) pair option t
val compound1 : Script.location -> _ t -> _ t tzresult
val compound2 : Script.location -> _ t -> _ t -> _ t tzresult
end
module Type_size : TYPE_SIZE = struct
type 'a t = int
let () =
let (_ : Saturation_repr.mul_safe Saturation_repr.t) =
Saturation_repr.mul_safe_of_int_exn Constants.michelson_maximum_type_size
in
()
let to_int = Saturation_repr.mul_safe_of_int_exn
let one = 1
let two = 2
let three = 3
let four = 4
let merge :
type a b error_trace.
error_details:error_trace Script_tc_errors.error_details ->
a t ->
b t ->
(a t, error_trace) result =
fun ~error_details x y ->
if Compare.Int.(x = y) then ok x
else
Error
(match error_details with
| Fast -> Inconsistent_types_fast
| Informative ->
trace_of_error @@ Script_tc_errors.Inconsistent_type_sizes (x, y))
let of_int loc size =
let max_size = Constants.michelson_maximum_type_size in
if Compare.Int.(size <= max_size) then ok size
else error (Script_tc_errors.Type_too_large (loc, max_size))
let compound1 loc size = of_int loc (1 + size)
let compound2 loc size1 size2 = of_int loc (1 + size1 + size2)
end
type empty_cell = EmptyCell
type end_of_stack = empty_cell * empty_cell
type 'a ty_metadata = {size : 'a Type_size.t} [@@unboxed]
type _ comparable_ty =
| Unit_key : unit comparable_ty
| Never_key : never comparable_ty
| Int_key : z num comparable_ty
| Nat_key : n num comparable_ty
| Signature_key : signature comparable_ty
| String_key : Script_string.t comparable_ty
| Bytes_key : Bytes.t comparable_ty
| Mutez_key : Tez.t comparable_ty
| Bool_key : bool comparable_ty
| Key_hash_key : public_key_hash comparable_ty
| Key_key : public_key comparable_ty
| Timestamp_key : Script_timestamp.t comparable_ty
| Chain_id_key : Script_chain_id.t comparable_ty
| Address_key : address comparable_ty
| Pair_key :
'a comparable_ty * 'b comparable_ty * ('a, 'b) pair ty_metadata
-> ('a, 'b) pair comparable_ty
| Union_key :
'a comparable_ty * 'b comparable_ty * ('a, 'b) union ty_metadata
-> ('a, 'b) union comparable_ty
| Option_key :
'v comparable_ty * 'v option ty_metadata
-> 'v option comparable_ty
let meta_basic = {size = Type_size.one}
let comparable_ty_metadata : type a. a comparable_ty -> a ty_metadata = function
| Unit_key | Never_key | Int_key | Nat_key | Signature_key | String_key
| Bytes_key | Mutez_key | Bool_key | Key_hash_key | Key_key | Timestamp_key
| Chain_id_key | Address_key ->
meta_basic
| Pair_key (_, _, meta) -> meta
| Union_key (_, _, meta) -> meta
| Option_key (_, meta) -> meta
let comparable_ty_size t = (comparable_ty_metadata t).size
let unit_key = Unit_key
let never_key = Never_key
let int_key = Int_key
let nat_key = Nat_key
let signature_key = Signature_key
let string_key = String_key
let bytes_key = Bytes_key
let mutez_key = Mutez_key
let bool_key = Bool_key
let key_hash_key = Key_hash_key
let key_key = Key_key
let timestamp_key = Timestamp_key
let chain_id_key = Chain_id_key
let address_key = Address_key
let pair_key loc l r =
Type_size.compound2 loc (comparable_ty_size l) (comparable_ty_size r)
>|? fun size -> Pair_key (l, r, {size})
let pair_3_key loc l m r = pair_key loc m r >>? fun r -> pair_key loc l r
let union_key loc l r =
Type_size.compound2 loc (comparable_ty_size l) (comparable_ty_size r)
>|? fun size -> Union_key (l, r, {size})
let option_key loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Option_key (t, {size})
This signature contains the exact set of functions used in the
protocol . We do not include all [ Set . S ] because this would
increase the size of the first class modules used to represent
[ boxed_set ] .
Warning : for any change in this signature , there must be a
change in [ Script_typed_ir_size.value_size ] which updates
[ boxing_space ] in the case for sets .
This signature contains the exact set of functions used in the
protocol. We do not include all [Set.S] because this would
increase the size of the first class modules used to represent
[boxed_set].
Warning: for any change in this signature, there must be a
change in [Script_typed_ir_size.value_size] which updates
[boxing_space] in the case for sets.
*)
module type Boxed_set_OPS = sig
type t
type elt
val empty : t
val add : elt -> t -> t
val mem : elt -> t -> bool
val remove : elt -> t -> t
val fold : (elt -> 'a -> 'a) -> t -> 'a -> 'a
end
module type Boxed_set = sig
type elt
val elt_ty : elt comparable_ty
module OPS : Boxed_set_OPS with type elt = elt
val boxed : OPS.t
val size : int
end
type 'elt set = Set_tag of (module Boxed_set with type elt = 'elt)
[@@ocaml.unboxed]
module type Boxed_map_OPS = sig
type t
type key
type value
val empty : t
val add : key -> value -> t -> t
val remove : key -> t -> t
val find : key -> t -> value option
val fold : (key -> value -> 'a -> 'a) -> t -> 'a -> 'a
end
module type Boxed_map = sig
type key
type value
val key_ty : key comparable_ty
module OPS : Boxed_map_OPS with type key = key and type value = value
val boxed : OPS.t
val size : int
end
type ('key, 'value) map =
| Map_tag of (module Boxed_map with type key = 'key and type value = 'value)
[@@ocaml.unboxed]
module Big_map_overlay = Map.Make (struct
type t = Script_expr_hash.t
let compare = Script_expr_hash.compare
end)
type ('key, 'value) big_map_overlay = {
map : ('key * 'value option) Big_map_overlay.t;
size : int;
}
type 'elt boxed_list = {elements : 'elt list; length : int}
module SMap = Map.Make (Script_string)
type view = {
input_ty : Script.node;
output_ty : Script.node;
view_code : Script.node;
}
type 'arg entrypoints = {
name : Entrypoint.t option;
nested : 'arg nested_entrypoints;
}
and 'arg nested_entrypoints =
| Entrypoints_Union : {
left : 'l entrypoints;
right : 'r entrypoints;
}
-> ('l, 'r) union nested_entrypoints
| Entrypoints_None : _ nested_entrypoints
let no_entrypoints = {name = None; nested = Entrypoints_None}
type ('arg, 'storage) script = {
code : (('arg, 'storage) pair, (operation boxed_list, 'storage) pair) lambda;
arg_type : 'arg ty;
storage : 'storage;
storage_type : 'storage ty;
views : view SMap.t;
entrypoints : 'arg entrypoints;
code_size : Cache_memory_helpers.sint;
}
and ('before_top, 'before, 'result_top, 'result) kinstr =
| IDrop :
('a, 'b * 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDup :
('a, 's) kinfo * ('a, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISwap :
('a, 'b * 's) kinfo * ('b, 'a * 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IConst :
('a, 's) kinfo * 'ty * ('ty, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ICons_pair :
('a, 'b * 's) kinfo * ('a * 'b, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| ICar :
('a * 'b, 's) kinfo * ('a, 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
| ICdr :
('a * 'b, 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
| IUnpair :
('a * 'b, 's) kinfo * ('a, 'b * 's, 'r, 'f) kinstr
-> ('a * 'b, 's, 'r, 'f) kinstr
| ICons_some :
('v, 's) kinfo * ('v option, 's, 'r, 'f) kinstr
-> ('v, 's, 'r, 'f) kinstr
| ICons_none :
('a, 's) kinfo * ('b option, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IIf_none : {
kinfo : ('a option, 'b * 's) kinfo;
branch_if_none : ('b, 's, 'c, 't) kinstr;
branch_if_some : ('a, 'b * 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> ('a option, 'b * 's, 'r, 'f) kinstr
| IOpt_map : {
kinfo : ('a option, 's) kinfo;
body : ('a, 's, 'b, 's) kinstr;
k : ('b option, 's, 'c, 't) kinstr;
}
-> ('a option, 's, 'c, 't) kinstr
| ICons_left :
('a, 's) kinfo * (('a, 'b) union, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ICons_right :
('b, 's) kinfo * (('a, 'b) union, 's, 'r, 'f) kinstr
-> ('b, 's, 'r, 'f) kinstr
| IIf_left : {
kinfo : (('a, 'b) union, 's) kinfo;
branch_if_left : ('a, 's, 'c, 't) kinstr;
branch_if_right : ('b, 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> (('a, 'b) union, 's, 'r, 'f) kinstr
| ICons_list :
('a, 'a boxed_list * 's) kinfo * ('a boxed_list, 's, 'r, 'f) kinstr
-> ('a, 'a boxed_list * 's, 'r, 'f) kinstr
| INil :
('a, 's) kinfo * ('b boxed_list, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IIf_cons : {
kinfo : ('a boxed_list, 'b * 's) kinfo;
branch_if_cons : ('a, 'a boxed_list * ('b * 's), 'c, 't) kinstr;
branch_if_nil : ('b, 's, 'c, 't) kinstr;
k : ('c, 't, 'r, 'f) kinstr;
}
-> ('a boxed_list, 'b * 's, 'r, 'f) kinstr
| IList_map :
('a boxed_list, 'c * 's) kinfo
* ('a, 'c * 's, 'b, 'c * 's) kinstr
* ('b boxed_list, 'c * 's, 'r, 'f) kinstr
-> ('a boxed_list, 'c * 's, 'r, 'f) kinstr
| IList_iter :
('a boxed_list, 'b * 's) kinfo
* ('a, 'b * 's, 'b, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> ('a boxed_list, 'b * 's, 'r, 'f) kinstr
| IList_size :
('a boxed_list, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> ('a boxed_list, 's, 'r, 'f) kinstr
| IEmpty_set :
('a, 's) kinfo * 'b comparable_ty * ('b set, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISet_iter :
('a set, 'b * 's) kinfo
* ('a, 'b * 's, 'b, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> ('a set, 'b * 's, 'r, 'f) kinstr
| ISet_mem :
('a, 'a set * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, 'a set * 's, 'r, 'f) kinstr
| ISet_update :
('a, bool * ('a set * 's)) kinfo * ('a set, 's, 'r, 'f) kinstr
-> ('a, bool * ('a set * 's), 'r, 'f) kinstr
| ISet_size :
('a set, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> ('a set, 's, 'r, 'f) kinstr
| IEmpty_map :
('a, 's) kinfo * 'b comparable_ty * (('b, 'c) map, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IMap_map :
(('a, 'b) map, 'd * 's) kinfo
* ('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* (('a, 'c) map, 'd * 's, 'r, 'f) kinstr
-> (('a, 'b) map, 'd * 's, 'r, 'f) kinstr
| IMap_iter :
(('a, 'b) map, 'c * 's) kinfo
* ('a * 'b, 'c * 's, 'c, 's) kinstr
* ('c, 's, 'r, 'f) kinstr
-> (('a, 'b) map, 'c * 's, 'r, 'f) kinstr
| IMap_mem :
('a, ('a, 'b) map * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) map * 's, 'r, 'f) kinstr
| IMap_get :
('a, ('a, 'b) map * 's) kinfo * ('b option, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) map * 's, 'r, 'f) kinstr
| IMap_update :
('a, 'b option * (('a, 'b) map * 's)) kinfo
* (('a, 'b) map, 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) map * 's), 'r, 'f) kinstr
| IMap_get_and_update :
('a, 'b option * (('a, 'b) map * 's)) kinfo
* ('b option, ('a, 'b) map * 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) map * 's), 'r, 'f) kinstr
| IMap_size :
(('a, 'b) map, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (('a, 'b) map, 's, 'r, 'f) kinstr
| IEmpty_big_map :
('a, 's) kinfo
* 'b comparable_ty
* 'c ty
* (('b, 'c) big_map, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IBig_map_mem :
('a, ('a, 'b) big_map * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) big_map * 's, 'r, 'f) kinstr
| IBig_map_get :
('a, ('a, 'b) big_map * 's) kinfo * ('b option, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) big_map * 's, 'r, 'f) kinstr
| IBig_map_update :
('a, 'b option * (('a, 'b) big_map * 's)) kinfo
* (('a, 'b) big_map, 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) big_map * 's), 'r, 'f) kinstr
| IBig_map_get_and_update :
('a, 'b option * (('a, 'b) big_map * 's)) kinfo
* ('b option, ('a, 'b) big_map * 's, 'r, 'f) kinstr
-> ('a, 'b option * (('a, 'b) big_map * 's), 'r, 'f) kinstr
| IConcat_string :
(Script_string.t boxed_list, 's) kinfo
* (Script_string.t, 's, 'r, 'f) kinstr
-> (Script_string.t boxed_list, 's, 'r, 'f) kinstr
| IConcat_string_pair :
(Script_string.t, Script_string.t * 's) kinfo
* (Script_string.t, 's, 'r, 'f) kinstr
-> (Script_string.t, Script_string.t * 's, 'r, 'f) kinstr
| ISlice_string :
(n num, n num * (Script_string.t * 's)) kinfo
* (Script_string.t option, 's, 'r, 'f) kinstr
-> (n num, n num * (Script_string.t * 's), 'r, 'f) kinstr
| IString_size :
(Script_string.t, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (Script_string.t, 's, 'r, 'f) kinstr
| IConcat_bytes :
(bytes boxed_list, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes boxed_list, 's, 'r, 'f) kinstr
| IConcat_bytes_pair :
(bytes, bytes * 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, bytes * 's, 'r, 'f) kinstr
| ISlice_bytes :
(n num, n num * (bytes * 's)) kinfo * (bytes option, 's, 'r, 'f) kinstr
-> (n num, n num * (bytes * 's), 'r, 'f) kinstr
| IBytes_size :
(bytes, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| IAdd_seconds_to_timestamp :
(z num, Script_timestamp.t * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (z num, Script_timestamp.t * 's, 'r, 'f) kinstr
| IAdd_timestamp_to_seconds :
(Script_timestamp.t, z num * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, z num * 's, 'r, 'f) kinstr
| ISub_timestamp_seconds :
(Script_timestamp.t, z num * 's) kinfo
* (Script_timestamp.t, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, z num * 's, 'r, 'f) kinstr
| IDiff_timestamps :
(Script_timestamp.t, Script_timestamp.t * 's) kinfo
* (z num, 's, 'r, 'f) kinstr
-> (Script_timestamp.t, Script_timestamp.t * 's, 'r, 'f) kinstr
Tez
---
Tez
---
*)
| IAdd_tez :
(Tez.t, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| ISub_tez :
(Tez.t, Tez.t * 's) kinfo * (Tez.t option, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| ISub_tez_legacy :
(Tez.t, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
| IMul_teznat :
(Tez.t, n num * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (Tez.t, n num * 's, 'r, 'f) kinstr
| IMul_nattez :
(n num, Tez.t * 's) kinfo * (Tez.t, 's, 'r, 'f) kinstr
-> (n num, Tez.t * 's, 'r, 'f) kinstr
| IEdiv_teznat :
(Tez.t, n num * 's) kinfo
* ((Tez.t, Tez.t) pair option, 's, 'r, 'f) kinstr
-> (Tez.t, n num * 's, 'r, 'f) kinstr
| IEdiv_tez :
(Tez.t, Tez.t * 's) kinfo
* ((n num, Tez.t) pair option, 's, 'r, 'f) kinstr
-> (Tez.t, Tez.t * 's, 'r, 'f) kinstr
Booleans
--------
Booleans
--------
*)
| IOr :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| IAnd :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| IXor :
(bool, bool * 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, bool * 's, 'r, 'f) kinstr
| INot :
(bool, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (bool, 's, 'r, 'f) kinstr
| IIs_nat :
(z num, 's) kinfo * (n num option, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| INeg :
('a num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 's, 'r, 'f) kinstr
| IAbs_int :
(z num, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IInt_nat :
(n num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> (n num, 's, 'r, 'f) kinstr
| IAdd_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IAdd_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| ISub_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IMul_int :
('a num, 'b num * 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IMul_nat :
(n num, 'a num * 's) kinfo * ('a num, 's, 'r, 'f) kinstr
-> (n num, 'a num * 's, 'r, 'f) kinstr
| IEdiv_int :
('a num, 'b num * 's) kinfo
* ((z num, n num) pair option, 's, 'r, 'f) kinstr
-> ('a num, 'b num * 's, 'r, 'f) kinstr
| IEdiv_nat :
(n num, 'a num * 's) kinfo
* (('a num, n num) pair option, 's, 'r, 'f) kinstr
-> (n num, 'a num * 's, 'r, 'f) kinstr
| ILsl_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| ILsr_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| IOr_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| IAnd_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| IAnd_int_nat :
(z num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (z num, n num * 's, 'r, 'f) kinstr
| IXor_nat :
(n num, n num * 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (n num, n num * 's, 'r, 'f) kinstr
| INot_int :
('a num, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> ('a num, 's, 'r, 'f) kinstr
| IIf : {
kinfo : (bool, 'a * 's) kinfo;
branch_if_true : ('a, 's, 'b, 'u) kinstr;
branch_if_false : ('a, 's, 'b, 'u) kinstr;
k : ('b, 'u, 'r, 'f) kinstr;
}
-> (bool, 'a * 's, 'r, 'f) kinstr
| ILoop :
(bool, 'a * 's) kinfo
* ('a, 's, bool, 'a * 's) kinstr
* ('a, 's, 'r, 'f) kinstr
-> (bool, 'a * 's, 'r, 'f) kinstr
| ILoop_left :
(('a, 'b) union, 's) kinfo
* ('a, 's, ('a, 'b) union, 's) kinstr
* ('b, 's, 'r, 'f) kinstr
-> (('a, 'b) union, 's, 'r, 'f) kinstr
| IDip :
('a, 'b * 's) kinfo
* ('b, 's, 'c, 't) kinstr
* ('a, 'c * 't, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IExec :
('a, ('a, 'b) lambda * 's) kinfo * ('b, 's, 'r, 'f) kinstr
-> ('a, ('a, 'b) lambda * 's, 'r, 'f) kinstr
| IApply :
('a, ('a * 'b, 'c) lambda * 's) kinfo
* 'a ty
* (('b, 'c) lambda, 's, 'r, 'f) kinstr
-> ('a, ('a * 'b, 'c) lambda * 's, 'r, 'f) kinstr
| ILambda :
('a, 's) kinfo
* ('b, 'c) lambda
* (('b, 'c) lambda, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IFailwith :
('a, 's) kinfo * Script.location * 'a ty
-> ('a, 's, 'r, 'f) kinstr
| ICompare :
('a, 'a * 's) kinfo * 'a comparable_ty * (z num, 's, 'r, 'f) kinstr
-> ('a, 'a * 's, 'r, 'f) kinstr
| IEq :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| INeq :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| ILt :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IGt :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| ILe :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IGe :
(z num, 's) kinfo * (bool, 's, 'r, 'f) kinstr
-> (z num, 's, 'r, 'f) kinstr
| IAddress :
('a typed_contract, 's) kinfo * (address, 's, 'r, 'f) kinstr
-> ('a typed_contract, 's, 'r, 'f) kinstr
| IContract :
(address, 's) kinfo
* 'a ty
* Entrypoint.t
* ('a typed_contract option, 's, 'r, 'f) kinstr
-> (address, 's, 'r, 'f) kinstr
| IView :
('a, address * 's) kinfo
* ('a, 'b) view_signature
* ('b option, 's, 'r, 'f) kinstr
-> ('a, address * 's, 'r, 'f) kinstr
| ITransfer_tokens :
('a, Tez.t * ('a typed_contract * 's)) kinfo
* (operation, 's, 'r, 'f) kinstr
-> ('a, Tez.t * ('a typed_contract * 's), 'r, 'f) kinstr
| IImplicit_account :
(public_key_hash, 's) kinfo * (unit typed_contract, 's, 'r, 'f) kinstr
-> (public_key_hash, 's, 'r, 'f) kinstr
| ICreate_contract : {
kinfo : (public_key_hash option, Tez.t * ('a * 's)) kinfo;
storage_type : 'a ty;
arg_type : 'b ty;
lambda : ('b * 'a, operation boxed_list * 'a) lambda;
views : view SMap.t;
entrypoints : 'b entrypoints;
k : (operation, address * 's, 'r, 'f) kinstr;
}
-> (public_key_hash option, Tez.t * ('a * 's), 'r, 'f) kinstr
| ISet_delegate :
(public_key_hash option, 's) kinfo * (operation, 's, 'r, 'f) kinstr
-> (public_key_hash option, 's, 'r, 'f) kinstr
| INow :
('a, 's) kinfo * (Script_timestamp.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IBalance :
('a, 's) kinfo * (Tez.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ILevel :
('a, 's) kinfo * (n num, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ICheck_signature :
(public_key, signature * (bytes * 's)) kinfo * (bool, 's, 'r, 'f) kinstr
-> (public_key, signature * (bytes * 's), 'r, 'f) kinstr
| IHash_key :
(public_key, 's) kinfo * (public_key_hash, 's, 'r, 'f) kinstr
-> (public_key, 's, 'r, 'f) kinstr
| IPack :
('a, 's) kinfo * 'a ty * (bytes, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IUnpack :
(bytes, 's) kinfo * 'a ty * ('a option, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| IBlake2b :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha256 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha512 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISource :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISender :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISelf :
('a, 's) kinfo
* 'b ty
* Entrypoint.t
* ('b typed_contract, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISelf_address :
('a, 's) kinfo * (address, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IAmount :
('a, 's) kinfo * (Tez.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ISapling_empty_state :
('a, 's) kinfo
* Sapling.Memo_size.t
* (Sapling.state, 'a * 's, 'b, 'f) kinstr
-> ('a, 's, 'b, 'f) kinstr
| ISapling_verify_update :
(Sapling.transaction, Sapling.state * 's) kinfo
* ((z num, Sapling.state) pair option, 's, 'r, 'f) kinstr
-> (Sapling.transaction, Sapling.state * 's, 'r, 'f) kinstr
| IDig :
('a, 's) kinfo
* int
* ('b, 'c * 't, 'c, 't, 'a, 's, 'd, 'u) stack_prefix_preservation_witness
* ('b, 'd * 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IDug :
('a, 'b * 's) kinfo
* int
* ('c, 't, 'a, 'c * 't, 'b, 's, 'd, 'u) stack_prefix_preservation_witness
* ('d, 'u, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDipn :
('a, 's) kinfo
* int
* ('c, 't, 'd, 'v, 'a, 's, 'b, 'u) stack_prefix_preservation_witness
* ('c, 't, 'd, 'v) kinstr
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IDropn :
('a, 's) kinfo
* int
* ('b, 'u, 'b, 'u, 'a, 's, 'a, 's) stack_prefix_preservation_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IChainId :
('a, 's) kinfo * (Script_chain_id.t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| INever : (never, 's) kinfo -> (never, 's, 'r, 'f) kinstr
| IVoting_power :
(public_key_hash, 's) kinfo * (n num, 's, 'r, 'f) kinstr
-> (public_key_hash, 's, 'r, 'f) kinstr
| ITotal_voting_power :
('a, 's) kinfo * (n num, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IKeccak :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| ISha3 :
(bytes, 's) kinfo * (bytes, 's, 'r, 'f) kinstr
-> (bytes, 's, 'r, 'f) kinstr
| IAdd_bls12_381_g1 :
(Script_bls.G1.t, Script_bls.G1.t * 's) kinfo
* (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, Script_bls.G1.t * 's, 'r, 'f) kinstr
| IAdd_bls12_381_g2 :
(Script_bls.G2.t, Script_bls.G2.t * 's) kinfo
* (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, Script_bls.G2.t * 's, 'r, 'f) kinstr
| IAdd_bls12_381_fr :
(Script_bls.Fr.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_g1 :
(Script_bls.G1.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_g2 :
(Script_bls.G2.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_fr :
(Script_bls.Fr.t, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IMul_bls12_381_z_fr :
(Script_bls.Fr.t, 'a num * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 'a num * 's, 'r, 'f) kinstr
| IMul_bls12_381_fr_z :
('a num, Script_bls.Fr.t * 's) kinfo
* (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> ('a num, Script_bls.Fr.t * 's, 'r, 'f) kinstr
| IInt_bls12_381_fr :
(Script_bls.Fr.t, 's) kinfo * (z num, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_g1 :
(Script_bls.G1.t, 's) kinfo * (Script_bls.G1.t, 's, 'r, 'f) kinstr
-> (Script_bls.G1.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_g2 :
(Script_bls.G2.t, 's) kinfo * (Script_bls.G2.t, 's, 'r, 'f) kinstr
-> (Script_bls.G2.t, 's, 'r, 'f) kinstr
| INeg_bls12_381_fr :
(Script_bls.Fr.t, 's) kinfo * (Script_bls.Fr.t, 's, 'r, 'f) kinstr
-> (Script_bls.Fr.t, 's, 'r, 'f) kinstr
| IPairing_check_bls12_381 :
((Script_bls.G1.t, Script_bls.G2.t) pair boxed_list, 's) kinfo
* (bool, 's, 'r, 'f) kinstr
-> ((Script_bls.G1.t, Script_bls.G2.t) pair boxed_list, 's, 'r, 'f) kinstr
| IComb :
('a, 's) kinfo
* int
* ('a * 's, 'b * 'u) comb_gadt_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IUncomb :
('a, 's) kinfo
* int
* ('a * 's, 'b * 'u) uncomb_gadt_witness
* ('b, 'u, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| IComb_get :
('t, 's) kinfo
* int
* ('t, 'v) comb_get_gadt_witness
* ('v, 's, 'r, 'f) kinstr
-> ('t, 's, 'r, 'f) kinstr
| IComb_set :
('a, 'b * 's) kinfo
* int
* ('a, 'b, 'c) comb_set_gadt_witness
* ('c, 's, 'r, 'f) kinstr
-> ('a, 'b * 's, 'r, 'f) kinstr
| IDup_n :
('a, 's) kinfo
* int
* ('a * 's, 't) dup_n_gadt_witness
* ('t, 'a * 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
| ITicket :
('a, n num * 's) kinfo * ('a ticket, 's, 'r, 'f) kinstr
-> ('a, n num * 's, 'r, 'f) kinstr
| IRead_ticket :
('a ticket, 's) kinfo
* (address * ('a * n num), 'a ticket * 's, 'r, 'f) kinstr
-> ('a ticket, 's, 'r, 'f) kinstr
| ISplit_ticket :
('a ticket, (n num * n num) * 's) kinfo
* (('a ticket * 'a ticket) option, 's, 'r, 'f) kinstr
-> ('a ticket, (n num * n num) * 's, 'r, 'f) kinstr
| IJoin_tickets :
('a ticket * 'a ticket, 's) kinfo
* 'a comparable_ty
* ('a ticket option, 's, 'r, 'f) kinstr
-> ('a ticket * 'a ticket, 's, 'r, 'f) kinstr
| IOpen_chest :
(Script_timelock.chest_key, Script_timelock.chest * (n num * 's)) kinfo
* ((bytes, bool) union, 's, 'r, 'f) kinstr
-> ( Script_timelock.chest_key,
Script_timelock.chest * (n num * 's),
'r,
'f )
kinstr
| IHalt : ('a, 's) kinfo -> ('a, 's, 'a, 's) kinstr
| ILog :
('a, 's) kinfo * logging_event * logger * ('a, 's, 'r, 'f) kinstr
-> ('a, 's, 'r, 'f) kinstr
and logging_event =
| LogEntry : logging_event
| LogExit : ('b, 'u) kinfo -> logging_event
and ('arg, 'ret) lambda =
| Lam :
('arg, end_of_stack, 'ret, end_of_stack) kdescr * Script.node
-> ('arg, 'ret) lambda
[@@coq_force_gadt]
and 'arg typed_contract = {arg_ty : 'arg ty; address : address}
and (_, _, _, _) continuation =
| KNil : ('r, 'f, 'r, 'f) continuation
| KCons :
('a, 's, 'b, 't) kinstr * ('b, 't, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KReturn :
's * ('a, 's, 'r, 'f) continuation
-> ('a, end_of_stack, 'r, 'f) continuation
| KMap_head :
('a -> 'b) * ('b, 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KUndip :
'b * ('b, 'a * 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KLoop_in :
('a, 's, bool, 'a * 's) kinstr * ('a, 's, 'r, 'f) continuation
-> (bool, 'a * 's, 'r, 'f) continuation
| KLoop_in_left :
('a, 's, ('a, 'b) union, 's) kinstr * ('b, 's, 'r, 'f) continuation
-> (('a, 'b) union, 's, 'r, 'f) continuation
| KIter :
('a, 'b * 's, 'b, 's) kinstr * 'a list * ('b, 's, 'r, 'f) continuation
-> ('b, 's, 'r, 'f) continuation
| KList_enter_body :
('a, 'c * 's, 'b, 'c * 's) kinstr
* 'a list
* 'b list
* int
* ('b boxed_list, 'c * 's, 'r, 'f) continuation
-> ('c, 's, 'r, 'f) continuation
| KList_exit_body :
('a, 'c * 's, 'b, 'c * 's) kinstr
* 'a list
* 'b list
* int
* ('b boxed_list, 'c * 's, 'r, 'f) continuation
-> ('b, 'c * 's, 'r, 'f) continuation
| KMap_enter_body :
('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* ('a * 'b) list
* ('a, 'c) map
* (('a, 'c) map, 'd * 's, 'r, 'f) continuation
-> ('d, 's, 'r, 'f) continuation
| KMap_exit_body :
('a * 'b, 'd * 's, 'c, 'd * 's) kinstr
* ('a * 'b) list
* ('a, 'c) map
* 'a
* (('a, 'c) map, 'd * 's, 'r, 'f) continuation
-> ('c, 'd * 's, 'r, 'f) continuation
| KView_exit :
step_constants * ('a, 's, 'r, 'f) continuation
-> ('a, 's, 'r, 'f) continuation
| KLog :
('a, 's, 'r, 'f) continuation * logger
-> ('a, 's, 'r, 'f) continuation
and ('a, 's, 'b, 'f, 'c, 'u) logging_function =
('a, 's, 'b, 'f) kinstr ->
context ->
Script.location ->
('c, 'u) stack_ty ->
'c * 'u ->
unit
and execution_trace = (Script.location * Gas.t * Script.expr list) list
and logger = {
log_interp : 'a 's 'b 'f 'c 'u. ('a, 's, 'b, 'f, 'c, 'u) logging_function;
log_entry : 'a 's 'b 'f. ('a, 's, 'b, 'f, 'a, 's) logging_function;
log_control : 'a 's 'b 'f. ('a, 's, 'b, 'f) continuation -> unit;
log_exit : 'a 's 'b 'f 'c 'u. ('a, 's, 'b, 'f, 'c, 'u) logging_function;
get_log : unit -> execution_trace option tzresult Lwt.t;
}
and 'ty ty =
| Unit_t : unit ty
| Int_t : z num ty
| Nat_t : n num ty
| Signature_t : signature ty
| String_t : Script_string.t ty
| Bytes_t : bytes ty
| Mutez_t : Tez.t ty
| Key_hash_t : public_key_hash ty
| Key_t : public_key ty
| Timestamp_t : Script_timestamp.t ty
| Address_t : address ty
| Bool_t : bool ty
| Pair_t : 'a ty * 'b ty * ('a, 'b) pair ty_metadata -> ('a, 'b) pair ty
| Union_t : 'a ty * 'b ty * ('a, 'b) union ty_metadata -> ('a, 'b) union ty
| Lambda_t :
'arg ty * 'ret ty * ('arg, 'ret) lambda ty_metadata
-> ('arg, 'ret) lambda ty
| Option_t : 'v ty * 'v option ty_metadata -> 'v option ty
| List_t : 'v ty * 'v boxed_list ty_metadata -> 'v boxed_list ty
| Set_t : 'v comparable_ty * 'v set ty_metadata -> 'v set ty
| Map_t :
'k comparable_ty * 'v ty * ('k, 'v) map ty_metadata
-> ('k, 'v) map ty
| Big_map_t :
'k comparable_ty * 'v ty * ('k, 'v) big_map ty_metadata
-> ('k, 'v) big_map ty
| Contract_t :
'arg ty * 'arg typed_contract ty_metadata
-> 'arg typed_contract ty
| Sapling_transaction_t : Sapling.Memo_size.t -> Sapling.transaction ty
| Sapling_state_t : Sapling.Memo_size.t -> Sapling.state ty
| Operation_t : operation ty
| Chain_id_t : Script_chain_id.t ty
| Never_t : never ty
| Bls12_381_g1_t : Script_bls.G1.t ty
| Bls12_381_g2_t : Script_bls.G2.t ty
| Bls12_381_fr_t : Script_bls.Fr.t ty
| Ticket_t : 'a comparable_ty * 'a ticket ty_metadata -> 'a ticket ty
| Chest_key_t : Script_timelock.chest_key ty
| Chest_t : Script_timelock.chest ty
and ('top_ty, 'resty) stack_ty =
| Item_t : 'ty ty * ('ty2, 'rest) stack_ty -> ('ty, 'ty2 * 'rest) stack_ty
| Bot_t : (empty_cell, empty_cell) stack_ty
and ('key, 'value) big_map = {
id : Big_map.Id.t option;
diff : ('key, 'value) big_map_overlay;
key_type : 'key comparable_ty;
value_type : 'value ty;
}
and ('a, 's, 'r, 'f) kdescr = {
kloc : Script.location;
kbef : ('a, 's) stack_ty;
kaft : ('r, 'f) stack_ty;
kinstr : ('a, 's, 'r, 'f) kinstr;
}
and ('a, 's) kinfo = {iloc : Script.location; kstack_ty : ('a, 's) stack_ty}
and (_, _, _, _, _, _, _, _) stack_prefix_preservation_witness =
| KPrefix :
('y, 'u) kinfo
* ('c, 'v, 'd, 'w, 'x, 's, 'y, 'u) stack_prefix_preservation_witness
-> ( 'c,
'v,
'd,
'w,
'a,
'x * 's,
'a,
'y * 'u )
stack_prefix_preservation_witness
| KRest : ('a, 's, 'b, 'u, 'a, 's, 'b, 'u) stack_prefix_preservation_witness
and ('before, 'after) comb_gadt_witness =
| Comb_one : ('a * ('x * 'before), 'a * ('x * 'before)) comb_gadt_witness
| Comb_succ :
('before, 'b * 'after) comb_gadt_witness
-> ('a * 'before, ('a * 'b) * 'after) comb_gadt_witness
and ('before, 'after) uncomb_gadt_witness =
| Uncomb_one : ('rest, 'rest) uncomb_gadt_witness
| Uncomb_succ :
('b * 'before, 'after) uncomb_gadt_witness
-> (('a * 'b) * 'before, 'a * 'after) uncomb_gadt_witness
and ('before, 'after) comb_get_gadt_witness =
| Comb_get_zero : ('b, 'b) comb_get_gadt_witness
| Comb_get_one : ('a * 'b, 'a) comb_get_gadt_witness
| Comb_get_plus_two :
('before, 'after) comb_get_gadt_witness
-> ('a * 'before, 'after) comb_get_gadt_witness
and ('value, 'before, 'after) comb_set_gadt_witness =
| Comb_set_zero : ('value, _, 'value) comb_set_gadt_witness
| Comb_set_one : ('value, 'hd * 'tl, 'value * 'tl) comb_set_gadt_witness
| Comb_set_plus_two :
('value, 'before, 'after) comb_set_gadt_witness
-> ('value, 'a * 'before, 'a * 'after) comb_set_gadt_witness
[@@coq_force_gadt]
and (_, _) dup_n_gadt_witness =
| Dup_n_zero : ('a * 'rest, 'a) dup_n_gadt_witness
| Dup_n_succ :
('stack, 'b) dup_n_gadt_witness
-> ('a * 'stack, 'b) dup_n_gadt_witness
and ('a, 'b) view_signature =
| View_signature of {
name : Script_string.t;
input_ty : 'a ty;
output_ty : 'b ty;
}
let kinfo_of_kinstr : type a s b f. (a, s, b, f) kinstr -> (a, s) kinfo =
fun i ->
match i with
| IDrop (kinfo, _) -> kinfo
| IDup (kinfo, _) -> kinfo
| ISwap (kinfo, _) -> kinfo
| IConst (kinfo, _, _) -> kinfo
| ICons_pair (kinfo, _) -> kinfo
| ICar (kinfo, _) -> kinfo
| ICdr (kinfo, _) -> kinfo
| IUnpair (kinfo, _) -> kinfo
| ICons_some (kinfo, _) -> kinfo
| ICons_none (kinfo, _) -> kinfo
| IIf_none {kinfo; _} -> kinfo
| IOpt_map {kinfo; _} -> kinfo
| ICons_left (kinfo, _) -> kinfo
| ICons_right (kinfo, _) -> kinfo
| IIf_left {kinfo; _} -> kinfo
| ICons_list (kinfo, _) -> kinfo
| INil (kinfo, _) -> kinfo
| IIf_cons {kinfo; _} -> kinfo
| IList_map (kinfo, _, _) -> kinfo
| IList_iter (kinfo, _, _) -> kinfo
| IList_size (kinfo, _) -> kinfo
| IEmpty_set (kinfo, _, _) -> kinfo
| ISet_iter (kinfo, _, _) -> kinfo
| ISet_mem (kinfo, _) -> kinfo
| ISet_update (kinfo, _) -> kinfo
| ISet_size (kinfo, _) -> kinfo
| IEmpty_map (kinfo, _, _) -> kinfo
| IMap_map (kinfo, _, _) -> kinfo
| IMap_iter (kinfo, _, _) -> kinfo
| IMap_mem (kinfo, _) -> kinfo
| IMap_get (kinfo, _) -> kinfo
| IMap_update (kinfo, _) -> kinfo
| IMap_get_and_update (kinfo, _) -> kinfo
| IMap_size (kinfo, _) -> kinfo
| IEmpty_big_map (kinfo, _, _, _) -> kinfo
| IBig_map_mem (kinfo, _) -> kinfo
| IBig_map_get (kinfo, _) -> kinfo
| IBig_map_update (kinfo, _) -> kinfo
| IBig_map_get_and_update (kinfo, _) -> kinfo
| IConcat_string (kinfo, _) -> kinfo
| IConcat_string_pair (kinfo, _) -> kinfo
| ISlice_string (kinfo, _) -> kinfo
| IString_size (kinfo, _) -> kinfo
| IConcat_bytes (kinfo, _) -> kinfo
| IConcat_bytes_pair (kinfo, _) -> kinfo
| ISlice_bytes (kinfo, _) -> kinfo
| IBytes_size (kinfo, _) -> kinfo
| IAdd_seconds_to_timestamp (kinfo, _) -> kinfo
| IAdd_timestamp_to_seconds (kinfo, _) -> kinfo
| ISub_timestamp_seconds (kinfo, _) -> kinfo
| IDiff_timestamps (kinfo, _) -> kinfo
| IAdd_tez (kinfo, _) -> kinfo
| ISub_tez (kinfo, _) -> kinfo
| ISub_tez_legacy (kinfo, _) -> kinfo
| IMul_teznat (kinfo, _) -> kinfo
| IMul_nattez (kinfo, _) -> kinfo
| IEdiv_teznat (kinfo, _) -> kinfo
| IEdiv_tez (kinfo, _) -> kinfo
| IOr (kinfo, _) -> kinfo
| IAnd (kinfo, _) -> kinfo
| IXor (kinfo, _) -> kinfo
| INot (kinfo, _) -> kinfo
| IIs_nat (kinfo, _) -> kinfo
| INeg (kinfo, _) -> kinfo
| IAbs_int (kinfo, _) -> kinfo
| IInt_nat (kinfo, _) -> kinfo
| IAdd_int (kinfo, _) -> kinfo
| IAdd_nat (kinfo, _) -> kinfo
| ISub_int (kinfo, _) -> kinfo
| IMul_int (kinfo, _) -> kinfo
| IMul_nat (kinfo, _) -> kinfo
| IEdiv_int (kinfo, _) -> kinfo
| IEdiv_nat (kinfo, _) -> kinfo
| ILsl_nat (kinfo, _) -> kinfo
| ILsr_nat (kinfo, _) -> kinfo
| IOr_nat (kinfo, _) -> kinfo
| IAnd_nat (kinfo, _) -> kinfo
| IAnd_int_nat (kinfo, _) -> kinfo
| IXor_nat (kinfo, _) -> kinfo
| INot_int (kinfo, _) -> kinfo
| IIf {kinfo; _} -> kinfo
| ILoop (kinfo, _, _) -> kinfo
| ILoop_left (kinfo, _, _) -> kinfo
| IDip (kinfo, _, _) -> kinfo
| IExec (kinfo, _) -> kinfo
| IApply (kinfo, _, _) -> kinfo
| ILambda (kinfo, _, _) -> kinfo
| IFailwith (kinfo, _, _) -> kinfo
| ICompare (kinfo, _, _) -> kinfo
| IEq (kinfo, _) -> kinfo
| INeq (kinfo, _) -> kinfo
| ILt (kinfo, _) -> kinfo
| IGt (kinfo, _) -> kinfo
| ILe (kinfo, _) -> kinfo
| IGe (kinfo, _) -> kinfo
| IAddress (kinfo, _) -> kinfo
| IContract (kinfo, _, _, _) -> kinfo
| ITransfer_tokens (kinfo, _) -> kinfo
| IView (kinfo, _, _) -> kinfo
| IImplicit_account (kinfo, _) -> kinfo
| ICreate_contract {kinfo; _} -> kinfo
| ISet_delegate (kinfo, _) -> kinfo
| INow (kinfo, _) -> kinfo
| IBalance (kinfo, _) -> kinfo
| ILevel (kinfo, _) -> kinfo
| ICheck_signature (kinfo, _) -> kinfo
| IHash_key (kinfo, _) -> kinfo
| IPack (kinfo, _, _) -> kinfo
| IUnpack (kinfo, _, _) -> kinfo
| IBlake2b (kinfo, _) -> kinfo
| ISha256 (kinfo, _) -> kinfo
| ISha512 (kinfo, _) -> kinfo
| ISource (kinfo, _) -> kinfo
| ISender (kinfo, _) -> kinfo
| ISelf (kinfo, _, _, _) -> kinfo
| ISelf_address (kinfo, _) -> kinfo
| IAmount (kinfo, _) -> kinfo
| ISapling_empty_state (kinfo, _, _) -> kinfo
| ISapling_verify_update (kinfo, _) -> kinfo
| IDig (kinfo, _, _, _) -> kinfo
| IDug (kinfo, _, _, _) -> kinfo
| IDipn (kinfo, _, _, _, _) -> kinfo
| IDropn (kinfo, _, _, _) -> kinfo
| IChainId (kinfo, _) -> kinfo
| INever kinfo -> kinfo
| IVoting_power (kinfo, _) -> kinfo
| ITotal_voting_power (kinfo, _) -> kinfo
| IKeccak (kinfo, _) -> kinfo
| ISha3 (kinfo, _) -> kinfo
| IAdd_bls12_381_g1 (kinfo, _) -> kinfo
| IAdd_bls12_381_g2 (kinfo, _) -> kinfo
| IAdd_bls12_381_fr (kinfo, _) -> kinfo
| IMul_bls12_381_g1 (kinfo, _) -> kinfo
| IMul_bls12_381_g2 (kinfo, _) -> kinfo
| IMul_bls12_381_fr (kinfo, _) -> kinfo
| IMul_bls12_381_z_fr (kinfo, _) -> kinfo
| IMul_bls12_381_fr_z (kinfo, _) -> kinfo
| IInt_bls12_381_fr (kinfo, _) -> kinfo
| INeg_bls12_381_g1 (kinfo, _) -> kinfo
| INeg_bls12_381_g2 (kinfo, _) -> kinfo
| INeg_bls12_381_fr (kinfo, _) -> kinfo
| IPairing_check_bls12_381 (kinfo, _) -> kinfo
| IComb (kinfo, _, _, _) -> kinfo
| IUncomb (kinfo, _, _, _) -> kinfo
| IComb_get (kinfo, _, _, _) -> kinfo
| IComb_set (kinfo, _, _, _) -> kinfo
| IDup_n (kinfo, _, _, _) -> kinfo
| ITicket (kinfo, _) -> kinfo
| IRead_ticket (kinfo, _) -> kinfo
| ISplit_ticket (kinfo, _) -> kinfo
| IJoin_tickets (kinfo, _, _) -> kinfo
| IHalt kinfo -> kinfo
| ILog (kinfo, _, _, _) -> kinfo
| IOpen_chest (kinfo, _) -> kinfo
type kinstr_rewritek = {
apply : 'b 'u 'r 'f. ('b, 'u, 'r, 'f) kinstr -> ('b, 'u, 'r, 'f) kinstr;
}
let kinstr_rewritek :
type a s r f. (a, s, r, f) kinstr -> kinstr_rewritek -> (a, s, r, f) kinstr
=
fun i f ->
match i with
| IDrop (kinfo, k) -> IDrop (kinfo, f.apply k)
| IDup (kinfo, k) -> IDup (kinfo, f.apply k)
| ISwap (kinfo, k) -> ISwap (kinfo, f.apply k)
| IConst (kinfo, x, k) -> IConst (kinfo, x, f.apply k)
| ICons_pair (kinfo, k) -> ICons_pair (kinfo, f.apply k)
| ICar (kinfo, k) -> ICar (kinfo, f.apply k)
| ICdr (kinfo, k) -> ICdr (kinfo, f.apply k)
| IUnpair (kinfo, k) -> IUnpair (kinfo, f.apply k)
| ICons_some (kinfo, k) -> ICons_some (kinfo, f.apply k)
| ICons_none (kinfo, k) -> ICons_none (kinfo, f.apply k)
| IIf_none {kinfo; branch_if_none; branch_if_some; k} ->
IIf_none
{
kinfo;
branch_if_none = f.apply branch_if_none;
branch_if_some = f.apply branch_if_some;
k = f.apply k;
}
| IOpt_map {kinfo; body; k} ->
let body = f.apply body in
let k = f.apply k in
IOpt_map {kinfo; body; k}
| ICons_left (kinfo, k) -> ICons_left (kinfo, f.apply k)
| ICons_right (kinfo, k) -> ICons_right (kinfo, f.apply k)
| IIf_left {kinfo; branch_if_left; branch_if_right; k} ->
IIf_left
{
kinfo;
branch_if_left = f.apply branch_if_left;
branch_if_right = f.apply branch_if_right;
k = f.apply k;
}
| ICons_list (kinfo, k) -> ICons_list (kinfo, f.apply k)
| INil (kinfo, k) -> INil (kinfo, f.apply k)
| IIf_cons {kinfo; branch_if_cons; branch_if_nil; k} ->
IIf_cons
{
kinfo;
branch_if_cons = f.apply branch_if_cons;
branch_if_nil = f.apply branch_if_nil;
k = f.apply k;
}
| IList_map (kinfo, body, k) -> IList_map (kinfo, f.apply body, f.apply k)
| IList_iter (kinfo, body, k) -> IList_iter (kinfo, f.apply body, f.apply k)
| IList_size (kinfo, k) -> IList_size (kinfo, f.apply k)
| IEmpty_set (kinfo, ty, k) -> IEmpty_set (kinfo, ty, f.apply k)
| ISet_iter (kinfo, body, k) -> ISet_iter (kinfo, f.apply body, f.apply k)
| ISet_mem (kinfo, k) -> ISet_mem (kinfo, f.apply k)
| ISet_update (kinfo, k) -> ISet_update (kinfo, f.apply k)
| ISet_size (kinfo, k) -> ISet_size (kinfo, f.apply k)
| IEmpty_map (kinfo, cty, k) -> IEmpty_map (kinfo, cty, f.apply k)
| IMap_map (kinfo, body, k) -> IMap_map (kinfo, f.apply body, f.apply k)
| IMap_iter (kinfo, body, k) -> IMap_iter (kinfo, f.apply body, f.apply k)
| IMap_mem (kinfo, k) -> IMap_mem (kinfo, f.apply k)
| IMap_get (kinfo, k) -> IMap_get (kinfo, f.apply k)
| IMap_update (kinfo, k) -> IMap_update (kinfo, f.apply k)
| IMap_get_and_update (kinfo, k) -> IMap_get_and_update (kinfo, f.apply k)
| IMap_size (kinfo, k) -> IMap_size (kinfo, f.apply k)
| IEmpty_big_map (kinfo, cty, ty, k) ->
IEmpty_big_map (kinfo, cty, ty, f.apply k)
| IBig_map_mem (kinfo, k) -> IBig_map_mem (kinfo, f.apply k)
| IBig_map_get (kinfo, k) -> IBig_map_get (kinfo, f.apply k)
| IBig_map_update (kinfo, k) -> IBig_map_update (kinfo, f.apply k)
| IBig_map_get_and_update (kinfo, k) ->
IBig_map_get_and_update (kinfo, f.apply k)
| IConcat_string (kinfo, k) -> IConcat_string (kinfo, f.apply k)
| IConcat_string_pair (kinfo, k) -> IConcat_string_pair (kinfo, f.apply k)
| ISlice_string (kinfo, k) -> ISlice_string (kinfo, f.apply k)
| IString_size (kinfo, k) -> IString_size (kinfo, f.apply k)
| IConcat_bytes (kinfo, k) -> IConcat_bytes (kinfo, f.apply k)
| IConcat_bytes_pair (kinfo, k) -> IConcat_bytes_pair (kinfo, f.apply k)
| ISlice_bytes (kinfo, k) -> ISlice_bytes (kinfo, f.apply k)
| IBytes_size (kinfo, k) -> IBytes_size (kinfo, f.apply k)
| IAdd_seconds_to_timestamp (kinfo, k) ->
IAdd_seconds_to_timestamp (kinfo, f.apply k)
| IAdd_timestamp_to_seconds (kinfo, k) ->
IAdd_timestamp_to_seconds (kinfo, f.apply k)
| ISub_timestamp_seconds (kinfo, k) ->
ISub_timestamp_seconds (kinfo, f.apply k)
| IDiff_timestamps (kinfo, k) -> IDiff_timestamps (kinfo, f.apply k)
| IAdd_tez (kinfo, k) -> IAdd_tez (kinfo, f.apply k)
| ISub_tez (kinfo, k) -> ISub_tez (kinfo, f.apply k)
| ISub_tez_legacy (kinfo, k) -> ISub_tez_legacy (kinfo, f.apply k)
| IMul_teznat (kinfo, k) -> IMul_teznat (kinfo, f.apply k)
| IMul_nattez (kinfo, k) -> IMul_nattez (kinfo, f.apply k)
| IEdiv_teznat (kinfo, k) -> IEdiv_teznat (kinfo, f.apply k)
| IEdiv_tez (kinfo, k) -> IEdiv_tez (kinfo, f.apply k)
| IOr (kinfo, k) -> IOr (kinfo, f.apply k)
| IAnd (kinfo, k) -> IAnd (kinfo, f.apply k)
| IXor (kinfo, k) -> IXor (kinfo, f.apply k)
| INot (kinfo, k) -> INot (kinfo, f.apply k)
| IIs_nat (kinfo, k) -> IIs_nat (kinfo, f.apply k)
| INeg (kinfo, k) -> INeg (kinfo, f.apply k)
| IAbs_int (kinfo, k) -> IAbs_int (kinfo, f.apply k)
| IInt_nat (kinfo, k) -> IInt_nat (kinfo, f.apply k)
| IAdd_int (kinfo, k) -> IAdd_int (kinfo, f.apply k)
| IAdd_nat (kinfo, k) -> IAdd_nat (kinfo, f.apply k)
| ISub_int (kinfo, k) -> ISub_int (kinfo, f.apply k)
| IMul_int (kinfo, k) -> IMul_int (kinfo, f.apply k)
| IMul_nat (kinfo, k) -> IMul_nat (kinfo, f.apply k)
| IEdiv_int (kinfo, k) -> IEdiv_int (kinfo, f.apply k)
| IEdiv_nat (kinfo, k) -> IEdiv_nat (kinfo, f.apply k)
| ILsl_nat (kinfo, k) -> ILsl_nat (kinfo, f.apply k)
| ILsr_nat (kinfo, k) -> ILsr_nat (kinfo, f.apply k)
| IOr_nat (kinfo, k) -> IOr_nat (kinfo, f.apply k)
| IAnd_nat (kinfo, k) -> IAnd_nat (kinfo, f.apply k)
| IAnd_int_nat (kinfo, k) -> IAnd_int_nat (kinfo, f.apply k)
| IXor_nat (kinfo, k) -> IXor_nat (kinfo, f.apply k)
| INot_int (kinfo, k) -> INot_int (kinfo, f.apply k)
| IIf {kinfo; branch_if_true; branch_if_false; k} ->
IIf
{
kinfo;
branch_if_true = f.apply branch_if_true;
branch_if_false = f.apply branch_if_false;
k = f.apply k;
}
| ILoop (kinfo, kbody, k) -> ILoop (kinfo, f.apply kbody, f.apply k)
| ILoop_left (kinfo, kl, kr) -> ILoop_left (kinfo, f.apply kl, f.apply kr)
| IDip (kinfo, body, k) -> IDip (kinfo, f.apply body, f.apply k)
| IExec (kinfo, k) -> IExec (kinfo, f.apply k)
| IApply (kinfo, ty, k) -> IApply (kinfo, ty, f.apply k)
| ILambda (kinfo, l, k) -> ILambda (kinfo, l, f.apply k)
| IFailwith (kinfo, i, ty) -> IFailwith (kinfo, i, ty)
| ICompare (kinfo, ty, k) -> ICompare (kinfo, ty, f.apply k)
| IEq (kinfo, k) -> IEq (kinfo, f.apply k)
| INeq (kinfo, k) -> INeq (kinfo, f.apply k)
| ILt (kinfo, k) -> ILt (kinfo, f.apply k)
| IGt (kinfo, k) -> IGt (kinfo, f.apply k)
| ILe (kinfo, k) -> ILe (kinfo, f.apply k)
| IGe (kinfo, k) -> IGe (kinfo, f.apply k)
| IAddress (kinfo, k) -> IAddress (kinfo, f.apply k)
| IContract (kinfo, ty, code, k) -> IContract (kinfo, ty, code, f.apply k)
| ITransfer_tokens (kinfo, k) -> ITransfer_tokens (kinfo, f.apply k)
| IView (kinfo, view_signature, k) -> IView (kinfo, view_signature, f.apply k)
| IImplicit_account (kinfo, k) -> IImplicit_account (kinfo, f.apply k)
| ICreate_contract
{kinfo; storage_type; arg_type; lambda; views; entrypoints; k} ->
let k = f.apply k in
ICreate_contract
{kinfo; storage_type; arg_type; lambda; views; entrypoints; k}
| ISet_delegate (kinfo, k) -> ISet_delegate (kinfo, f.apply k)
| INow (kinfo, k) -> INow (kinfo, f.apply k)
| IBalance (kinfo, k) -> IBalance (kinfo, f.apply k)
| ILevel (kinfo, k) -> ILevel (kinfo, f.apply k)
| ICheck_signature (kinfo, k) -> ICheck_signature (kinfo, f.apply k)
| IHash_key (kinfo, k) -> IHash_key (kinfo, f.apply k)
| IPack (kinfo, ty, k) -> IPack (kinfo, ty, f.apply k)
| IUnpack (kinfo, ty, k) -> IUnpack (kinfo, ty, f.apply k)
| IBlake2b (kinfo, k) -> IBlake2b (kinfo, f.apply k)
| ISha256 (kinfo, k) -> ISha256 (kinfo, f.apply k)
| ISha512 (kinfo, k) -> ISha512 (kinfo, f.apply k)
| ISource (kinfo, k) -> ISource (kinfo, f.apply k)
| ISender (kinfo, k) -> ISender (kinfo, f.apply k)
| ISelf (kinfo, ty, s, k) -> ISelf (kinfo, ty, s, f.apply k)
| ISelf_address (kinfo, k) -> ISelf_address (kinfo, f.apply k)
| IAmount (kinfo, k) -> IAmount (kinfo, f.apply k)
| ISapling_empty_state (kinfo, s, k) ->
ISapling_empty_state (kinfo, s, f.apply k)
| ISapling_verify_update (kinfo, k) ->
ISapling_verify_update (kinfo, f.apply k)
| IDig (kinfo, n, p, k) -> IDig (kinfo, n, p, f.apply k)
| IDug (kinfo, n, p, k) -> IDug (kinfo, n, p, f.apply k)
| IDipn (kinfo, n, p, k1, k2) -> IDipn (kinfo, n, p, f.apply k1, f.apply k2)
| IDropn (kinfo, n, p, k) -> IDropn (kinfo, n, p, f.apply k)
| IChainId (kinfo, k) -> IChainId (kinfo, f.apply k)
| INever kinfo -> INever kinfo
| IVoting_power (kinfo, k) -> IVoting_power (kinfo, f.apply k)
| ITotal_voting_power (kinfo, k) -> ITotal_voting_power (kinfo, f.apply k)
| IKeccak (kinfo, k) -> IKeccak (kinfo, f.apply k)
| ISha3 (kinfo, k) -> ISha3 (kinfo, f.apply k)
| IAdd_bls12_381_g1 (kinfo, k) -> IAdd_bls12_381_g1 (kinfo, f.apply k)
| IAdd_bls12_381_g2 (kinfo, k) -> IAdd_bls12_381_g2 (kinfo, f.apply k)
| IAdd_bls12_381_fr (kinfo, k) -> IAdd_bls12_381_fr (kinfo, f.apply k)
| IMul_bls12_381_g1 (kinfo, k) -> IMul_bls12_381_g1 (kinfo, f.apply k)
| IMul_bls12_381_g2 (kinfo, k) -> IMul_bls12_381_g2 (kinfo, f.apply k)
| IMul_bls12_381_fr (kinfo, k) -> IMul_bls12_381_fr (kinfo, f.apply k)
| IMul_bls12_381_z_fr (kinfo, k) -> IMul_bls12_381_z_fr (kinfo, f.apply k)
| IMul_bls12_381_fr_z (kinfo, k) -> IMul_bls12_381_fr_z (kinfo, f.apply k)
| IInt_bls12_381_fr (kinfo, k) -> IInt_bls12_381_fr (kinfo, f.apply k)
| INeg_bls12_381_g1 (kinfo, k) -> INeg_bls12_381_g1 (kinfo, f.apply k)
| INeg_bls12_381_g2 (kinfo, k) -> INeg_bls12_381_g2 (kinfo, f.apply k)
| INeg_bls12_381_fr (kinfo, k) -> INeg_bls12_381_fr (kinfo, f.apply k)
| IPairing_check_bls12_381 (kinfo, k) ->
IPairing_check_bls12_381 (kinfo, f.apply k)
| IComb (kinfo, n, p, k) -> IComb (kinfo, n, p, f.apply k)
| IUncomb (kinfo, n, p, k) -> IUncomb (kinfo, n, p, f.apply k)
| IComb_get (kinfo, n, p, k) -> IComb_get (kinfo, n, p, f.apply k)
| IComb_set (kinfo, n, p, k) -> IComb_set (kinfo, n, p, f.apply k)
| IDup_n (kinfo, n, p, k) -> IDup_n (kinfo, n, p, f.apply k)
| ITicket (kinfo, k) -> ITicket (kinfo, f.apply k)
| IRead_ticket (kinfo, k) -> IRead_ticket (kinfo, f.apply k)
| ISplit_ticket (kinfo, k) -> ISplit_ticket (kinfo, f.apply k)
| IJoin_tickets (kinfo, ty, k) -> IJoin_tickets (kinfo, ty, f.apply k)
| IHalt kinfo -> IHalt kinfo
| ILog (kinfo, event, logger, k) -> ILog (kinfo, event, logger, k)
| IOpen_chest (kinfo, k) -> IOpen_chest (kinfo, f.apply k)
let ty_metadata : type a. a ty -> a ty_metadata = function
| Unit_t | Never_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t
| Mutez_t | Bool_t | Key_hash_t | Key_t | Timestamp_t | Chain_id_t | Address_t
->
meta_basic
| Pair_t (_, _, meta) -> meta
| Union_t (_, _, meta) -> meta
| Option_t (_, meta) -> meta
| Lambda_t (_, _, meta) -> meta
| List_t (_, meta) -> meta
| Set_t (_, meta) -> meta
| Map_t (_, _, meta) -> meta
| Big_map_t (_, _, meta) -> meta
| Ticket_t (_, meta) -> meta
| Contract_t (_, meta) -> meta
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Bls12_381_g1_t
| Bls12_381_g2_t | Bls12_381_fr_t | Chest_t | Chest_key_t ->
meta_basic
let ty_size t = (ty_metadata t).size
let unit_t = Unit_t
let int_t = Int_t
let nat_t = Nat_t
let signature_t = Signature_t
let string_t = String_t
let bytes_t = Bytes_t
let mutez_t = Mutez_t
let key_hash_t = Key_hash_t
let key_t = Key_t
let timestamp_t = Timestamp_t
let address_t = Address_t
let bool_t = Bool_t
let pair_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Pair_t (l, r, {size})
let union_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Union_t (l, r, {size})
let union_bytes_bool_t = Union_t (bytes_t, bool_t, {size = Type_size.three})
let lambda_t loc l r =
Type_size.compound2 loc (ty_size l) (ty_size r) >|? fun size ->
Lambda_t (l, r, {size})
let option_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> Option_t (t, {size})
let option_mutez_t = Option_t (mutez_t, {size = Type_size.two})
let option_string_t = Option_t (string_t, {size = Type_size.two})
let option_bytes_t = Option_t (bytes_t, {size = Type_size.two})
let option_nat_t = Option_t (nat_t, {size = Type_size.two})
let option_pair_nat_nat_t =
Option_t
(Pair_t (nat_t, nat_t, {size = Type_size.three}), {size = Type_size.four})
let option_pair_nat_mutez_t =
Option_t
(Pair_t (nat_t, mutez_t, {size = Type_size.three}), {size = Type_size.four})
let option_pair_mutez_mutez_t =
Option_t
( Pair_t (mutez_t, mutez_t, {size = Type_size.three}),
{size = Type_size.four} )
let option_pair_int_nat_t =
Option_t
(Pair_t (int_t, nat_t, {size = Type_size.three}), {size = Type_size.four})
let list_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> List_t (t, {size})
let operation_t = Operation_t
let list_operation_t = List_t (operation_t, {size = Type_size.two})
let set_t loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Set_t (t, {size})
let map_t loc l r =
Type_size.compound2 loc (comparable_ty_size l) (ty_size r) >|? fun size ->
Map_t (l, r, {size})
let big_map_t loc l r =
Type_size.compound2 loc (comparable_ty_size l) (ty_size r) >|? fun size ->
Big_map_t (l, r, {size})
let contract_t loc t =
Type_size.compound1 loc (ty_size t) >|? fun size -> Contract_t (t, {size})
let contract_unit_t = Contract_t (unit_t, {size = Type_size.two})
let sapling_transaction_t ~memo_size = Sapling_transaction_t memo_size
let sapling_state_t ~memo_size = Sapling_state_t memo_size
let chain_id_t = Chain_id_t
let never_t = Never_t
let bls12_381_g1_t = Bls12_381_g1_t
let bls12_381_g2_t = Bls12_381_g2_t
let bls12_381_fr_t = Bls12_381_fr_t
let ticket_t loc t =
Type_size.compound1 loc (comparable_ty_size t) >|? fun size ->
Ticket_t (t, {size})
let chest_key_t = Chest_key_t
let chest_t = Chest_t
type 'a kinstr_traverse = {
apply : 'b 'u 'r 'f. 'a -> ('b, 'u, 'r, 'f) kinstr -> 'a;
}
let kinstr_traverse i init f =
let rec aux :
type ret a s r f. 'accu -> (a, s, r, f) kinstr -> ('accu -> ret) -> ret =
fun accu t continue ->
let accu = f.apply accu t in
let next k =
(aux [@ocaml.tailcall]) accu k @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next2 k1 k2 =
(aux [@ocaml.tailcall]) accu k1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next3 k1 k2 k3 =
(aux [@ocaml.tailcall]) accu k1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k2 @@ fun accu ->
(aux [@ocaml.tailcall]) accu k3 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match t with
| IDrop (_, k) -> (next [@ocaml.tailcall]) k
| IDup (_, k) -> (next [@ocaml.tailcall]) k
| ISwap (_, k) -> (next [@ocaml.tailcall]) k
| IConst (_, _, k) -> (next [@ocaml.tailcall]) k
| ICons_pair (_, k) -> (next [@ocaml.tailcall]) k
| ICar (_, k) -> (next [@ocaml.tailcall]) k
| ICdr (_, k) -> (next [@ocaml.tailcall]) k
| IUnpair (_, k) -> (next [@ocaml.tailcall]) k
| ICons_some (_, k) -> (next [@ocaml.tailcall]) k
| ICons_none (_, k) -> (next [@ocaml.tailcall]) k
| IIf_none {kinfo = _; branch_if_none = k1; branch_if_some = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| IOpt_map {kinfo = _; body; k} -> (next2 [@ocaml.tailcall]) body k
| ICons_left (_, k) -> (next [@ocaml.tailcall]) k
| ICons_right (_, k) -> (next [@ocaml.tailcall]) k
| IIf_left {kinfo = _; branch_if_left = k1; branch_if_right = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| ICons_list (_, k) -> (next [@ocaml.tailcall]) k
| INil (_, k) -> (next [@ocaml.tailcall]) k
| IIf_cons {kinfo = _; branch_if_nil = k1; branch_if_cons = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| IList_map (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IList_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IList_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_set (_, _, k) -> (next [@ocaml.tailcall]) k
| ISet_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| ISet_mem (_, k) -> (next [@ocaml.tailcall]) k
| ISet_update (_, k) -> (next [@ocaml.tailcall]) k
| ISet_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_map (_, _, k) -> (next [@ocaml.tailcall]) k
| IMap_map (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IMap_iter (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IMap_mem (_, k) -> (next [@ocaml.tailcall]) k
| IMap_get (_, k) -> (next [@ocaml.tailcall]) k
| IMap_update (_, k) -> (next [@ocaml.tailcall]) k
| IMap_get_and_update (_, k) -> (next [@ocaml.tailcall]) k
| IMap_size (_, k) -> (next [@ocaml.tailcall]) k
| IEmpty_big_map (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IBig_map_mem (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_get (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_update (_, k) -> (next [@ocaml.tailcall]) k
| IBig_map_get_and_update (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_string (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_string_pair (_, k) -> (next [@ocaml.tailcall]) k
| ISlice_string (_, k) -> (next [@ocaml.tailcall]) k
| IString_size (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_bytes (_, k) -> (next [@ocaml.tailcall]) k
| IConcat_bytes_pair (_, k) -> (next [@ocaml.tailcall]) k
| ISlice_bytes (_, k) -> (next [@ocaml.tailcall]) k
| IBytes_size (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_seconds_to_timestamp (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_timestamp_to_seconds (_, k) -> (next [@ocaml.tailcall]) k
| ISub_timestamp_seconds (_, k) -> (next [@ocaml.tailcall]) k
| IDiff_timestamps (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_tez (_, k) -> (next [@ocaml.tailcall]) k
| ISub_tez (_, k) -> (next [@ocaml.tailcall]) k
| ISub_tez_legacy (_, k) -> (next [@ocaml.tailcall]) k
| IMul_teznat (_, k) -> (next [@ocaml.tailcall]) k
| IMul_nattez (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_teznat (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_tez (_, k) -> (next [@ocaml.tailcall]) k
| IOr (_, k) -> (next [@ocaml.tailcall]) k
| IAnd (_, k) -> (next [@ocaml.tailcall]) k
| IXor (_, k) -> (next [@ocaml.tailcall]) k
| INot (_, k) -> (next [@ocaml.tailcall]) k
| IIs_nat (_, k) -> (next [@ocaml.tailcall]) k
| INeg (_, k) -> (next [@ocaml.tailcall]) k
| IAbs_int (_, k) -> (next [@ocaml.tailcall]) k
| IInt_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_int (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_nat (_, k) -> (next [@ocaml.tailcall]) k
| ISub_int (_, k) -> (next [@ocaml.tailcall]) k
| IMul_int (_, k) -> (next [@ocaml.tailcall]) k
| IMul_nat (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_int (_, k) -> (next [@ocaml.tailcall]) k
| IEdiv_nat (_, k) -> (next [@ocaml.tailcall]) k
| ILsl_nat (_, k) -> (next [@ocaml.tailcall]) k
| ILsr_nat (_, k) -> (next [@ocaml.tailcall]) k
| IOr_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAnd_nat (_, k) -> (next [@ocaml.tailcall]) k
| IAnd_int_nat (_, k) -> (next [@ocaml.tailcall]) k
| IXor_nat (_, k) -> (next [@ocaml.tailcall]) k
| INot_int (_, k) -> (next [@ocaml.tailcall]) k
| IIf {kinfo = _; branch_if_true = k1; branch_if_false = k2; k} ->
(next3 [@ocaml.tailcall]) k1 k2 k
| ILoop (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| ILoop_left (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IDip (_, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IExec (_, k) -> (next [@ocaml.tailcall]) k
| IApply (_, _, k) -> (next [@ocaml.tailcall]) k
| ILambda (_, _, k) -> (next [@ocaml.tailcall]) k
| IFailwith (_, _, _) -> (return [@ocaml.tailcall]) ()
| ICompare (_, _, k) -> (next [@ocaml.tailcall]) k
| IEq (_, k) -> (next [@ocaml.tailcall]) k
| INeq (_, k) -> (next [@ocaml.tailcall]) k
| ILt (_, k) -> (next [@ocaml.tailcall]) k
| IGt (_, k) -> (next [@ocaml.tailcall]) k
| ILe (_, k) -> (next [@ocaml.tailcall]) k
| IGe (_, k) -> (next [@ocaml.tailcall]) k
| IAddress (_, k) -> (next [@ocaml.tailcall]) k
| IContract (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IView (_, _, k) -> (next [@ocaml.tailcall]) k
| ITransfer_tokens (_, k) -> (next [@ocaml.tailcall]) k
| IImplicit_account (_, k) -> (next [@ocaml.tailcall]) k
| ICreate_contract {k; _} -> (next [@ocaml.tailcall]) k
| ISet_delegate (_, k) -> (next [@ocaml.tailcall]) k
| INow (_, k) -> (next [@ocaml.tailcall]) k
| IBalance (_, k) -> (next [@ocaml.tailcall]) k
| ILevel (_, k) -> (next [@ocaml.tailcall]) k
| ICheck_signature (_, k) -> (next [@ocaml.tailcall]) k
| IHash_key (_, k) -> (next [@ocaml.tailcall]) k
| IPack (_, _, k) -> (next [@ocaml.tailcall]) k
| IUnpack (_, _, k) -> (next [@ocaml.tailcall]) k
| IBlake2b (_, k) -> (next [@ocaml.tailcall]) k
| ISha256 (_, k) -> (next [@ocaml.tailcall]) k
| ISha512 (_, k) -> (next [@ocaml.tailcall]) k
| ISource (_, k) -> (next [@ocaml.tailcall]) k
| ISender (_, k) -> (next [@ocaml.tailcall]) k
| ISelf (_, _, _, k) -> (next [@ocaml.tailcall]) k
| ISelf_address (_, k) -> (next [@ocaml.tailcall]) k
| IAmount (_, k) -> (next [@ocaml.tailcall]) k
| ISapling_empty_state (_, _, k) -> (next [@ocaml.tailcall]) k
| ISapling_verify_update (_, k) -> (next [@ocaml.tailcall]) k
| IDig (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDug (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDipn (_, _, _, k1, k2) -> (next2 [@ocaml.tailcall]) k1 k2
| IDropn (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IChainId (_, k) -> (next [@ocaml.tailcall]) k
| INever _ -> (return [@ocaml.tailcall]) ()
| IVoting_power (_, k) -> (next [@ocaml.tailcall]) k
| ITotal_voting_power (_, k) -> (next [@ocaml.tailcall]) k
| IKeccak (_, k) -> (next [@ocaml.tailcall]) k
| ISha3 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| IAdd_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_z_fr (_, k) -> (next [@ocaml.tailcall]) k
| IMul_bls12_381_fr_z (_, k) -> (next [@ocaml.tailcall]) k
| IInt_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_g1 (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_g2 (_, k) -> (next [@ocaml.tailcall]) k
| INeg_bls12_381_fr (_, k) -> (next [@ocaml.tailcall]) k
| IPairing_check_bls12_381 (_, k) -> (next [@ocaml.tailcall]) k
| IComb (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IUncomb (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IComb_get (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IComb_set (_, _, _, k) -> (next [@ocaml.tailcall]) k
| IDup_n (_, _, _, k) -> (next [@ocaml.tailcall]) k
| ITicket (_, k) -> (next [@ocaml.tailcall]) k
| IRead_ticket (_, k) -> (next [@ocaml.tailcall]) k
| ISplit_ticket (_, k) -> (next [@ocaml.tailcall]) k
| IJoin_tickets (_, _, k) -> (next [@ocaml.tailcall]) k
| IOpen_chest (_, k) -> (next [@ocaml.tailcall]) k
| IHalt _ -> (return [@ocaml.tailcall]) ()
| ILog (_, _, _, k) -> (next [@ocaml.tailcall]) k
in
aux init i (fun accu -> accu)
type 'a ty_traverse = {
apply : 't. 'a -> 't ty -> 'a;
apply_comparable : 't. 'a -> 't comparable_ty -> 'a;
}
let (ty_traverse, comparable_ty_traverse) =
let rec aux :
type t ret accu.
accu ty_traverse -> accu -> t comparable_ty -> (accu -> ret) -> ret =
fun f accu ty continue ->
let accu = f.apply_comparable accu ty in
let next2 ty1 ty2 =
(aux [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(aux [@ocaml.tailcall]) f accu ty2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 =
(aux [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match ty with
| Unit_key | Int_key | Nat_key | Signature_key | String_key | Bytes_key
| Mutez_key | Key_hash_key | Key_key | Timestamp_key | Address_key
| Bool_key | Chain_id_key | Never_key ->
(return [@ocaml.tailcall]) ()
| Pair_key (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2
| Union_key (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2
| Option_key (ty, _) -> (next [@ocaml.tailcall]) ty
and aux' :
type ret t accu. accu ty_traverse -> accu -> t ty -> (accu -> ret) -> ret
=
fun f accu ty continue ->
let accu = f.apply accu ty in
match (ty : t ty) with
| Unit_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t | Mutez_t
| Key_hash_t | Key_t | Timestamp_t | Address_t | Bool_t
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Chain_id_t
| Never_t | Bls12_381_g1_t | Bls12_381_g2_t | Bls12_381_fr_t ->
(continue [@ocaml.tailcall]) accu
| Ticket_t (cty, _) -> aux f accu cty continue
| Chest_key_t | Chest_t -> (continue [@ocaml.tailcall]) accu
| Pair_t (ty1, ty2, _) -> (next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Union_t (ty1, ty2, _) ->
(next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Lambda_t (ty1, ty2, _) ->
(next2' [@ocaml.tailcall]) f accu ty1 ty2 continue
| Option_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
| List_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
| Set_t (cty, _) -> (aux [@ocaml.tailcall]) f accu cty @@ continue
| Map_t (cty, ty1, _) ->
(aux [@ocaml.tailcall]) f accu cty @@ fun accu ->
(next' [@ocaml.tailcall]) f accu ty1 continue
| Big_map_t (cty, ty1, _) ->
(aux [@ocaml.tailcall]) f accu cty @@ fun accu ->
(next' [@ocaml.tailcall]) f accu ty1 continue
| Contract_t (ty1, _) -> (next' [@ocaml.tailcall]) f accu ty1 continue
and next2' :
type a b ret accu.
accu ty_traverse -> accu -> a ty -> b ty -> (accu -> ret) -> ret =
fun f accu ty1 ty2 continue ->
(aux' [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(aux' [@ocaml.tailcall]) f accu ty2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
and next' :
type a ret accu. accu ty_traverse -> accu -> a ty -> (accu -> ret) -> ret
=
fun f accu ty1 continue ->
(aux' [@ocaml.tailcall]) f accu ty1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
( (fun ty init f -> aux' f init ty (fun accu -> accu)),
fun cty init f -> aux f init cty (fun accu -> accu) )
type 'accu stack_ty_traverse = {
apply : 'ty 's. 'accu -> ('ty, 's) stack_ty -> 'accu;
}
let stack_ty_traverse (type a t) (sty : (a, t) stack_ty) init f =
let rec aux : type b u. 'accu -> (b, u) stack_ty -> 'accu =
fun accu sty ->
match sty with
| Bot_t -> f.apply accu sty
| Item_t (_, sty') -> aux (f.apply accu sty) sty'
in
aux init sty
type 'a value_traverse = {
apply : 't. 'a -> 't ty -> 't -> 'a;
apply_comparable : 't. 'a -> 't comparable_ty -> 't -> 'a;
}
let value_traverse (type t) (ty : (t ty, t comparable_ty) union) (x : t) init f
=
let rec aux : type ret t. 'accu -> t ty -> t -> ('accu -> ret) -> ret =
fun accu ty x continue ->
let accu = f.apply accu ty x in
let next2 ty1 ty2 x1 x2 =
(aux [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(aux [@ocaml.tailcall]) accu ty2 x2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 x1 =
(aux [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
let rec on_list ty' accu = function
| [] -> (continue [@ocaml.tailcall]) accu
| x :: xs ->
(aux [@ocaml.tailcall]) accu ty' x @@ fun accu ->
(on_list [@ocaml.tailcall]) ty' accu xs
in
match ty with
| Unit_t | Int_t | Nat_t | Signature_t | String_t | Bytes_t | Mutez_t
| Key_hash_t | Key_t | Timestamp_t | Address_t | Bool_t
| Sapling_transaction_t _ | Sapling_state_t _ | Operation_t | Chain_id_t
| Never_t | Bls12_381_g1_t | Bls12_381_g2_t | Bls12_381_fr_t | Chest_key_t
| Chest_t
| Lambda_t (_, _, _) ->
(return [@ocaml.tailcall]) ()
| Pair_t (ty1, ty2, _) -> (next2 [@ocaml.tailcall]) ty1 ty2 (fst x) (snd x)
| Union_t (ty1, ty2, _) -> (
match x with
| L l -> (next [@ocaml.tailcall]) ty1 l
| R r -> (next [@ocaml.tailcall]) ty2 r)
| Option_t (ty, _) -> (
match x with
| None -> return ()
| Some v -> (next [@ocaml.tailcall]) ty v)
| Ticket_t (cty, _) -> (aux' [@ocaml.tailcall]) accu cty x.contents continue
| List_t (ty', _) -> on_list ty' accu x.elements
| Map_t (kty, ty', _) ->
let (Map_tag (module M)) = x in
let bindings = M.OPS.fold (fun k v bs -> (k, v) :: bs) M.boxed [] in
on_bindings accu kty ty' continue bindings
| Set_t (ty', _) ->
let (Set_tag (module M)) = x in
let elements = M.OPS.fold (fun x s -> x :: s) M.boxed [] in
on_list' accu ty' elements continue
| Big_map_t (_, _, _) ->
(return [@ocaml.tailcall]) ()
| Contract_t (_, _) -> (return [@ocaml.tailcall]) ()
and on_list' :
type ret t. 'accu -> t comparable_ty -> t list -> ('accu -> ret) -> ret =
fun accu ty' xs continue ->
match xs with
| [] -> (continue [@ocaml.tailcall]) accu
| x :: xs ->
(aux' [@ocaml.tailcall]) accu ty' x @@ fun accu ->
(on_list' [@ocaml.tailcall]) accu ty' xs continue
and on_bindings :
type ret k v.
'accu -> k comparable_ty -> v ty -> ('accu -> ret) -> (k * v) list -> ret
=
fun accu kty ty' continue xs ->
match xs with
| [] -> (continue [@ocaml.tailcall]) accu
| (k, v) :: xs ->
(aux' [@ocaml.tailcall]) accu kty k @@ fun accu ->
(aux [@ocaml.tailcall]) accu ty' v @@ fun accu ->
(on_bindings [@ocaml.tailcall]) accu kty ty' continue xs
and aux' : type ret t. 'accu -> t comparable_ty -> t -> ('accu -> ret) -> ret
=
fun accu ty x continue ->
let accu = f.apply_comparable accu ty x in
let next2 ty1 ty2 x1 x2 =
(aux' [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(aux' [@ocaml.tailcall]) accu ty2 x2 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let next ty1 x1 =
(aux' [@ocaml.tailcall]) accu ty1 x1 @@ fun accu ->
(continue [@ocaml.tailcall]) accu
in
let return () = (continue [@ocaml.tailcall]) accu in
match ty with
| Unit_key | Int_key | Nat_key | Signature_key | String_key | Bytes_key
| Mutez_key | Key_hash_key | Key_key | Timestamp_key | Address_key
| Bool_key | Chain_id_key | Never_key ->
(return [@ocaml.tailcall]) ()
| Pair_key (ty1, ty2, _) ->
(next2 [@ocaml.tailcall]) ty1 ty2 (fst x) (snd x)
| Union_key (ty1, ty2, _) -> (
match x with
| L l -> (next [@ocaml.tailcall]) ty1 l
| R r -> (next [@ocaml.tailcall]) ty2 r)
| Option_key (ty, _) -> (
match x with
| None -> (return [@ocaml.tailcall]) ()
| Some v -> (next [@ocaml.tailcall]) ty v)
in
match ty with
| L ty -> aux init ty x (fun accu -> accu)
| R cty -> aux' init cty x (fun accu -> accu)
[@@coq_axiom_with_reason "local mutually recursive definition not handled"]
let stack_top_ty : type a b s. (a, b * s) stack_ty -> a ty = function
| Item_t (ty, _) -> ty
|
8d081af4d30d91b0c4bb24e7494793385b331c13c6a1bcfcf2bd2909af3389a9 | ZHaskell/stdio | UTF8Codec.hs | # LANGUAGE BangPatterns #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
|
Module : Std . Data . Text . UTF8Codec
Description : UTF-8 codecs and helpers .
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
UTF-8 codecs and helpers .
Module : Std.Data.Text.UTF8Codec
Description : UTF-8 codecs and helpers.
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
UTF-8 codecs and helpers.
-}
module Std.Data.Text.UTF8Codec where
import Control.Monad.Primitive
import Data.Primitive.ByteArray
import Data.Primitive.PrimArray
import GHC.Prim
import GHC.ST
import GHC.Types
import GHC.Word
-- | Return a codepoint's encoded length in bytes
--
-- If the codepoint is invalid, we return 3(encoded bytes length of replacement char @\U+FFFD@).
--
encodeCharLength :: Char -> Int
# INLINE encodeCharLength #
encodeCharLength n
| n <= '\x00007F' = 1
| n <= '\x0007FF' = 2
| n <= '\x00FFFF' = 3
| n <= '\x10FFFF' = 4
| otherwise = 3
| Encode a ' ' into bytes , write ' replacementChar ' for invalid unicode codepoint .
--
-- This function assumed there're enough space for encoded bytes, and return the advanced index.
encodeChar :: MutablePrimArray s Word8 -> Int -> Char -> ST s Int
# INLINE encodeChar #
encodeChar (MutablePrimArray mba#) (I# i#) (C# c#) = ST (\ s# ->
let !(# s1#, j# #) = encodeChar# mba# i# c# s# in (# s1#, I# j# #))
-- | The unboxed version of 'encodeChar'.
--
-- This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
-- due to too much branches.
encodeChar# :: MutableByteArray# s -> Int# -> Char# -> State# s -> (# State# s, Int# #)
# NOINLINE encodeChar # #
encodeChar# mba# i# c# = case (int2Word# (ord# c#)) of
n#
| isTrue# (n# `leWord#` 0x0000007F##) -> \ s# ->
let s1# = writeWord8Array# mba# i# n# s#
in (# s1#, i# +# 1# #)
| isTrue# (n# `leWord#` 0x000007FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xC0## `or#` (n# `uncheckedShiftRL#` 6#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` (n# `and#` 0x3F##)) s1#
in (# s2#, i# +# 2# #)
| isTrue# (n# `leWord#` 0x0000D7FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
| isTrue# (n# `leWord#` 0x0000DFFF##) -> \ s# -> -- write replacement char \U+FFFD
let s1# = writeWord8Array# mba# i# 0xEF## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0xBF## s1#
s3# = writeWord8Array# mba# (i# +# 2#) 0xBD## s2#
in (# s3#, i# +# 3# #)
| isTrue# (n# `leWord#` 0x0000FFFF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
| isTrue# (n# `leWord#` 0x0010FFFF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xF0## `or#` (n# `uncheckedShiftRL#` 18#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 12#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s2#
s4# = writeWord8Array# mba# (i# +# 3#) (0x80## `or#` (n# `and#` 0x3F##)) s3#
in (# s4#, i# +# 4# #)
| otherwise -> \ s# -> -- write replacement char \U+FFFD
let s1# = writeWord8Array# mba# i# 0xEF## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0xBF## s1#
s3# = writeWord8Array# mba# (i# +# 2#) 0xBD## s2#
in (# s3#, i# +# 3# #)
| Encode a ' ' into bytes with non - standard UTF-8 encoding(Used in " Data . CBytes " ) .
--
' \NUL ' is encoded as two bytes @C0 80@ , ' \xD800 ' ~ ' \xDFFF ' is encoded as a three bytes normal UTF-8 codepoint .
-- This function assumed there're enough space for encoded bytes, and return the advanced index.
encodeCharModifiedUTF8 :: (PrimMonad m) => MutablePrimArray (PrimState m) Word8 -> Int -> Char -> m Int
# INLINE encodeCharModifiedUTF8 #
encodeCharModifiedUTF8 (MutablePrimArray mba#) (I# i#) (C# c#) = primitive (\ s# ->
let !(# s1#, j# #) = encodeCharModifiedUTF8# mba# i# c# s# in (# s1#, I# j# #))
-- | The unboxed version of 'encodeCharModifiedUTF8'.
encodeCharModifiedUTF8# :: MutableByteArray# s -> Int# -> Char# -> State# s -> (# State# s, Int# #)
# NOINLINE encodeCharModifiedUTF8 # #
encodeCharModifiedUTF8# mba# i# c# = case (int2Word# (ord# c#)) of
n#
encode \NUL as \xC0 \x80
let s1# = writeWord8Array# mba# i# 0xC0## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0x80## s1#
in (# s2#, i# +# 2# #)
| isTrue# (n# `leWord#` 0x0000007F##) -> \ s# ->
let s1# = writeWord8Array# mba# i# n# s#
in (# s1#, i# +# 1# #)
| isTrue# (n# `leWord#` 0x000007FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xC0## `or#` (n# `uncheckedShiftRL#` 6#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` (n# `and#` 0x3F##)) s1#
in (# s2#, i# +# 2# #)
\xD800 ~ \xDFFF is encoded as normal UTF-8 codepoints
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
| otherwise -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xF0## `or#` (n# `uncheckedShiftRL#` 18#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 12#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s2#
s4# = writeWord8Array# mba# (i# +# 3#) (0x80## `or#` (n# `and#` 0x3F##)) s3#
in (# s4#, i# +# 4# #)
--------------------------------------------------------------------------------
| Decode a ' ' from bytes
--
This function assumed all bytes are UTF-8 encoded , and the index param point to the
-- beginning of a codepoint, the decoded character and the advancing offset are returned.
--
-- It's annoying to use unboxed tuple here but we really don't want allocation even if
GHC ca n't optimize it away .
decodeChar :: PrimArray Word8 -> Int -> (# Char, Int #)
# INLINE decodeChar #
decodeChar (PrimArray ba#) (I# idx#) =
let !(# c#, i# #) = decodeChar# ba# idx# in (# C# c#, I# i# #)
decodeChar_ :: PrimArray Word8 -> Int -> Char
{-# INLINE decodeChar_ #-}
decodeChar_ (PrimArray ba#) (I# idx#) =
let !(# c#, _ #) = decodeChar# ba# idx# in C# c#
-- | The unboxed version of 'decodeChar'
--
-- This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
-- due to too much branches.
decodeChar# :: ByteArray# -> Int# -> (# Char#, Int# #)
This branchy code make GHC impossible to fuse , DON'T inline
decodeChar# ba# idx# = case indexWord8Array# ba# idx# of
w1#
| isTrue# (w1# `leWord#` 0x7F##) -> (# chr1# w1#, 1# #)
| isTrue# (w1# `leWord#` 0xDF##) ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
in (# chr2# w1# w2#, 2# #)
| isTrue# (w1# `leWord#` 0xEF##) ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
w3# = indexWord8Array# ba# (idx# +# 2#)
in (# chr3# w1# w2# w3#, 3# #)
| otherwise ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
w3# = indexWord8Array# ba# (idx# +# 2#)
w4# = indexWord8Array# ba# (idx# +# 3#)
in (# chr4# w1# w2# w3# w4#, 4# #)
-- | Decode a codepoint's length in bytes
--
This function assumed all bytes are UTF-8 encoded , and the index param point to the
-- beginning of a codepoint.
--
decodeCharLen :: PrimArray Word8 -> Int -> Int
# INLINE decodeCharLen #
decodeCharLen (PrimArray ba#) (I# idx#) =
let i# = decodeCharLen# ba# idx# in I# i#
-- | The unboxed version of 'decodeCharLen'
--
-- This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
-- due to too much branches.
decodeCharLen# :: ByteArray# -> Int# -> Int#
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharLen# ba# idx# = case indexWord8Array# ba# idx# of
w1#
| isTrue# (w1# `leWord#` 0x7F##) -> 1#
| isTrue# (w1# `leWord#` 0xDF##) -> 2#
| isTrue# (w1# `leWord#` 0xEF##) -> 3#
| otherwise -> 4#
| Decode a ' ' from bytes in rerverse order .
--
This function assumed all bytes are UTF-8 encoded , and the index param point to the end
-- of a codepoint, the decoded character and the backward advancing offset are returned.
--
decodeCharReverse :: PrimArray Word8 -> Int -> (# Char, Int #)
# INLINE decodeCharReverse #
decodeCharReverse (PrimArray ba#) (I# idx#) =
let !(# c#, i# #) = decodeCharReverse# ba# idx# in (# C# c#, I# i# #)
decodeCharReverse_ :: PrimArray Word8 -> Int -> Char
{-# INLINE decodeCharReverse_ #-}
decodeCharReverse_ (PrimArray ba#) (I# idx#) =
let !(# c#, _ #) = decodeCharReverse# ba# idx# in C# c#
-- | The unboxed version of 'decodeCharReverse'
--
-- This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
-- due to too much branches.
decodeCharReverse# :: ByteArray# -> Int# -> (# Char#, Int# #)
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharReverse# ba# idx# =
let w1# = indexWord8Array# ba# idx#
in if isContinueByte# w1#
then
let w2# = indexWord8Array# ba# (idx# -# 1#)
in if isContinueByte# w2#
then
let w3# = indexWord8Array# ba# (idx# -# 2#)
in if isContinueByte# w3#
then
let w4# = indexWord8Array# ba# (idx# -# 3#)
in (# chr4# w4# w3# w2# w1#, 4# #)
else (# chr3# w3# w2# w1#, 3# #)
else (# chr2# w2# w1#, 2# #)
else (# chr1# w1#, 1# #)
-- | Decode a codepoint's length in bytes in reverse order.
--
This function assumed all bytes are UTF-8 encoded , and the index param point to the end
-- of a codepoint.
--
decodeCharLenReverse :: PrimArray Word8 -> Int -> Int
# INLINE decodeCharLenReverse #
decodeCharLenReverse (PrimArray ba#) (I# idx#) =
let i# = decodeCharLenReverse# ba# idx# in I# i#
-- | The unboxed version of 'decodeCharLenReverse'
--
-- This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
-- due to too much branches.
decodeCharLenReverse# :: ByteArray# -> Int# -> Int#
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharLenReverse# ba# idx# =
let w1# = indexWord8Array# ba# idx#
in if isContinueByte# w1#
then
let w2# = indexWord8Array# ba# (idx# -# 1#)
in if isContinueByte# w2#
then
let w3# = indexWord8Array# ba# (idx# -# 2#)
in if isContinueByte# w3#
then 4#
else 3#
else 2#
else 1#
--------------------------------------------------------------------------------
between# :: Word# -> Word# -> Word# -> Bool
# INLINE between # #
between# w# l# h# = isTrue# (w# `geWord#` l#) && isTrue# (w# `leWord#` h#)
isContinueByte# :: Word# -> Bool
# INLINE isContinueByte # #
isContinueByte# w# = isTrue# (and# w# 0xC0## `eqWord#` 0x80##)
chr1# :: Word# -> Char#
# INLINE chr1 # #
chr1# x1# = chr# y1#
where
!y1# = word2Int# x1#
chr2# :: Word# -> Word# -> Char#
# INLINE chr2 # #
chr2# x1# x2# = chr# (z1# +# z2#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6#
!z2# = y2# -# 0x80#
chr3# :: Word# -> Word# -> Word# -> Char#
# INLINE chr3 # #
chr3# x1# x2# x3# = chr# (z1# +# z2# +# z3#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 6#
!z3# = y3# -# 0x80#
chr4# :: Word# -> Word# -> Word# -> Word# -> Char#
# INLINE chr4 # #
chr4# x1# x2# x3# x4# = chr# (z1# +# z2# +# z3# +# z4#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!y4# = word2Int# x4#
!z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 12#
!z3# = uncheckedIShiftL# (y3# -# 0x80#) 6#
!z4# = y4# -# 0x80#
--------------------------------------------------------------------------------
-- | Unrolled copy loop for copying a utf8-encoded codepoint from source array to target array.
--
copy length , must be 1 , 2 , 3 or 4
-> MutablePrimArray s Word8 -- target array
-> Int -- writing offset
-> PrimArray Word8 -- source array
-> Int -- reading offset
-> ST s ()
# INLINE copyChar #
copyChar !l !mba !j !ba !i = case l of
1 -> do writePrimArray mba j $ indexPrimArray ba i
2 -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
3 -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
writePrimArray mba (j+2) $ indexPrimArray ba (i+2)
_ -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
writePrimArray mba (j+2) $ indexPrimArray ba (i+2)
writePrimArray mba (j+3) $ indexPrimArray ba (i+3)
-- | Unrolled copy loop for copying a utf8-encoded codepoint from source array to target array.
--
copy length , must be 1 , 2 , 3 or 4
-> MutablePrimArray s Word8 -- target array
-> Int -- writing offset
-> MutablePrimArray s Word8 -- source array
-> Int -- reading offset
-> ST s ()
# INLINE copyChar ' #
copyChar' !l !mba !j !ba !i = case l of
1 -> do writePrimArray mba j =<< readPrimArray ba i
2 -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
3 -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
writePrimArray mba (j+2) =<< readPrimArray ba (i+2)
_ -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
writePrimArray mba (j+2) =<< readPrimArray ba (i+2)
writePrimArray mba (j+3) =<< readPrimArray ba (i+3)
-- | @\xFFFD@, which will be encoded as @0xEF 0xBF 0xBD@ 3 bytes.
replacementChar :: Char
replacementChar = '\xFFFD'
| null | https://raw.githubusercontent.com/ZHaskell/stdio/7887b9413dc9feb957ddcbea96184f904cf37c12/std-data/Std/Data/Text/UTF8Codec.hs | haskell | | Return a codepoint's encoded length in bytes
If the codepoint is invalid, we return 3(encoded bytes length of replacement char @\U+FFFD@).
This function assumed there're enough space for encoded bytes, and return the advanced index.
| The unboxed version of 'encodeChar'.
This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
due to too much branches.
write replacement char \U+FFFD
write replacement char \U+FFFD
This function assumed there're enough space for encoded bytes, and return the advanced index.
| The unboxed version of 'encodeCharModifiedUTF8'.
------------------------------------------------------------------------------
beginning of a codepoint, the decoded character and the advancing offset are returned.
It's annoying to use unboxed tuple here but we really don't want allocation even if
# INLINE decodeChar_ #
| The unboxed version of 'decodeChar'
This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
due to too much branches.
| Decode a codepoint's length in bytes
beginning of a codepoint.
| The unboxed version of 'decodeCharLen'
This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
due to too much branches.
of a codepoint, the decoded character and the backward advancing offset are returned.
# INLINE decodeCharReverse_ #
| The unboxed version of 'decodeCharReverse'
This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
due to too much branches.
| Decode a codepoint's length in bytes in reverse order.
of a codepoint.
| The unboxed version of 'decodeCharLenReverse'
This function is marked as @NOINLINE@ to reduce code size, and stop messing up simplifier
due to too much branches.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| Unrolled copy loop for copying a utf8-encoded codepoint from source array to target array.
target array
writing offset
source array
reading offset
| Unrolled copy loop for copying a utf8-encoded codepoint from source array to target array.
target array
writing offset
source array
reading offset
| @\xFFFD@, which will be encoded as @0xEF 0xBF 0xBD@ 3 bytes. | # LANGUAGE BangPatterns #
# LANGUAGE MagicHash #
# LANGUAGE UnboxedTuples #
|
Module : Std . Data . Text . UTF8Codec
Description : UTF-8 codecs and helpers .
Copyright : ( c ) , 2017 - 2018
License : BSD
Maintainer :
Stability : experimental
Portability : non - portable
UTF-8 codecs and helpers .
Module : Std.Data.Text.UTF8Codec
Description : UTF-8 codecs and helpers.
Copyright : (c) Dong Han, 2017-2018
License : BSD
Maintainer :
Stability : experimental
Portability : non-portable
UTF-8 codecs and helpers.
-}
module Std.Data.Text.UTF8Codec where
import Control.Monad.Primitive
import Data.Primitive.ByteArray
import Data.Primitive.PrimArray
import GHC.Prim
import GHC.ST
import GHC.Types
import GHC.Word
encodeCharLength :: Char -> Int
# INLINE encodeCharLength #
encodeCharLength n
| n <= '\x00007F' = 1
| n <= '\x0007FF' = 2
| n <= '\x00FFFF' = 3
| n <= '\x10FFFF' = 4
| otherwise = 3
| Encode a ' ' into bytes , write ' replacementChar ' for invalid unicode codepoint .
encodeChar :: MutablePrimArray s Word8 -> Int -> Char -> ST s Int
# INLINE encodeChar #
encodeChar (MutablePrimArray mba#) (I# i#) (C# c#) = ST (\ s# ->
let !(# s1#, j# #) = encodeChar# mba# i# c# s# in (# s1#, I# j# #))
encodeChar# :: MutableByteArray# s -> Int# -> Char# -> State# s -> (# State# s, Int# #)
# NOINLINE encodeChar # #
encodeChar# mba# i# c# = case (int2Word# (ord# c#)) of
n#
| isTrue# (n# `leWord#` 0x0000007F##) -> \ s# ->
let s1# = writeWord8Array# mba# i# n# s#
in (# s1#, i# +# 1# #)
| isTrue# (n# `leWord#` 0x000007FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xC0## `or#` (n# `uncheckedShiftRL#` 6#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` (n# `and#` 0x3F##)) s1#
in (# s2#, i# +# 2# #)
| isTrue# (n# `leWord#` 0x0000D7FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
let s1# = writeWord8Array# mba# i# 0xEF## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0xBF## s1#
s3# = writeWord8Array# mba# (i# +# 2#) 0xBD## s2#
in (# s3#, i# +# 3# #)
| isTrue# (n# `leWord#` 0x0000FFFF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
| isTrue# (n# `leWord#` 0x0010FFFF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xF0## `or#` (n# `uncheckedShiftRL#` 18#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 12#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s2#
s4# = writeWord8Array# mba# (i# +# 3#) (0x80## `or#` (n# `and#` 0x3F##)) s3#
in (# s4#, i# +# 4# #)
let s1# = writeWord8Array# mba# i# 0xEF## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0xBF## s1#
s3# = writeWord8Array# mba# (i# +# 2#) 0xBD## s2#
in (# s3#, i# +# 3# #)
| Encode a ' ' into bytes with non - standard UTF-8 encoding(Used in " Data . CBytes " ) .
' \NUL ' is encoded as two bytes @C0 80@ , ' \xD800 ' ~ ' \xDFFF ' is encoded as a three bytes normal UTF-8 codepoint .
encodeCharModifiedUTF8 :: (PrimMonad m) => MutablePrimArray (PrimState m) Word8 -> Int -> Char -> m Int
# INLINE encodeCharModifiedUTF8 #
encodeCharModifiedUTF8 (MutablePrimArray mba#) (I# i#) (C# c#) = primitive (\ s# ->
let !(# s1#, j# #) = encodeCharModifiedUTF8# mba# i# c# s# in (# s1#, I# j# #))
encodeCharModifiedUTF8# :: MutableByteArray# s -> Int# -> Char# -> State# s -> (# State# s, Int# #)
# NOINLINE encodeCharModifiedUTF8 # #
encodeCharModifiedUTF8# mba# i# c# = case (int2Word# (ord# c#)) of
n#
encode \NUL as \xC0 \x80
let s1# = writeWord8Array# mba# i# 0xC0## s#
s2# = writeWord8Array# mba# (i# +# 1#) 0x80## s1#
in (# s2#, i# +# 2# #)
| isTrue# (n# `leWord#` 0x0000007F##) -> \ s# ->
let s1# = writeWord8Array# mba# i# n# s#
in (# s1#, i# +# 1# #)
| isTrue# (n# `leWord#` 0x000007FF##) -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xC0## `or#` (n# `uncheckedShiftRL#` 6#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` (n# `and#` 0x3F##)) s1#
in (# s2#, i# +# 2# #)
\xD800 ~ \xDFFF is encoded as normal UTF-8 codepoints
let s1# = writeWord8Array# mba# i# (0xE0## `or#` (n# `uncheckedShiftRL#` 12#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` (n# `and#` 0x3F##)) s2#
in (# s3#, i# +# 3# #)
| otherwise -> \ s# ->
let s1# = writeWord8Array# mba# i# (0xF0## `or#` (n# `uncheckedShiftRL#` 18#)) s#
s2# = writeWord8Array# mba# (i# +# 1#) (0x80## `or#` ((n# `uncheckedShiftRL#` 12#) `and#` 0x3F##)) s1#
s3# = writeWord8Array# mba# (i# +# 2#) (0x80## `or#` ((n# `uncheckedShiftRL#` 6#) `and#` 0x3F##)) s2#
s4# = writeWord8Array# mba# (i# +# 3#) (0x80## `or#` (n# `and#` 0x3F##)) s3#
in (# s4#, i# +# 4# #)
| Decode a ' ' from bytes
This function assumed all bytes are UTF-8 encoded , and the index param point to the
GHC ca n't optimize it away .
decodeChar :: PrimArray Word8 -> Int -> (# Char, Int #)
# INLINE decodeChar #
decodeChar (PrimArray ba#) (I# idx#) =
let !(# c#, i# #) = decodeChar# ba# idx# in (# C# c#, I# i# #)
decodeChar_ :: PrimArray Word8 -> Int -> Char
decodeChar_ (PrimArray ba#) (I# idx#) =
let !(# c#, _ #) = decodeChar# ba# idx# in C# c#
decodeChar# :: ByteArray# -> Int# -> (# Char#, Int# #)
This branchy code make GHC impossible to fuse , DON'T inline
decodeChar# ba# idx# = case indexWord8Array# ba# idx# of
w1#
| isTrue# (w1# `leWord#` 0x7F##) -> (# chr1# w1#, 1# #)
| isTrue# (w1# `leWord#` 0xDF##) ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
in (# chr2# w1# w2#, 2# #)
| isTrue# (w1# `leWord#` 0xEF##) ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
w3# = indexWord8Array# ba# (idx# +# 2#)
in (# chr3# w1# w2# w3#, 3# #)
| otherwise ->
let w2# = indexWord8Array# ba# (idx# +# 1#)
w3# = indexWord8Array# ba# (idx# +# 2#)
w4# = indexWord8Array# ba# (idx# +# 3#)
in (# chr4# w1# w2# w3# w4#, 4# #)
This function assumed all bytes are UTF-8 encoded , and the index param point to the
decodeCharLen :: PrimArray Word8 -> Int -> Int
# INLINE decodeCharLen #
decodeCharLen (PrimArray ba#) (I# idx#) =
let i# = decodeCharLen# ba# idx# in I# i#
decodeCharLen# :: ByteArray# -> Int# -> Int#
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharLen# ba# idx# = case indexWord8Array# ba# idx# of
w1#
| isTrue# (w1# `leWord#` 0x7F##) -> 1#
| isTrue# (w1# `leWord#` 0xDF##) -> 2#
| isTrue# (w1# `leWord#` 0xEF##) -> 3#
| otherwise -> 4#
| Decode a ' ' from bytes in rerverse order .
This function assumed all bytes are UTF-8 encoded , and the index param point to the end
decodeCharReverse :: PrimArray Word8 -> Int -> (# Char, Int #)
# INLINE decodeCharReverse #
decodeCharReverse (PrimArray ba#) (I# idx#) =
let !(# c#, i# #) = decodeCharReverse# ba# idx# in (# C# c#, I# i# #)
decodeCharReverse_ :: PrimArray Word8 -> Int -> Char
decodeCharReverse_ (PrimArray ba#) (I# idx#) =
let !(# c#, _ #) = decodeCharReverse# ba# idx# in C# c#
decodeCharReverse# :: ByteArray# -> Int# -> (# Char#, Int# #)
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharReverse# ba# idx# =
let w1# = indexWord8Array# ba# idx#
in if isContinueByte# w1#
then
let w2# = indexWord8Array# ba# (idx# -# 1#)
in if isContinueByte# w2#
then
let w3# = indexWord8Array# ba# (idx# -# 2#)
in if isContinueByte# w3#
then
let w4# = indexWord8Array# ba# (idx# -# 3#)
in (# chr4# w4# w3# w2# w1#, 4# #)
else (# chr3# w3# w2# w1#, 3# #)
else (# chr2# w2# w1#, 2# #)
else (# chr1# w1#, 1# #)
This function assumed all bytes are UTF-8 encoded , and the index param point to the end
decodeCharLenReverse :: PrimArray Word8 -> Int -> Int
# INLINE decodeCharLenReverse #
decodeCharLenReverse (PrimArray ba#) (I# idx#) =
let i# = decodeCharLenReverse# ba# idx# in I# i#
decodeCharLenReverse# :: ByteArray# -> Int# -> Int#
This branchy code make GHC impossible to fuse , DON'T inline
decodeCharLenReverse# ba# idx# =
let w1# = indexWord8Array# ba# idx#
in if isContinueByte# w1#
then
let w2# = indexWord8Array# ba# (idx# -# 1#)
in if isContinueByte# w2#
then
let w3# = indexWord8Array# ba# (idx# -# 2#)
in if isContinueByte# w3#
then 4#
else 3#
else 2#
else 1#
between# :: Word# -> Word# -> Word# -> Bool
# INLINE between # #
between# w# l# h# = isTrue# (w# `geWord#` l#) && isTrue# (w# `leWord#` h#)
isContinueByte# :: Word# -> Bool
# INLINE isContinueByte # #
isContinueByte# w# = isTrue# (and# w# 0xC0## `eqWord#` 0x80##)
chr1# :: Word# -> Char#
# INLINE chr1 # #
chr1# x1# = chr# y1#
where
!y1# = word2Int# x1#
chr2# :: Word# -> Word# -> Char#
# INLINE chr2 # #
chr2# x1# x2# = chr# (z1# +# z2#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!z1# = uncheckedIShiftL# (y1# -# 0xC0#) 6#
!z2# = y2# -# 0x80#
chr3# :: Word# -> Word# -> Word# -> Char#
# INLINE chr3 # #
chr3# x1# x2# x3# = chr# (z1# +# z2# +# z3#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!z1# = uncheckedIShiftL# (y1# -# 0xE0#) 12#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 6#
!z3# = y3# -# 0x80#
chr4# :: Word# -> Word# -> Word# -> Word# -> Char#
# INLINE chr4 # #
chr4# x1# x2# x3# x4# = chr# (z1# +# z2# +# z3# +# z4#)
where
!y1# = word2Int# x1#
!y2# = word2Int# x2#
!y3# = word2Int# x3#
!y4# = word2Int# x4#
!z1# = uncheckedIShiftL# (y1# -# 0xF0#) 18#
!z2# = uncheckedIShiftL# (y2# -# 0x80#) 12#
!z3# = uncheckedIShiftL# (y3# -# 0x80#) 6#
!z4# = y4# -# 0x80#
copy length , must be 1 , 2 , 3 or 4
-> ST s ()
# INLINE copyChar #
copyChar !l !mba !j !ba !i = case l of
1 -> do writePrimArray mba j $ indexPrimArray ba i
2 -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
3 -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
writePrimArray mba (j+2) $ indexPrimArray ba (i+2)
_ -> do writePrimArray mba j $ indexPrimArray ba i
writePrimArray mba (j+1) $ indexPrimArray ba (i+1)
writePrimArray mba (j+2) $ indexPrimArray ba (i+2)
writePrimArray mba (j+3) $ indexPrimArray ba (i+3)
copy length , must be 1 , 2 , 3 or 4
-> ST s ()
# INLINE copyChar ' #
copyChar' !l !mba !j !ba !i = case l of
1 -> do writePrimArray mba j =<< readPrimArray ba i
2 -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
3 -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
writePrimArray mba (j+2) =<< readPrimArray ba (i+2)
_ -> do writePrimArray mba j =<< readPrimArray ba i
writePrimArray mba (j+1) =<< readPrimArray ba (i+1)
writePrimArray mba (j+2) =<< readPrimArray ba (i+2)
writePrimArray mba (j+3) =<< readPrimArray ba (i+3)
replacementChar :: Char
replacementChar = '\xFFFD'
|
bbef72792b5f60125a949f66f40ffb5f611aa64ac330096e54c88177201859fb | kakaranet/monitor | hal_sup.erl | -module(hal_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 5, 10}, []} }.
| null | https://raw.githubusercontent.com/kakaranet/monitor/348ac7e51721f94c95dc29c611addb5da6e18e57/apps/hal/src/hal_sup.erl | erlang | -module(hal_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
{ok, { {one_for_one, 5, 10}, []} }.
|
|
6dd78beff74a053998763fe73c9cfc6a0a7eaa2ca666ea089c7ef21a688b7ba7 | IBM/wcs-ocaml | json.mli |
* This file is part of the Watson Conversation Service OCaml API project .
*
* Copyright 2016 - 2017 IBM Corporation
*
* 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 .
* This file is part of the Watson Conversation Service OCaml API project.
*
* Copyright 2016-2017 IBM Corporation
*
* 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.
*)
(** Json utilities. *)
open Wcs_t
val read_json_file : (Yojson.lexer_state -> Lexing.lexbuf -> 'a) -> string -> 'a
*
[ read_json_file reader fname ] reads the file [ fname ] using the
reader [ reader ] generated by atdgen .
[read_json_file reader fname] reads the file [fname] using the
reader [reader] generated by atdgen.
*)
* { 6 Builders }
val null : json
(** The [null] value of JSON. *)
val int : int -> json
(** [int n] build the value of JSON [n]. *)
val bool : bool -> json
(** [bool b] build the value of JSON [b]. *)
val string : string -> json
(** [string s] build the value of JSON [s]. *)
val assoc : (string * json) list -> json
(** [assoc o] build the JSON object [o]. *)
val list : json list -> json
(** [list l] build the JSON list [l]. *)
* { 6 Manipulation functions }
val set : json -> string -> json -> json
(**
[set o x v] add (or replace) the a field [x] of the object [o] with
value [v].
*)
val get : json -> string -> json option
(**
[get o x] gets the value of the field [x] of the object [o].
*)
val take : json -> string -> json * json option
(**
[take o x] gets the value of the field [x] of the object [o] and
remove the field from the object. The left part of the return value
is the modified object and the right part is the value of the
field.
*)
val assign : json list -> json
*
[ assign [ o1 ; ... ; on ] ] create a json object that contains all the
fields of the objets [ o1 ] , ... , [ on ] . It is similare the the JavaScript
function [ Object.assing ( { } , o1 , ... on ) ] .
[assign [o1; ...; on]] create a json object that contains all the
fields of the objets [o1], ..., [on]. It is similare the the JavaScript
function [Object.assing({}, o1, ... on)].
*)
val push : json -> string -> json -> json
(**
[push o x v] add the value [v] in the list stored in a field [x]
of the object [o]. It the field [x] doesn't exists, it creates it.
*)
val pop : json -> string -> json * json option
(**
[pop o x] take a value in a list stored in the field [x] of [o].
*)
* { 6 Setters and getters }
* { 8 Boolean fields }
val set_bool : json -> string -> bool -> json
(**
[set_bool o x b] sets the a field [x] of the object [o] with value
[b].
*)
val get_bool : json -> string -> bool option
(**
[get_bool o x] gets the value of the field [x] of the object [o].
*)
* { 8 String fields }
val set_string : json -> string -> string -> json
(**
[set_string o x x] sets the a field [x] of the object [o] with string
[s].
*)
val get_string : json -> string -> string option
(**
[get_string o x] gets the value of the field [x] of the object [o].
*)
val take_string : json -> string -> json * string option
(**
[take_string o x] takes the value of the field [x] of the object [o].
*)
| null | https://raw.githubusercontent.com/IBM/wcs-ocaml/b237b7057f44caa09d36e466be015e2bc3173dd5/wcs-lib/json.mli | ocaml | * Json utilities.
* The [null] value of JSON.
* [int n] build the value of JSON [n].
* [bool b] build the value of JSON [b].
* [string s] build the value of JSON [s].
* [assoc o] build the JSON object [o].
* [list l] build the JSON list [l].
*
[set o x v] add (or replace) the a field [x] of the object [o] with
value [v].
*
[get o x] gets the value of the field [x] of the object [o].
*
[take o x] gets the value of the field [x] of the object [o] and
remove the field from the object. The left part of the return value
is the modified object and the right part is the value of the
field.
*
[push o x v] add the value [v] in the list stored in a field [x]
of the object [o]. It the field [x] doesn't exists, it creates it.
*
[pop o x] take a value in a list stored in the field [x] of [o].
*
[set_bool o x b] sets the a field [x] of the object [o] with value
[b].
*
[get_bool o x] gets the value of the field [x] of the object [o].
*
[set_string o x x] sets the a field [x] of the object [o] with string
[s].
*
[get_string o x] gets the value of the field [x] of the object [o].
*
[take_string o x] takes the value of the field [x] of the object [o].
|
* This file is part of the Watson Conversation Service OCaml API project .
*
* Copyright 2016 - 2017 IBM Corporation
*
* 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 .
* This file is part of the Watson Conversation Service OCaml API project.
*
* Copyright 2016-2017 IBM Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* -2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
open Wcs_t
val read_json_file : (Yojson.lexer_state -> Lexing.lexbuf -> 'a) -> string -> 'a
*
[ read_json_file reader fname ] reads the file [ fname ] using the
reader [ reader ] generated by atdgen .
[read_json_file reader fname] reads the file [fname] using the
reader [reader] generated by atdgen.
*)
* { 6 Builders }
val null : json
val int : int -> json
val bool : bool -> json
val string : string -> json
val assoc : (string * json) list -> json
val list : json list -> json
* { 6 Manipulation functions }
val set : json -> string -> json -> json
val get : json -> string -> json option
val take : json -> string -> json * json option
val assign : json list -> json
*
[ assign [ o1 ; ... ; on ] ] create a json object that contains all the
fields of the objets [ o1 ] , ... , [ on ] . It is similare the the JavaScript
function [ Object.assing ( { } , o1 , ... on ) ] .
[assign [o1; ...; on]] create a json object that contains all the
fields of the objets [o1], ..., [on]. It is similare the the JavaScript
function [Object.assing({}, o1, ... on)].
*)
val push : json -> string -> json -> json
val pop : json -> string -> json * json option
* { 6 Setters and getters }
* { 8 Boolean fields }
val set_bool : json -> string -> bool -> json
val get_bool : json -> string -> bool option
* { 8 String fields }
val set_string : json -> string -> string -> json
val get_string : json -> string -> string option
val take_string : json -> string -> json * string option
|
50ff56a7c3b3aafdb9bbd4946a2061e6d9c841da800cc37c00bbf517e3627d2d | OCamlPro/techelson | sigs.mli | open Base
open Common
(** Contract environment.
Contains a type and some functions to store
- a user-provided name-contract map (for deployment)
- a map from addresses to live (deployed) contracts
*)
module type ContractEnv = sig
(** The underlying theory. *)
module Theory : Theo.Sigs.Theory
(** Type of the contract environment. *)
type t
(** An operation.
We do not use `Theory.operation` directly because we need to be able to detect when the
exact same operation runs twice.
*)
type operation
(** Clones an environment.
This is useful when an operation can fail: it acts as a backtracking mechanism.
*)
val clone : t -> t
val expired_uids : t -> IntSet.t
(** Functions over operations. *)
module Op : sig
(** Operation formatter. *)
val fmt : formatter -> operation -> unit
(** Theory operation accessor.
This function uses the environment to check whether the operation can run. That is,
it will fail if the uid of the operation is expired.
*)
val op : t -> operation -> Theory.operation
* MustFail version of an operation .
The operation is not considered processed : does not invalid the uid of the operation .
This is used when wrapping an operation into a ` MustFail ` .
The operation is not considered processed: does not invalid the uid of the operation.
This is used when wrapping an operation into a `MustFail`.
*)
val must_fail :
t ->
(Theory.value * Dtyp.t) option ->
operation ->
Theory.value
(** The unique identifier of the operation. *)
val uid : operation -> int
(** Constructor. *)
val mk : int -> Theory.operation -> operation
end
(** Type of a live contract. *)
type live = private {
address : Theory.Address.t ;
(** Address of the live contract. *)
contract : Contract.t ;
(** Contract declaration. *)
mutable balance : Theory.Tez.t ;
(** Balance of the contract. *)
mutable storage : Theory.value ;
(** Value of the storage. *)
params : Theory.contract_params ;
(** Parameters the contract was created with. *)
}
(** Generates a unique identifier for some operation. *)
val get_uid : t -> int
(** An empty contract environment. *)
val empty : unit -> t
(** Registers a name/contract binding.
Throws an exception if the name is already mapped to something.
*)
val add : Contract.t -> t -> unit
(** Retrieves a contract from its name. *)
val get : string -> t -> Contract.t
* Type checks two types .
val unify : t -> Dtyp.t -> Dtyp.t -> unit
(** Formats the live contracts of an environment. *)
val fmt : formatter -> t -> unit
(** Operations dealing with live contracts. *)
module Live : sig
(** Creates a live contract. *)
val create : Theory.contract_params -> Contract.t -> t -> unit
(** Live contract formatter. *)
val fmt : formatter -> live -> unit
(** Retrieves a live contract from its address. *)
val get : Theory.Address.t -> t -> live option
(** Number of live contracts. *)
val count : t -> int
(** Transfers some money to a live contract. *)
val transfer : src : live option -> Theory.Tez.t -> live -> unit
(** Collects some money from a live contract. *)
val collect : tgt : live -> Theory.Tez.t -> live -> unit
(** Updates a live contract.
Arguments
- new balance, will replace the old balance
- new storage and its type
- address of the contract being updated
- environment
The new balance is **not** added to the old one, it's a purely destructive update.
*)
val update : Theory.Tez.t -> Theory.value * Dtyp.t -> Theory.Address.t -> t -> unit
(** Updates the storage of a live contract. *)
val update_storage : t -> Theory.value -> Dtyp.t -> live -> unit
(** Sets the delegate of a live contract.
This can throw a protocol exception if the contract is not delegatable.
*)
val set_delegate : Theory.KeyH.t option -> live -> unit
end
(** Account related functions. *)
module Account : sig
* Retrieves an implicit account for some key hash .
Creates the account with zero mutez if it does not exist .
Creates the account with zero mutez if it does not exist.
*)
val implicit : Theory.KeyH.t -> t -> live
end
end
(** A stack and its most basic operations. *)
module type StackBase = sig
(** Underlying theory. *)
module Theory : Theo.Sigs.Theory
* Underling contract environment .
module Env : ContractEnv with module Theory = Theory
(** Type of the stack. *)
type t
(** Contract environment. *)
val contract_env : t -> Env.t
(** Stack formatter. *)
val fmt : formatter -> t -> unit
(** The empty stack. *)
val empty : Env.t -> t
(** True if the stack is empty. *)
val is_empty : t -> bool
(** Pushes something on the stack. *)
val push : ?binding : Annot.Var.t option -> Dtyp.t -> Theory.value -> t -> unit
(** Pops something from the stack. *)
val pop : t -> Theory.value * Dtyp.t
* Type checks two types .
val unify : t -> Dtyp.t -> Dtyp.t -> unit
(** Clears the stack completely.
Used when running into errors.
*)
val clear : t -> unit
(** Map over the last element on the stack. *)
val map_last : (Theory.value -> Dtyp.t -> Theory.value) -> t -> unit
* Swaps the last two elements of the stack .
val swap : t -> unit
* Dips the stack by one level .
val dip : t -> unit
(** Duplicates the last element on the stack. *)
val dup : ?binding : Annot.Var.t option -> t -> unit
* Undips the stack by one level .
val undip : t -> unit
end
* Augments ` StackBase ` with helper functions to pop / push stuff .
module type Stack = sig
include StackBase
(** Convenience pop helpers. *)
module Pop : sig
(** Pops a boolean value. *)
val bool : t -> bool * Dtyp.t
(** Pops an integer value. *)
val int : t -> Theory.Int.t * Dtyp.t
(** Pops a natural value. *)
val nat : t -> Theory.Nat.t * Dtyp.t
(** Pops a string value. *)
val str : t -> Theory.Str.t * Dtyp.t
(** Pops some bytes. *)
val bytes : t -> Theory.Bytes.t * Dtyp.t
(** Pops a string. *)
val string : t -> Theory.Str.t * Dtyp.t
(** Pops a timestamp. *)
val timestamp : t -> Theory.TStamp.t * Dtyp.t
(** Pops a key hash. *)
val key_hash : t -> Theory.KeyH.t * Dtyp.t
(** Pops an optional key hash. *)
val key_hash_option : t -> Theory.KeyH.t option * Dtyp.t
(** Pops a mutez value. *)
val tez : t -> Theory.Tez.t * Dtyp.t
(** Pops a comparable value. *)
val cmp : t -> Theory.Cmp.t * Dtyp.t
(** Pops an address. *)
val address : t -> Theory.Address.t * Dtyp.t
(** Pops an optional address. *)
val address_option : t -> Theory.Address.t option * Dtyp.t
(** Pops a contract. *)
val contract : t -> Theory.Address.t option * Mic.contract
(** Pops a disjunction. *)
val either : t -> (Theory.value, Theory.value) Theory.Either.t * Dtyp.t
(** Pops an option. *)
val option : t -> Theory.value Theory.Option.t * Dtyp.t
(** Pops a list. *)
val list : t -> Theory.value Theory.Lst.t * Dtyp.t
(** Pops a set. *)
val set : t -> Theory.Set.t * Dtyp.t
(** Pops a map. *)
val map : t -> Theory.value Theory.Map.t * Dtyp.t
(** Pops a pair. *)
val pair : t -> (Theory.value * Dtyp.t) * (Theory.value * Dtyp.t)
(** Pops a lambda. *)
val lambda : t -> Dtyp.t * Dtyp.t * Mic.t
(** Pops an operation. *)
val operation : t -> Env.operation * Dtyp.t
(** Pops a list of operation. *)
val operation_list : t -> Env.operation list * Dtyp.t
(** Pops an address or a contract. *)
val address_or_contract : t -> Theory.Address.t option
(** Pops the result of a contract call.
A list of operations and the new storage value. The datatype returned is that of the
storage value.
*)
val contract_res : t -> Env.operation list * Theory.value * Dtyp.t
(** Pops parameters for a contract creation.
Takes the address generated by the interpreter for this particular contract creation
operation.
*)
val contract_params : Theory.Address.t -> t -> Theory.contract_params * Dtyp.t
(** Pops parameters for a contract creation with the entry given as a lambda. *)
val contract_params_and_lambda :
Theory.Address.t -> t -> Theory.contract_params * Mic.contract
(** Pops parameters for an account creation.
The difference with `contract_params` is that this one does not retrieve the
`spendable` flag and initial storage value from the stack. They are set to `true` and
`unit`.
*)
val account_params : Theory.Address.t -> t -> Theory.contract_params
end
(** Convenience push operation. *)
module Push : sig
(** Pushes on the stack `Some` of the last element of the stack. *)
val some :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
t ->
unit
(** Pushes a `None` value on the stack. *)
val none :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
(** Pushes a left value for a disjunction. *)
val left :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
(** Pushes a right value for a disjunction. *)
val right :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
(** Pushes a `nil` value. *)
val nil : ?binding : Annot.Var.t option -> ?alias : Dtyp.alias -> Dtyp.t -> t -> unit
(** Pushes an empty set value. *)
val empty_set : ?binding : Annot.Var.t option -> ?alias : Dtyp.alias -> Dtyp.t -> t -> unit
(** Pushes an empty map value. *)
val empty_map :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
Dtyp.t ->
Dtyp.t ->
t ->
unit
(** Pushes an address on the stack. *)
val address :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
Theory.Address.t ->
t ->
unit
end
* Prepend operation over lists .
Pushes on the stack the result of prepending the last element on the stack to the
second - to - last element on the stack .
Pushes on the stack the result of prepending the last element on the stack to the
second-to-last element on the stack.
*)
val cons : t -> unit
(** Renames the element on the top of the stack. *)
val rename : Annot.Var.t option -> t -> unit
end
| null | https://raw.githubusercontent.com/OCamlPro/techelson/932fbf08675cd13d34a07e3b3d77234bdafcf5bc/src/5_stack/sigs.mli | ocaml | * Contract environment.
Contains a type and some functions to store
- a user-provided name-contract map (for deployment)
- a map from addresses to live (deployed) contracts
* The underlying theory.
* Type of the contract environment.
* An operation.
We do not use `Theory.operation` directly because we need to be able to detect when the
exact same operation runs twice.
* Clones an environment.
This is useful when an operation can fail: it acts as a backtracking mechanism.
* Functions over operations.
* Operation formatter.
* Theory operation accessor.
This function uses the environment to check whether the operation can run. That is,
it will fail if the uid of the operation is expired.
* The unique identifier of the operation.
* Constructor.
* Type of a live contract.
* Address of the live contract.
* Contract declaration.
* Balance of the contract.
* Value of the storage.
* Parameters the contract was created with.
* Generates a unique identifier for some operation.
* An empty contract environment.
* Registers a name/contract binding.
Throws an exception if the name is already mapped to something.
* Retrieves a contract from its name.
* Formats the live contracts of an environment.
* Operations dealing with live contracts.
* Creates a live contract.
* Live contract formatter.
* Retrieves a live contract from its address.
* Number of live contracts.
* Transfers some money to a live contract.
* Collects some money from a live contract.
* Updates a live contract.
Arguments
- new balance, will replace the old balance
- new storage and its type
- address of the contract being updated
- environment
The new balance is **not** added to the old one, it's a purely destructive update.
* Updates the storage of a live contract.
* Sets the delegate of a live contract.
This can throw a protocol exception if the contract is not delegatable.
* Account related functions.
* A stack and its most basic operations.
* Underlying theory.
* Type of the stack.
* Contract environment.
* Stack formatter.
* The empty stack.
* True if the stack is empty.
* Pushes something on the stack.
* Pops something from the stack.
* Clears the stack completely.
Used when running into errors.
* Map over the last element on the stack.
* Duplicates the last element on the stack.
* Convenience pop helpers.
* Pops a boolean value.
* Pops an integer value.
* Pops a natural value.
* Pops a string value.
* Pops some bytes.
* Pops a string.
* Pops a timestamp.
* Pops a key hash.
* Pops an optional key hash.
* Pops a mutez value.
* Pops a comparable value.
* Pops an address.
* Pops an optional address.
* Pops a contract.
* Pops a disjunction.
* Pops an option.
* Pops a list.
* Pops a set.
* Pops a map.
* Pops a pair.
* Pops a lambda.
* Pops an operation.
* Pops a list of operation.
* Pops an address or a contract.
* Pops the result of a contract call.
A list of operations and the new storage value. The datatype returned is that of the
storage value.
* Pops parameters for a contract creation.
Takes the address generated by the interpreter for this particular contract creation
operation.
* Pops parameters for a contract creation with the entry given as a lambda.
* Pops parameters for an account creation.
The difference with `contract_params` is that this one does not retrieve the
`spendable` flag and initial storage value from the stack. They are set to `true` and
`unit`.
* Convenience push operation.
* Pushes on the stack `Some` of the last element of the stack.
* Pushes a `None` value on the stack.
* Pushes a left value for a disjunction.
* Pushes a right value for a disjunction.
* Pushes a `nil` value.
* Pushes an empty set value.
* Pushes an empty map value.
* Pushes an address on the stack.
* Renames the element on the top of the stack. | open Base
open Common
module type ContractEnv = sig
module Theory : Theo.Sigs.Theory
type t
type operation
val clone : t -> t
val expired_uids : t -> IntSet.t
module Op : sig
val fmt : formatter -> operation -> unit
val op : t -> operation -> Theory.operation
* MustFail version of an operation .
The operation is not considered processed : does not invalid the uid of the operation .
This is used when wrapping an operation into a ` MustFail ` .
The operation is not considered processed: does not invalid the uid of the operation.
This is used when wrapping an operation into a `MustFail`.
*)
val must_fail :
t ->
(Theory.value * Dtyp.t) option ->
operation ->
Theory.value
val uid : operation -> int
val mk : int -> Theory.operation -> operation
end
type live = private {
address : Theory.Address.t ;
contract : Contract.t ;
mutable balance : Theory.Tez.t ;
mutable storage : Theory.value ;
params : Theory.contract_params ;
}
val get_uid : t -> int
val empty : unit -> t
val add : Contract.t -> t -> unit
val get : string -> t -> Contract.t
* Type checks two types .
val unify : t -> Dtyp.t -> Dtyp.t -> unit
val fmt : formatter -> t -> unit
module Live : sig
val create : Theory.contract_params -> Contract.t -> t -> unit
val fmt : formatter -> live -> unit
val get : Theory.Address.t -> t -> live option
val count : t -> int
val transfer : src : live option -> Theory.Tez.t -> live -> unit
val collect : tgt : live -> Theory.Tez.t -> live -> unit
val update : Theory.Tez.t -> Theory.value * Dtyp.t -> Theory.Address.t -> t -> unit
val update_storage : t -> Theory.value -> Dtyp.t -> live -> unit
val set_delegate : Theory.KeyH.t option -> live -> unit
end
module Account : sig
* Retrieves an implicit account for some key hash .
Creates the account with zero mutez if it does not exist .
Creates the account with zero mutez if it does not exist.
*)
val implicit : Theory.KeyH.t -> t -> live
end
end
module type StackBase = sig
module Theory : Theo.Sigs.Theory
* Underling contract environment .
module Env : ContractEnv with module Theory = Theory
type t
val contract_env : t -> Env.t
val fmt : formatter -> t -> unit
val empty : Env.t -> t
val is_empty : t -> bool
val push : ?binding : Annot.Var.t option -> Dtyp.t -> Theory.value -> t -> unit
val pop : t -> Theory.value * Dtyp.t
* Type checks two types .
val unify : t -> Dtyp.t -> Dtyp.t -> unit
val clear : t -> unit
val map_last : (Theory.value -> Dtyp.t -> Theory.value) -> t -> unit
* Swaps the last two elements of the stack .
val swap : t -> unit
* Dips the stack by one level .
val dip : t -> unit
val dup : ?binding : Annot.Var.t option -> t -> unit
* Undips the stack by one level .
val undip : t -> unit
end
* Augments ` StackBase ` with helper functions to pop / push stuff .
module type Stack = sig
include StackBase
module Pop : sig
val bool : t -> bool * Dtyp.t
val int : t -> Theory.Int.t * Dtyp.t
val nat : t -> Theory.Nat.t * Dtyp.t
val str : t -> Theory.Str.t * Dtyp.t
val bytes : t -> Theory.Bytes.t * Dtyp.t
val string : t -> Theory.Str.t * Dtyp.t
val timestamp : t -> Theory.TStamp.t * Dtyp.t
val key_hash : t -> Theory.KeyH.t * Dtyp.t
val key_hash_option : t -> Theory.KeyH.t option * Dtyp.t
val tez : t -> Theory.Tez.t * Dtyp.t
val cmp : t -> Theory.Cmp.t * Dtyp.t
val address : t -> Theory.Address.t * Dtyp.t
val address_option : t -> Theory.Address.t option * Dtyp.t
val contract : t -> Theory.Address.t option * Mic.contract
val either : t -> (Theory.value, Theory.value) Theory.Either.t * Dtyp.t
val option : t -> Theory.value Theory.Option.t * Dtyp.t
val list : t -> Theory.value Theory.Lst.t * Dtyp.t
val set : t -> Theory.Set.t * Dtyp.t
val map : t -> Theory.value Theory.Map.t * Dtyp.t
val pair : t -> (Theory.value * Dtyp.t) * (Theory.value * Dtyp.t)
val lambda : t -> Dtyp.t * Dtyp.t * Mic.t
val operation : t -> Env.operation * Dtyp.t
val operation_list : t -> Env.operation list * Dtyp.t
val address_or_contract : t -> Theory.Address.t option
val contract_res : t -> Env.operation list * Theory.value * Dtyp.t
val contract_params : Theory.Address.t -> t -> Theory.contract_params * Dtyp.t
val contract_params_and_lambda :
Theory.Address.t -> t -> Theory.contract_params * Mic.contract
val account_params : Theory.Address.t -> t -> Theory.contract_params
end
module Push : sig
val some :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
t ->
unit
val none :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
val left :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
val right :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
?field : Annot.Field.t option ->
Dtyp.t ->
t ->
unit
val nil : ?binding : Annot.Var.t option -> ?alias : Dtyp.alias -> Dtyp.t -> t -> unit
val empty_set : ?binding : Annot.Var.t option -> ?alias : Dtyp.alias -> Dtyp.t -> t -> unit
val empty_map :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
Dtyp.t ->
Dtyp.t ->
t ->
unit
val address :
?binding : Annot.Var.t option ->
?alias : Dtyp.alias ->
Theory.Address.t ->
t ->
unit
end
* Prepend operation over lists .
Pushes on the stack the result of prepending the last element on the stack to the
second - to - last element on the stack .
Pushes on the stack the result of prepending the last element on the stack to the
second-to-last element on the stack.
*)
val cons : t -> unit
val rename : Annot.Var.t option -> t -> unit
end
|
f4e7bf88748c21e12bd43a4028249270ab8cfa9edf5e2d2a7fb060438f154b87 | GlideAngle/flare-timing | Mask.hs | {-# OPTIONS_GHC -fplugin Data.UnitsOfMeasure.Plugin #-}
# OPTIONS_GHC -fno - warn - partial - type - signatures #
module Mask (writeMask) where
import Control.Lens ((^?), element)
import Control.Monad.Except (runExceptT)
import Control.Concurrent.ParallelIO (parallel)
import Flight.Clip (FlyCut(..), FlyClipping(..))
import qualified Flight.Comp as Cmp (Nominal(..))
import Flight.Comp
( ScoringInputFiles
, CompTaskSettings(..)
, Pilot(..)
, Task(..)
, Tweak(..)
, IxTask(..)
, TrackFileFail(..)
, RoutesLookupTaskDistance(..)
)
import Flight.Mask (FnIxTask, settingsLogs)
import Flight.Track.Tag (CompTagging)
import Flight.Kml (LatLngAlt(..), MarkedFixes(..))
import Flight.Lookup.Stop (ScoredLookup(..))
import Flight.Track.Arrival (TrackArrival(..), arrivalsByTime, arrivalsByRank)
import qualified Flight.Track.Arrival as Arrival (TrackArrival(..))
import qualified Flight.Lookup as Lookup
(scoredTimeRange, arrivalRank, compRoutes, pilotTime, pilotEssTime)
import Flight.Lookup.Tag (tagArrivalRank, tagPilotTime)
import Flight.TrackLog (pilotTrack)
import Flight.Scribe (writeCompMaskArrival, writeCompMaskSpeed)
import "flight-gap-allot" Flight.Score (ArrivalFraction(..), powerExp23)
import Flight.Span.Math (Math(..))
import Stats (TimeStats(..), FlightStats(..), nullStats, altToAlt)
import MaskArrival (maskArrival, arrivalInputs)
import MaskSpeed (maskSpeed)
import MaskPilots (maskPilots)
type IOStep k = Either (Pilot, TrackFileFail) (Pilot, Pilot -> FlightStats k)
writeMask
:: CompTaskSettings k
-> RoutesLookupTaskDistance
-> Math
-> ScoredLookup
-> Maybe CompTagging
-> [IxTask]
-> [Pilot]
-> ScoringInputFiles
-> IO ()
writeMask
CompTaskSettings
{ nominal = Cmp.Nominal{free}
, compTweak
, tasks
, pilotGroups
}
routes
math
flying
tags
ixSelectTasks selectPilots inFiles@(compFile, _) = do
(_, selectedCompLogs) <- settingsLogs inFiles ixSelectTasks selectPilots
fss :: [[IOStep k]] <-
sequence
[
parallel
[ runExceptT $ pilotTrack (flown math flying tags tasks ixTask) pilotLog
| pilotLog <- taskLogs
]
| ixTask <- IxTask <$> [1..]
| taskLogs <- selectedCompLogs
]
let iTasks = IxTask <$> [1 .. length fss]
Task lengths ( ls ) .
let lsTask' = Lookup.compRoutes routes iTasks
let yss = maskPilots free tasks lsTask' pilotGroups fss
-- Arrivals (as).
let as :: [[(Pilot, TrackArrival)]] =
[
let aRank = maybe True arrivalRank tweak
aTime = maybe False arrivalTime tweak
ys' = arrivalInputs ys
in
case (aRank, aTime) of
(True, _) -> arrivalsByRank ys'
(False, True) -> arrivalsByTime ys'
-- NOTE: We're not using either kind of arrival
for points so zero the fraction .
(False, False) ->
[ (p, ta{Arrival.frac = ArrivalFraction 0})
| (p, ta) <- arrivalsByRank ys'
]
| Task{taskTweak = tweak} <- tasks
| ys <- yss
]
REVIEW : Waiting on feedback on GAP rule question about altitude
-- bonus distance pushing a flight to goal so that it arrives.
writeCompMaskArrival compFile (maskArrival as)
let tpe = maybe powerExp23 timePowerExponent compTweak
let (_gsBestTime, maskSpeed') = maskSpeed tpe lsTask' yss
-- NOTE: For time and leading points do not use altitude bonus distances.
writeCompMaskSpeed compFile maskSpeed'
flown :: Math -> ScoredLookup -> Maybe CompTagging -> FnIxTask k (Pilot -> FlightStats k)
flown Rational _ _ _ _ _ _ = error "Nigh for rationals not yet implemented."
flown Floating flying tags tasks iTask@(IxTask i) mf@MarkedFixes{mark0} p =
case maybeTask of
Nothing -> nullStats
Just _ ->
case (ssTime, gsTime, esTime, arrivalRank) of
(Just a, Just b, Just e, c@(Just _)) ->
nullStats {statTimeRank = Just $ TimeStats a b e c}
_ ->
nullStats
{ statAlt =
case reverse ys of
[] -> Nothing
y : _ -> Just . altToAlt $ altGps y
}
where
maybeTask = tasks ^? element (i - 1)
(_, esTime) = Lookup.pilotEssTime (tagPilotTime tags) mf iTask [] speedSection' p
ssTime = Lookup.pilotTime (tagPilotTime tags) mf iTask [] speedSection' p
gsTime = Lookup.pilotTime (tagPilotTime tags) mf iTask startGates' speedSection' p
arrivalRank = Lookup.arrivalRank (tagArrivalRank tags) mf iTask speedSection' p
FlyCut{uncut = MarkedFixes{fixes = ys}} = clipToCut xs
xs =
FlyCut
{ cut = Lookup.scoredTimeRange flying mark0 iTask p
, uncut = mf
}
(startGates', speedSection') =
case tasks ^? element (i - 1) of
Nothing -> ([], Nothing)
Just Task{..} -> (startGates, speedSection)
| null | https://raw.githubusercontent.com/GlideAngle/flare-timing/34873946be9b93c37048ed118ef5b4649c71d630/lang-haskell/flare-timing/prod-apps/mask-arrival/Mask.hs | haskell | # OPTIONS_GHC -fplugin Data.UnitsOfMeasure.Plugin #
Arrivals (as).
NOTE: We're not using either kind of arrival
bonus distance pushing a flight to goal so that it arrives.
NOTE: For time and leading points do not use altitude bonus distances. | # OPTIONS_GHC -fno - warn - partial - type - signatures #
module Mask (writeMask) where
import Control.Lens ((^?), element)
import Control.Monad.Except (runExceptT)
import Control.Concurrent.ParallelIO (parallel)
import Flight.Clip (FlyCut(..), FlyClipping(..))
import qualified Flight.Comp as Cmp (Nominal(..))
import Flight.Comp
( ScoringInputFiles
, CompTaskSettings(..)
, Pilot(..)
, Task(..)
, Tweak(..)
, IxTask(..)
, TrackFileFail(..)
, RoutesLookupTaskDistance(..)
)
import Flight.Mask (FnIxTask, settingsLogs)
import Flight.Track.Tag (CompTagging)
import Flight.Kml (LatLngAlt(..), MarkedFixes(..))
import Flight.Lookup.Stop (ScoredLookup(..))
import Flight.Track.Arrival (TrackArrival(..), arrivalsByTime, arrivalsByRank)
import qualified Flight.Track.Arrival as Arrival (TrackArrival(..))
import qualified Flight.Lookup as Lookup
(scoredTimeRange, arrivalRank, compRoutes, pilotTime, pilotEssTime)
import Flight.Lookup.Tag (tagArrivalRank, tagPilotTime)
import Flight.TrackLog (pilotTrack)
import Flight.Scribe (writeCompMaskArrival, writeCompMaskSpeed)
import "flight-gap-allot" Flight.Score (ArrivalFraction(..), powerExp23)
import Flight.Span.Math (Math(..))
import Stats (TimeStats(..), FlightStats(..), nullStats, altToAlt)
import MaskArrival (maskArrival, arrivalInputs)
import MaskSpeed (maskSpeed)
import MaskPilots (maskPilots)
type IOStep k = Either (Pilot, TrackFileFail) (Pilot, Pilot -> FlightStats k)
writeMask
:: CompTaskSettings k
-> RoutesLookupTaskDistance
-> Math
-> ScoredLookup
-> Maybe CompTagging
-> [IxTask]
-> [Pilot]
-> ScoringInputFiles
-> IO ()
writeMask
CompTaskSettings
{ nominal = Cmp.Nominal{free}
, compTweak
, tasks
, pilotGroups
}
routes
math
flying
tags
ixSelectTasks selectPilots inFiles@(compFile, _) = do
(_, selectedCompLogs) <- settingsLogs inFiles ixSelectTasks selectPilots
fss :: [[IOStep k]] <-
sequence
[
parallel
[ runExceptT $ pilotTrack (flown math flying tags tasks ixTask) pilotLog
| pilotLog <- taskLogs
]
| ixTask <- IxTask <$> [1..]
| taskLogs <- selectedCompLogs
]
let iTasks = IxTask <$> [1 .. length fss]
Task lengths ( ls ) .
let lsTask' = Lookup.compRoutes routes iTasks
let yss = maskPilots free tasks lsTask' pilotGroups fss
let as :: [[(Pilot, TrackArrival)]] =
[
let aRank = maybe True arrivalRank tweak
aTime = maybe False arrivalTime tweak
ys' = arrivalInputs ys
in
case (aRank, aTime) of
(True, _) -> arrivalsByRank ys'
(False, True) -> arrivalsByTime ys'
for points so zero the fraction .
(False, False) ->
[ (p, ta{Arrival.frac = ArrivalFraction 0})
| (p, ta) <- arrivalsByRank ys'
]
| Task{taskTweak = tweak} <- tasks
| ys <- yss
]
REVIEW : Waiting on feedback on GAP rule question about altitude
writeCompMaskArrival compFile (maskArrival as)
let tpe = maybe powerExp23 timePowerExponent compTweak
let (_gsBestTime, maskSpeed') = maskSpeed tpe lsTask' yss
writeCompMaskSpeed compFile maskSpeed'
flown :: Math -> ScoredLookup -> Maybe CompTagging -> FnIxTask k (Pilot -> FlightStats k)
flown Rational _ _ _ _ _ _ = error "Nigh for rationals not yet implemented."
flown Floating flying tags tasks iTask@(IxTask i) mf@MarkedFixes{mark0} p =
case maybeTask of
Nothing -> nullStats
Just _ ->
case (ssTime, gsTime, esTime, arrivalRank) of
(Just a, Just b, Just e, c@(Just _)) ->
nullStats {statTimeRank = Just $ TimeStats a b e c}
_ ->
nullStats
{ statAlt =
case reverse ys of
[] -> Nothing
y : _ -> Just . altToAlt $ altGps y
}
where
maybeTask = tasks ^? element (i - 1)
(_, esTime) = Lookup.pilotEssTime (tagPilotTime tags) mf iTask [] speedSection' p
ssTime = Lookup.pilotTime (tagPilotTime tags) mf iTask [] speedSection' p
gsTime = Lookup.pilotTime (tagPilotTime tags) mf iTask startGates' speedSection' p
arrivalRank = Lookup.arrivalRank (tagArrivalRank tags) mf iTask speedSection' p
FlyCut{uncut = MarkedFixes{fixes = ys}} = clipToCut xs
xs =
FlyCut
{ cut = Lookup.scoredTimeRange flying mark0 iTask p
, uncut = mf
}
(startGates', speedSection') =
case tasks ^? element (i - 1) of
Nothing -> ([], Nothing)
Just Task{..} -> (startGates, speedSection)
|
5d11dacbbc30542005618ae93014d07ac07f754554c6d1ceff10703bde5e69c5 | Kakadu/fp2022 | channel.mli | * Copyright 2021 - 2022 , Kakadu , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
type 'v t
val create : unit -> 'v t
val send : 'v t -> 'v -> unit
val receive : 'v t -> 'v
| null | https://raw.githubusercontent.com/Kakadu/fp2022/7b828b045771dfa9da59f547a555e05d382fc9cd/Golang/lib/channel.mli | ocaml | * Copyright 2021 - 2022 , Kakadu , and contributors
* SPDX - License - Identifier : LGPL-3.0 - or - later
type 'v t
val create : unit -> 'v t
val send : 'v t -> 'v -> unit
val receive : 'v t -> 'v
|
|
a0a27f161cb3b9168a94643032907b059125f570138bb28c7640c392580ac0ce | vodori/missing | core_test.clj | (ns missing.core-test
(:require [clojure.test :refer :all :exclude (testing)]
[missing.core :refer :all]
[clojure.set :as sets])
(:import (java.time Duration)
(java.util Arrays)))
(def invokes (atom []))
(def capture (fn [x] (swap! invokes conj x) x))
(def clear! (fn [] (reset! invokes [])))
(use-fixtures :each
(fn [tests]
(clear!)
(tests)
(clear!)))
(defmacro testing [description & body]
`(clojure.test/testing ~description
(do (clear!) ~@body (clear!))))
(deftest filter-keys-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (filter-keys any? nil)))
(is (= {1 2 3 4} (filter-keys odd? m)))))
(deftest filter-vals-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (filter-vals any? nil)))
(is (= {6 5 8 7} (filter-vals odd? m)))))
(deftest map-keys-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (map-keys inc nil)))
(is (= {2 2 4 4 7 5 9 7} (map-keys inc m)))))
(deftest map-vals-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (map-vals inc nil)))
(is (= {1 3 3 5 6 6 8 8} (map-vals inc m)))))
(deftest reverse-map-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (reverse-map nil)))
(is (= {2 1 4 3 5 6 7 8} (reverse-map m)))))
(deftest index-by-test
(let [coll [{:id 1} {:id 2} {:id 3}]]
(is (= {1 {:id 1} 2 {:id 2} 3 {:id 3}} (index-by :id coll)))))
(deftest contains-all?-test
(let [coll #{1 2 3 4 5}]
(is (contains-all? coll []))
(is (contains-all? coll [1 2]))
(is (contains-all? coll [1 2 3 4 5]))
(is (not (contains-all? coll [1 6])))))
(deftest intersect?-test
(is (intersect? #{1 2} #{2} #{2 3}))
(is (not (intersect? #{1} #{2} #{3})))
(is (not (intersect? #{1 2} #{2} #{3}))))
(deftest exclusive?-test
(is (not (exclusive? #{1 2} #{2} #{2 3})))
(is (exclusive? #{1} #{2} #{3}))
(is (exclusive? #{1 2} #{3} #{4 5})))
(deftest keepcat-test
(let [coll [[1 2 3 nil nil 4] [nil 5 6]]]
(is (= [1 2 3 4 5 6] (into [] (keepcat identity) coll)))
(is (= [1 2 3 4 5 6] (vec (keepcat identity coll))))))
(deftest lift-by-test
(let [f (fn [x] (* x x))]
(is (= 9 ((lift-by (partial * 3) f) 1)))))
(deftest deep-merge-test
(let [m1 {1 {:stuff 3 :thing 2 :other 100} 2 4 :ten 10} m2 {1 {:things 4 :stuff 5 :other nil} :ten nil}]
(is (= {1 {:thing 2 :stuff 5 :things 4 :other nil} 2 4 :ten nil} (deep-merge m1 m2)))))
(deftest key=-test
(is (key= :stuff :stuff))
(is (key= "stuff" :stuff))
(is (not (key= :badger :stuff)))
(is (not (key= "badger" :stuff))))
(deftest nor-test
(let [state (atom [])]
(is (not (nor true (swap! state conj 1))))
(is (= [] @state)))
(let [state (atom [])]
(is (not (nor (identity false) (swap! state conj 1))))
(is (= [1] @state)))
(let [state (atom true) state2 (atom true)]
(is (nor (identity false) (reset! state false) (reset! state2 false)))
(is (false? @state))
(is (false? @state2))))
(deftest sort-by-value-test
(let [m {1 2 4 5 3 4 0 5}]
(is (= [[4 5] [0 5] [3 4] [1 2]] (seq (sorted-map-by-value m (flip compare)))))
(is (= [[1 2] [3 4] [0 5] [4 5]] (seq (sorted-map-by-value m))))))
(deftest dissoc-in-test
(let [m {1 {:stuff 3 :thing 2} 2 4}]
(is (= {1 {:thing 2} 2 4} (dissoc-in m [1 :stuff])))))
(deftest distinct-by-test
(let [vs [{:stuff 5 :thing 2} {:thing 3 :stuff 7} {:thing 4 :stuff 5}]]
(is (= vs (distinct-by :thing vs)))
(is (= vs (into [] (distinct-by :thing) vs)))
(is (= [(get vs 0) (get vs 1)] (distinct-by :stuff vs)))
(is (= [(get vs 0) (get vs 1)] (into [] (distinct-by :stuff) vs)))))
(deftest merge-sort-test
(let [v1 (range 0 10 2) v2 (range 1 10 2)]
(is (= (range 0 10) (merge-sort [v1 v2])))))
(deftest do-force-test
(let [state (atom [])]
(is (nil?
(doforce
(do (swap! state conj 1) (throw (ex-info "" {})))
(do (swap! state conj 2) (throw (ex-info "" {})))
(do (swap! state conj 3) (throw (ex-info "" {})))
(do (swap! state conj 4) (throw (ex-info "" {}))))))
(is (= [1 2 3 4] @state))))
(deftest with-timeout-test
(let [start (System/currentTimeMillis)
[success result] (with-timeout 1000 (Thread/sleep 5000))
stop (System/currentTimeMillis)]
(is (not success))
(is (nil? result))
(is (> 2000 (- stop start)))))
(deftest run-par!-test
(let [task-durations [500 600 800]
[millis _] (timing (run-par! #(Thread/sleep %) task-durations))]
(is (> (/ (reduce + 0 task-durations) 2) millis))))
(deftest together-test
(let [[millis [one two three]]
(timing (together
(do (Thread/sleep 500) 1)
(do (Thread/sleep 600) 2)
(do (Thread/sleep 800) 3)))]
(is (> (/ (reduce + 0 [500 600 800]) 2) millis))
(is (= one 1))
(is (= two 2))
(is (= three 3))))
(deftest get-extension-test
(is (nil? (get-extension "stuff")))
(is (= ".pdf" (get-extension "stuff.txt.pdf")))
(is (= "." (get-extension "stuff.")))
(is (= ".stuff" (get-extension ".stuff")))
(is (= ".txt" (get-extension ".stuff.txt"))))
(deftest basename-test
(is (= "stuff" (basename "stuff")))
(is (= "stuff.txt" (basename "stuff.txt.pdf")))
(is (= "stuff" (basename "stuff.")))
(is (= ".stuff" (basename ".stuff"))))
(deftest not-blank?-test
(is (not-blank? "testing"))
(is (not (not-blank? "")))
(is (not (not-blank? nil)))
(is (not (not-blank? " \n\t \r\n"))))
(deftest duration-explain-test
(is (= "2 days, 22 hours, 50 seconds, 233 milliseconds"
(duration-explain (Duration/ofMillis 252050233)))))
(deftest subset-test
(is (= #{#{} #{1} #{2} #{3} #{1 2} #{1 3} #{2 3} #{1 2 3}} (subsets #{1 2 3}))))
(deftest group-by-labels-test
(let [maps [{:labels {:one 1 :two 2 :three 3 :four 5}}
{:labels {:one 2 :two 2 :three 4 :four 5}}]
grouped (group-by-labels :labels maps)]
(is (nil? (get grouped {:bananas true})))
(is (= [(first maps)] (get grouped {:one 1})))
(is (= maps (get grouped {})))
(is (= maps (get grouped {:two 2})))
(is (= maps (get grouped {:two 2 :four 5})))
(is (= [(second maps)] (get grouped {:three 4})))))
(deftest greatest-by-test
(let [data [{:one 1 :two 2} {:one 2 :two 1}]]
(is (= (first data) (greatest-by :two data)))
(is (= (second data) (greatest-by :one data)))))
(deftest least-by-test
(let [data [{:one 1 :two 2} {:one 2 :two 1}]]
(is (= (first data) (least-by :one data)))
(is (= (second data) (least-by :two data)))))
(deftest contiguous-by-test
(let [data [{:startIndex 0 :stopIndex 20} {:startIndex 5 :stopIndex 26} {:startIndex 28 :stopIndex 50}]]
(is (= [[{:startIndex 0 :stopIndex 20} {:startIndex 5 :stopIndex 26}] [{:startIndex 28 :stopIndex 50}]]
(contiguous-by :startIndex :stopIndex data)))))
(deftest invert-grouping-test
(let [m (group-by even? (range 10))
inverted (reverse-grouping m)]
(dotimes [x 10]
(is (= (even? x) (get inverted x))))))
(deftest seek-test
(let [coll [1 2 3 4 5 6 7]]
(is (= 4 (seek (partial < 3) coll)))
(is (nil? (seek (partial < 100) coll)))))
(deftest seek-indexed-test
(let [coll [1 2 3 4 5 6 7]]
(is (= [3 4] (seek-indexed (partial < 3) coll)))
(is (nil? (seek-indexed (partial < 100) coll)))))
(deftest indexcat-by-test
(let [a {:keys [1 2] :a true}
b {:keys [3 4] :b true}]
(is (= {1 a 2 a 3 b 4 b}
(indexcat-by :keys [a b])))))
(deftest join-paths-test
(let [s1 ""]
(is (= s1 (join-paths s1)))
(is (= ""
(join-paths s1 ["results/" "//vodori/" ["/employees" ["paul/"]]])))))
(deftest collate-test
(let [pk ""
person-info [{:id pk :name "Paul" :age 26}]
account-info [{:email pk :year-joined 2018}]
table (collate [[:id person-info]
[:email account-info]])]
(is (contains? table pk))
(is (= [(first person-info)
(first account-info)]
(table pk)))))
(deftest paths-test
(testing "I can extract all paths to all values contained in a structure."
(let [structure {:test [:things [{:more 1} {:more 2}] #{"one" {:whoa :sweet :things [1 2]}}]}]
(is (= {[:test 0] :things,
[:test 1 0 :more] 1,
[:test 1 1 :more] 2,
[:test 2 {:whoa :sweet, :things [1 2]} :whoa] :sweet,
[:test 2 {:whoa :sweet, :things [1 2]} :things 0] 1,
[:test 2 {:whoa :sweet, :things [1 2]} :things 1] 2,
[:test 2 "one"] "one"}
(index-values-by-paths structure))))))
(deftest paging-test
(let [source (vec (range 100))
counter (atom 0)
fetch (fn [offset limit]
(swap! counter inc)
(subvec source
(min offset (count source))
(min (+ offset limit) (count source))))]
(let [stream (paging 25 fetch)]
(is (= 0 @counter))
(is (= source (vec stream)))
(is (= 5 @counter)))
(reset! counter 0)
(let [stream (paging 25 fetch)]
(is (= (range 25) (take 25 stream)))
(is (= 1 @counter))
(is (= (range 26) (take 26 stream)))
(is (= 2 @counter)))))
(deftest uniqueifier-test
(testing "Uniquifying a few names"
(let [uniq (uniqueifier)]
(is (= "stuff.pdf" (uniq "stuff.pdf")))
(is (= "stuff(1).pdf" (uniq "stuff.pdf")))
(is (= "stuff(2).pdf" (uniq "stuff.pdf")))
(is (= "stuff(1)(1).pdf" (uniq "stuff(1).pdf")))))
(testing "Trying weird filenames"
(let [uniq (uniqueifier)]
(is (= "stuff(1)" (uniq "stuff(1)")))
(is (= "cats" (uniq "cats")))
(is (= "stuff(1)(1)" (uniq "stuff(1)")))
(is (= "cats(1)" (uniq "cats")))
(is (= "dogs.stuff.txt.pdf" (uniq "dogs.stuff.txt.pdf")))
(is (= "dogs.stuff.txt(1).pdf" (uniq "dogs.stuff.txt.pdf")))
(is (= "dogs.stuff.txt(2).pdf" (uniq "dogs.stuff.txt.pdf"))))))
(deftest glob-seq-test
(testing "Globs against an exact dot file."
(is (= 1 (count (glob-seq (System/getenv "PWD") ".gitignore")))))
(testing "Globs against a wildcard extension."
(is (= #{".clj"} (set (map #(get-extension (.getName %)) (glob-seq (System/getenv "PWD") "*.clj")))))))
(deftest distinct-by?-test
(let [xs [{:x 1 :y 1} {:x 2 :y 1} {:x 3 :y 3} {:x 4 :y 4}]]
(is (distinct-by? identity []))
(is (distinct-by? :x xs))
(is (not (distinct-by? :y xs)))))
(deftest =ic-test
(is (=ic "test" "TEST" "tesT"))
(is (not (=ic "test" "TEST" "tset")))
(is (=ic "test"))
(is (not (=ic "test" "tset")))
(is (=ic "test" "test")))
(deftest =select-test
(is (=select {:a "stuff" :b "things"} {:a "stuff" :b "things" :c "other-things"}))
(is (not (=select {:a "stuff" :b "things"} {:a "stuff" :b "thoughts" :c "other-things"})))
(is (=select {:a odd? :b even?} {:a 1 :b 2 :c "other-things"}))
(is (not (=select {:a odd? :b even?} {:a 2 :b 1 :c "other-things"}))))
(deftest diff-by-test
(let [a #{{:x 1 :v 1} {:x 1 :v 11} {:x 2 :v 2} {:x 3 :v 3}}
b #{{:x 2 :v 2} {:x 3 :v 3} {:x 4 :v 4}}
[only-a only-b both] (diff-by :x a b)]
(is (sets/subset? only-a a))
(is (not (intersect? only-a b)))
(is (sets/subset? only-b b))
(is (not (intersect? only-b a)))
(is (sets/subset? both a))
(is (sets/subset? both b))))
(deftest default-test
(let [m {:a 1 :b 2}
m' (default m 3)]
(is (= 3 (m' :c)))))
(deftest letd-test
(testing "unusued bindings are never evaluated."
(letd [a (capture 1)
b (capture (+ a 1))]
(is (empty? @invokes))))
(testing "usage of early bindings doesn't force later bindings"
(letd [a (capture 1)
b (capture (+ a 1))]
(is (= 1 a))
(is (= [1] @invokes))))
(testing "referencing bindings multiple times only evaluates once"
(letd [a (capture 1)
b (capture (+ a 1))]
(is (= 2 b))
(is (= 2 b))
(is (= [1 2] @invokes))))
(testing "bindings can be evaluated in any order."
(letd [x (capture 10)
{:keys [a b]} (capture {:a 1 :b 2})
c (capture (+ a b))
d (capture (+ a b x))]
(is (empty? @invokes))
(is (= x 10))
(is (= [10] @invokes))
(is (= 13 d))
(is (= [10 {:a 1 :b 2} 13] @invokes))
(is (= 3 c))
(is (= [10 {:a 1 :b 2} 13 3] @invokes))))
(testing "bindings can be nested"
(letd [y (capture (letd [x (capture 1)
y (capture (+ x x x))]
y))]
(is (empty? @invokes))
(is (= y 3))
(is (= [1 3 3] @invokes))))
(testing "bindings aren't evaluated if fully shadowed."
(let [f (fn [x]
(letd [{:keys [a b c]} (capture {:a 1 :b 2 :c 3})]
(let [{:keys [a b]} {:a 3 :b 4}]
(if (odd? x)
(+ a b)
(+ a b c)))))
v (f 3)]
(is (empty? @invokes))
(is (= v 7))
(is (empty? @invokes))
(let [v2 (f 4)]
(is (= [{:a 1 :b 2 :c 3}] @invokes))
(is (= v2 10)))))
(testing "bindings aren't evaluated if shadowed fn"
(let [f (letd [x (capture 1)]
(fn [x] (+ x x)))]
(is (empty? @invokes))
(is (= 8 (f 4)))
(is (empty? @invokes))))
(testing "supports linear deps"
(letd [a 1 b (+ a 1)]
(is (= b 2))))
(testing "supports shadowing by self"
(letd [a 1]
(is (= a 1))
(letd [a 2]
(is (= a 2)))
(is (= a 1))))
(testing "supports shadowing by let"
(letd [a 1]
(is (= a 1))
(let [a 2]
(is (= a 2)))
(is (= a 1))))
(testing "supports shadowing by loop"
(letd [a 1]
(is (= a 1))
(is (= 2 (loop [a 2]
a)))
(is (= a 1))))
(testing "supports shadowing by fn"
(letd [a 1]
(is (= a 1))
(is (= 2 ((fn [a] a) 2)))
(is (= a 1))))
(testing "supports destructuring"
(letd [{:keys [a b]} {:a 1 :b 2}]
(is (= a 1))
(is (= b 2)))))
(deftest letp-test
(let [v (letp [a (+ 1 2 3)
b (if (even? a) (preempt 4) 5)
c (capture b)]
c)]
(is (= v 4))
(is (empty? @invokes))))
(deftest zip-test
(is (= [[1] [2] [3]] (into [] (zip) [1 2 3])))
(is (= [] (zip [])))
(is (= [] (zip [] [])))
(is (= [] (zip [] [1])))
(is (= [[1 3] [2 4]] (zip [1 2] [3 4])))
(is (= [[1 3 5] [2 4 6]] (zip [1 2] [3 4] [5 6]))))
(deftest map-groups-test
(is (= {:a []} (map-groups inc {:a []})))
(is (= {:a [1 2 3] :b [4 5 6]} (map-groups inc {:a [0 1 2] :b [3 4 5]}))))
(deftest mapcat-groups-test
(is (= {:a []} (mapcat-groups #(vector % %) {:a []})))
(is (= {:a [1 1 2 2] :b [3 3]} (mapcat-groups #(repeat 2 %) {:a [1 2] :b [3]}))))
(deftest filter-groups-test
(is (= {:a []} (filter-groups odd? {:a []})))
(is (= {:a [1 3] :b []} (filter-groups odd? {:a [1 2 3] :b [4]}))))
(deftest remove-groups-test
(is (= {:a []} (remove-groups inc {:a []})))
(is (= {:a [2] :b [4]} (remove-groups odd? {:a [1 2 3] :b [4]}))))
(deftest reduce-groups-test
(is (= {:a 0 :b 0} (reduce-groups + {:a [] :b []})))
(is (= {:a 6 :b 15} (reduce-groups + {:a [1 2 3] :b [4 5 6]}))))
(deftest iterable?-test
(is (iterable? [1 2 3]))
(is (iterable? '(1 2 3)))
(is (iterable? #{1 2 3}))
(is (iterable? (take 1 [1 2])))
(is (iterable? (keys {:a :b :c :d})))
(is (iterable? (vals {:a :b :c :d})))
(is (not (iterable? "test")))
(is (not (iterable? {:a [1 2 3]}))))
(deftest one?-test
(is (one? even? [1 2 3]))
(is (not (one? odd? [1 2 3]))))
(deftest extrema-test
(is (= [nil nil] (extrema [])))
(is (= [Double/MAX_VALUE Double/MAX_VALUE] (extrema [Double/MAX_VALUE])))
(is (= [-3 6] (extrema [-1 -2 -3 6 5 4])))
(is (= [[1 -2] [50 9]] (extrema [[1 2] [1 -2] [50 -9] [50 9] [50 8]]))))
(deftest piecewise-test
(is (= [4 5 6] (piecewise + [1 2 3] [4 5 6] [-1 -2 -3])))
(is (= [-1 -1 -1] (piecewise - [1 1 1] [1 1 1] [1 1 1]))))
(deftest keyed-test
(let [x [1 2 3] y [4 5 6]]
(is (= {:x [1 2 3] :y [4 5 6]} (keyed x y)))))
(deftest single?-test
(is (not (single? #{})))
(is (not (single? [])))
(is (not (single? {:a :b})))
(is (single? [:a]))
(is (single? '(:a))))
(deftest fixed-point-test
(letfn [(step [x] (Math/abs ^long x))]
(is (= 5 (fixed-point step -5)))))
(deftest merge-sort-by-test
(let [colls [[{:x 1} {:x 3} {:x 5}] [] [{:x 2} {:x 4} {:x 6}]]]
(is (= () (merge-sort-by :x [])))
(is (= () (merge-sort-by :x [[] []])))
(is (= '({:x 1} {:x 2} {:x 3} {:x 4} {:x 5} {:x 6}) (merge-sort-by :x colls)))))
(deftest merge-sort-test
(let [colls [[1 3 5] [] [2 4 6]]]
(is (= () (merge-sort [])))
(is (= () (merge-sort [[] []])))
(is (= '(1 2 3 4 5 6) (merge-sort colls)))
(is (= '(6 5 4 3 2 1) (merge-sort (flip compare) (map reverse colls))))))
(deftest if-let-test
(is (if-let* [a (odd? 1) b (even? 2)] true false))
(is (not (if-let* [a (even? 1) b false] true false)))
(is (not (if-let* [a (even? 1) b nil] true false))))
(deftest if-some-test
(is (if-some* [a (odd? 1) b (even? 2)] true false))
(is (if-some* [a (even? 1) b false] true false))
(is (not (if-some* [a (even? 1) b nil] true false))))
(deftest when-let-test
(is (= 3 (when-let* [a 1 b 2 c (+ a b)] c)))
(is (nil? (when-let* [a 1 b 2 c (+ a b) d false] c)))
(is (nil? (when-let* [a 1 b 2 c (+ a b) d nil] c))))
(deftest when-some-test
(is (= 3 (when-some* [a 1 b 2 c (+ a b)] c)))
(is (= 3 (when-some* [a 1 b 2 c (+ a b) d false] c)))
(is (nil? (when-some* [a 1 b 2 c (+ a b) d nil] c))))
(deftest once-and-only-once
(once (capture "1"))
(once (capture "1"))
(is (= ["1"] @invokes)))
(deftest ascending-by?-test
(let [a {:x 1 :y 4} b {:x 2 :y 3} c {:x 3 :y 2} d {:x 3 :y 1}]
(is (ascending-by? :x [a b c d]))
(is (not (ascending-by? :y [a b c d])))
(is (not (ascending-by? :y [a c b d])))
(is (ascending? [1 2 3 4 5]))
(is (not (ascending? [5 5 5 5 4 3])))
(is (ascending? [1 1 1 1 1]))))
(deftest descending-by?-test
(let [a {:x 1 :y 4} b {:x 2 :y 3} c {:x 3 :y 2} d {:x 3 :y 1}]
(is (descending-by? :y [a b c d]))
(is (not (descending-by? :x [a b c d])))
(is (descending? [5 4 3 2 1]))
(is (not (descending? [1 1 1 2 3])))
(is (descending? [1 1 1 1 1]))))
(deftest symmetric-difference-test
(let [a #{1 2 3} b #{2 3 4}]
(is (= #{1 4} (symmetric-difference a b)))))
(deftest supermap?-test
(is (supermap? {:a 1 :b 2} {:b 2}))
(is (supermap? {:a 1 :b 2} {:a 1}))
(is (supermap? {:a 1 :b 2} {:a 1 :b 2}))
(is (not (supermap? {:a 1} {:a 1 :b 2})))
(is (not (supermap? {:a 1 :b 3} {:a 1 :b 2}))))
(deftest submap?-test
(is (submap? {:b 2} {:a 1 :b 2}))
(is (submap? {:a 1} {:a 1 :b 2}))
(is (submap? {:a 1 :b 2} {:a 1 :b 2}))
(is (not (submap? {:a 1 :b 2} {:a 1})))
(is (not (submap? {:a 1 :b 2} {:a 1 :b 3}))))
(deftest template-test
(is (= "1" (template "{test}" {:test 1})))
(is (= "2" (template "{test.badger}" {:test {:badger 2}})))
(is (= "2|3" (template "{test.badger}|{test.items.0}" {:test {:badger 2 :items [3]}})))
(is (= "" (template "{test.badger}" {}))))
(deftest range-search-test
(let [a [1 10] b [11 50] c [51 60]]
(is (= a (range-search [a b c] 5)))
(is (= b (range-search [a b c] 11)))
(is (= b (range-search [a b c] 50)))
(is (= c (range-search [a b c] 51)))))
(deftest stringed-test
(let [a 1 b 2 c 3]
(is (= {"a" 1 "b" 2 "c" 3}
(stringed a b c)))))
(deftest left-pad-test
(is (= "0001" (left-pad "01" 4 "0"))))
(deftest right-pad-test
(is (= "1000" (right-pad "10" 4 "0"))))
(deftest if-text-test
(is (= 2 (if-text [s ""] 1 2)))
(is (= 2 (if-text [s nil] 1 2)))
(is (= 1 (if-text [s "test"] 1 2))))
(deftest |intersection|-test
(is (= 1 (|intersection| #{1 2} #{2 3}))))
(deftest |union|-test
(is (= 3 (|union| #{1 2} #{2 3}))))
(deftest hex->bytes-test
(let [a "round-trip" bites (.getBytes a)]
(is (Arrays/equals bites (hex->bytes (bytes->hex bites))))))
(deftest base64->bytes-test
(let [a "round-trip" bites (.getBytes a)]
(is (Arrays/equals bites (base64->bytes (bytes->base64 bites))))))
(deftest read-edn-string-test
(let [s {:a 1 :b 2 :c {:d #{1 2 3}}}]
(is (= s (read-edn-string (pr-str s)))))
(is (tagged-literal? (read-edn-string (pr-str *ns*)))))
(deftest tuxt-test
(is (= [1 2] ((tuxt inc dec) [0 3]))))
| null | https://raw.githubusercontent.com/vodori/missing/aec1678a1fecf781f11174a4fbad0315ce37f981/test/missing/core_test.clj | clojure | (ns missing.core-test
(:require [clojure.test :refer :all :exclude (testing)]
[missing.core :refer :all]
[clojure.set :as sets])
(:import (java.time Duration)
(java.util Arrays)))
(def invokes (atom []))
(def capture (fn [x] (swap! invokes conj x) x))
(def clear! (fn [] (reset! invokes [])))
(use-fixtures :each
(fn [tests]
(clear!)
(tests)
(clear!)))
(defmacro testing [description & body]
`(clojure.test/testing ~description
(do (clear!) ~@body (clear!))))
(deftest filter-keys-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (filter-keys any? nil)))
(is (= {1 2 3 4} (filter-keys odd? m)))))
(deftest filter-vals-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (filter-vals any? nil)))
(is (= {6 5 8 7} (filter-vals odd? m)))))
(deftest map-keys-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (map-keys inc nil)))
(is (= {2 2 4 4 7 5 9 7} (map-keys inc m)))))
(deftest map-vals-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (map-vals inc nil)))
(is (= {1 3 3 5 6 6 8 8} (map-vals inc m)))))
(deftest reverse-map-test
(let [m {1 2 3 4 6 5 8 7}]
(is (= {} (reverse-map nil)))
(is (= {2 1 4 3 5 6 7 8} (reverse-map m)))))
(deftest index-by-test
(let [coll [{:id 1} {:id 2} {:id 3}]]
(is (= {1 {:id 1} 2 {:id 2} 3 {:id 3}} (index-by :id coll)))))
(deftest contains-all?-test
(let [coll #{1 2 3 4 5}]
(is (contains-all? coll []))
(is (contains-all? coll [1 2]))
(is (contains-all? coll [1 2 3 4 5]))
(is (not (contains-all? coll [1 6])))))
(deftest intersect?-test
(is (intersect? #{1 2} #{2} #{2 3}))
(is (not (intersect? #{1} #{2} #{3})))
(is (not (intersect? #{1 2} #{2} #{3}))))
(deftest exclusive?-test
(is (not (exclusive? #{1 2} #{2} #{2 3})))
(is (exclusive? #{1} #{2} #{3}))
(is (exclusive? #{1 2} #{3} #{4 5})))
(deftest keepcat-test
(let [coll [[1 2 3 nil nil 4] [nil 5 6]]]
(is (= [1 2 3 4 5 6] (into [] (keepcat identity) coll)))
(is (= [1 2 3 4 5 6] (vec (keepcat identity coll))))))
(deftest lift-by-test
(let [f (fn [x] (* x x))]
(is (= 9 ((lift-by (partial * 3) f) 1)))))
(deftest deep-merge-test
(let [m1 {1 {:stuff 3 :thing 2 :other 100} 2 4 :ten 10} m2 {1 {:things 4 :stuff 5 :other nil} :ten nil}]
(is (= {1 {:thing 2 :stuff 5 :things 4 :other nil} 2 4 :ten nil} (deep-merge m1 m2)))))
(deftest key=-test
(is (key= :stuff :stuff))
(is (key= "stuff" :stuff))
(is (not (key= :badger :stuff)))
(is (not (key= "badger" :stuff))))
(deftest nor-test
(let [state (atom [])]
(is (not (nor true (swap! state conj 1))))
(is (= [] @state)))
(let [state (atom [])]
(is (not (nor (identity false) (swap! state conj 1))))
(is (= [1] @state)))
(let [state (atom true) state2 (atom true)]
(is (nor (identity false) (reset! state false) (reset! state2 false)))
(is (false? @state))
(is (false? @state2))))
(deftest sort-by-value-test
(let [m {1 2 4 5 3 4 0 5}]
(is (= [[4 5] [0 5] [3 4] [1 2]] (seq (sorted-map-by-value m (flip compare)))))
(is (= [[1 2] [3 4] [0 5] [4 5]] (seq (sorted-map-by-value m))))))
(deftest dissoc-in-test
(let [m {1 {:stuff 3 :thing 2} 2 4}]
(is (= {1 {:thing 2} 2 4} (dissoc-in m [1 :stuff])))))
(deftest distinct-by-test
(let [vs [{:stuff 5 :thing 2} {:thing 3 :stuff 7} {:thing 4 :stuff 5}]]
(is (= vs (distinct-by :thing vs)))
(is (= vs (into [] (distinct-by :thing) vs)))
(is (= [(get vs 0) (get vs 1)] (distinct-by :stuff vs)))
(is (= [(get vs 0) (get vs 1)] (into [] (distinct-by :stuff) vs)))))
(deftest merge-sort-test
(let [v1 (range 0 10 2) v2 (range 1 10 2)]
(is (= (range 0 10) (merge-sort [v1 v2])))))
(deftest do-force-test
(let [state (atom [])]
(is (nil?
(doforce
(do (swap! state conj 1) (throw (ex-info "" {})))
(do (swap! state conj 2) (throw (ex-info "" {})))
(do (swap! state conj 3) (throw (ex-info "" {})))
(do (swap! state conj 4) (throw (ex-info "" {}))))))
(is (= [1 2 3 4] @state))))
(deftest with-timeout-test
(let [start (System/currentTimeMillis)
[success result] (with-timeout 1000 (Thread/sleep 5000))
stop (System/currentTimeMillis)]
(is (not success))
(is (nil? result))
(is (> 2000 (- stop start)))))
(deftest run-par!-test
(let [task-durations [500 600 800]
[millis _] (timing (run-par! #(Thread/sleep %) task-durations))]
(is (> (/ (reduce + 0 task-durations) 2) millis))))
(deftest together-test
(let [[millis [one two three]]
(timing (together
(do (Thread/sleep 500) 1)
(do (Thread/sleep 600) 2)
(do (Thread/sleep 800) 3)))]
(is (> (/ (reduce + 0 [500 600 800]) 2) millis))
(is (= one 1))
(is (= two 2))
(is (= three 3))))
(deftest get-extension-test
(is (nil? (get-extension "stuff")))
(is (= ".pdf" (get-extension "stuff.txt.pdf")))
(is (= "." (get-extension "stuff.")))
(is (= ".stuff" (get-extension ".stuff")))
(is (= ".txt" (get-extension ".stuff.txt"))))
(deftest basename-test
(is (= "stuff" (basename "stuff")))
(is (= "stuff.txt" (basename "stuff.txt.pdf")))
(is (= "stuff" (basename "stuff.")))
(is (= ".stuff" (basename ".stuff"))))
(deftest not-blank?-test
(is (not-blank? "testing"))
(is (not (not-blank? "")))
(is (not (not-blank? nil)))
(is (not (not-blank? " \n\t \r\n"))))
(deftest duration-explain-test
(is (= "2 days, 22 hours, 50 seconds, 233 milliseconds"
(duration-explain (Duration/ofMillis 252050233)))))
(deftest subset-test
(is (= #{#{} #{1} #{2} #{3} #{1 2} #{1 3} #{2 3} #{1 2 3}} (subsets #{1 2 3}))))
(deftest group-by-labels-test
(let [maps [{:labels {:one 1 :two 2 :three 3 :four 5}}
{:labels {:one 2 :two 2 :three 4 :four 5}}]
grouped (group-by-labels :labels maps)]
(is (nil? (get grouped {:bananas true})))
(is (= [(first maps)] (get grouped {:one 1})))
(is (= maps (get grouped {})))
(is (= maps (get grouped {:two 2})))
(is (= maps (get grouped {:two 2 :four 5})))
(is (= [(second maps)] (get grouped {:three 4})))))
(deftest greatest-by-test
(let [data [{:one 1 :two 2} {:one 2 :two 1}]]
(is (= (first data) (greatest-by :two data)))
(is (= (second data) (greatest-by :one data)))))
(deftest least-by-test
(let [data [{:one 1 :two 2} {:one 2 :two 1}]]
(is (= (first data) (least-by :one data)))
(is (= (second data) (least-by :two data)))))
(deftest contiguous-by-test
(let [data [{:startIndex 0 :stopIndex 20} {:startIndex 5 :stopIndex 26} {:startIndex 28 :stopIndex 50}]]
(is (= [[{:startIndex 0 :stopIndex 20} {:startIndex 5 :stopIndex 26}] [{:startIndex 28 :stopIndex 50}]]
(contiguous-by :startIndex :stopIndex data)))))
(deftest invert-grouping-test
(let [m (group-by even? (range 10))
inverted (reverse-grouping m)]
(dotimes [x 10]
(is (= (even? x) (get inverted x))))))
(deftest seek-test
(let [coll [1 2 3 4 5 6 7]]
(is (= 4 (seek (partial < 3) coll)))
(is (nil? (seek (partial < 100) coll)))))
(deftest seek-indexed-test
(let [coll [1 2 3 4 5 6 7]]
(is (= [3 4] (seek-indexed (partial < 3) coll)))
(is (nil? (seek-indexed (partial < 100) coll)))))
(deftest indexcat-by-test
(let [a {:keys [1 2] :a true}
b {:keys [3 4] :b true}]
(is (= {1 a 2 a 3 b 4 b}
(indexcat-by :keys [a b])))))
(deftest join-paths-test
(let [s1 ""]
(is (= s1 (join-paths s1)))
(is (= ""
(join-paths s1 ["results/" "//vodori/" ["/employees" ["paul/"]]])))))
(deftest collate-test
(let [pk ""
person-info [{:id pk :name "Paul" :age 26}]
account-info [{:email pk :year-joined 2018}]
table (collate [[:id person-info]
[:email account-info]])]
(is (contains? table pk))
(is (= [(first person-info)
(first account-info)]
(table pk)))))
(deftest paths-test
(testing "I can extract all paths to all values contained in a structure."
(let [structure {:test [:things [{:more 1} {:more 2}] #{"one" {:whoa :sweet :things [1 2]}}]}]
(is (= {[:test 0] :things,
[:test 1 0 :more] 1,
[:test 1 1 :more] 2,
[:test 2 {:whoa :sweet, :things [1 2]} :whoa] :sweet,
[:test 2 {:whoa :sweet, :things [1 2]} :things 0] 1,
[:test 2 {:whoa :sweet, :things [1 2]} :things 1] 2,
[:test 2 "one"] "one"}
(index-values-by-paths structure))))))
(deftest paging-test
(let [source (vec (range 100))
counter (atom 0)
fetch (fn [offset limit]
(swap! counter inc)
(subvec source
(min offset (count source))
(min (+ offset limit) (count source))))]
(let [stream (paging 25 fetch)]
(is (= 0 @counter))
(is (= source (vec stream)))
(is (= 5 @counter)))
(reset! counter 0)
(let [stream (paging 25 fetch)]
(is (= (range 25) (take 25 stream)))
(is (= 1 @counter))
(is (= (range 26) (take 26 stream)))
(is (= 2 @counter)))))
(deftest uniqueifier-test
(testing "Uniquifying a few names"
(let [uniq (uniqueifier)]
(is (= "stuff.pdf" (uniq "stuff.pdf")))
(is (= "stuff(1).pdf" (uniq "stuff.pdf")))
(is (= "stuff(2).pdf" (uniq "stuff.pdf")))
(is (= "stuff(1)(1).pdf" (uniq "stuff(1).pdf")))))
(testing "Trying weird filenames"
(let [uniq (uniqueifier)]
(is (= "stuff(1)" (uniq "stuff(1)")))
(is (= "cats" (uniq "cats")))
(is (= "stuff(1)(1)" (uniq "stuff(1)")))
(is (= "cats(1)" (uniq "cats")))
(is (= "dogs.stuff.txt.pdf" (uniq "dogs.stuff.txt.pdf")))
(is (= "dogs.stuff.txt(1).pdf" (uniq "dogs.stuff.txt.pdf")))
(is (= "dogs.stuff.txt(2).pdf" (uniq "dogs.stuff.txt.pdf"))))))
(deftest glob-seq-test
(testing "Globs against an exact dot file."
(is (= 1 (count (glob-seq (System/getenv "PWD") ".gitignore")))))
(testing "Globs against a wildcard extension."
(is (= #{".clj"} (set (map #(get-extension (.getName %)) (glob-seq (System/getenv "PWD") "*.clj")))))))
(deftest distinct-by?-test
(let [xs [{:x 1 :y 1} {:x 2 :y 1} {:x 3 :y 3} {:x 4 :y 4}]]
(is (distinct-by? identity []))
(is (distinct-by? :x xs))
(is (not (distinct-by? :y xs)))))
(deftest =ic-test
(is (=ic "test" "TEST" "tesT"))
(is (not (=ic "test" "TEST" "tset")))
(is (=ic "test"))
(is (not (=ic "test" "tset")))
(is (=ic "test" "test")))
(deftest =select-test
(is (=select {:a "stuff" :b "things"} {:a "stuff" :b "things" :c "other-things"}))
(is (not (=select {:a "stuff" :b "things"} {:a "stuff" :b "thoughts" :c "other-things"})))
(is (=select {:a odd? :b even?} {:a 1 :b 2 :c "other-things"}))
(is (not (=select {:a odd? :b even?} {:a 2 :b 1 :c "other-things"}))))
(deftest diff-by-test
(let [a #{{:x 1 :v 1} {:x 1 :v 11} {:x 2 :v 2} {:x 3 :v 3}}
b #{{:x 2 :v 2} {:x 3 :v 3} {:x 4 :v 4}}
[only-a only-b both] (diff-by :x a b)]
(is (sets/subset? only-a a))
(is (not (intersect? only-a b)))
(is (sets/subset? only-b b))
(is (not (intersect? only-b a)))
(is (sets/subset? both a))
(is (sets/subset? both b))))
(deftest default-test
(let [m {:a 1 :b 2}
m' (default m 3)]
(is (= 3 (m' :c)))))
(deftest letd-test
(testing "unusued bindings are never evaluated."
(letd [a (capture 1)
b (capture (+ a 1))]
(is (empty? @invokes))))
(testing "usage of early bindings doesn't force later bindings"
(letd [a (capture 1)
b (capture (+ a 1))]
(is (= 1 a))
(is (= [1] @invokes))))
(testing "referencing bindings multiple times only evaluates once"
(letd [a (capture 1)
b (capture (+ a 1))]
(is (= 2 b))
(is (= 2 b))
(is (= [1 2] @invokes))))
(testing "bindings can be evaluated in any order."
(letd [x (capture 10)
{:keys [a b]} (capture {:a 1 :b 2})
c (capture (+ a b))
d (capture (+ a b x))]
(is (empty? @invokes))
(is (= x 10))
(is (= [10] @invokes))
(is (= 13 d))
(is (= [10 {:a 1 :b 2} 13] @invokes))
(is (= 3 c))
(is (= [10 {:a 1 :b 2} 13 3] @invokes))))
(testing "bindings can be nested"
(letd [y (capture (letd [x (capture 1)
y (capture (+ x x x))]
y))]
(is (empty? @invokes))
(is (= y 3))
(is (= [1 3 3] @invokes))))
(testing "bindings aren't evaluated if fully shadowed."
(let [f (fn [x]
(letd [{:keys [a b c]} (capture {:a 1 :b 2 :c 3})]
(let [{:keys [a b]} {:a 3 :b 4}]
(if (odd? x)
(+ a b)
(+ a b c)))))
v (f 3)]
(is (empty? @invokes))
(is (= v 7))
(is (empty? @invokes))
(let [v2 (f 4)]
(is (= [{:a 1 :b 2 :c 3}] @invokes))
(is (= v2 10)))))
(testing "bindings aren't evaluated if shadowed fn"
(let [f (letd [x (capture 1)]
(fn [x] (+ x x)))]
(is (empty? @invokes))
(is (= 8 (f 4)))
(is (empty? @invokes))))
(testing "supports linear deps"
(letd [a 1 b (+ a 1)]
(is (= b 2))))
(testing "supports shadowing by self"
(letd [a 1]
(is (= a 1))
(letd [a 2]
(is (= a 2)))
(is (= a 1))))
(testing "supports shadowing by let"
(letd [a 1]
(is (= a 1))
(let [a 2]
(is (= a 2)))
(is (= a 1))))
(testing "supports shadowing by loop"
(letd [a 1]
(is (= a 1))
(is (= 2 (loop [a 2]
a)))
(is (= a 1))))
(testing "supports shadowing by fn"
(letd [a 1]
(is (= a 1))
(is (= 2 ((fn [a] a) 2)))
(is (= a 1))))
(testing "supports destructuring"
(letd [{:keys [a b]} {:a 1 :b 2}]
(is (= a 1))
(is (= b 2)))))
(deftest letp-test
(let [v (letp [a (+ 1 2 3)
b (if (even? a) (preempt 4) 5)
c (capture b)]
c)]
(is (= v 4))
(is (empty? @invokes))))
(deftest zip-test
(is (= [[1] [2] [3]] (into [] (zip) [1 2 3])))
(is (= [] (zip [])))
(is (= [] (zip [] [])))
(is (= [] (zip [] [1])))
(is (= [[1 3] [2 4]] (zip [1 2] [3 4])))
(is (= [[1 3 5] [2 4 6]] (zip [1 2] [3 4] [5 6]))))
(deftest map-groups-test
(is (= {:a []} (map-groups inc {:a []})))
(is (= {:a [1 2 3] :b [4 5 6]} (map-groups inc {:a [0 1 2] :b [3 4 5]}))))
(deftest mapcat-groups-test
(is (= {:a []} (mapcat-groups #(vector % %) {:a []})))
(is (= {:a [1 1 2 2] :b [3 3]} (mapcat-groups #(repeat 2 %) {:a [1 2] :b [3]}))))
(deftest filter-groups-test
(is (= {:a []} (filter-groups odd? {:a []})))
(is (= {:a [1 3] :b []} (filter-groups odd? {:a [1 2 3] :b [4]}))))
(deftest remove-groups-test
(is (= {:a []} (remove-groups inc {:a []})))
(is (= {:a [2] :b [4]} (remove-groups odd? {:a [1 2 3] :b [4]}))))
(deftest reduce-groups-test
(is (= {:a 0 :b 0} (reduce-groups + {:a [] :b []})))
(is (= {:a 6 :b 15} (reduce-groups + {:a [1 2 3] :b [4 5 6]}))))
(deftest iterable?-test
(is (iterable? [1 2 3]))
(is (iterable? '(1 2 3)))
(is (iterable? #{1 2 3}))
(is (iterable? (take 1 [1 2])))
(is (iterable? (keys {:a :b :c :d})))
(is (iterable? (vals {:a :b :c :d})))
(is (not (iterable? "test")))
(is (not (iterable? {:a [1 2 3]}))))
(deftest one?-test
(is (one? even? [1 2 3]))
(is (not (one? odd? [1 2 3]))))
(deftest extrema-test
(is (= [nil nil] (extrema [])))
(is (= [Double/MAX_VALUE Double/MAX_VALUE] (extrema [Double/MAX_VALUE])))
(is (= [-3 6] (extrema [-1 -2 -3 6 5 4])))
(is (= [[1 -2] [50 9]] (extrema [[1 2] [1 -2] [50 -9] [50 9] [50 8]]))))
(deftest piecewise-test
(is (= [4 5 6] (piecewise + [1 2 3] [4 5 6] [-1 -2 -3])))
(is (= [-1 -1 -1] (piecewise - [1 1 1] [1 1 1] [1 1 1]))))
(deftest keyed-test
(let [x [1 2 3] y [4 5 6]]
(is (= {:x [1 2 3] :y [4 5 6]} (keyed x y)))))
(deftest single?-test
(is (not (single? #{})))
(is (not (single? [])))
(is (not (single? {:a :b})))
(is (single? [:a]))
(is (single? '(:a))))
(deftest fixed-point-test
(letfn [(step [x] (Math/abs ^long x))]
(is (= 5 (fixed-point step -5)))))
(deftest merge-sort-by-test
(let [colls [[{:x 1} {:x 3} {:x 5}] [] [{:x 2} {:x 4} {:x 6}]]]
(is (= () (merge-sort-by :x [])))
(is (= () (merge-sort-by :x [[] []])))
(is (= '({:x 1} {:x 2} {:x 3} {:x 4} {:x 5} {:x 6}) (merge-sort-by :x colls)))))
(deftest merge-sort-test
(let [colls [[1 3 5] [] [2 4 6]]]
(is (= () (merge-sort [])))
(is (= () (merge-sort [[] []])))
(is (= '(1 2 3 4 5 6) (merge-sort colls)))
(is (= '(6 5 4 3 2 1) (merge-sort (flip compare) (map reverse colls))))))
(deftest if-let-test
(is (if-let* [a (odd? 1) b (even? 2)] true false))
(is (not (if-let* [a (even? 1) b false] true false)))
(is (not (if-let* [a (even? 1) b nil] true false))))
(deftest if-some-test
(is (if-some* [a (odd? 1) b (even? 2)] true false))
(is (if-some* [a (even? 1) b false] true false))
(is (not (if-some* [a (even? 1) b nil] true false))))
(deftest when-let-test
(is (= 3 (when-let* [a 1 b 2 c (+ a b)] c)))
(is (nil? (when-let* [a 1 b 2 c (+ a b) d false] c)))
(is (nil? (when-let* [a 1 b 2 c (+ a b) d nil] c))))
(deftest when-some-test
(is (= 3 (when-some* [a 1 b 2 c (+ a b)] c)))
(is (= 3 (when-some* [a 1 b 2 c (+ a b) d false] c)))
(is (nil? (when-some* [a 1 b 2 c (+ a b) d nil] c))))
(deftest once-and-only-once
(once (capture "1"))
(once (capture "1"))
(is (= ["1"] @invokes)))
(deftest ascending-by?-test
(let [a {:x 1 :y 4} b {:x 2 :y 3} c {:x 3 :y 2} d {:x 3 :y 1}]
(is (ascending-by? :x [a b c d]))
(is (not (ascending-by? :y [a b c d])))
(is (not (ascending-by? :y [a c b d])))
(is (ascending? [1 2 3 4 5]))
(is (not (ascending? [5 5 5 5 4 3])))
(is (ascending? [1 1 1 1 1]))))
(deftest descending-by?-test
(let [a {:x 1 :y 4} b {:x 2 :y 3} c {:x 3 :y 2} d {:x 3 :y 1}]
(is (descending-by? :y [a b c d]))
(is (not (descending-by? :x [a b c d])))
(is (descending? [5 4 3 2 1]))
(is (not (descending? [1 1 1 2 3])))
(is (descending? [1 1 1 1 1]))))
(deftest symmetric-difference-test
(let [a #{1 2 3} b #{2 3 4}]
(is (= #{1 4} (symmetric-difference a b)))))
(deftest supermap?-test
(is (supermap? {:a 1 :b 2} {:b 2}))
(is (supermap? {:a 1 :b 2} {:a 1}))
(is (supermap? {:a 1 :b 2} {:a 1 :b 2}))
(is (not (supermap? {:a 1} {:a 1 :b 2})))
(is (not (supermap? {:a 1 :b 3} {:a 1 :b 2}))))
(deftest submap?-test
(is (submap? {:b 2} {:a 1 :b 2}))
(is (submap? {:a 1} {:a 1 :b 2}))
(is (submap? {:a 1 :b 2} {:a 1 :b 2}))
(is (not (submap? {:a 1 :b 2} {:a 1})))
(is (not (submap? {:a 1 :b 2} {:a 1 :b 3}))))
(deftest template-test
(is (= "1" (template "{test}" {:test 1})))
(is (= "2" (template "{test.badger}" {:test {:badger 2}})))
(is (= "2|3" (template "{test.badger}|{test.items.0}" {:test {:badger 2 :items [3]}})))
(is (= "" (template "{test.badger}" {}))))
(deftest range-search-test
(let [a [1 10] b [11 50] c [51 60]]
(is (= a (range-search [a b c] 5)))
(is (= b (range-search [a b c] 11)))
(is (= b (range-search [a b c] 50)))
(is (= c (range-search [a b c] 51)))))
(deftest stringed-test
(let [a 1 b 2 c 3]
(is (= {"a" 1 "b" 2 "c" 3}
(stringed a b c)))))
(deftest left-pad-test
(is (= "0001" (left-pad "01" 4 "0"))))
(deftest right-pad-test
(is (= "1000" (right-pad "10" 4 "0"))))
(deftest if-text-test
(is (= 2 (if-text [s ""] 1 2)))
(is (= 2 (if-text [s nil] 1 2)))
(is (= 1 (if-text [s "test"] 1 2))))
(deftest |intersection|-test
(is (= 1 (|intersection| #{1 2} #{2 3}))))
(deftest |union|-test
(is (= 3 (|union| #{1 2} #{2 3}))))
(deftest hex->bytes-test
(let [a "round-trip" bites (.getBytes a)]
(is (Arrays/equals bites (hex->bytes (bytes->hex bites))))))
(deftest base64->bytes-test
(let [a "round-trip" bites (.getBytes a)]
(is (Arrays/equals bites (base64->bytes (bytes->base64 bites))))))
(deftest read-edn-string-test
(let [s {:a 1 :b 2 :c {:d #{1 2 3}}}]
(is (= s (read-edn-string (pr-str s)))))
(is (tagged-literal? (read-edn-string (pr-str *ns*)))))
(deftest tuxt-test
(is (= [1 2] ((tuxt inc dec) [0 3]))))
|
|
fd67123b2e7d5e15bad5d4c821c96119b024f48ffc03b855f8e3102acc52343e | aryx/lfs | duree_logic.ml | open Common
open Common_logic
type interval = Val of int | Sup of int | Inf of int | In of (int * int)
let parse = fun s ->
match s with
| s when s =~ "^[0-9]+$" -> Val (s_to_i s)
| s when s =~ "^>\\([0-9]+\\)$" -> Sup (s_to_i (matched1 s))
| s when s =~ "^<\\([0-9]+\\)$" -> Inf (s_to_i (matched1 s))
| s when s =~ "^\\[\\([0-9]+\\)\\.\\.\\([0-9]+\\)\\]$" ->
let (x1, x2) = matched2 s +> pair s_to_i in
let _ = assert(x1 < x2) in
In (x1, x2)
(* sugar *)
| s when s =~ "^>=\\([0-9]+\\)$" -> Sup (s_to_i (matched1 s) - 1)
| s when s =~ "^<=\\([0-9]+\\)$" -> Inf (s_to_i (matched1 s) + 1)
| s -> failwith ("parsing error on interval:" ^ s)
* note pour < = et > = aimerait ptet via | , mais peut pas :(
* = > decaler l'entier :)
* mais ptet certains sugar neederait ca = > comment faire ?
* peut faire des trucs via axiomes , bon
* note pour <= et >= aimerait ptet via |, mais peut pas :(
* => decaler l'entier :)
* mais ptet certains sugar neederait ca => comment faire ?
* peut faire des trucs via axiomes, mais bon
*)
let ( interval_logic : logic ) = fun ( Prop s1 ) ( Prop s2 ) - >
let ( x1 , x2 ) = ( parse s1 , parse s2 ) in
let (interval_logic: logic) = fun (Prop s1) (Prop s2) ->
let (x1, x2) = (parse s1, parse s2) in
*)
let (interval_logic: interval -> interval -> bool) = fun x1 x2 ->
(match (x1, x2) with
2 |= 2
2 |= > 1
2 |= <3
2 |= [ 0 .. 3 ]
> 3 |= > 2
< 2 |= <3
[ 2 .. 3 ] |= [ 0 .. 4 ]
[ 1 .. 4 ] |= > 0
[ 1 .. 4 ] |= < 5
| _ -> false
)
TODO hour , or put all in date_logic ( mais fast_logic :( )
type duree = { big: interval; low: interval }
let modulo = 59
let parse = fun s ->
match s with
ca nt put [ 0 - 9 ] cos can have intervalle , ...
| s when s =~ "\\(.*\\)min\\(.*\\)sec" -> let (big, low) = matched2 s in
{ big = parse big; low = parse low}
| s when s =~ "\\(.*\\):\\(.*\\)" -> let (big, low) = matched2 s in
{ big = parse big; low = parse low}
if do > 45sec , file of 1min or more will not satisfy ( have to do > 45sec|>1min
{ big = Val 0; low = parse low }
| s when s =~ "\\(.*\\)min" -> let big = matched1 s in
{ big = parse big; low = In (0, modulo) }
| s -> failwith ("parsing error with size:" ^ s)
let (size_logic: logic) = fun (Prop s1) (Prop s2) ->
let (x1, x2) = (parse s1, parse s2) in
let (|=) = interval_logic in
x1.big |= x2.big && x1.low |= x2.low
let is_formula (Prop s) =
match parse s with
| {big = Val _; low = Val _ } -> false
| _ -> true
let (main: unit) = interact_logic size_logic is_formula
| null | https://raw.githubusercontent.com/aryx/lfs/b931530c7132b77dfaf3c99d452dc044fce37589/p_logic/duree_logic.ml | ocaml | sugar | open Common
open Common_logic
type interval = Val of int | Sup of int | Inf of int | In of (int * int)
let parse = fun s ->
match s with
| s when s =~ "^[0-9]+$" -> Val (s_to_i s)
| s when s =~ "^>\\([0-9]+\\)$" -> Sup (s_to_i (matched1 s))
| s when s =~ "^<\\([0-9]+\\)$" -> Inf (s_to_i (matched1 s))
| s when s =~ "^\\[\\([0-9]+\\)\\.\\.\\([0-9]+\\)\\]$" ->
let (x1, x2) = matched2 s +> pair s_to_i in
let _ = assert(x1 < x2) in
In (x1, x2)
| s when s =~ "^>=\\([0-9]+\\)$" -> Sup (s_to_i (matched1 s) - 1)
| s when s =~ "^<=\\([0-9]+\\)$" -> Inf (s_to_i (matched1 s) + 1)
| s -> failwith ("parsing error on interval:" ^ s)
* note pour < = et > = aimerait ptet via | , mais peut pas :(
* = > decaler l'entier :)
* mais ptet certains sugar neederait ca = > comment faire ?
* peut faire des trucs via axiomes , bon
* note pour <= et >= aimerait ptet via |, mais peut pas :(
* => decaler l'entier :)
* mais ptet certains sugar neederait ca => comment faire ?
* peut faire des trucs via axiomes, mais bon
*)
let ( interval_logic : logic ) = fun ( Prop s1 ) ( Prop s2 ) - >
let ( x1 , x2 ) = ( parse s1 , parse s2 ) in
let (interval_logic: logic) = fun (Prop s1) (Prop s2) ->
let (x1, x2) = (parse s1, parse s2) in
*)
let (interval_logic: interval -> interval -> bool) = fun x1 x2 ->
(match (x1, x2) with
2 |= 2
2 |= > 1
2 |= <3
2 |= [ 0 .. 3 ]
> 3 |= > 2
< 2 |= <3
[ 2 .. 3 ] |= [ 0 .. 4 ]
[ 1 .. 4 ] |= > 0
[ 1 .. 4 ] |= < 5
| _ -> false
)
TODO hour , or put all in date_logic ( mais fast_logic :( )
type duree = { big: interval; low: interval }
let modulo = 59
let parse = fun s ->
match s with
ca nt put [ 0 - 9 ] cos can have intervalle , ...
| s when s =~ "\\(.*\\)min\\(.*\\)sec" -> let (big, low) = matched2 s in
{ big = parse big; low = parse low}
| s when s =~ "\\(.*\\):\\(.*\\)" -> let (big, low) = matched2 s in
{ big = parse big; low = parse low}
if do > 45sec , file of 1min or more will not satisfy ( have to do > 45sec|>1min
{ big = Val 0; low = parse low }
| s when s =~ "\\(.*\\)min" -> let big = matched1 s in
{ big = parse big; low = In (0, modulo) }
| s -> failwith ("parsing error with size:" ^ s)
let (size_logic: logic) = fun (Prop s1) (Prop s2) ->
let (x1, x2) = (parse s1, parse s2) in
let (|=) = interval_logic in
x1.big |= x2.big && x1.low |= x2.low
let is_formula (Prop s) =
match parse s with
| {big = Val _; low = Val _ } -> false
| _ -> true
let (main: unit) = interact_logic size_logic is_formula
|
59aa62412d8878dc69cd0c4435b208023e7d19203589712f0554051bee4140fb | votinginfoproject/data-processor | external_file.clj | (ns vip.data-processor.validation.v6.external-file
(:require [korma.core :as korma]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.validation.v5.util :as util]
[vip.data-processor.errors :as errors]
[clojure.tools.logging :as log]))
(def validate-no-missing-file-uris
(util/build-xml-tree-value-query-validator
:errors :external-files :missing :missing-file-name
"SELECT xtv.path
FROM (SELECT DISTINCT subltree(path, 0, 4) || 'FileUri' AS path
FROM xml_tree_values WHERE results_id = ?
AND subltree(simple_path, 0, 2) = 'VipObject.ExternalFile') xtv
LEFT JOIN (SELECT path FROM xml_tree_values WHERE results_id = ?) xtv2
ON xtv.path = subltree(xtv2.path, 0, 5)
WHERE xtv2.path IS NULL"
util/two-import-ids))
| null | https://raw.githubusercontent.com/votinginfoproject/data-processor/b4baf334b3a6219d12125af8e8c1e3de93ba1dc9/src/vip/data_processor/validation/v6/external_file.clj | clojure | (ns vip.data-processor.validation.v6.external-file
(:require [korma.core :as korma]
[vip.data-processor.db.postgres :as postgres]
[vip.data-processor.validation.v5.util :as util]
[vip.data-processor.errors :as errors]
[clojure.tools.logging :as log]))
(def validate-no-missing-file-uris
(util/build-xml-tree-value-query-validator
:errors :external-files :missing :missing-file-name
"SELECT xtv.path
FROM (SELECT DISTINCT subltree(path, 0, 4) || 'FileUri' AS path
FROM xml_tree_values WHERE results_id = ?
AND subltree(simple_path, 0, 2) = 'VipObject.ExternalFile') xtv
LEFT JOIN (SELECT path FROM xml_tree_values WHERE results_id = ?) xtv2
ON xtv.path = subltree(xtv2.path, 0, 5)
WHERE xtv2.path IS NULL"
util/two-import-ids))
|
|
31b90896f1554ce618c3458c509db91214d746108ef896e25bd4b53254cec038 | metabase/metabase | rotate_encryption_key_test.clj | (ns metabase.cmd.rotate-encryption-key-test
(:require
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[metabase.cmd :as cmd]
[metabase.cmd.dump-to-h2-test :as dump-to-h2-test]
[metabase.cmd.load-from-h2 :as load-from-h2]
[metabase.cmd.rotate-encryption-key :refer [rotate-encryption-key!]]
[metabase.cmd.test-util :as cmd.test-util]
[metabase.db.connection :as mdb.connection]
[metabase.driver :as driver]
[metabase.models :refer [Database Secret Setting User]]
[metabase.models.interface :as mi]
[metabase.models.setting :as setting]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[metabase.util.encryption :as encryption]
[metabase.util.encryption-test :as encryption-test]
[metabase.util.i18n :as i18n]
[methodical.core :as methodical]
[toucan.db :as db]
[toucan.models :as models])
(:import
(java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
(use-fixtures :once (fixtures/initialize :db))
(defn- do-with-encrypted-json-caching-disabled
[thunk]
(let [mf (methodical/add-primary-method
@#'models/type-fn
[:encrypted-json :out]
(fn [_next-method _type _direction]
#'mi/encrypted-json-out))]
(with-redefs [models/type-fn mf]
(thunk))))
(defmacro ^:private with-encrypted-json-caching-disabled
"Replace the Toucan `:encrypted-json` `:out` type function with `:json` `:out`. This will prevent cached values from
being returned by [[metabase.models.interface/cached-encrypted-json-out]]. This might seem fishy -- shouldn't we be
including the secret key in the cache key itself, if we have to swap out the Toucan type function to get this test
to pass? But under normal usage the cache key cannot change at runtime -- only in this test do we change it -- so
making the code in [[metabase.models.interface]] smarter is not necessary."
{:style/indent 0}
[& body]
`(do-with-encrypted-json-caching-disabled (^:once fn* [] ~@body)))
(defn- raw-value [keyy]
(:value (first (jdbc/query {:datasource (mdb.connection/data-source)}
[(if (= driver/*driver* :h2)
"select \"VALUE\" from setting where setting.\"KEY\"=?;"
"select value from setting where setting.key=?;") keyy]))))
(deftest cmd-rotate-encryption-key-errors-when-failed-test
(with-redefs [rotate-encryption-key! #(throw "err")
cmd/system-exit! identity]
(is (= 1 (cmd/rotate-encryption-key
"89ulvIGoiYw6mNELuOoEZphQafnF/zYe+3vT+v70D1A=")))))
(deftest rotate-encryption-key!-test
(encryption-test/with-secret-key nil
(let [h2-fixture-db-file @cmd.test-util/fixture-db-file-path
db-name (str "test_" (u/lower-case-en (mt/random-name)))
original-timestamp "2021-02-11 18:38:56.042236+00"
[k1 k2 k3] ["89ulvIGoiYw6mNELuOoEZphQafnF/zYe+3vT+v70D1A="
"yHa/6VEQuIItMyd5CNcgV9nXvzZcX6bWmiY0oOh6pLU="
"BCQbKNVu6N8TQ2BwyTC0U0oCBqsvFVr2uhEM/tRgJUM="]
user-id (atom nil)
secret-val "surprise!"
secret-id-enc (atom nil)
secret-id-unenc (atom nil)]
(mt/test-drivers #{:postgres :h2 :mysql}
(with-encrypted-json-caching-disabled
(let [data-source (dump-to-h2-test/persistent-data-source driver/*driver* db-name)]
EXPLANATION FOR WHY THIS TEST WAS FLAKY
;; at this point, all the state switching craziness that happens for
;; `metabase.util.i18n.impl/site-locale-from-setting` has already taken place, so this function has
;; been bootstrapped to now return the site locale from the real, actual setting function
;; the trouble is, when we are swapping out the app DB, attempting to fetch the setting value WILL
FAIL , since there is no ` SETTING ` table yet created
;; the `load-from-h2!`, by way of invoking `copy!`, below, needs the site locale to internationalize
;; its loading progress messages (ex: "Set up h2 source database and run migrations...")
;; the reason this test has been flaky is that if we get "lucky" the *cached* value of the site
;; locale setting is returned, instead of the setting code having to query the app DB for it, and
;; hence no error occurs, but for a cache miss, then the error happens
;; this dynamic rebinding will bypass the call to `i18n/site-locale` and hence avoid that whole mess
i18n/*site-locale-override* "en"
;; while we're at it, disable the setting cache entirely; we are effectively creating a new app DB
;; so the cache itself is invalid and can only mask the real issues
setting/*disable-cache* true?
mdb.connection/*application-db* (mdb.connection/application-db driver/*driver* data-source)]
(when-not (= driver/*driver* :h2)
(tx/create-db! driver/*driver* {:database-name db-name}))
(load-from-h2/load-from-h2! h2-fixture-db-file)
(db/insert! Setting {:key "nocrypt", :value "unencrypted value"})
(db/insert! Setting {:key "settings-last-updated", :value original-timestamp})
(let [u (db/insert! User {:email ""
:first_name "No"
:last_name "Body"
:password "nopassword"
:is_active true
:is_superuser false})]
(reset! user-id (u/the-id u)))
(let [secret (db/insert! Secret {:name "My Secret (plaintext)"
:kind "password"
:value (.getBytes secret-val StandardCharsets/UTF_8)
:creator_id @user-id})]
(reset! secret-id-unenc (u/the-id secret)))
(encryption-test/with-secret-key k1
(db/insert! Setting {:key "k1crypted", :value "encrypted with k1"})
(db/update! Database 1 {:details "{\"db\":\"/tmp/test.db\"}"})
(let [secret (db/insert! Secret {:name "My Secret (encrypted)"
:kind "password"
:value (.getBytes secret-val StandardCharsets/UTF_8)
:creator_id @user-id})]
(reset! secret-id-enc (u/the-id secret))))
(testing "rotating with the same key is a noop"
(encryption-test/with-secret-key k1
(rotate-encryption-key! k1)
;; plain->newkey
(testing "for unencrypted values"
(is (not= "unencrypted value" (raw-value "nocrypt")))
(is (= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc))))
;; samekey->samekey
(testing "for values encrypted with the same key"
(is (not= "encrypted with k1" (raw-value "k1crypted")))
(is (= "encrypted with k1" (db/select-one-field :value Setting :key "k1crypted")))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-enc))))))
(testing "settings-last-updated is updated AND plaintext"
(is (not= original-timestamp (raw-value "settings-last-updated")))
(is (not (encryption/possibly-encrypted-string? (raw-value "settings-last-updated")))))
(testing "rotating with a new key is recoverable"
(encryption-test/with-secret-key k1 (rotate-encryption-key! k2))
(testing "with new key"
(encryption-test/with-secret-key k2
(is (= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (= {:db "/tmp/test.db"} (db/select-one-field :details Database :id 1)))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc)))))
(testing "but not with old key"
(encryption-test/with-secret-key k1
(is (not= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (not= "{\"db\":\"/tmp/test.db\"}" (db/select-one-field :details Database :id 1)))
(is (not (mt/secret-value-equals? secret-val
(db/select-one-field :value Secret :id @secret-id-unenc)))))))
(testing "full rollback when a database details looks encrypted with a different key than the current one"
(encryption-test/with-secret-key k3
(let [db (db/insert! Database {:name "k3", :engine :mysql, :details "{\"db\":\"/tmp/k3.db\"}"})]
(is (=? {:name "k3"}
db))))
(encryption-test/with-secret-key k2
(let [db (db/insert! Database {:name "k2", :engine :mysql, :details "{\"db\":\"/tmp/k2.db\"}"})]
(is (=? {:name "k2"}
db)))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Can't decrypt app db with MB_ENCRYPTION_SECRET_KEY"
(rotate-encryption-key! k3))))
(encryption-test/with-secret-key k3
(is (not= {:db "/tmp/k2.db"} (db/select-one-field :details Database :name "k2")))
(is (= {:db "/tmp/k3.db"} (db/select-one-field :details Database :name "k3")))))
(testing "rotate-encryption-key! to nil decrypts the encrypted keys"
(db/update! Database 1 {:details "{\"db\":\"/tmp/test.db\"}"})
(db/update-where! Database {:name "k3"} :details "{\"db\":\"/tmp/test.db\"}")
(encryption-test/with-secret-key k2 ; with the last key that we rotated to in the test
(rotate-encryption-key! nil))
(is (= "unencrypted value" (raw-value "nocrypt")))
;; at this point, both the originally encrypted, and the originally unencrypted secret instances
;; should be decrypted
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc)))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-enc))))
(testing "short keys fail to rotate"
(is (thrown? Throwable (rotate-encryption-key! "short")))))))))))
| null | https://raw.githubusercontent.com/metabase/metabase/7e3048bf73f6cb7527579446166d054292166163/test/metabase/cmd/rotate_encryption_key_test.clj | clojure | at this point, all the state switching craziness that happens for
`metabase.util.i18n.impl/site-locale-from-setting` has already taken place, so this function has
been bootstrapped to now return the site locale from the real, actual setting function
the trouble is, when we are swapping out the app DB, attempting to fetch the setting value WILL
the `load-from-h2!`, by way of invoking `copy!`, below, needs the site locale to internationalize
its loading progress messages (ex: "Set up h2 source database and run migrations...")
the reason this test has been flaky is that if we get "lucky" the *cached* value of the site
locale setting is returned, instead of the setting code having to query the app DB for it, and
hence no error occurs, but for a cache miss, then the error happens
this dynamic rebinding will bypass the call to `i18n/site-locale` and hence avoid that whole mess
while we're at it, disable the setting cache entirely; we are effectively creating a new app DB
so the cache itself is invalid and can only mask the real issues
plain->newkey
samekey->samekey
with the last key that we rotated to in the test
at this point, both the originally encrypted, and the originally unencrypted secret instances
should be decrypted | (ns metabase.cmd.rotate-encryption-key-test
(:require
[clojure.java.jdbc :as jdbc]
[clojure.test :refer :all]
[metabase.cmd :as cmd]
[metabase.cmd.dump-to-h2-test :as dump-to-h2-test]
[metabase.cmd.load-from-h2 :as load-from-h2]
[metabase.cmd.rotate-encryption-key :refer [rotate-encryption-key!]]
[metabase.cmd.test-util :as cmd.test-util]
[metabase.db.connection :as mdb.connection]
[metabase.driver :as driver]
[metabase.models :refer [Database Secret Setting User]]
[metabase.models.interface :as mi]
[metabase.models.setting :as setting]
[metabase.test :as mt]
[metabase.test.data.interface :as tx]
[metabase.test.fixtures :as fixtures]
[metabase.util :as u]
[metabase.util.encryption :as encryption]
[metabase.util.encryption-test :as encryption-test]
[metabase.util.i18n :as i18n]
[methodical.core :as methodical]
[toucan.db :as db]
[toucan.models :as models])
(:import
(java.nio.charset StandardCharsets)))
(set! *warn-on-reflection* true)
(use-fixtures :once (fixtures/initialize :db))
(defn- do-with-encrypted-json-caching-disabled
[thunk]
(let [mf (methodical/add-primary-method
@#'models/type-fn
[:encrypted-json :out]
(fn [_next-method _type _direction]
#'mi/encrypted-json-out))]
(with-redefs [models/type-fn mf]
(thunk))))
(defmacro ^:private with-encrypted-json-caching-disabled
"Replace the Toucan `:encrypted-json` `:out` type function with `:json` `:out`. This will prevent cached values from
being returned by [[metabase.models.interface/cached-encrypted-json-out]]. This might seem fishy -- shouldn't we be
including the secret key in the cache key itself, if we have to swap out the Toucan type function to get this test
to pass? But under normal usage the cache key cannot change at runtime -- only in this test do we change it -- so
making the code in [[metabase.models.interface]] smarter is not necessary."
{:style/indent 0}
[& body]
`(do-with-encrypted-json-caching-disabled (^:once fn* [] ~@body)))
(defn- raw-value [keyy]
(:value (first (jdbc/query {:datasource (mdb.connection/data-source)}
[(if (= driver/*driver* :h2)
"select \"VALUE\" from setting where setting.\"KEY\"=?;"
"select value from setting where setting.key=?;") keyy]))))
(deftest cmd-rotate-encryption-key-errors-when-failed-test
(with-redefs [rotate-encryption-key! #(throw "err")
cmd/system-exit! identity]
(is (= 1 (cmd/rotate-encryption-key
"89ulvIGoiYw6mNELuOoEZphQafnF/zYe+3vT+v70D1A=")))))
(deftest rotate-encryption-key!-test
(encryption-test/with-secret-key nil
(let [h2-fixture-db-file @cmd.test-util/fixture-db-file-path
db-name (str "test_" (u/lower-case-en (mt/random-name)))
original-timestamp "2021-02-11 18:38:56.042236+00"
[k1 k2 k3] ["89ulvIGoiYw6mNELuOoEZphQafnF/zYe+3vT+v70D1A="
"yHa/6VEQuIItMyd5CNcgV9nXvzZcX6bWmiY0oOh6pLU="
"BCQbKNVu6N8TQ2BwyTC0U0oCBqsvFVr2uhEM/tRgJUM="]
user-id (atom nil)
secret-val "surprise!"
secret-id-enc (atom nil)
secret-id-unenc (atom nil)]
(mt/test-drivers #{:postgres :h2 :mysql}
(with-encrypted-json-caching-disabled
(let [data-source (dump-to-h2-test/persistent-data-source driver/*driver* db-name)]
EXPLANATION FOR WHY THIS TEST WAS FLAKY
FAIL , since there is no ` SETTING ` table yet created
i18n/*site-locale-override* "en"
setting/*disable-cache* true?
mdb.connection/*application-db* (mdb.connection/application-db driver/*driver* data-source)]
(when-not (= driver/*driver* :h2)
(tx/create-db! driver/*driver* {:database-name db-name}))
(load-from-h2/load-from-h2! h2-fixture-db-file)
(db/insert! Setting {:key "nocrypt", :value "unencrypted value"})
(db/insert! Setting {:key "settings-last-updated", :value original-timestamp})
(let [u (db/insert! User {:email ""
:first_name "No"
:last_name "Body"
:password "nopassword"
:is_active true
:is_superuser false})]
(reset! user-id (u/the-id u)))
(let [secret (db/insert! Secret {:name "My Secret (plaintext)"
:kind "password"
:value (.getBytes secret-val StandardCharsets/UTF_8)
:creator_id @user-id})]
(reset! secret-id-unenc (u/the-id secret)))
(encryption-test/with-secret-key k1
(db/insert! Setting {:key "k1crypted", :value "encrypted with k1"})
(db/update! Database 1 {:details "{\"db\":\"/tmp/test.db\"}"})
(let [secret (db/insert! Secret {:name "My Secret (encrypted)"
:kind "password"
:value (.getBytes secret-val StandardCharsets/UTF_8)
:creator_id @user-id})]
(reset! secret-id-enc (u/the-id secret))))
(testing "rotating with the same key is a noop"
(encryption-test/with-secret-key k1
(rotate-encryption-key! k1)
(testing "for unencrypted values"
(is (not= "unencrypted value" (raw-value "nocrypt")))
(is (= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc))))
(testing "for values encrypted with the same key"
(is (not= "encrypted with k1" (raw-value "k1crypted")))
(is (= "encrypted with k1" (db/select-one-field :value Setting :key "k1crypted")))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-enc))))))
(testing "settings-last-updated is updated AND plaintext"
(is (not= original-timestamp (raw-value "settings-last-updated")))
(is (not (encryption/possibly-encrypted-string? (raw-value "settings-last-updated")))))
(testing "rotating with a new key is recoverable"
(encryption-test/with-secret-key k1 (rotate-encryption-key! k2))
(testing "with new key"
(encryption-test/with-secret-key k2
(is (= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (= {:db "/tmp/test.db"} (db/select-one-field :details Database :id 1)))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc)))))
(testing "but not with old key"
(encryption-test/with-secret-key k1
(is (not= "unencrypted value" (db/select-one-field :value Setting :key "nocrypt")))
(is (not= "{\"db\":\"/tmp/test.db\"}" (db/select-one-field :details Database :id 1)))
(is (not (mt/secret-value-equals? secret-val
(db/select-one-field :value Secret :id @secret-id-unenc)))))))
(testing "full rollback when a database details looks encrypted with a different key than the current one"
(encryption-test/with-secret-key k3
(let [db (db/insert! Database {:name "k3", :engine :mysql, :details "{\"db\":\"/tmp/k3.db\"}"})]
(is (=? {:name "k3"}
db))))
(encryption-test/with-secret-key k2
(let [db (db/insert! Database {:name "k2", :engine :mysql, :details "{\"db\":\"/tmp/k2.db\"}"})]
(is (=? {:name "k2"}
db)))
(is (thrown-with-msg?
clojure.lang.ExceptionInfo
#"Can't decrypt app db with MB_ENCRYPTION_SECRET_KEY"
(rotate-encryption-key! k3))))
(encryption-test/with-secret-key k3
(is (not= {:db "/tmp/k2.db"} (db/select-one-field :details Database :name "k2")))
(is (= {:db "/tmp/k3.db"} (db/select-one-field :details Database :name "k3")))))
(testing "rotate-encryption-key! to nil decrypts the encrypted keys"
(db/update! Database 1 {:details "{\"db\":\"/tmp/test.db\"}"})
(db/update-where! Database {:name "k3"} :details "{\"db\":\"/tmp/test.db\"}")
(rotate-encryption-key! nil))
(is (= "unencrypted value" (raw-value "nocrypt")))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-unenc)))
(is (mt/secret-value-equals? secret-val (db/select-one-field :value Secret :id @secret-id-enc))))
(testing "short keys fail to rotate"
(is (thrown? Throwable (rotate-encryption-key! "short")))))))))))
|
5e186ae00a647730e71297d7f41f994a3428df5157cb6661093eb03514c38c55 | wh5a/thih | LetBind.hs |
Output : 20
foo :: Int -> Int
foo = \y -> let
-- app :: (a -> b) -> a -> b
app = \f x -> f x
fun :: (a -> b) -> a -> b
fun = let
-- myid :: a -> a
myid = \x -> x
-- bar :: (a -> b) -> a -> b
bar = app
in myid (let
-- ram :: (a -> b) -> a -> b
ram = bar
in ram
)
in (fun plus 1 2) + (fun plus 1 2)
plus :: Int -> Int -> Int
plus = \x y -> x + y
addThree :: Int -> Int -> Int -> Int
addThree = \a b c -> a + b + c
-- main :: Int
main = (foo 3) + (mysum ( mymap (\x -> 1 + x) [1,2,3]))
mymap :: (a -> b) -> [a] -> [b]
mymap = mymap
mysum :: Num a => [a] -> a
mysum = mysum
| null | https://raw.githubusercontent.com/wh5a/thih/dc5cb16ba4e998097135beb0c7b0b416cac7bfae/hatchet/examples/LetBind.hs | haskell | app :: (a -> b) -> a -> b
myid :: a -> a
bar :: (a -> b) -> a -> b
ram :: (a -> b) -> a -> b
main :: Int |
Output : 20
foo :: Int -> Int
foo = \y -> let
app = \f x -> f x
fun :: (a -> b) -> a -> b
fun = let
myid = \x -> x
bar = app
in myid (let
ram = bar
in ram
)
in (fun plus 1 2) + (fun plus 1 2)
plus :: Int -> Int -> Int
plus = \x y -> x + y
addThree :: Int -> Int -> Int -> Int
addThree = \a b c -> a + b + c
main = (foo 3) + (mysum ( mymap (\x -> 1 + x) [1,2,3]))
mymap :: (a -> b) -> [a] -> [b]
mymap = mymap
mysum :: Num a => [a] -> a
mysum = mysum
|
dd03207a4cb8076a6d2bfc4075c5d268edc4948044d58b4d53285db834b8fd03 | IndianRoboticsOrganization/ArimaTTS | INST_us_VOX_duration.scm | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; ;;;
Carnegie Mellon University ; ; ;
and and ; ; ;
Copyright ( c ) 1998 - 2000 ; ; ;
All Rights Reserved . ; ; ;
;;; ;;;
;;; Permission is hereby granted, free of charge, to use and distribute ;;;
;;; this software and its documentation without restriction, including ;;;
;;; without limitation the rights to use, copy, modify, merge, publish, ;;;
;;; distribute, sublicense, and/or sell copies of this work, and to ;;;
;;; permit persons to whom this work is furnished to do so, subject to ;;;
;;; the following conditions: ;;;
1 . The code must retain the above copyright notice , this list of ; ; ;
;;; conditions and the following disclaimer. ;;;
2 . Any modifications must be clearly marked as such . ; ; ;
3 . Original authors ' names are not deleted . ; ; ;
4 . The authors ' names are not used to endorse or promote products ; ; ;
;;; derived from this software without specific prior written ;;;
;;; permission. ;;;
;;; ;;;
CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK ; ; ;
;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE ; ; ;
;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;
;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
;;; THIS SOFTWARE. ;;;
;;; ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Duration for English
;;;
;;; Load any necessary files here
(require 'INST_us_VOX_durdata)
(define (INST_us_VOX::select_duration)
"(INST_us_VOX::select_duration)
Set up duration for English."
(set! duration_cart_tree INST_us_VOX::zdur_tree)
(set! duration_ph_info INST_us_VOX::phone_durs)
(Parameter.set 'Duration_Method 'Tree_ZScores)
(Parameter.set 'Duration_Stretch 1.0)
)
(define (INST_us_VOX::reset_duration)
"(INST_us_VOX::reset_duration)
Reset duration information."
t
)
(provide 'INST_us_VOX_duration)
| null | https://raw.githubusercontent.com/IndianRoboticsOrganization/ArimaTTS/7377dca466306e2e6b90a063427273142cd50616/festvox/src/vox_files/us/INST_us_VOX_duration.scm | scheme |
;;;
; ;
; ;
; ;
; ;
;;;
Permission is hereby granted, free of charge, to use and distribute ;;;
this software and its documentation without restriction, including ;;;
without limitation the rights to use, copy, modify, merge, publish, ;;;
distribute, sublicense, and/or sell copies of this work, and to ;;;
permit persons to whom this work is furnished to do so, subject to ;;;
the following conditions: ;;;
; ;
conditions and the following disclaimer. ;;;
; ;
; ;
; ;
derived from this software without specific prior written ;;;
permission. ;;;
;;;
; ;
DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;;;
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;;;
; ;
FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;;;
; ;
AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;;;
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;;;
THIS SOFTWARE. ;;;
;;;
Load any necessary files here | Duration for English
(require 'INST_us_VOX_durdata)
(define (INST_us_VOX::select_duration)
"(INST_us_VOX::select_duration)
Set up duration for English."
(set! duration_cart_tree INST_us_VOX::zdur_tree)
(set! duration_ph_info INST_us_VOX::phone_durs)
(Parameter.set 'Duration_Method 'Tree_ZScores)
(Parameter.set 'Duration_Stretch 1.0)
)
(define (INST_us_VOX::reset_duration)
"(INST_us_VOX::reset_duration)
Reset duration information."
t
)
(provide 'INST_us_VOX_duration)
|
4c583d7d514cd48e19a42ff30c37db7670a842dc9840a521f5b1570b45da5263 | sneeuwballen/zipperposition | SClause.ml |
* { 1 Simple Clause }
open Logtk
module TPAsKey = struct
type t = (Term.t * Position.t)
let equal = (fun (_,p1) (_,p2) -> Position.equal p1 p2)
let hash = (fun (_,p1) -> Position.hash p1)
let compare = (fun (_,p1) (_,p2) -> Position.compare p1 p2)
end
module TPSet = CCSet.Make(TPAsKey)
type flag = int
type t = {
id : int; (** unique ID of the clause *)
lits : Literal.t array; (** the literals *)
trail : Trail.t; (** boolean trail *)
mutable flags : flag; (** boolean flags for the clause *)
}
let id_count_ = ref 0
* { 2 Basics }
let make ~trail lits =
let id = !id_count_ in
incr id_count_;
{ lits; trail; id; flags=0; }
let[@inline] equal c1 c2 = c1.id = c2.id
let[@inline] compare c1 c2 = CCShims_.Stdlib.compare c1.id c2.id
let[@inline] id c = c.id
let[@inline] hash c = Hash.int c.id
let[@inline] lits c = c.lits
let[@inline] trail c = c.trail
let[@inline] length c = Array.length c.lits
let is_empty c = length c = 0 && Trail.is_empty c.trail
let update_trail f c = make ~trail:(f c.trail) c.lits
let add_trail_ trail f =
let module F = TypedSTerm.Form in
if Trail.is_empty trail
then f
else F.imply (Trail.to_s_form trail) f
let to_s_form ?allow_free_db ?(ctx=Term.Conv.create()) c =
let module F = TypedSTerm.Form in
Literals.Conv.to_s_form ?allow_free_db ~ctx (lits c)
|> add_trail_ (trail c)
|> F.close_forall
(** {2 Flags} *)
let new_flag =
let flag_gen = Util.Flag.create () in
fun () -> Util.Flag.get_new flag_gen
let flag_lemma = new_flag ()
let flag_persistent = new_flag ()
let flag_redundant = new_flag ()
let flag_backward_simplified = new_flag()
let flag_poly_arg_cong_res = new_flag()
let flag_initial = new_flag ()
let set_flag flag c truth =
if truth
then c.flags <- c.flags lor flag
else c.flags <- c.flags land (lnot flag)
let[@inline] get_flag flag c = (c.flags land flag) != 0
let mark_redundant c = set_flag flag_redundant c true
let[@inline] is_redundant c = get_flag flag_redundant c
let mark_backward_simplified c = set_flag flag_backward_simplified c true
let[@inline] is_backward_simplified c = get_flag flag_backward_simplified c
* { 2 IO }
let pp_trail out trail =
if not (Trail.is_empty trail)
then
Format.fprintf out "@ @<2>← @[<hv>%a@]"
(Util.pp_iter ~sep:" ⊓ " BBox.pp) (Trail.to_iter trail)
let pp_vars out c =
let pp_vars out = function
| [] -> ()
| l ->
Format.fprintf out "forall @[%a@].@ "
(Util.pp_list ~sep:" " Type.pp_typed_var) l
in
pp_vars out (Literals.vars c.lits)
let pp out c =
Format.fprintf out "@[%a@[<2>%a%a@]@](%d)"
pp_vars c Literals.pp c.lits pp_trail c.trail c.id;
()
let pp_trail_zf out trail =
Format.fprintf out "@[<hv>%a@]"
(Util.pp_iter ~sep:" && " BBox.pp_zf) (Trail.to_iter trail)
let pp_zf out c =
if Trail.is_empty c.trail
then Literals.pp_zf_closed out c.lits
else
Format.fprintf out "@[<2>(%a)@ => (%a)@]"
pp_trail_zf c.trail Literals.pp_zf_closed c.lits
print a trail in TPTP
let pp_trail_tstp out trail =
(* print a single boolean box *)
let pp_box_unsigned out b = match BBox.payload b with
| BBox.Case p ->
let lits = List.map Cover_set.Case.to_lit p |> Array.of_list in
Literals.pp_tstp out lits
| BBox.Clause_component lits ->
CCFormat.within "(" ")" Literals.pp_tstp_closed out lits
| BBox.Lemma f ->
CCFormat.within "(" ")" Cut_form.pp_tstp out f
| BBox.Fresh -> failwith "cannot print <fresh> boolean box"
in
let pp_box out b =
if BBox.Lit.sign b then pp_box_unsigned out b
else Format.fprintf out "@[~@ %a@]" pp_box_unsigned b
in
Format.fprintf out "@[<hv>%a@]"
(Util.pp_iter ~sep:" & " pp_box)
(Trail.to_iter trail)
let pp_tstp out c =
if Trail.is_empty c.trail
then Literals.pp_tstp_closed out c.lits
else
Format.fprintf out "@[<2>(@[%a@])@ <= (%a)@]"
Literals.pp_tstp_closed c.lits pp_trail_tstp c.trail
TODO : if all vars are [: term ] and trail is empty , use CNF ; else use TFF
let pp_tstp_full out c =
Format.fprintf out "@[<2>tff(%d, plain,@ %a).@]" c.id pp_tstp c
let pp_in = function
| Output_format.O_zf -> pp_zf
| Output_format.O_tptp -> pp_tstp
| Output_format.O_normal -> pp
| Output_format.O_none -> CCFormat.silent
* { 2 Proofs }
exception E_proof of t
(* conversion to simple formula after instantiation, including the
substitution used for instantiating *)
let to_s_form_subst ~ctx subst c : _ * _ Var.Subst.t =
let module F = TypedSTerm.Form in
let module SP = Subst.Projection in
let f =
Literals.apply_subst (SP.renaming subst) (SP.subst subst) (lits c,SP.scope subst)
|> Literals.Conv.to_s_form ~allow_free_db:true ~ctx
|> add_trail_ (trail c)
|> F.close_forall
and inst_subst =
SP.as_inst ~allow_free_db:true ~ctx subst (Literals.vars (lits c))
in
f, inst_subst
let proof_tc cl =
Proof.Result.make_tc
~of_exn:(function | E_proof c -> Some c | _ -> None)
~to_exn:(fun c -> E_proof c)
~compare:compare
~flavor:(fun c ->
if Literals.is_absurd (lits c)
then if Trail.is_empty (trail c) then `Proof_of_false
else `Absurd_lits
else `Vanilla)
~to_form:(fun ~ctx c -> to_s_form ~allow_free_db:true ~ctx c)
~is_dead_cl:(fun () -> is_redundant cl)
~to_form_subst:to_s_form_subst
~name:(fun cl -> "zip_derived_cl" ^ CCInt.to_string cl.id)
~pp_in
()
let mk_proof_res cl = Proof.Result.make (proof_tc cl) cl
let adapt p c = Proof.S.adapt p (mk_proof_res c)
| null | https://raw.githubusercontent.com/sneeuwballen/zipperposition/71798cc0559d2c365ad43a0a54e204a2d079cebd/src/prover/SClause.ml | ocaml | * unique ID of the clause
* the literals
* boolean trail
* boolean flags for the clause
* {2 Flags}
print a single boolean box
conversion to simple formula after instantiation, including the
substitution used for instantiating |
* { 1 Simple Clause }
open Logtk
module TPAsKey = struct
type t = (Term.t * Position.t)
let equal = (fun (_,p1) (_,p2) -> Position.equal p1 p2)
let hash = (fun (_,p1) -> Position.hash p1)
let compare = (fun (_,p1) (_,p2) -> Position.compare p1 p2)
end
module TPSet = CCSet.Make(TPAsKey)
type flag = int
type t = {
}
let id_count_ = ref 0
* { 2 Basics }
let make ~trail lits =
let id = !id_count_ in
incr id_count_;
{ lits; trail; id; flags=0; }
let[@inline] equal c1 c2 = c1.id = c2.id
let[@inline] compare c1 c2 = CCShims_.Stdlib.compare c1.id c2.id
let[@inline] id c = c.id
let[@inline] hash c = Hash.int c.id
let[@inline] lits c = c.lits
let[@inline] trail c = c.trail
let[@inline] length c = Array.length c.lits
let is_empty c = length c = 0 && Trail.is_empty c.trail
let update_trail f c = make ~trail:(f c.trail) c.lits
let add_trail_ trail f =
let module F = TypedSTerm.Form in
if Trail.is_empty trail
then f
else F.imply (Trail.to_s_form trail) f
let to_s_form ?allow_free_db ?(ctx=Term.Conv.create()) c =
let module F = TypedSTerm.Form in
Literals.Conv.to_s_form ?allow_free_db ~ctx (lits c)
|> add_trail_ (trail c)
|> F.close_forall
let new_flag =
let flag_gen = Util.Flag.create () in
fun () -> Util.Flag.get_new flag_gen
let flag_lemma = new_flag ()
let flag_persistent = new_flag ()
let flag_redundant = new_flag ()
let flag_backward_simplified = new_flag()
let flag_poly_arg_cong_res = new_flag()
let flag_initial = new_flag ()
let set_flag flag c truth =
if truth
then c.flags <- c.flags lor flag
else c.flags <- c.flags land (lnot flag)
let[@inline] get_flag flag c = (c.flags land flag) != 0
let mark_redundant c = set_flag flag_redundant c true
let[@inline] is_redundant c = get_flag flag_redundant c
let mark_backward_simplified c = set_flag flag_backward_simplified c true
let[@inline] is_backward_simplified c = get_flag flag_backward_simplified c
* { 2 IO }
let pp_trail out trail =
if not (Trail.is_empty trail)
then
Format.fprintf out "@ @<2>← @[<hv>%a@]"
(Util.pp_iter ~sep:" ⊓ " BBox.pp) (Trail.to_iter trail)
let pp_vars out c =
let pp_vars out = function
| [] -> ()
| l ->
Format.fprintf out "forall @[%a@].@ "
(Util.pp_list ~sep:" " Type.pp_typed_var) l
in
pp_vars out (Literals.vars c.lits)
let pp out c =
Format.fprintf out "@[%a@[<2>%a%a@]@](%d)"
pp_vars c Literals.pp c.lits pp_trail c.trail c.id;
()
let pp_trail_zf out trail =
Format.fprintf out "@[<hv>%a@]"
(Util.pp_iter ~sep:" && " BBox.pp_zf) (Trail.to_iter trail)
let pp_zf out c =
if Trail.is_empty c.trail
then Literals.pp_zf_closed out c.lits
else
Format.fprintf out "@[<2>(%a)@ => (%a)@]"
pp_trail_zf c.trail Literals.pp_zf_closed c.lits
print a trail in TPTP
let pp_trail_tstp out trail =
let pp_box_unsigned out b = match BBox.payload b with
| BBox.Case p ->
let lits = List.map Cover_set.Case.to_lit p |> Array.of_list in
Literals.pp_tstp out lits
| BBox.Clause_component lits ->
CCFormat.within "(" ")" Literals.pp_tstp_closed out lits
| BBox.Lemma f ->
CCFormat.within "(" ")" Cut_form.pp_tstp out f
| BBox.Fresh -> failwith "cannot print <fresh> boolean box"
in
let pp_box out b =
if BBox.Lit.sign b then pp_box_unsigned out b
else Format.fprintf out "@[~@ %a@]" pp_box_unsigned b
in
Format.fprintf out "@[<hv>%a@]"
(Util.pp_iter ~sep:" & " pp_box)
(Trail.to_iter trail)
let pp_tstp out c =
if Trail.is_empty c.trail
then Literals.pp_tstp_closed out c.lits
else
Format.fprintf out "@[<2>(@[%a@])@ <= (%a)@]"
Literals.pp_tstp_closed c.lits pp_trail_tstp c.trail
TODO : if all vars are [: term ] and trail is empty , use CNF ; else use TFF
let pp_tstp_full out c =
Format.fprintf out "@[<2>tff(%d, plain,@ %a).@]" c.id pp_tstp c
let pp_in = function
| Output_format.O_zf -> pp_zf
| Output_format.O_tptp -> pp_tstp
| Output_format.O_normal -> pp
| Output_format.O_none -> CCFormat.silent
* { 2 Proofs }
exception E_proof of t
let to_s_form_subst ~ctx subst c : _ * _ Var.Subst.t =
let module F = TypedSTerm.Form in
let module SP = Subst.Projection in
let f =
Literals.apply_subst (SP.renaming subst) (SP.subst subst) (lits c,SP.scope subst)
|> Literals.Conv.to_s_form ~allow_free_db:true ~ctx
|> add_trail_ (trail c)
|> F.close_forall
and inst_subst =
SP.as_inst ~allow_free_db:true ~ctx subst (Literals.vars (lits c))
in
f, inst_subst
let proof_tc cl =
Proof.Result.make_tc
~of_exn:(function | E_proof c -> Some c | _ -> None)
~to_exn:(fun c -> E_proof c)
~compare:compare
~flavor:(fun c ->
if Literals.is_absurd (lits c)
then if Trail.is_empty (trail c) then `Proof_of_false
else `Absurd_lits
else `Vanilla)
~to_form:(fun ~ctx c -> to_s_form ~allow_free_db:true ~ctx c)
~is_dead_cl:(fun () -> is_redundant cl)
~to_form_subst:to_s_form_subst
~name:(fun cl -> "zip_derived_cl" ^ CCInt.to_string cl.id)
~pp_in
()
let mk_proof_res cl = Proof.Result.make (proof_tc cl) cl
let adapt p c = Proof.S.adapt p (mk_proof_res c)
|
4246fff1236fe18e7bc7469e5688444064e4fe4b485aa76e90296c4b43e1bbcd | mlakewood/roll-a-ball | player.clj | (ns rollball.player
(:require [arcadia.core :as a]
[arcadia.linear :as l]
[rollball.common :refer [ensure-hook! ensure-state! ensure-game-object!]]
)
(:import [UnityEngine Input GameObject Vector3]))
(defn set-count-text [go]
(let [count (a/state go :count)
count-text (if (> count 9)
"You Win!"
(str "Count: " count))]
count-text)
)
(defn player-start [go]
(a/set-state! go :win-text "")
(a/set-state! go :count 0)
(a/set-state! go :count-text (set-count-text go))
)
(defn player-fixed-update [go]
(let [move-horizontal (Input/GetAxis "Horizontal")
move-vertical (Input/GetAxis "Vertical")
movement (Vector3. move-horizontal, 0.0, move-vertical)
speed (a/state go :speed)
rb (a/cmpt go UnityEngine.Rigidbody)
force (if rb
(.AddForce rb (l/v3* movement speed))
nil)
]
)
)
(defn player-on-trigger-enter [go other]
(if (.CompareTag other "Pick Up")
(let [other_go (.gameObject other)
_ (.SetActive other_go false)
cur-count (a/state go :count)
_ (a/set-state! go :count (+ cur-count 1))
_ (set-count-text go)])
)
)
(defn define-player-controller []
(let [player (ensure-game-object! "player" :sphere)]
(ensure-state! player :speed 10)
(a/ensure-cmpt player UnityEngine.Rigidbody)
(set! (.name player) "player")
(set! (.position (.transform player)) (Vector3. 0 0.5 0) )
(ensure-hook! player :start #'player-start)
(ensure-hook! player :fixed-update #'player-fixed-update)
(ensure-hook! player :on-trigger-enter #'player-on-trigger-enter)
player)
)
| null | https://raw.githubusercontent.com/mlakewood/roll-a-ball/b5c9d5c74ca974e3da77c3d88cd8dc4f6007f776/Assets/rollball/player.clj | clojure | (ns rollball.player
(:require [arcadia.core :as a]
[arcadia.linear :as l]
[rollball.common :refer [ensure-hook! ensure-state! ensure-game-object!]]
)
(:import [UnityEngine Input GameObject Vector3]))
(defn set-count-text [go]
(let [count (a/state go :count)
count-text (if (> count 9)
"You Win!"
(str "Count: " count))]
count-text)
)
(defn player-start [go]
(a/set-state! go :win-text "")
(a/set-state! go :count 0)
(a/set-state! go :count-text (set-count-text go))
)
(defn player-fixed-update [go]
(let [move-horizontal (Input/GetAxis "Horizontal")
move-vertical (Input/GetAxis "Vertical")
movement (Vector3. move-horizontal, 0.0, move-vertical)
speed (a/state go :speed)
rb (a/cmpt go UnityEngine.Rigidbody)
force (if rb
(.AddForce rb (l/v3* movement speed))
nil)
]
)
)
(defn player-on-trigger-enter [go other]
(if (.CompareTag other "Pick Up")
(let [other_go (.gameObject other)
_ (.SetActive other_go false)
cur-count (a/state go :count)
_ (a/set-state! go :count (+ cur-count 1))
_ (set-count-text go)])
)
)
(defn define-player-controller []
(let [player (ensure-game-object! "player" :sphere)]
(ensure-state! player :speed 10)
(a/ensure-cmpt player UnityEngine.Rigidbody)
(set! (.name player) "player")
(set! (.position (.transform player)) (Vector3. 0 0.5 0) )
(ensure-hook! player :start #'player-start)
(ensure-hook! player :fixed-update #'player-fixed-update)
(ensure-hook! player :on-trigger-enter #'player-on-trigger-enter)
player)
)
|
|
c64ebdcdad7e9d3920cd89653cccd2720ab043c3620f84db37c177c34f8ce20f | sky-big/RabbitMQ | amqp_channels_manager.erl | The contents of this file are subject to the Mozilla Public License
%% Version 1.1 (the "License"); you may not use this file except in
%% compliance with the License. You may obtain a copy of the License at
%% /
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
%% License for the specific language governing rights and limitations
%% under the License.
%%
The Original Code is RabbitMQ .
%%
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
%%
@private
-module(amqp_channels_manager).
-include("amqp_client_internal.hrl").
-behaviour(gen_server).
-export([start_link/3, open_channel/4, set_channel_max/2, is_empty/1,
num_channels/1, pass_frame/3, signal_connection_closing/3,
process_channel_frame/4]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-record(state, {
connection, %% 连接进程的Pid
channel_sup_sup, %% amqp_channel_sup_sup监督进程Pid
Number - > { Pid , AState }
map_pid_num = dict:new(), %% Pid -> Number
channel_max = ?MAX_CHANNEL_NUMBER, %% 当前连接中channel的最大个数
closing = false %% 当前的状态
}).
%%---------------------------------------------------------------------------
Interface
%%---------------------------------------------------------------------------
%% 启动amqp_channels_manager进程的入口API函数
start_link(Connection, ConnName, ChSupSup) ->
gen_server:start_link(?MODULE, [Connection, ConnName, ChSupSup], []).
%% 启动新的频道的入口API函数
open_channel(ChMgr, ProposedNumber, Consumer, InfraArgs) ->
gen_server:call(ChMgr, {open_channel, ProposedNumber, Consumer, InfraArgs},
infinity).
set_channel_max(ChMgr, ChannelMax) ->
gen_server:cast(ChMgr, {set_channel_max, ChannelMax}).
is_empty(ChMgr) ->
gen_server:call(ChMgr, is_empty, infinity).
num_channels(ChMgr) ->
gen_server:call(ChMgr, num_channels, infinity).
%% ChNumber不为0,将frame数据发送到amqp_channel_manager进程进行处理,amqp_channel_manager进程通过ChNumber找到对应的channel进程进行相关的处理
pass_frame(ChMgr, ChNumber, Frame) ->
gen_server:cast(ChMgr, {pass_frame, ChNumber, Frame}).
signal_connection_closing(ChMgr, ChannelCloseType, Reason) ->
gen_server:cast(ChMgr, {connection_closing, ChannelCloseType, Reason}).
%% channel为0则默认发送给amqp_gen_connection进程进行处理
%% channel如果不为0,则ChPid为channel对应的频道Pid,将得到的Frame消息发送给ChPid进程处理
process_channel_frame(Frame, Channel, ChPid, AState) ->
case rabbit_command_assembler:process(Frame, AState) of
此处是没有得到对应的Method,则将上次收到的消息存储起来,等待后续的Frame消息的到达
{ok, NewAState} -> NewAState;
只得到AMQP消息
{ok, Method, NewAState} -> rabbit_channel:do(ChPid, Method),
NewAState;
%% 得到AMQP消息以及带的消息内容
{ok, Method, Content, NewAState} -> rabbit_channel:do(ChPid, Method,
Content),
NewAState;
%% 出错
{error, Reason} -> ChPid ! {channel_exit, Channel,
Reason},
AState
end.
%%---------------------------------------------------------------------------
%% gen_server callbacks
%%---------------------------------------------------------------------------
init([Connection, ConnName, ChSupSup]) ->
?store_proc_name(ConnName),
{ok, #state{connection = Connection, channel_sup_sup = ChSupSup}}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% 处理新建频道的消息
handle_call({open_channel, ProposedNumber, Consumer, InfraArgs}, _,
State = #state{closing = false}) ->
handle_open_channel(ProposedNumber, Consumer, InfraArgs, State);
handle_call(is_empty, _, State) ->
{reply, internal_is_empty(State), State};
handle_call(num_channels, _, State) ->
{reply, internal_num_channels(State), State}.
handle_cast({set_channel_max, ChannelMax}, State) ->
{noreply, State#state{channel_max = ChannelMax}};
%% 处理amqp_main_reader进程读取的RabbitMQ系统发送过来的Frame消息
handle_cast({pass_frame, ChNumber, Frame}, State) ->
{noreply, internal_pass_frame(ChNumber, Frame, State)};
handle_cast({connection_closing, ChannelCloseType, Reason}, State) ->
handle_connection_closing(ChannelCloseType, Reason, State).
handle_info({'DOWN', _, process, Pid, Reason}, State) ->
handle_down(Pid, Reason, State).
%%---------------------------------------------------------------------------
Internal plumbing
%%---------------------------------------------------------------------------
实际的打开新的频道的处理过程
handle_open_channel(ProposedNumber, Consumer, InfraArgs,
State = #state{channel_sup_sup = ChSupSup}) ->
case new_number(ProposedNumber, State) of
{ok, Number} ->
{ok, _ChSup, {Ch, AState}} =
amqp_channel_sup_sup:start_channel_sup(ChSupSup, InfraArgs,
Number, Consumer),
%% 将新创建的channel信息记录下来
NewState = internal_register(Number, Ch, AState, State),
erlang:monitor(process, Ch),
{reply, {ok, Ch}, NewState};
{error, _} = Error ->
{reply, Error, State}
end.
%% 得到一个新的频道数字
new_number(none, #state{channel_max = ChannelMax, map_num_pa = MapNPA}) ->
case gb_trees:is_empty(MapNPA) of
true -> {ok, 1};
false -> {Smallest, _} = gb_trees:smallest(MapNPA),
if Smallest > 1 ->
{ok, Smallest - 1};
true ->
{Largest, _} = gb_trees:largest(MapNPA),
if Largest < ChannelMax -> {ok, Largest + 1};
true -> find_free(MapNPA)
end
end
end;
new_number(Proposed, State = #state{channel_max = ChannelMax,
map_num_pa = MapNPA}) ->
IsValid = Proposed > 0 andalso Proposed =< ChannelMax andalso
not gb_trees:is_defined(Proposed, MapNPA),
case IsValid of true -> {ok, Proposed};
false -> new_number(none, State)
end.
find_free(MapNPA) ->
find_free(gb_trees:iterator(MapNPA), 1).
find_free(It, Candidate) ->
case gb_trees:next(It) of
{Number, _, It1} -> if Number > Candidate ->
{ok, Number - 1};
Number =:= Candidate ->
find_free(It1, Candidate + 1)
end;
none -> {error, out_of_channel_numbers}
end.
handle_down(Pid, Reason, State) ->
case internal_lookup_pn(Pid, State) of
undefined -> {stop, {error, unexpected_down}, State};
Number -> handle_channel_down(Pid, Number, Reason, State)
end.
handle_channel_down(Pid, Number, Reason, State) ->
maybe_report_down(Pid, case Reason of {shutdown, R} -> R;
_ -> Reason
end,
State),
NewState = internal_unregister(Number, Pid, State),
check_all_channels_terminated(NewState),
{noreply, NewState}.
maybe_report_down(_Pid, normal, _State) ->
ok;
maybe_report_down(_Pid, shutdown, _State) ->
ok;
maybe_report_down(_Pid, {app_initiated_close, _, _}, _State) ->
ok;
maybe_report_down(_Pid, {server_initiated_close, _, _}, _State) ->
ok;
maybe_report_down(_Pid, {connection_closing, _}, _State) ->
ok;
maybe_report_down(_Pid, {server_misbehaved, AmqpError},
#state{connection = Connection}) ->
amqp_gen_connection:server_misbehaved(Connection, AmqpError);
maybe_report_down(Pid, Other, #state{connection = Connection}) ->
amqp_gen_connection:channel_internal_error(Connection, Pid, Other).
check_all_channels_terminated(#state{closing = false}) ->
ok;
check_all_channels_terminated(State = #state{closing = true,
connection = Connection}) ->
case internal_is_empty(State) of
true -> amqp_gen_connection:channels_terminated(Connection);
false -> ok
end.
handle_connection_closing(ChannelCloseType, Reason,
State = #state{connection = Connection}) ->
case internal_is_empty(State) of
true -> amqp_gen_connection:channels_terminated(Connection);
false -> signal_channels_connection_closing(ChannelCloseType, Reason,
State)
end,
{noreply, State#state{closing = true}}.
%%---------------------------------------------------------------------------
internal_pass_frame(Number, Frame, State) ->
case internal_lookup_npa(Number, State) of
undefined ->
?LOG_INFO("Dropping frame ~p for invalid or closed "
"channel number ~p~n", [Frame, Number]),
State;
{ChPid, AState} ->
NewAState = process_channel_frame(Frame, Number, ChPid, AState),
internal_update_npa(Number, ChPid, NewAState, State)
end.
将新创建的amqp_channel进程的信息存储起来
internal_register(Number, Pid, AState,
State = #state{map_num_pa = MapNPA, map_pid_num = MapPN}) ->
MapNPA1 = gb_trees:enter(Number, {Pid, AState}, MapNPA),
MapPN1 = dict:store(Pid, Number, MapPN),
State#state{map_num_pa = MapNPA1,
map_pid_num = MapPN1}.
internal_unregister(Number, Pid,
State = #state{map_num_pa = MapNPA, map_pid_num = MapPN}) ->
MapNPA1 = gb_trees:delete(Number, MapNPA),
MapPN1 = dict:erase(Pid, MapPN),
State#state{map_num_pa = MapNPA1,
map_pid_num = MapPN1}.
internal_is_empty(#state{map_num_pa = MapNPA}) ->
gb_trees:is_empty(MapNPA).
internal_num_channels(#state{map_num_pa = MapNPA}) ->
gb_trees:size(MapNPA).
%% 根据频道数字得到对应的amqp_channel进程的PID和状态
internal_lookup_npa(Number, #state{map_num_pa = MapNPA}) ->
case gb_trees:lookup(Number, MapNPA) of {value, PA} -> PA;
none -> undefined
end.
internal_lookup_pn(Pid, #state{map_pid_num = MapPN}) ->
case dict:find(Pid, MapPN) of {ok, Number} -> Number;
error -> undefined
end.
internal_update_npa(Number, Pid, AState, State = #state{map_num_pa = MapNPA}) ->
State#state{map_num_pa = gb_trees:update(Number, {Pid, AState}, MapNPA)}.
signal_channels_connection_closing(ChannelCloseType, Reason,
#state{map_pid_num = MapPN}) ->
[amqp_channel:connection_closing(Pid, ChannelCloseType, Reason)
|| Pid <- dict:fetch_keys(MapPN)].
| null | https://raw.githubusercontent.com/sky-big/RabbitMQ/d7a773e11f93fcde4497c764c9fa185aad049ce2/plugins-src/rabbitmq-erlang-client/src/amqp_channels_manager.erl | erlang | Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
/
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
License for the specific language governing rights and limitations
under the License.
连接进程的Pid
amqp_channel_sup_sup监督进程Pid
Pid -> Number
当前连接中channel的最大个数
当前的状态
---------------------------------------------------------------------------
---------------------------------------------------------------------------
启动amqp_channels_manager进程的入口API函数
启动新的频道的入口API函数
ChNumber不为0,将frame数据发送到amqp_channel_manager进程进行处理,amqp_channel_manager进程通过ChNumber找到对应的channel进程进行相关的处理
channel为0则默认发送给amqp_gen_connection进程进行处理
channel如果不为0,则ChPid为channel对应的频道Pid,将得到的Frame消息发送给ChPid进程处理
得到AMQP消息以及带的消息内容
出错
---------------------------------------------------------------------------
gen_server callbacks
---------------------------------------------------------------------------
处理新建频道的消息
处理amqp_main_reader进程读取的RabbitMQ系统发送过来的Frame消息
---------------------------------------------------------------------------
---------------------------------------------------------------------------
将新创建的channel信息记录下来
得到一个新的频道数字
---------------------------------------------------------------------------
根据频道数字得到对应的amqp_channel进程的PID和状态 | The contents of this file are subject to the Mozilla Public License
Software distributed under the License is distributed on an " AS IS "
The Original Code is RabbitMQ .
The Initial Developer of the Original Code is GoPivotal , Inc.
Copyright ( c ) 2007 - 2014 GoPivotal , Inc. All rights reserved .
@private
-module(amqp_channels_manager).
-include("amqp_client_internal.hrl").
-behaviour(gen_server).
-export([start_link/3, open_channel/4, set_channel_max/2, is_empty/1,
num_channels/1, pass_frame/3, signal_connection_closing/3,
process_channel_frame/4]).
-export([init/1, terminate/2, code_change/3, handle_call/3, handle_cast/2,
handle_info/2]).
-record(state, {
Number - > { Pid , AState }
}).
Interface
start_link(Connection, ConnName, ChSupSup) ->
gen_server:start_link(?MODULE, [Connection, ConnName, ChSupSup], []).
open_channel(ChMgr, ProposedNumber, Consumer, InfraArgs) ->
gen_server:call(ChMgr, {open_channel, ProposedNumber, Consumer, InfraArgs},
infinity).
set_channel_max(ChMgr, ChannelMax) ->
gen_server:cast(ChMgr, {set_channel_max, ChannelMax}).
is_empty(ChMgr) ->
gen_server:call(ChMgr, is_empty, infinity).
num_channels(ChMgr) ->
gen_server:call(ChMgr, num_channels, infinity).
pass_frame(ChMgr, ChNumber, Frame) ->
gen_server:cast(ChMgr, {pass_frame, ChNumber, Frame}).
signal_connection_closing(ChMgr, ChannelCloseType, Reason) ->
gen_server:cast(ChMgr, {connection_closing, ChannelCloseType, Reason}).
process_channel_frame(Frame, Channel, ChPid, AState) ->
case rabbit_command_assembler:process(Frame, AState) of
此处是没有得到对应的Method,则将上次收到的消息存储起来,等待后续的Frame消息的到达
{ok, NewAState} -> NewAState;
只得到AMQP消息
{ok, Method, NewAState} -> rabbit_channel:do(ChPid, Method),
NewAState;
{ok, Method, Content, NewAState} -> rabbit_channel:do(ChPid, Method,
Content),
NewAState;
{error, Reason} -> ChPid ! {channel_exit, Channel,
Reason},
AState
end.
init([Connection, ConnName, ChSupSup]) ->
?store_proc_name(ConnName),
{ok, #state{connection = Connection, channel_sup_sup = ChSupSup}}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
handle_call({open_channel, ProposedNumber, Consumer, InfraArgs}, _,
State = #state{closing = false}) ->
handle_open_channel(ProposedNumber, Consumer, InfraArgs, State);
handle_call(is_empty, _, State) ->
{reply, internal_is_empty(State), State};
handle_call(num_channels, _, State) ->
{reply, internal_num_channels(State), State}.
handle_cast({set_channel_max, ChannelMax}, State) ->
{noreply, State#state{channel_max = ChannelMax}};
handle_cast({pass_frame, ChNumber, Frame}, State) ->
{noreply, internal_pass_frame(ChNumber, Frame, State)};
handle_cast({connection_closing, ChannelCloseType, Reason}, State) ->
handle_connection_closing(ChannelCloseType, Reason, State).
handle_info({'DOWN', _, process, Pid, Reason}, State) ->
handle_down(Pid, Reason, State).
Internal plumbing
实际的打开新的频道的处理过程
handle_open_channel(ProposedNumber, Consumer, InfraArgs,
State = #state{channel_sup_sup = ChSupSup}) ->
case new_number(ProposedNumber, State) of
{ok, Number} ->
{ok, _ChSup, {Ch, AState}} =
amqp_channel_sup_sup:start_channel_sup(ChSupSup, InfraArgs,
Number, Consumer),
NewState = internal_register(Number, Ch, AState, State),
erlang:monitor(process, Ch),
{reply, {ok, Ch}, NewState};
{error, _} = Error ->
{reply, Error, State}
end.
new_number(none, #state{channel_max = ChannelMax, map_num_pa = MapNPA}) ->
case gb_trees:is_empty(MapNPA) of
true -> {ok, 1};
false -> {Smallest, _} = gb_trees:smallest(MapNPA),
if Smallest > 1 ->
{ok, Smallest - 1};
true ->
{Largest, _} = gb_trees:largest(MapNPA),
if Largest < ChannelMax -> {ok, Largest + 1};
true -> find_free(MapNPA)
end
end
end;
new_number(Proposed, State = #state{channel_max = ChannelMax,
map_num_pa = MapNPA}) ->
IsValid = Proposed > 0 andalso Proposed =< ChannelMax andalso
not gb_trees:is_defined(Proposed, MapNPA),
case IsValid of true -> {ok, Proposed};
false -> new_number(none, State)
end.
find_free(MapNPA) ->
find_free(gb_trees:iterator(MapNPA), 1).
find_free(It, Candidate) ->
case gb_trees:next(It) of
{Number, _, It1} -> if Number > Candidate ->
{ok, Number - 1};
Number =:= Candidate ->
find_free(It1, Candidate + 1)
end;
none -> {error, out_of_channel_numbers}
end.
handle_down(Pid, Reason, State) ->
case internal_lookup_pn(Pid, State) of
undefined -> {stop, {error, unexpected_down}, State};
Number -> handle_channel_down(Pid, Number, Reason, State)
end.
handle_channel_down(Pid, Number, Reason, State) ->
maybe_report_down(Pid, case Reason of {shutdown, R} -> R;
_ -> Reason
end,
State),
NewState = internal_unregister(Number, Pid, State),
check_all_channels_terminated(NewState),
{noreply, NewState}.
maybe_report_down(_Pid, normal, _State) ->
ok;
maybe_report_down(_Pid, shutdown, _State) ->
ok;
maybe_report_down(_Pid, {app_initiated_close, _, _}, _State) ->
ok;
maybe_report_down(_Pid, {server_initiated_close, _, _}, _State) ->
ok;
maybe_report_down(_Pid, {connection_closing, _}, _State) ->
ok;
maybe_report_down(_Pid, {server_misbehaved, AmqpError},
#state{connection = Connection}) ->
amqp_gen_connection:server_misbehaved(Connection, AmqpError);
maybe_report_down(Pid, Other, #state{connection = Connection}) ->
amqp_gen_connection:channel_internal_error(Connection, Pid, Other).
check_all_channels_terminated(#state{closing = false}) ->
ok;
check_all_channels_terminated(State = #state{closing = true,
connection = Connection}) ->
case internal_is_empty(State) of
true -> amqp_gen_connection:channels_terminated(Connection);
false -> ok
end.
handle_connection_closing(ChannelCloseType, Reason,
State = #state{connection = Connection}) ->
case internal_is_empty(State) of
true -> amqp_gen_connection:channels_terminated(Connection);
false -> signal_channels_connection_closing(ChannelCloseType, Reason,
State)
end,
{noreply, State#state{closing = true}}.
internal_pass_frame(Number, Frame, State) ->
case internal_lookup_npa(Number, State) of
undefined ->
?LOG_INFO("Dropping frame ~p for invalid or closed "
"channel number ~p~n", [Frame, Number]),
State;
{ChPid, AState} ->
NewAState = process_channel_frame(Frame, Number, ChPid, AState),
internal_update_npa(Number, ChPid, NewAState, State)
end.
将新创建的amqp_channel进程的信息存储起来
internal_register(Number, Pid, AState,
State = #state{map_num_pa = MapNPA, map_pid_num = MapPN}) ->
MapNPA1 = gb_trees:enter(Number, {Pid, AState}, MapNPA),
MapPN1 = dict:store(Pid, Number, MapPN),
State#state{map_num_pa = MapNPA1,
map_pid_num = MapPN1}.
internal_unregister(Number, Pid,
State = #state{map_num_pa = MapNPA, map_pid_num = MapPN}) ->
MapNPA1 = gb_trees:delete(Number, MapNPA),
MapPN1 = dict:erase(Pid, MapPN),
State#state{map_num_pa = MapNPA1,
map_pid_num = MapPN1}.
internal_is_empty(#state{map_num_pa = MapNPA}) ->
gb_trees:is_empty(MapNPA).
internal_num_channels(#state{map_num_pa = MapNPA}) ->
gb_trees:size(MapNPA).
internal_lookup_npa(Number, #state{map_num_pa = MapNPA}) ->
case gb_trees:lookup(Number, MapNPA) of {value, PA} -> PA;
none -> undefined
end.
internal_lookup_pn(Pid, #state{map_pid_num = MapPN}) ->
case dict:find(Pid, MapPN) of {ok, Number} -> Number;
error -> undefined
end.
internal_update_npa(Number, Pid, AState, State = #state{map_num_pa = MapNPA}) ->
State#state{map_num_pa = gb_trees:update(Number, {Pid, AState}, MapNPA)}.
signal_channels_connection_closing(ChannelCloseType, Reason,
#state{map_pid_num = MapPN}) ->
[amqp_channel:connection_closing(Pid, ChannelCloseType, Reason)
|| Pid <- dict:fetch_keys(MapPN)].
|
5b8d360da78f40378141d70aef5316bd508de2dd25b6b88eb8019a77a8dffc01 | philnguyen/soft-contract | issue-105.rkt | #lang racket
(struct foo (x))
(define leak (foo 'foo))
(provide (contract-out (foo-x (-> foo? integer?))
(leak foo?)))
| null | https://raw.githubusercontent.com/philnguyen/soft-contract/5e07dc2d622ee80b961f4e8aebd04ce950720239/soft-contract/test/programs/unsafe/issues/issue-105.rkt | racket | #lang racket
(struct foo (x))
(define leak (foo 'foo))
(provide (contract-out (foo-x (-> foo? integer?))
(leak foo?)))
|
|
d453c159e8f9de66be7eb776554008b76ee48fb5b59d4056b6e983e13395ea6a | vseloved/cl-parsec | arithmetic.lisp | (in-package :parsec-test)
(defparser spaces ()
(skip-many #\Space))
(defparser expression ()
(prog1 (many+ #'tok)
(spaces)
(eof)))
(defparser tok ()
(spaces)
(either #`(parse-integer (coerce (many+ #`(parsecall #'digit-char-p))
'string))
#`(parsecall #\( :lparen)
#`(parsecall #\) :rparen)
#'operator))
(defparser operator ()
(list :op (parsecall '(member (#\- #\+ #\* #\/))))) | null | https://raw.githubusercontent.com/vseloved/cl-parsec/f86660cc7d372df598d2a8348040a4b53c90631f/examples/arithmetic.lisp | lisp | (in-package :parsec-test)
(defparser spaces ()
(skip-many #\Space))
(defparser expression ()
(prog1 (many+ #'tok)
(spaces)
(eof)))
(defparser tok ()
(spaces)
(either #`(parse-integer (coerce (many+ #`(parsecall #'digit-char-p))
'string))
#`(parsecall #\( :lparen)
#`(parsecall #\) :rparen)
#'operator))
(defparser operator ()
(list :op (parsecall '(member (#\- #\+ #\* #\/))))) |
|
83a9d1d8af14458ceb9e995fe7a04d7eace3febf92c6c46041de7110aead85f7 | herd/herdtools7 | ASLParseTest.ml | (****************************************************************************)
(* the diy toolsuite *)
(* *)
, University College London , UK .
, INRIA Paris - Rocquencourt , France .
(* *)
Copyright 2023 - present Institut National de Recherche en Informatique et
(* en Automatique and the authors. All rights reserved. *)
(* *)
This software is governed by the CeCILL - B license under French law and
(* abiding by the rules of distribution of free software. You can use, *)
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
(****************************************************************************)
module Make (Conf : RunTest.Config) (ModelConfig : MemCat.Config) = struct
module ArchConfig = SemExtra.ConfigToArchConfig (Conf)
module ASLS = ASLSem.Make (Conf)
module ASLA = ASLS.ASL64AH
module ASLLexParse = struct
type instruction = ASLA.parsedPseudo
type token = Asllib.Parser.token
let lexer = Asllib.Lexer.token
let parser = ASLBase.asl_generic_parser
end
module ASLM = MemCat.Make (ModelConfig) (ASLS)
module P = GenParser.Make (Conf) (ASLA) (ASLLexParse)
module X = RunTest.Make (ASLS) (P) (ASLM) (Conf)
let run = X.run
end
| null | https://raw.githubusercontent.com/herd/herdtools7/daedd7431cb00884afea2ec39749222e2c367c6b/herd/ASLParseTest.ml | ocaml | **************************************************************************
the diy toolsuite
en Automatique and the authors. All rights reserved.
abiding by the rules of distribution of free software. You can use,
************************************************************************** | , University College London , UK .
, INRIA Paris - Rocquencourt , France .
Copyright 2023 - present Institut National de Recherche en Informatique et
This software is governed by the CeCILL - B license under French law and
modify and/ or redistribute the software under the terms of the CeCILL - B
license as circulated by CEA , CNRS and INRIA at the following URL
" " . We also give a copy in LICENSE.txt .
module Make (Conf : RunTest.Config) (ModelConfig : MemCat.Config) = struct
module ArchConfig = SemExtra.ConfigToArchConfig (Conf)
module ASLS = ASLSem.Make (Conf)
module ASLA = ASLS.ASL64AH
module ASLLexParse = struct
type instruction = ASLA.parsedPseudo
type token = Asllib.Parser.token
let lexer = Asllib.Lexer.token
let parser = ASLBase.asl_generic_parser
end
module ASLM = MemCat.Make (ModelConfig) (ASLS)
module P = GenParser.Make (Conf) (ASLA) (ASLLexParse)
module X = RunTest.Make (ASLS) (P) (ASLM) (Conf)
let run = X.run
end
|
e5c715db59c78eccf395c886b3db0851bf3d9e5ea881b0fb94468d3358eba02f | CloudI/CloudI | cloudi_service_http_rest.erl | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
%%%
%%%------------------------------------------------------------------------
%%% @doc
%%% ==CloudI HTTP REST Integration==
Provide an easy way of connecting CloudI service requests to
Erlang function calls for a HTTP REST API , with service configuration
%%% arguments.
%%% @end
%%%
MIT License
%%%
Copyright ( c ) 2015 - 2019 < mjtruog at protonmail dot com >
%%%
%%% 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.
%%%
@author < mjtruog at protonmail dot com >
2015 - 2019
%%% @version 1.8.0 {@date} {@time}
%%%------------------------------------------------------------------------
-module(cloudi_service_http_rest).
-author('mjtruog at protonmail dot com').
-behaviour(cloudi_service).
cloudi_service callbacks
-export([cloudi_service_init/4,
cloudi_service_handle_request/11,
cloudi_service_handle_info/3,
cloudi_service_terminate/3]).
-include_lib("cloudi_core/include/cloudi_logger.hrl").
-define(DEFAULT_INITIALIZE, undefined). % see below:
% If necessary, provide an initialization function to be called
% for initializing REST handler state data. The initialize
% function can be specified as an anonymous function or a
% {module(), FunctionName :: atom()} tuple.
-define(DEFAULT_TERMINATE, undefined). % see below:
% If necessary, provide a terminate function to be called
% for terminating the REST handler's state data. The terminate
% function can be specified as an anonymous function or a
% {module(), FunctionName :: atom()} tuple.
-define(DEFAULT_HANDLERS, undefined). % see below:
% Provide a list of handler functions to be used with the
% service name prefix. Each handler function entry in the list
% takes the form:
% {Method :: atom() | string(), Path :: string(), handler()}
% (e.g., Method == 'GET', Path == "index.html")
% The handler function can be specified as an anonymous function or a
% {module(), FunctionName :: atom()} tuple.
-define(DEFAULT_INFO, undefined). % see below:
% If necessary, provide an info function to be called
for Erlang messages received by the process . The info
% function can be specified as an anonymous function or a
% {module(), FunctionName :: atom()} tuple.
-define(DEFAULT_FORMATS, undefined). % see below:
% Provide a list of formats to handle that are added as file type
% suffixes on the URL path which also determine the content-type used
% for the request and response.
-define(DEFAULT_SET_CONTENT_DISPOSITION, false).
% Set the content-disposition header value for any content-type values
% that are tagged as an attachment.
-define(DEFAULT_USE_OPTIONS_METHOD, false).
% Provide default handling of the OPTIONS method based on the
% configured handlers.
-define(DEFAULT_USE_TRACE_METHOD, false).
Provide default handling of the TRACE method based on the
% configured handlers.
-define(DEFAULT_DEBUG, false). % log output for debugging
-define(DEFAULT_DEBUG_LEVEL, trace).
-type method() :: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' |
'PATCH' | 'TRACE' | 'CONNECT'.
-type initialize_f() :: fun((Args :: list(),
Timeout :: cloudi_service_api:
timeout_initialize_value_milliseconds(),
Dispatcher :: cloudi:dispatcher()) ->
{ok, State :: any()} |
{stop, Reason :: any()} |
{stop, Reason :: any(), State :: any()}).
-type handler_f_11() :: fun((Method :: method(),
Path :: cloudi:service_name_pattern(),
Parameters :: list(string()),
Format :: atom(),
RequestInfo :: any(),
Request :: any(),
Timeout :: cloudi:timeout_value_milliseconds(),
Priority :: cloudi:priority_value(),
TransId :: cloudi:trans_id(),
State :: any(),
Dispatcher :: cloudi:dispatcher()) ->
{reply, Response :: any(), NewState :: any()} |
{reply, ResponseInfo :: any(), Response :: any(), NewState :: any()} |
{forward, NextName :: cloudi:service_name(),
NextRequestInfo :: any(), NextRequest :: any(), NewState :: any()} |
{forward, NextName :: cloudi:service_name(),
NextRequestInfo :: any(), NextRequest :: any(),
NextTimeout :: cloudi:timeout_value_milliseconds(),
NextPriority :: cloudi:priority_value(), NewState :: any()} |
{noreply, NewState :: any()} |
{stop, Reason :: any(), NewState :: any()}).
-type info_f() :: fun((Request :: any(),
State :: any(),
Dispatcher :: cloudi:dispatcher()) ->
{noreply, NewState :: any()} |
{stop, Reason :: any(), NewState :: any()}).
-type terminate_f() :: fun((Reason :: any(),
Timeout :: cloudi_service_api:
timeout_terminate_value_milliseconds(),
State :: any()) ->
ok).
-export_type([method/0,
initialize_f/0,
handler_f_11/0,
info_f/0,
terminate_f/0]).
-record(api,
{
method :: method(),
path :: cloudi:service_name_pattern(),
parameters :: boolean(),
format :: atom(),
handler_f :: handler_f_11(),
arity :: 11
}).
-record(state,
{
prefix :: cloudi:service_name_pattern(),
lookup :: cloudi_x_trie:cloudi_x_trie(),
info_f :: info_f() | undefined,
terminate_f :: terminate_f() | undefined,
content_types :: #{atom() := {request | attachment, binary()}},
content_disposition :: boolean(),
debug_level :: off | trace | debug | info | warn | error | fatal,
api_state :: any()
}).
%%%------------------------------------------------------------------------
%%% External interface functions
%%%------------------------------------------------------------------------
%%%------------------------------------------------------------------------
Callback functions from cloudi_service
%%%------------------------------------------------------------------------
cloudi_service_init(Args, Prefix, Timeout, Dispatcher) ->
Defaults = [
{initialize, ?DEFAULT_INITIALIZE},
{terminate, ?DEFAULT_TERMINATE},
{handlers, ?DEFAULT_HANDLERS},
{info, ?DEFAULT_INFO},
{formats, ?DEFAULT_FORMATS},
{set_content_disposition, ?DEFAULT_SET_CONTENT_DISPOSITION},
{use_options_method, ?DEFAULT_USE_OPTIONS_METHOD},
{use_trace_method, ?DEFAULT_USE_TRACE_METHOD},
{debug, ?DEFAULT_DEBUG},
{debug_level, ?DEFAULT_DEBUG_LEVEL}],
[Initialize, Terminate0, Handlers0, Info0, Formats0,
SetContentDisposition, UseOptionsMethod, UseTraceMethod,
Debug, DebugLevel | ArgsAPI] =
cloudi_proplists:take_values(Defaults, Args),
TerminateN = cloudi_args_type:function_optional(Terminate0, 3),
true = is_list(Handlers0),
lists:foreach(fun({Method, Path, _}) ->
MethodString = if
is_atom(Method) ->
erlang:atom_to_list(Method);
is_list(Method), is_integer(hd(Method)) ->
Method
end,
MethodString = cloudi_string:uppercase(MethodString),
true = is_list(Path) andalso is_integer(hd(Path))
end, Handlers0),
InfoN = cloudi_args_type:function_optional(Info0, 3),
true = is_list(Formats0),
true = is_boolean(SetContentDisposition),
true = is_boolean(UseOptionsMethod),
true = is_boolean(UseTraceMethod),
true = is_boolean(Debug),
true = ((DebugLevel =:= trace) orelse
(DebugLevel =:= debug) orelse
(DebugLevel =:= info) orelse
(DebugLevel =:= warn) orelse
(DebugLevel =:= error) orelse
(DebugLevel =:= fatal)),
DebugLogLevel = if
Debug =:= false ->
off;
Debug =:= true ->
DebugLevel
end,
ContentTypes = cloudi_response_info:lookup_content_type(),
FormatsN = lists:map(fun(Format0) ->
FormatN = if
is_list(Format0), is_integer(hd(Format0)) ->
Format0;
is_atom(Format0) ->
erlang:atom_to_list(Format0)
end,
true = cloudi_x_trie:is_key("." ++ FormatN, ContentTypes),
FormatN
end, Formats0),
ContentTypeLookupN = lists:foldl(fun(FormatN, ContentTypeLookup0) ->
maps:put(erlang:list_to_atom(FormatN),
cloudi_x_trie:fetch("." ++ FormatN, ContentTypes),
ContentTypeLookup0)
end, #{}, FormatsN),
MethodListsN = cloudi_x_trie:to_list(lists:foldr(fun({Method, Path, _},
MethodLists0) ->
MethodString = if
is_atom(Method) ->
erlang:atom_to_list(Method);
is_list(Method) ->
Method
end,
cloudi_x_trie:update(Path, fun(MethodList0) ->
lists:umerge(MethodList0, [MethodString])
end, [MethodString], MethodLists0)
end, cloudi_x_trie:new(), Handlers0)),
Handlers1 = if
UseTraceMethod =:= true ->
lists:map(fun({Path, _}) ->
HandlerTrace = fun(_, _, _, _, _, _, _, _, _,
TraceHandlerState, _) ->
{reply,
[{<<"via">>, <<"1.1 CloudI">>}], <<>>, TraceHandlerState}
end,
{'TRACE', Path, HandlerTrace}
end, MethodListsN) ++ Handlers0;
UseTraceMethod =:= false ->
Handlers0
end,
HandlersN = if
UseOptionsMethod =:= true ->
lists:map(fun({Path, MethodList1}) ->
MethodListN = lists:umerge(MethodList1, ["OPTIONS"]),
Methods = erlang:list_to_binary(lists:join(", ", MethodListN)),
HandlerOptions = fun(_, _, _, _, _, _, _, _, _,
OptionsHandlerState, _) ->
% content-type is set automatically by HTTP process
{reply,
[{<<"allow">>, Methods}], <<>>, OptionsHandlerState}
end,
{'OPTIONS', Path, HandlerOptions}
end, MethodListsN) ++ Handlers1;
UseOptionsMethod =:= false ->
Handlers1
end,
LookupN = lists:foldl(fun({Method, Path, Handler0}, Lookup0) ->
{Handler1,
Arity} = cloudi_args_type:function_required_pick(Handler0, [11]),
HandlerMethod = if
is_atom(Method) ->
Method;
is_list(Method) ->
erlang:list_to_atom(Method)
end,
API = #api{method = HandlerMethod,
path = Path,
parameters = cloudi_service_name:pattern(Prefix ++ Path),
handler_f = Handler1,
arity = Arity},
subscribe_paths(Method, Path, FormatsN, API, Lookup0, Dispatcher)
end, cloudi_x_trie:new(), HandlersN),
State = #state{prefix = Prefix,
lookup = LookupN,
info_f = InfoN,
terminate_f = TerminateN,
content_types = ContentTypeLookupN,
content_disposition = SetContentDisposition,
debug_level = DebugLogLevel},
ReturnAPI = case cloudi_args_type:function_optional(Initialize, 3) of
undefined ->
true = (ArgsAPI == []),
{ok, undefined};
InitializeFunction ->
InitializeFunction(ArgsAPI, Timeout, Dispatcher)
end,
case ReturnAPI of
{ok, StateAPI} ->
{ok, State#state{api_state = StateAPI}};
{stop, Reason} ->
{stop, Reason, State};
{stop, Reason, StateAPI} ->
{stop, Reason, State#state{api_state = StateAPI}}
end.
cloudi_service_handle_request(_RequestType, Name, Pattern, RequestInfo, Request,
Timeout, Priority, TransId, _Source,
#state{prefix = Prefix,
lookup = Lookup,
content_types = ContentTypes,
content_disposition = ContentDisposition,
debug_level = DebugLevel,
api_state = StateAPI} = State,
Dispatcher) ->
Suffix = cloudi_service_name:suffix(Prefix, Pattern),
#api{method = Method,
path = Path,
parameters = Parameters,
format = Format,
handler_f = Handler,
arity = Arity} = cloudi_x_trie:fetch(Suffix, Lookup),
ParametersL = if
Parameters =:= true ->
cloudi_service_name:parse(Name, Pattern);
Parameters =:= false ->
[]
end,
if
DebugLevel =:= off ->
ok;
RequestInfo /= <<>> ->
?LOG(DebugLevel,
"request ~p ~p",
[Name, {RequestInfo, Request}]);
true ->
?LOG(DebugLevel,
"request ~p ~p",
[Name, Request])
end,
true = is_list(ParametersL),
ReturnAPI = if
Arity == 11 ->
Handler(Method, Path, ParametersL, Format, RequestInfo, Request,
Timeout, Priority, TransId, StateAPI, Dispatcher)
end,
case ReturnAPI of
{reply, Response, NewStateAPI} ->
ResponseInfo = response_info_headers([], Name, Format,
ContentTypes,
ContentDisposition),
?LOG(DebugLevel,
"response ~p ~p",
[Name, {ResponseInfo, Response}]),
{reply, ResponseInfo, Response,
State#state{api_state = NewStateAPI}};
{reply, ResponseInfo, Response, NewStateAPI} ->
NewResponseInfo = response_info_headers(ResponseInfo, Name, Format,
ContentTypes,
ContentDisposition),
?LOG(DebugLevel,
"response ~p ~p",
[Name, {NewResponseInfo, Response}]),
{reply, NewResponseInfo, Response,
State#state{api_state = NewStateAPI}};
{forward, NextName, NextRequestInfo, NextRequest, NewStateAPI} ->
?LOG(DebugLevel,
"forward ~p to ~p ~p",
[Name, NextName, {NextRequestInfo, NextRequest}]),
{forward, NextName, NextRequestInfo, NextRequest,
State#state{api_state = NewStateAPI}};
{forward, NextName, NextRequestInfo, NextRequest,
NextTimeout, NextPriority, NewStateAPI} ->
?LOG(DebugLevel,
"forward ~p to ~p ~p",
[Name, NextName, {NextRequestInfo, NextRequest}]),
{forward, NextName, NextRequestInfo, NextRequest,
NextTimeout, NextPriority,
State#state{api_state = NewStateAPI}};
{noreply, NewStateAPI} ->
{noreply, State#state{api_state = NewStateAPI}};
{stop, Reason, NewStateAPI} ->
{stop, Reason, State#state{api_state = NewStateAPI}}
end.
cloudi_service_handle_info(Request,
#state{info_f = InfoF,
api_state = StateAPI} = State,
Dispatcher) ->
if
InfoF =:= undefined ->
?LOG_WARN("Unknown info \"~w\"", [Request]),
{noreply, State};
true ->
case InfoF(Request, StateAPI, Dispatcher) of
{noreply, NewStateAPI} ->
{noreply, State#state{api_state = NewStateAPI}};
{stop, Reason, NewStateAPI} ->
{stop, Reason, State#state{api_state = NewStateAPI}}
end
end.
cloudi_service_terminate(_Reason, _Timeout, undefined) ->
ok;
cloudi_service_terminate(Reason, Timeout,
#state{terminate_f = TerminateF,
api_state = StateAPI}) ->
if
TerminateF =:= undefined ->
ok;
true ->
(catch TerminateF(Reason, Timeout, StateAPI))
end,
ok.
%%%------------------------------------------------------------------------
%%% Private functions
%%%------------------------------------------------------------------------
subscribe_path([], _, _, _, Lookup, _) ->
Lookup;
subscribe_path([Format | Formats], Path, MethodSuffix, API,
Lookup, Dispatcher) ->
Suffix = Path ++ "." ++ Format ++ MethodSuffix,
ok = cloudi_service:subscribe(Dispatcher, Suffix),
NewAPI = API#api{format = erlang:list_to_atom(Format)},
NewLookup = cloudi_x_trie:store(Suffix, NewAPI, Lookup),
subscribe_path(Formats, Path, MethodSuffix, API,
NewLookup, Dispatcher).
subscribe_paths('GET', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/get", API, Lookup, Dispatcher);
subscribe_paths('POST', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/post", API, Lookup, Dispatcher);
subscribe_paths('PUT', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/put", API, Lookup, Dispatcher);
subscribe_paths('DELETE', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/delete", API, Lookup, Dispatcher);
subscribe_paths('HEAD', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/head", API, Lookup, Dispatcher);
subscribe_paths('OPTIONS', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/options", API, Lookup, Dispatcher);
subscribe_paths('PATCH', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/patch", API, Lookup, Dispatcher);
subscribe_paths('TRACE', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/trace", API, Lookup, Dispatcher);
subscribe_paths('CONNECT', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/connect", API, Lookup, Dispatcher);
subscribe_paths(Method, Path, Formats, API, Lookup, Dispatcher)
when is_list(Method) ->
MethodSuffix = [$/ | cloudi_string:lowercase(Method)],
subscribe_path(Formats, Path, MethodSuffix, API, Lookup, Dispatcher).
response_info_headers(ResponseInfo0, Name, Format,
ContentTypes, ContentDisposition)
when is_list(ResponseInfo0) ->
{AttachmentGuess, ContentType} = maps:get(Format, ContentTypes),
ResponseInfo1 = if
(ContentDisposition =:= true) andalso
(AttachmentGuess =:= attachment) ->
case lists:keyfind(<<"content-disposition">>, 1,
ResponseInfo0) of
false ->
FilePath = cloudi_string:beforer($/, Name),
ContentDispositionValue = erlang:iolist_to_binary(
["attachment; filename=\"",
filename:basename(FilePath), "\""]),
[{<<"content-disposition">>,
ContentDispositionValue} | ResponseInfo0];
{_, _} ->
ResponseInfo0
end;
true ->
ResponseInfo0
end,
ResponseInfoN = case lists:keyfind(<<"content-type">>, 1,
ResponseInfo0) of
false ->
[{<<"content-type">>, ContentType} | ResponseInfo1];
{_, _} ->
ResponseInfo1
end,
ResponseInfoN;
response_info_headers(ResponseInfo, _, _, _, _) ->
ResponseInfo.
| null | https://raw.githubusercontent.com/CloudI/CloudI/ec951deffbedcce823b16f82cef89e768f2ac07c/src/lib/cloudi_service_http_rest/src/cloudi_service_http_rest.erl | erlang |
------------------------------------------------------------------------
@doc
==CloudI HTTP REST Integration==
arguments.
@end
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
the rights to use, copy, modify, merge, publish, distribute, sublicense,
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
@version 1.8.0 {@date} {@time}
------------------------------------------------------------------------
see below:
If necessary, provide an initialization function to be called
for initializing REST handler state data. The initialize
function can be specified as an anonymous function or a
{module(), FunctionName :: atom()} tuple.
see below:
If necessary, provide a terminate function to be called
for terminating the REST handler's state data. The terminate
function can be specified as an anonymous function or a
{module(), FunctionName :: atom()} tuple.
see below:
Provide a list of handler functions to be used with the
service name prefix. Each handler function entry in the list
takes the form:
{Method :: atom() | string(), Path :: string(), handler()}
(e.g., Method == 'GET', Path == "index.html")
The handler function can be specified as an anonymous function or a
{module(), FunctionName :: atom()} tuple.
see below:
If necessary, provide an info function to be called
function can be specified as an anonymous function or a
{module(), FunctionName :: atom()} tuple.
see below:
Provide a list of formats to handle that are added as file type
suffixes on the URL path which also determine the content-type used
for the request and response.
Set the content-disposition header value for any content-type values
that are tagged as an attachment.
Provide default handling of the OPTIONS method based on the
configured handlers.
configured handlers.
log output for debugging
------------------------------------------------------------------------
External interface functions
------------------------------------------------------------------------
------------------------------------------------------------------------
------------------------------------------------------------------------
content-type is set automatically by HTTP process
------------------------------------------------------------------------
Private functions
------------------------------------------------------------------------ | -*-Mode : erlang;coding : utf-8;tab - width:4;c - basic - offset:4;indent - tabs - mode:()-*-
ex : set utf-8 sts=4 ts=4 sw=4 et nomod :
Provide an easy way of connecting CloudI service requests to
Erlang function calls for a HTTP REST API , with service configuration
MIT License
Copyright ( c ) 2015 - 2019 < mjtruog at protonmail dot com >
to deal in the Software without restriction , including without limitation
and/or sell copies of the Software , and to permit persons to whom the
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING
@author < mjtruog at protonmail dot com >
2015 - 2019
-module(cloudi_service_http_rest).
-author('mjtruog at protonmail dot com').
-behaviour(cloudi_service).
cloudi_service callbacks
-export([cloudi_service_init/4,
cloudi_service_handle_request/11,
cloudi_service_handle_info/3,
cloudi_service_terminate/3]).
-include_lib("cloudi_core/include/cloudi_logger.hrl").
for Erlang messages received by the process . The info
-define(DEFAULT_SET_CONTENT_DISPOSITION, false).
-define(DEFAULT_USE_OPTIONS_METHOD, false).
-define(DEFAULT_USE_TRACE_METHOD, false).
Provide default handling of the TRACE method based on the
-define(DEFAULT_DEBUG_LEVEL, trace).
-type method() :: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'HEAD' | 'OPTIONS' |
'PATCH' | 'TRACE' | 'CONNECT'.
-type initialize_f() :: fun((Args :: list(),
Timeout :: cloudi_service_api:
timeout_initialize_value_milliseconds(),
Dispatcher :: cloudi:dispatcher()) ->
{ok, State :: any()} |
{stop, Reason :: any()} |
{stop, Reason :: any(), State :: any()}).
-type handler_f_11() :: fun((Method :: method(),
Path :: cloudi:service_name_pattern(),
Parameters :: list(string()),
Format :: atom(),
RequestInfo :: any(),
Request :: any(),
Timeout :: cloudi:timeout_value_milliseconds(),
Priority :: cloudi:priority_value(),
TransId :: cloudi:trans_id(),
State :: any(),
Dispatcher :: cloudi:dispatcher()) ->
{reply, Response :: any(), NewState :: any()} |
{reply, ResponseInfo :: any(), Response :: any(), NewState :: any()} |
{forward, NextName :: cloudi:service_name(),
NextRequestInfo :: any(), NextRequest :: any(), NewState :: any()} |
{forward, NextName :: cloudi:service_name(),
NextRequestInfo :: any(), NextRequest :: any(),
NextTimeout :: cloudi:timeout_value_milliseconds(),
NextPriority :: cloudi:priority_value(), NewState :: any()} |
{noreply, NewState :: any()} |
{stop, Reason :: any(), NewState :: any()}).
-type info_f() :: fun((Request :: any(),
State :: any(),
Dispatcher :: cloudi:dispatcher()) ->
{noreply, NewState :: any()} |
{stop, Reason :: any(), NewState :: any()}).
-type terminate_f() :: fun((Reason :: any(),
Timeout :: cloudi_service_api:
timeout_terminate_value_milliseconds(),
State :: any()) ->
ok).
-export_type([method/0,
initialize_f/0,
handler_f_11/0,
info_f/0,
terminate_f/0]).
-record(api,
{
method :: method(),
path :: cloudi:service_name_pattern(),
parameters :: boolean(),
format :: atom(),
handler_f :: handler_f_11(),
arity :: 11
}).
-record(state,
{
prefix :: cloudi:service_name_pattern(),
lookup :: cloudi_x_trie:cloudi_x_trie(),
info_f :: info_f() | undefined,
terminate_f :: terminate_f() | undefined,
content_types :: #{atom() := {request | attachment, binary()}},
content_disposition :: boolean(),
debug_level :: off | trace | debug | info | warn | error | fatal,
api_state :: any()
}).
Callback functions from cloudi_service
cloudi_service_init(Args, Prefix, Timeout, Dispatcher) ->
Defaults = [
{initialize, ?DEFAULT_INITIALIZE},
{terminate, ?DEFAULT_TERMINATE},
{handlers, ?DEFAULT_HANDLERS},
{info, ?DEFAULT_INFO},
{formats, ?DEFAULT_FORMATS},
{set_content_disposition, ?DEFAULT_SET_CONTENT_DISPOSITION},
{use_options_method, ?DEFAULT_USE_OPTIONS_METHOD},
{use_trace_method, ?DEFAULT_USE_TRACE_METHOD},
{debug, ?DEFAULT_DEBUG},
{debug_level, ?DEFAULT_DEBUG_LEVEL}],
[Initialize, Terminate0, Handlers0, Info0, Formats0,
SetContentDisposition, UseOptionsMethod, UseTraceMethod,
Debug, DebugLevel | ArgsAPI] =
cloudi_proplists:take_values(Defaults, Args),
TerminateN = cloudi_args_type:function_optional(Terminate0, 3),
true = is_list(Handlers0),
lists:foreach(fun({Method, Path, _}) ->
MethodString = if
is_atom(Method) ->
erlang:atom_to_list(Method);
is_list(Method), is_integer(hd(Method)) ->
Method
end,
MethodString = cloudi_string:uppercase(MethodString),
true = is_list(Path) andalso is_integer(hd(Path))
end, Handlers0),
InfoN = cloudi_args_type:function_optional(Info0, 3),
true = is_list(Formats0),
true = is_boolean(SetContentDisposition),
true = is_boolean(UseOptionsMethod),
true = is_boolean(UseTraceMethod),
true = is_boolean(Debug),
true = ((DebugLevel =:= trace) orelse
(DebugLevel =:= debug) orelse
(DebugLevel =:= info) orelse
(DebugLevel =:= warn) orelse
(DebugLevel =:= error) orelse
(DebugLevel =:= fatal)),
DebugLogLevel = if
Debug =:= false ->
off;
Debug =:= true ->
DebugLevel
end,
ContentTypes = cloudi_response_info:lookup_content_type(),
FormatsN = lists:map(fun(Format0) ->
FormatN = if
is_list(Format0), is_integer(hd(Format0)) ->
Format0;
is_atom(Format0) ->
erlang:atom_to_list(Format0)
end,
true = cloudi_x_trie:is_key("." ++ FormatN, ContentTypes),
FormatN
end, Formats0),
ContentTypeLookupN = lists:foldl(fun(FormatN, ContentTypeLookup0) ->
maps:put(erlang:list_to_atom(FormatN),
cloudi_x_trie:fetch("." ++ FormatN, ContentTypes),
ContentTypeLookup0)
end, #{}, FormatsN),
MethodListsN = cloudi_x_trie:to_list(lists:foldr(fun({Method, Path, _},
MethodLists0) ->
MethodString = if
is_atom(Method) ->
erlang:atom_to_list(Method);
is_list(Method) ->
Method
end,
cloudi_x_trie:update(Path, fun(MethodList0) ->
lists:umerge(MethodList0, [MethodString])
end, [MethodString], MethodLists0)
end, cloudi_x_trie:new(), Handlers0)),
Handlers1 = if
UseTraceMethod =:= true ->
lists:map(fun({Path, _}) ->
HandlerTrace = fun(_, _, _, _, _, _, _, _, _,
TraceHandlerState, _) ->
{reply,
[{<<"via">>, <<"1.1 CloudI">>}], <<>>, TraceHandlerState}
end,
{'TRACE', Path, HandlerTrace}
end, MethodListsN) ++ Handlers0;
UseTraceMethod =:= false ->
Handlers0
end,
HandlersN = if
UseOptionsMethod =:= true ->
lists:map(fun({Path, MethodList1}) ->
MethodListN = lists:umerge(MethodList1, ["OPTIONS"]),
Methods = erlang:list_to_binary(lists:join(", ", MethodListN)),
HandlerOptions = fun(_, _, _, _, _, _, _, _, _,
OptionsHandlerState, _) ->
{reply,
[{<<"allow">>, Methods}], <<>>, OptionsHandlerState}
end,
{'OPTIONS', Path, HandlerOptions}
end, MethodListsN) ++ Handlers1;
UseOptionsMethod =:= false ->
Handlers1
end,
LookupN = lists:foldl(fun({Method, Path, Handler0}, Lookup0) ->
{Handler1,
Arity} = cloudi_args_type:function_required_pick(Handler0, [11]),
HandlerMethod = if
is_atom(Method) ->
Method;
is_list(Method) ->
erlang:list_to_atom(Method)
end,
API = #api{method = HandlerMethod,
path = Path,
parameters = cloudi_service_name:pattern(Prefix ++ Path),
handler_f = Handler1,
arity = Arity},
subscribe_paths(Method, Path, FormatsN, API, Lookup0, Dispatcher)
end, cloudi_x_trie:new(), HandlersN),
State = #state{prefix = Prefix,
lookup = LookupN,
info_f = InfoN,
terminate_f = TerminateN,
content_types = ContentTypeLookupN,
content_disposition = SetContentDisposition,
debug_level = DebugLogLevel},
ReturnAPI = case cloudi_args_type:function_optional(Initialize, 3) of
undefined ->
true = (ArgsAPI == []),
{ok, undefined};
InitializeFunction ->
InitializeFunction(ArgsAPI, Timeout, Dispatcher)
end,
case ReturnAPI of
{ok, StateAPI} ->
{ok, State#state{api_state = StateAPI}};
{stop, Reason} ->
{stop, Reason, State};
{stop, Reason, StateAPI} ->
{stop, Reason, State#state{api_state = StateAPI}}
end.
cloudi_service_handle_request(_RequestType, Name, Pattern, RequestInfo, Request,
Timeout, Priority, TransId, _Source,
#state{prefix = Prefix,
lookup = Lookup,
content_types = ContentTypes,
content_disposition = ContentDisposition,
debug_level = DebugLevel,
api_state = StateAPI} = State,
Dispatcher) ->
Suffix = cloudi_service_name:suffix(Prefix, Pattern),
#api{method = Method,
path = Path,
parameters = Parameters,
format = Format,
handler_f = Handler,
arity = Arity} = cloudi_x_trie:fetch(Suffix, Lookup),
ParametersL = if
Parameters =:= true ->
cloudi_service_name:parse(Name, Pattern);
Parameters =:= false ->
[]
end,
if
DebugLevel =:= off ->
ok;
RequestInfo /= <<>> ->
?LOG(DebugLevel,
"request ~p ~p",
[Name, {RequestInfo, Request}]);
true ->
?LOG(DebugLevel,
"request ~p ~p",
[Name, Request])
end,
true = is_list(ParametersL),
ReturnAPI = if
Arity == 11 ->
Handler(Method, Path, ParametersL, Format, RequestInfo, Request,
Timeout, Priority, TransId, StateAPI, Dispatcher)
end,
case ReturnAPI of
{reply, Response, NewStateAPI} ->
ResponseInfo = response_info_headers([], Name, Format,
ContentTypes,
ContentDisposition),
?LOG(DebugLevel,
"response ~p ~p",
[Name, {ResponseInfo, Response}]),
{reply, ResponseInfo, Response,
State#state{api_state = NewStateAPI}};
{reply, ResponseInfo, Response, NewStateAPI} ->
NewResponseInfo = response_info_headers(ResponseInfo, Name, Format,
ContentTypes,
ContentDisposition),
?LOG(DebugLevel,
"response ~p ~p",
[Name, {NewResponseInfo, Response}]),
{reply, NewResponseInfo, Response,
State#state{api_state = NewStateAPI}};
{forward, NextName, NextRequestInfo, NextRequest, NewStateAPI} ->
?LOG(DebugLevel,
"forward ~p to ~p ~p",
[Name, NextName, {NextRequestInfo, NextRequest}]),
{forward, NextName, NextRequestInfo, NextRequest,
State#state{api_state = NewStateAPI}};
{forward, NextName, NextRequestInfo, NextRequest,
NextTimeout, NextPriority, NewStateAPI} ->
?LOG(DebugLevel,
"forward ~p to ~p ~p",
[Name, NextName, {NextRequestInfo, NextRequest}]),
{forward, NextName, NextRequestInfo, NextRequest,
NextTimeout, NextPriority,
State#state{api_state = NewStateAPI}};
{noreply, NewStateAPI} ->
{noreply, State#state{api_state = NewStateAPI}};
{stop, Reason, NewStateAPI} ->
{stop, Reason, State#state{api_state = NewStateAPI}}
end.
cloudi_service_handle_info(Request,
#state{info_f = InfoF,
api_state = StateAPI} = State,
Dispatcher) ->
if
InfoF =:= undefined ->
?LOG_WARN("Unknown info \"~w\"", [Request]),
{noreply, State};
true ->
case InfoF(Request, StateAPI, Dispatcher) of
{noreply, NewStateAPI} ->
{noreply, State#state{api_state = NewStateAPI}};
{stop, Reason, NewStateAPI} ->
{stop, Reason, State#state{api_state = NewStateAPI}}
end
end.
cloudi_service_terminate(_Reason, _Timeout, undefined) ->
ok;
cloudi_service_terminate(Reason, Timeout,
#state{terminate_f = TerminateF,
api_state = StateAPI}) ->
if
TerminateF =:= undefined ->
ok;
true ->
(catch TerminateF(Reason, Timeout, StateAPI))
end,
ok.
subscribe_path([], _, _, _, Lookup, _) ->
Lookup;
subscribe_path([Format | Formats], Path, MethodSuffix, API,
Lookup, Dispatcher) ->
Suffix = Path ++ "." ++ Format ++ MethodSuffix,
ok = cloudi_service:subscribe(Dispatcher, Suffix),
NewAPI = API#api{format = erlang:list_to_atom(Format)},
NewLookup = cloudi_x_trie:store(Suffix, NewAPI, Lookup),
subscribe_path(Formats, Path, MethodSuffix, API,
NewLookup, Dispatcher).
subscribe_paths('GET', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/get", API, Lookup, Dispatcher);
subscribe_paths('POST', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/post", API, Lookup, Dispatcher);
subscribe_paths('PUT', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/put", API, Lookup, Dispatcher);
subscribe_paths('DELETE', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/delete", API, Lookup, Dispatcher);
subscribe_paths('HEAD', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/head", API, Lookup, Dispatcher);
subscribe_paths('OPTIONS', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/options", API, Lookup, Dispatcher);
subscribe_paths('PATCH', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/patch", API, Lookup, Dispatcher);
subscribe_paths('TRACE', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/trace", API, Lookup, Dispatcher);
subscribe_paths('CONNECT', Path, Formats, API, Lookup, Dispatcher) ->
subscribe_path(Formats, Path, "/connect", API, Lookup, Dispatcher);
subscribe_paths(Method, Path, Formats, API, Lookup, Dispatcher)
when is_list(Method) ->
MethodSuffix = [$/ | cloudi_string:lowercase(Method)],
subscribe_path(Formats, Path, MethodSuffix, API, Lookup, Dispatcher).
response_info_headers(ResponseInfo0, Name, Format,
ContentTypes, ContentDisposition)
when is_list(ResponseInfo0) ->
{AttachmentGuess, ContentType} = maps:get(Format, ContentTypes),
ResponseInfo1 = if
(ContentDisposition =:= true) andalso
(AttachmentGuess =:= attachment) ->
case lists:keyfind(<<"content-disposition">>, 1,
ResponseInfo0) of
false ->
FilePath = cloudi_string:beforer($/, Name),
ContentDispositionValue = erlang:iolist_to_binary(
["attachment; filename=\"",
filename:basename(FilePath), "\""]),
[{<<"content-disposition">>,
ContentDispositionValue} | ResponseInfo0];
{_, _} ->
ResponseInfo0
end;
true ->
ResponseInfo0
end,
ResponseInfoN = case lists:keyfind(<<"content-type">>, 1,
ResponseInfo0) of
false ->
[{<<"content-type">>, ContentType} | ResponseInfo1];
{_, _} ->
ResponseInfo1
end,
ResponseInfoN;
response_info_headers(ResponseInfo, _, _, _, _) ->
ResponseInfo.
|
b7483cc544e7c529466533c39d39f4e74ad7eb88a08a23b30c44deb949560a8d | IGJoshua/glfw-clj | core_test.clj | (ns glfw-clj.core-test
(:require [clojure.test :as t]
[glfw-clj.core :as sut]))
(t/deftest a-test
(t/testing "FIXME, I fail."
(t/is (= 0 1))))
| null | https://raw.githubusercontent.com/IGJoshua/glfw-clj/9cfb2830924f752bad5031f1b8895ee6fba0d6cb/test/glfw_clj/core_test.clj | clojure | (ns glfw-clj.core-test
(:require [clojure.test :as t]
[glfw-clj.core :as sut]))
(t/deftest a-test
(t/testing "FIXME, I fail."
(t/is (= 0 1))))
|
|
e637313c44c61e7346774fa32b5cfaa34a21469f642762b6eca40241c6d2a2a7 | target/theta-idl | Versions.hs | {-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
| This module specifies which versions of the Theta protocol are
supported by this version of the package ( library and
-- executables).
--
-- Each release of the package can support a range of versions. Theta
-- modules specify the versions needed to work with the module in the
-- module metadata; any module whose versions are not supported by
-- this release will fail with a graceful error message.
module Theta.Versions where
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Version as Cabal
import Test.QuickCheck (Arbitrary (arbitrary))
import qualified Test.QuickCheck as QuickCheck
import Theta.Metadata (Version)
-- * Language Versions
-- | A version range with an /inclusive/ lower bound and an
-- /exclusive/ upper bound.
--
-- @
-- Range { lower = "1.0.0", upper = "1.1.0" }
-- @
--
-- represents
--
-- @
-- version >= "1.0.0" && version < "1.1.0"
-- @
data Range = Range
{ lower :: Version
-- ^ The /inclusive/ lower bound.
, upper :: Version
-- ^ The /exclusive/ upper bound.
, name :: Text
-- ^ A human-readable description of what this version represents
-- (ie "language-version" vs "avro-version").
} deriving (Show, Eq, Ord)
instance Arbitrary Range where
arbitrary = Range <$> arbitrary <*> arbitrary <*> name
where name = QuickCheck.elements ["avro-version", "theta-version"]
-- | Check whether a version is within the specified 'Range'.
inRange :: Range -> Version -> Bool
inRange Range { lower, upper } version = version >= lower && version < upper
| Is the given version of the Theta language supported by this
-- version of the package?
--
Specified as @language - version@ in the header of every Theta
-- module.
theta :: Range
theta = Range { name = "theta-version", lower = "1.0.0", upper = "1.2.0" }
| Is the given version of the Theta Avro encoding supported by this
-- version of the package?
--
Specified as - version@ in the header of every Theta module .
avro :: Range
avro = Range { name = "avro-version", lower = "1.0.0", upper = "1.2.0" }
-- * Package Version
Having the @theta@ library component depend on @Paths_theta@ caused
unnecessary rebuilds with Stack ( see GitHub issue[1 ] ) . To fix this ,
-- we hardcode the packageVersion in this module, then have a unit
-- test that checks that it is up to date with the version in
-- @Paths_theta@.
--
[ 1 ] : -idl/issues/37
| Which version of the Theta package this is .
packageVersion :: Cabal.Version
packageVersion = Cabal.makeVersion [1, 0, 0, 2]
| Which version of the Theta package this is as ' Text ' .
packageVersion' :: Text
packageVersion' = Text.pack $ Cabal.showVersion packageVersion
| null | https://raw.githubusercontent.com/target/theta-idl/2bda6a8836817f8d782c2165d7f250fe296b97c2/theta/src/Theta/Versions.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings #
executables).
Each release of the package can support a range of versions. Theta
modules specify the versions needed to work with the module in the
module metadata; any module whose versions are not supported by
this release will fail with a graceful error message.
* Language Versions
| A version range with an /inclusive/ lower bound and an
/exclusive/ upper bound.
@
Range { lower = "1.0.0", upper = "1.1.0" }
@
represents
@
version >= "1.0.0" && version < "1.1.0"
@
^ The /inclusive/ lower bound.
^ The /exclusive/ upper bound.
^ A human-readable description of what this version represents
(ie "language-version" vs "avro-version").
| Check whether a version is within the specified 'Range'.
version of the package?
module.
version of the package?
* Package Version
we hardcode the packageVersion in this module, then have a unit
test that checks that it is up to date with the version in
@Paths_theta@.
|
| This module specifies which versions of the Theta protocol are
supported by this version of the package ( library and
module Theta.Versions where
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Version as Cabal
import Test.QuickCheck (Arbitrary (arbitrary))
import qualified Test.QuickCheck as QuickCheck
import Theta.Metadata (Version)
data Range = Range
{ lower :: Version
, upper :: Version
, name :: Text
} deriving (Show, Eq, Ord)
instance Arbitrary Range where
arbitrary = Range <$> arbitrary <*> arbitrary <*> name
where name = QuickCheck.elements ["avro-version", "theta-version"]
inRange :: Range -> Version -> Bool
inRange Range { lower, upper } version = version >= lower && version < upper
| Is the given version of the Theta language supported by this
Specified as @language - version@ in the header of every Theta
theta :: Range
theta = Range { name = "theta-version", lower = "1.0.0", upper = "1.2.0" }
| Is the given version of the Theta Avro encoding supported by this
Specified as - version@ in the header of every Theta module .
avro :: Range
avro = Range { name = "avro-version", lower = "1.0.0", upper = "1.2.0" }
Having the @theta@ library component depend on @Paths_theta@ caused
unnecessary rebuilds with Stack ( see GitHub issue[1 ] ) . To fix this ,
[ 1 ] : -idl/issues/37
| Which version of the Theta package this is .
packageVersion :: Cabal.Version
packageVersion = Cabal.makeVersion [1, 0, 0, 2]
| Which version of the Theta package this is as ' Text ' .
packageVersion' :: Text
packageVersion' = Text.pack $ Cabal.showVersion packageVersion
|
3e4622d419455786099abe715ed6dc1e19b56c24fc11e11aa7be0b17c9a61f66 | wyager/metastrip | Main.hs | module Main (main) where
import qualified Options.Applicative as OA
import Control.Applicative (some, (<|>), (<**>))
import qualified Codec.Picture as Pic
import Lib(Aggressiveness(Normal,High),fastRandom,clean')
import Crypto.Random (getRandomBytes)
import qualified Data.ByteArray.Encoding as BE
import qualified Data.ByteString.Char8 as B8
import qualified GHC.Conc as Conc
import Control.Concurrent.Async (forConcurrently_)
import Data.Pool (createPool, withResource)
import qualified System.FilePath.Posix as Path
import Data.Char (toUpper)
-- How to name the output files
data Naming = Random | SameName | BeforeExtension String deriving Show
-- Where to put them
data Directory = Same | Different FilePath deriving Show
-- How much to randomize the pixels
data Randomization = NoRandomization | RandomizeWith Aggressiveness deriving Show
-- How many threads to do it on
data NumThreads = AutoSelectNumThreads | SpecifiedNumThreads Int deriving Show
data Command
= Clean Naming Directory Randomization Int NumThreads [FilePath]
deriving Show
command :: OA.Parser Command
command = Clean <$> naming <*> directory <*> randomization <*> jpegSaveQuality <*> numThreads <*> filepaths
where
filepaths = some $ OA.argument OA.str $ OA.metavar "FILES..."
jpegSaveQuality = OA.option OA.auto
(OA.long "jpeg-quality"
<> OA.short 'j'
<> OA.help "JPEG save quality (1-100)"
<> OA.showDefault
<> OA.value 50)
directory = OA.option (OA.maybeReader $ Just . Different)
(OA.long "output-dir"
<> OA.short 'o'
<> OA.help "Output directory (default: Same directory)"
<> OA.value Same
<> OA.metavar "DIR")
numThreads = specifiedNumThreads <|> pure AutoSelectNumThreads
where specifiedNumThreads = SpecifiedNumThreads <$> OA.option OA.auto
(OA.long "num-threads"
<> OA.short 'n'
<> OA.help "Specify number of threads (default: # of cores available)"
<> OA.metavar "INT")
randomization = highAggressiveness <|> none <|> defaultAggressiveness
where
highAggressiveness = OA.flag' (RandomizeWith High) $
OA.long "aggressive"
<> OA.short 'a'
<> OA.help "Aggressively randomize pixel values (default: Slight randomization)"
none = OA.flag' NoRandomization $
OA.long "dont-randomize"
<> OA.short 'd'
<> OA.help "Do not randomize pixel values at all"
defaultAggressiveness = pure (RandomizeWith Normal)
naming = random <|> inPlace <|> beforeExtension
where
random = OA.flag' Random (OA.long "random-name"
<> OA.short 'r'
<> OA.help "Write output files with a random name")
inPlace = OA.flag' SameName (OA.long "same-name"
<> OA.short 's'
<> OA.help "Write output files with the same name as the input files, overwriting if necessary")
beforeExtension = BeforeExtension <$> OA.strOption
(OA.long "before-extension"
<> OA.short 'b'
<> OA.metavar "PREFIX"
<> OA.value "scrubbed"
<> OA.showDefault
<> OA.help "Output a scrubbed copy of a.jpg at a.PREFIX.jpg")
getCommand :: IO Command
getCommand = OA.customExecParser
(OA.prefs (OA.showHelpOnError <> OA.showHelpOnEmpty))
(OA.info (command <**> OA.helper) OA.fullDesc)
cleanFile :: Naming -> Directory -> Randomization -> Int -> FilePath -> IO (Either String ())
cleanFile naming directory rand jpegQuality path = case map toUpper ext of
".PNG" -> go Pic.savePngImage
".JPG" -> go (Pic.saveJpgImage jpegQuality)
".JPEG" -> go (Pic.saveJpgImage jpegQuality)
".BMP" -> go Pic.saveBmpImage
".TIFF" -> go Pic.saveTiffImage
_ -> return $ Left $ "Unsupported extension " ++ ext ++ " for file " ++ path
where
ext = Path.takeExtension path
basename = Path.takeBaseName path
directoryPath = case directory of
Same -> Path.takeDirectory path
Different dir -> dir
outPath = case naming of
SameName -> return (directoryPath Path.</> basename ++ ext)
BeforeExtension str -> return $ directoryPath Path.</> basename ++ ('.':str) ++ ext
Random -> do
randomBytes :: B8.ByteString <- getRandomBytes 4
let filename = B8.unpack $ BE.convertToBase BE.Base32 randomBytes
return (directoryPath Path.</> filename ++ ext)
go formatter =
Pic.readImage path >>= \case
Left err -> return (Left $ "Error with image " ++ path ++ ": " ++ err)
Right image -> Right <$> do
image' <- case rand of
NoRandomization -> return image
RandomizeWith aggr -> fastRandom $ clean' aggr image
thePath <- outPath
formatter thePath image'
main :: IO ()
main = do
Clean naming dir rand jpegQuality numThreads paths <- getCommand
numProcessors <- Conc.getNumProcessors
Conc.setNumCapabilities numProcessors
let numThreads' = case numThreads of
AutoSelectNumThreads -> numProcessors
SpecifiedNumThreads n -> n
threadPool <- createPool (return ()) (const $ return ()) 1 1.0 numThreads'
forConcurrently_ paths $ \path ->
withResource threadPool $ \() -> do
result <- cleanFile naming dir rand jpegQuality path
either print return result
| null | https://raw.githubusercontent.com/wyager/metastrip/9b8236ea5c7305512d55a17c89e94582a5969374/app/Main.hs | haskell | How to name the output files
Where to put them
How much to randomize the pixels
How many threads to do it on | module Main (main) where
import qualified Options.Applicative as OA
import Control.Applicative (some, (<|>), (<**>))
import qualified Codec.Picture as Pic
import Lib(Aggressiveness(Normal,High),fastRandom,clean')
import Crypto.Random (getRandomBytes)
import qualified Data.ByteArray.Encoding as BE
import qualified Data.ByteString.Char8 as B8
import qualified GHC.Conc as Conc
import Control.Concurrent.Async (forConcurrently_)
import Data.Pool (createPool, withResource)
import qualified System.FilePath.Posix as Path
import Data.Char (toUpper)
data Naming = Random | SameName | BeforeExtension String deriving Show
data Directory = Same | Different FilePath deriving Show
data Randomization = NoRandomization | RandomizeWith Aggressiveness deriving Show
data NumThreads = AutoSelectNumThreads | SpecifiedNumThreads Int deriving Show
data Command
= Clean Naming Directory Randomization Int NumThreads [FilePath]
deriving Show
command :: OA.Parser Command
command = Clean <$> naming <*> directory <*> randomization <*> jpegSaveQuality <*> numThreads <*> filepaths
where
filepaths = some $ OA.argument OA.str $ OA.metavar "FILES..."
jpegSaveQuality = OA.option OA.auto
(OA.long "jpeg-quality"
<> OA.short 'j'
<> OA.help "JPEG save quality (1-100)"
<> OA.showDefault
<> OA.value 50)
directory = OA.option (OA.maybeReader $ Just . Different)
(OA.long "output-dir"
<> OA.short 'o'
<> OA.help "Output directory (default: Same directory)"
<> OA.value Same
<> OA.metavar "DIR")
numThreads = specifiedNumThreads <|> pure AutoSelectNumThreads
where specifiedNumThreads = SpecifiedNumThreads <$> OA.option OA.auto
(OA.long "num-threads"
<> OA.short 'n'
<> OA.help "Specify number of threads (default: # of cores available)"
<> OA.metavar "INT")
randomization = highAggressiveness <|> none <|> defaultAggressiveness
where
highAggressiveness = OA.flag' (RandomizeWith High) $
OA.long "aggressive"
<> OA.short 'a'
<> OA.help "Aggressively randomize pixel values (default: Slight randomization)"
none = OA.flag' NoRandomization $
OA.long "dont-randomize"
<> OA.short 'd'
<> OA.help "Do not randomize pixel values at all"
defaultAggressiveness = pure (RandomizeWith Normal)
naming = random <|> inPlace <|> beforeExtension
where
random = OA.flag' Random (OA.long "random-name"
<> OA.short 'r'
<> OA.help "Write output files with a random name")
inPlace = OA.flag' SameName (OA.long "same-name"
<> OA.short 's'
<> OA.help "Write output files with the same name as the input files, overwriting if necessary")
beforeExtension = BeforeExtension <$> OA.strOption
(OA.long "before-extension"
<> OA.short 'b'
<> OA.metavar "PREFIX"
<> OA.value "scrubbed"
<> OA.showDefault
<> OA.help "Output a scrubbed copy of a.jpg at a.PREFIX.jpg")
getCommand :: IO Command
getCommand = OA.customExecParser
(OA.prefs (OA.showHelpOnError <> OA.showHelpOnEmpty))
(OA.info (command <**> OA.helper) OA.fullDesc)
cleanFile :: Naming -> Directory -> Randomization -> Int -> FilePath -> IO (Either String ())
cleanFile naming directory rand jpegQuality path = case map toUpper ext of
".PNG" -> go Pic.savePngImage
".JPG" -> go (Pic.saveJpgImage jpegQuality)
".JPEG" -> go (Pic.saveJpgImage jpegQuality)
".BMP" -> go Pic.saveBmpImage
".TIFF" -> go Pic.saveTiffImage
_ -> return $ Left $ "Unsupported extension " ++ ext ++ " for file " ++ path
where
ext = Path.takeExtension path
basename = Path.takeBaseName path
directoryPath = case directory of
Same -> Path.takeDirectory path
Different dir -> dir
outPath = case naming of
SameName -> return (directoryPath Path.</> basename ++ ext)
BeforeExtension str -> return $ directoryPath Path.</> basename ++ ('.':str) ++ ext
Random -> do
randomBytes :: B8.ByteString <- getRandomBytes 4
let filename = B8.unpack $ BE.convertToBase BE.Base32 randomBytes
return (directoryPath Path.</> filename ++ ext)
go formatter =
Pic.readImage path >>= \case
Left err -> return (Left $ "Error with image " ++ path ++ ": " ++ err)
Right image -> Right <$> do
image' <- case rand of
NoRandomization -> return image
RandomizeWith aggr -> fastRandom $ clean' aggr image
thePath <- outPath
formatter thePath image'
main :: IO ()
main = do
Clean naming dir rand jpegQuality numThreads paths <- getCommand
numProcessors <- Conc.getNumProcessors
Conc.setNumCapabilities numProcessors
let numThreads' = case numThreads of
AutoSelectNumThreads -> numProcessors
SpecifiedNumThreads n -> n
threadPool <- createPool (return ()) (const $ return ()) 1 1.0 numThreads'
forConcurrently_ paths $ \path ->
withResource threadPool $ \() -> do
result <- cleanFile naming dir rand jpegQuality path
either print return result
|
ec2c618c2965de04c1162b0b4e8acec8b3295cd05459a2c6d510c9852728f96d | facebook/duckling | Tests.hs | Copyright ( c ) 2016 - present , Facebook , Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.PhoneNumber.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Test.Tasty.HUnit
import Duckling.Dimensions.Types
import Duckling.PhoneNumber.Corpus
import Duckling.PhoneNumber.Types
import Duckling.Testing.Asserts
import Duckling.Testing.Types
import qualified Duckling.PhoneNumber.AR.Tests as AR
import qualified Duckling.PhoneNumber.PT.Tests as PT
tests :: TestTree
tests = testGroup "PhoneNumber Tests"
[ makeCorpusTest [Seal PhoneNumber] corpus
, makeNegativeCorpusTest [Seal PhoneNumber] negativeCorpus
, surroundTests
, PT.tests
, AR.tests
]
surroundTests :: TestTree
surroundTests = testCase "Surround Tests" $
mapM_ (analyzedFirstTest testContext testOptions .
withTargets [Seal PhoneNumber]) xs
where
xs = examples (PhoneNumberValue "06354640807")
[ "hey 06354640807"
, "06354640807 hey"
, "hey 06354640807 hey"
]
++ examples (PhoneNumberValue "18998078030")
[ "a 18998078030 b"
]
| null | https://raw.githubusercontent.com/facebook/duckling/72f45e8e2c7385f41f2f8b1f063e7b5daa6dca94/tests/Duckling/PhoneNumber/Tests.hs | haskell | All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
# LANGUAGE OverloadedStrings # | Copyright ( c ) 2016 - present , Facebook , Inc.
module Duckling.PhoneNumber.Tests
( tests
) where
import Data.String
import Prelude
import Test.Tasty
import Test.Tasty.HUnit
import Duckling.Dimensions.Types
import Duckling.PhoneNumber.Corpus
import Duckling.PhoneNumber.Types
import Duckling.Testing.Asserts
import Duckling.Testing.Types
import qualified Duckling.PhoneNumber.AR.Tests as AR
import qualified Duckling.PhoneNumber.PT.Tests as PT
tests :: TestTree
tests = testGroup "PhoneNumber Tests"
[ makeCorpusTest [Seal PhoneNumber] corpus
, makeNegativeCorpusTest [Seal PhoneNumber] negativeCorpus
, surroundTests
, PT.tests
, AR.tests
]
surroundTests :: TestTree
surroundTests = testCase "Surround Tests" $
mapM_ (analyzedFirstTest testContext testOptions .
withTargets [Seal PhoneNumber]) xs
where
xs = examples (PhoneNumberValue "06354640807")
[ "hey 06354640807"
, "06354640807 hey"
, "hey 06354640807 hey"
]
++ examples (PhoneNumberValue "18998078030")
[ "a 18998078030 b"
]
|
7417f8c827d671217566f83f8fd2235ac8ffe3a1e176f3e9704847b1518526de | f-o-a-m/kepler | Class.hs | # LANGUAGE UndecidableInstances #
module Tendermint.Utils.TxClient.Class
( ClientConfig(..)
, RunTxClient(..)
, HasTxClient(..)
, EmptyTxClient(..)
, defaultClientTxOpts
) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ReaderT, ask)
import qualified Data.ByteArray.Base64String as Base64
import Data.Kind (Type)
import Data.Proxy
import Data.String.Conversions (cs)
import Data.Text (Text)
import Data.Word (Word64)
import GHC.TypeLits (KnownSymbol, symbolVal)
import qualified Network.Tendermint.Client as RPC
import Servant.API ((:<|>) (..), (:>))
import qualified Tendermint.SDK.BaseApp.Transaction as T
import Tendermint.SDK.Codec (HasCodec (..))
import Tendermint.SDK.Types.Address (Address)
import Tendermint.SDK.Types.Message (HasMessageType (..),
TypedMessage (..))
import Tendermint.SDK.Types.Transaction (RawTransaction (..))
import Tendermint.Utils.TxClient.Types
class Monad m => RunTxClient m where
-- | How to make a request.
runTx :: RawTransaction -> m RPC.ResultBroadcastTxCommit
getNonce :: Address -> m Word64
data ClientConfig = ClientConfig
{ clientRPC :: RPC.Config
, clientGetNonce :: Address -> IO Word64
}
instance RunTxClient (ReaderT ClientConfig IO) where
getNonce addr = do
nonceGetter <- clientGetNonce <$> ask
liftIO $ nonceGetter addr
runTx tx = do
let txReq = RPC.broadcastTxCommit . RPC.RequestBroadcastTxCommit . Base64.fromBytes . encode $ tx
rpc <- clientRPC <$> ask
liftIO . RPC.runTendermintM rpc $ txReq
data ClientTxOpts = ClientTxOpts
{ clientTxOptsRoute :: Text
, clientTxOptsNonce :: Word64
}
defaultClientTxOpts :: ClientTxOpts
defaultClientTxOpts = ClientTxOpts "" 0
class HasTxClient m layoutC layoutD where
type ClientT (m :: Type -> Type) layoutC layoutD :: Type
genClientT :: Proxy m -> Proxy layoutC -> Proxy layoutD -> ClientTxOpts -> ClientT m layoutC layoutD
instance (HasTxClient m a c, HasTxClient m b d) => HasTxClient m (a :<|> b) (c :<|> d) where
type ClientT m (a :<|> b) (c :<|> d) = ClientT m a c :<|> ClientT m b d
genClientT pm _ _ opts = genClientT pm (Proxy @a) (Proxy @c) opts :<|>
genClientT pm (Proxy @b) (Proxy @d) opts
instance (KnownSymbol path, HasTxClient m a b) => HasTxClient m (path :> a) (path :> b) where
type ClientT m (path :> a) (path :> b) = ClientT m a b
genClientT pm _ _ clientOpts =
let clientOpts' = clientOpts { clientTxOptsRoute = cs $ symbolVal (Proxy @path) }
in genClientT pm (Proxy @a) (Proxy @b) clientOpts'
makeRawTxForSigning
:: forall msg.
HasMessageType msg
=> HasCodec msg
=> ClientTxOpts
-> TxOpts
-> msg
-> RawTransaction
makeRawTxForSigning ClientTxOpts{..} TxOpts{..} msg =
RawTransaction
{ rawTransactionData = TypedMessage (encode msg) (messageType $ Proxy @msg)
, rawTransactionGas = txOptsGas
, rawTransactionNonce = clientTxOptsNonce
, rawTransactionRoute = clientTxOptsRoute
, rawTransactionSignature = ""
}
instance ( HasMessageType msg, HasCodec msg
, HasCodec check, HasCodec deliver
, RunTxClient m
) => HasTxClient m (T.TypedMessage msg T.:~> T.Return check) (T.TypedMessage msg T.:~> T.Return deliver) where
type ClientT m (T.TypedMessage msg T.:~> T.Return check) (T.TypedMessage msg T.:~> T.Return deliver) =
TxOpts -> msg -> m (TxClientResponse check deliver)
genClientT _ _ _ clientOpts opts msg = do
let Signer signerAddress signer = txOptsSigner opts
nonce <- getNonce signerAddress
let clientOpts' = clientOpts {clientTxOptsNonce = nonce}
rawTxForSigning = makeRawTxForSigning clientOpts' opts msg
rawTxWithSig = signer rawTxForSigning
txRes <- runTx rawTxWithSig
pure $ parseRPCResponse txRes
-- | Singleton type representing a client for an empty API.
data EmptyTxClient = EmptyTxClient deriving (Eq, Show, Bounded, Enum)
instance HasTxClient m T.EmptyTxServer T.EmptyTxServer where
type ClientT m T.EmptyTxServer T.EmptyTxServer = EmptyTxClient
genClientT _ _ _ _ = EmptyTxClient
| null | https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-test-utils/src/Tendermint/Utils/TxClient/Class.hs | haskell | | How to make a request.
| Singleton type representing a client for an empty API. | # LANGUAGE UndecidableInstances #
module Tendermint.Utils.TxClient.Class
( ClientConfig(..)
, RunTxClient(..)
, HasTxClient(..)
, EmptyTxClient(..)
, defaultClientTxOpts
) where
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Reader (ReaderT, ask)
import qualified Data.ByteArray.Base64String as Base64
import Data.Kind (Type)
import Data.Proxy
import Data.String.Conversions (cs)
import Data.Text (Text)
import Data.Word (Word64)
import GHC.TypeLits (KnownSymbol, symbolVal)
import qualified Network.Tendermint.Client as RPC
import Servant.API ((:<|>) (..), (:>))
import qualified Tendermint.SDK.BaseApp.Transaction as T
import Tendermint.SDK.Codec (HasCodec (..))
import Tendermint.SDK.Types.Address (Address)
import Tendermint.SDK.Types.Message (HasMessageType (..),
TypedMessage (..))
import Tendermint.SDK.Types.Transaction (RawTransaction (..))
import Tendermint.Utils.TxClient.Types
class Monad m => RunTxClient m where
runTx :: RawTransaction -> m RPC.ResultBroadcastTxCommit
getNonce :: Address -> m Word64
data ClientConfig = ClientConfig
{ clientRPC :: RPC.Config
, clientGetNonce :: Address -> IO Word64
}
instance RunTxClient (ReaderT ClientConfig IO) where
getNonce addr = do
nonceGetter <- clientGetNonce <$> ask
liftIO $ nonceGetter addr
runTx tx = do
let txReq = RPC.broadcastTxCommit . RPC.RequestBroadcastTxCommit . Base64.fromBytes . encode $ tx
rpc <- clientRPC <$> ask
liftIO . RPC.runTendermintM rpc $ txReq
data ClientTxOpts = ClientTxOpts
{ clientTxOptsRoute :: Text
, clientTxOptsNonce :: Word64
}
defaultClientTxOpts :: ClientTxOpts
defaultClientTxOpts = ClientTxOpts "" 0
class HasTxClient m layoutC layoutD where
type ClientT (m :: Type -> Type) layoutC layoutD :: Type
genClientT :: Proxy m -> Proxy layoutC -> Proxy layoutD -> ClientTxOpts -> ClientT m layoutC layoutD
instance (HasTxClient m a c, HasTxClient m b d) => HasTxClient m (a :<|> b) (c :<|> d) where
type ClientT m (a :<|> b) (c :<|> d) = ClientT m a c :<|> ClientT m b d
genClientT pm _ _ opts = genClientT pm (Proxy @a) (Proxy @c) opts :<|>
genClientT pm (Proxy @b) (Proxy @d) opts
instance (KnownSymbol path, HasTxClient m a b) => HasTxClient m (path :> a) (path :> b) where
type ClientT m (path :> a) (path :> b) = ClientT m a b
genClientT pm _ _ clientOpts =
let clientOpts' = clientOpts { clientTxOptsRoute = cs $ symbolVal (Proxy @path) }
in genClientT pm (Proxy @a) (Proxy @b) clientOpts'
makeRawTxForSigning
:: forall msg.
HasMessageType msg
=> HasCodec msg
=> ClientTxOpts
-> TxOpts
-> msg
-> RawTransaction
makeRawTxForSigning ClientTxOpts{..} TxOpts{..} msg =
RawTransaction
{ rawTransactionData = TypedMessage (encode msg) (messageType $ Proxy @msg)
, rawTransactionGas = txOptsGas
, rawTransactionNonce = clientTxOptsNonce
, rawTransactionRoute = clientTxOptsRoute
, rawTransactionSignature = ""
}
instance ( HasMessageType msg, HasCodec msg
, HasCodec check, HasCodec deliver
, RunTxClient m
) => HasTxClient m (T.TypedMessage msg T.:~> T.Return check) (T.TypedMessage msg T.:~> T.Return deliver) where
type ClientT m (T.TypedMessage msg T.:~> T.Return check) (T.TypedMessage msg T.:~> T.Return deliver) =
TxOpts -> msg -> m (TxClientResponse check deliver)
genClientT _ _ _ clientOpts opts msg = do
let Signer signerAddress signer = txOptsSigner opts
nonce <- getNonce signerAddress
let clientOpts' = clientOpts {clientTxOptsNonce = nonce}
rawTxForSigning = makeRawTxForSigning clientOpts' opts msg
rawTxWithSig = signer rawTxForSigning
txRes <- runTx rawTxWithSig
pure $ parseRPCResponse txRes
data EmptyTxClient = EmptyTxClient deriving (Eq, Show, Bounded, Enum)
instance HasTxClient m T.EmptyTxServer T.EmptyTxServer where
type ClientT m T.EmptyTxServer T.EmptyTxServer = EmptyTxClient
genClientT _ _ _ _ = EmptyTxClient
|
9c8b5e109b9df734252573eca5a7bb9c5c63b75ba060ffc854a2624e5f847299 | cbaggers/skitter | keys.lisp | (in-package skitter.sdl2.keys)
(defun key.id (name/event)
(etypecase name/event
(keyword
(or (position name/event skitter.sdl2::*key-button-names*)
(error "key.id: invalid name ~s" name/event)))
(t (error "key.id: Must be given a keyword name or an instance of the button event.~%Recieved ~s"
name/event))))
(defconstant key.a 4)
(defconstant key.b 5)
(defconstant key.c 6)
(defconstant key.d 7)
(defconstant key.e 8)
(defconstant key.f 9)
(defconstant key.g 10)
(defconstant key.h 11)
(defconstant key.i 12)
(defconstant key.j 13)
(defconstant key.k 14)
(defconstant key.l 15)
(defconstant key.m 16)
(defconstant key.n 17)
(defconstant key.o 18)
(defconstant key.p 19)
(defconstant key.q 20)
(defconstant key.r 21)
(defconstant key.s 22)
(defconstant key.t 23)
(defconstant key.u 24)
(defconstant key.v 25)
(defconstant key.w 26)
(defconstant key.x 27)
(defconstant key.y 28)
(defconstant key.z 29)
(defconstant key.1 30)
(defconstant key.2 31)
(defconstant key.3 32)
(defconstant key.4 33)
(defconstant key.5 34)
(defconstant key.6 35)
(defconstant key.7 36)
(defconstant key.8 37)
(defconstant key.9 38)
(defconstant key.0 39)
(defconstant key.return 40)
(defconstant key.escape 41)
(defconstant key.backspace 42)
(defconstant key.tab 43)
(defconstant key.space 44)
(defconstant key.minus 45)
(defconstant key.equals 46)
(defconstant key.leftbracket 47)
(defconstant key.rightbracket 48)
(defconstant key.backslash 49)
(defconstant key.nonushash 50)
(defconstant key.semicolon 51)
(defconstant key.apostrophe 52)
(defconstant key.grave 53)
(defconstant key.comma 54)
(defconstant key.period 55)
(defconstant key.slash 56)
(defconstant key.capslock 57)
(defconstant key.f1 58)
(defconstant key.f2 59)
(defconstant key.f3 60)
(defconstant key.f4 61)
(defconstant key.f5 62)
(defconstant key.f6 63)
(defconstant key.f7 64)
(defconstant key.f8 65)
(defconstant key.f9 66)
(defconstant key.f10 67)
(defconstant key.f11 68)
(defconstant key.f12 69)
(defconstant key.printscreen 70)
(defconstant key.scrolllock 71)
(defconstant key.pause 72)
(defconstant key.insert 73)
(defconstant key.home 74)
(defconstant key.pageup 75)
(defconstant key.delete 76)
(defconstant key.end 77)
(defconstant key.pagedown 78)
(defconstant key.right 79)
(defconstant key.left 80)
(defconstant key.down 81)
(defconstant key.up 82)
(defconstant key.numlockclear 83)
(defconstant key.kp_divide 84)
(defconstant key.kp_multiply 85)
(defconstant key.kp_minus 86)
(defconstant key.kp_plus 87)
(defconstant key.kp_enter 88)
(defconstant key.kp_1 89)
(defconstant key.kp_2 90)
(defconstant key.kp_3 91)
(defconstant key.kp_4 92)
(defconstant key.kp_5 93)
(defconstant key.kp_6 94)
(defconstant key.kp_7 95)
(defconstant key.kp_8 96)
(defconstant key.kp_9 97)
(defconstant key.kp_0 98)
(defconstant key.kp_period 99)
(defconstant key.nonusbackslash 100)
(defconstant key.application 101)
(defconstant key.power 102)
(defconstant key.kp_equals 103)
(defconstant key.f13 104)
(defconstant key.f14 105)
(defconstant key.f15 106)
(defconstant key.f16 107)
(defconstant key.f17 108)
(defconstant key.f18 109)
(defconstant key.f19 110)
(defconstant key.f20 111)
(defconstant key.f21 112)
(defconstant key.f22 113)
(defconstant key.f23 114)
(defconstant key.f24 115)
(defconstant key.execute 116)
(defconstant key.help 117)
(defconstant key.menu 118)
(defconstant key.select 119)
(defconstant key.stop 120)
(defconstant key.again 121)
(defconstant key.undo 122)
(defconstant key.cut 123)
(defconstant key.copy 124)
(defconstant key.paste 125)
(defconstant key.find 126)
(defconstant key.mute 127)
(defconstant key.volumeup 128)
(defconstant key.volumedown 129)
(defconstant key.lockingcapslock 130)
(defconstant key.lockingnumlock 131)
(defconstant key.lockingscrolllock 132)
(defconstant key.kp_comma 133)
(defconstant key.kp_equalsas400 134)
(defconstant key.international1 135)
(defconstant key.international2 136)
(defconstant key.international3 137)
(defconstant key.international4 138)
(defconstant key.international5 139)
(defconstant key.international6 140)
(defconstant key.international7 141)
(defconstant key.international8 142)
(defconstant key.international9 143)
(defconstant key.lang1 144)
(defconstant key.lang2 145)
(defconstant key.lang3 146)
(defconstant key.lang4 147)
(defconstant key.lang5 148)
(defconstant key.lang6 149)
(defconstant key.lang7 150)
(defconstant key.lang8 151)
(defconstant key.lang9 152)
(defconstant key.alterase 153)
(defconstant key.sysreq 154)
(defconstant key.cancel 155)
(defconstant key.clear 156)
(defconstant key.prior 157)
(defconstant key.return2 158)
(defconstant key.separator 159)
(defconstant key.out 160)
(defconstant key.oper 161)
(defconstant key.clearagain 162)
(defconstant key.crsel 163)
(defconstant key.exsel 164)
(defconstant key.kp_00 176)
(defconstant key.kp_000 177)
(defconstant key.thousandsseparator 178)
(defconstant key.decimalseparator 179)
(defconstant key.currencyunit 180)
(defconstant key.currencysubunit 181)
(defconstant key.kp_leftparen 182)
(defconstant key.kp_rightparen 183)
(defconstant key.kp_leftbrace 184)
(defconstant key.kp_rightbrace 185)
(defconstant key.kp_tab 186)
(defconstant key.kp_backspace 187)
(defconstant key.kp_a 188)
(defconstant key.kp_b 189)
(defconstant key.kp_c 190)
(defconstant key.kp_d 191)
(defconstant key.kp_e 192)
(defconstant key.kp_f 193)
(defconstant key.kp_xor 194)
(defconstant key.kp_power 195)
(defconstant key.kp_percent 196)
(defconstant key.kp_less 197)
(defconstant key.kp_greater 198)
(defconstant key.kp_ampersand 199)
(defconstant key.kp_dblampersand 200)
(defconstant key.kp_verticalbar 201)
(defconstant key.kp_dblverticalbar 202)
(defconstant key.kp_colon 203)
(defconstant key.kp_hash 204)
(defconstant key.kp_space 205)
(defconstant key.kp_at 206)
(defconstant key.kp_exclam 207)
(defconstant key.kp_memstore 208)
(defconstant key.kp_memrecall 209)
(defconstant key.kp_memclear 210)
(defconstant key.kp_memadd 211)
(defconstant key.kp_memsubtract 212)
(defconstant key.kp_memmultiply 213)
(defconstant key.kp_memdivide 214)
(defconstant key.kp_plusminus 215)
(defconstant key.kp_clear 216)
(defconstant key.kp_clearentry 217)
(defconstant key.kp_binary 218)
(defconstant key.kp_octal 219)
(defconstant key.kp_decimal 220)
(defconstant key.kp_hexadecimal 221)
(defconstant key.lctrl 224)
(defconstant key.lshift 225)
(defconstant key.lalt 226)
(defconstant key.lgui 227)
(defconstant key.rctrl 228)
(defconstant key.rshift 229)
(defconstant key.ralt 230)
(defconstant key.rgui 231)
(defconstant key.mode 257)
(defconstant key.audionext 258)
(defconstant key.audioprev 259)
(defconstant key.audiostop 260)
(defconstant key.audioplay 261)
(defconstant key.audiomute 262)
(defconstant key.mediaselect 263)
(defconstant key.www 264)
(defconstant key.mail 265)
(defconstant key.calculator 266)
(defconstant key.computer 267)
(defconstant key.ac_search 268)
(defconstant key.ac_home 269)
(defconstant key.ac_back 270)
(defconstant key.ac_forward 271)
(defconstant key.ac_stop 272)
(defconstant key.ac_refresh 273)
(defconstant key.ac_bookmarks 274)
(defconstant key.brightnessdown 275)
(defconstant key.brightnessup 276)
(defconstant key.displayswitch 277)
(defconstant key.kbdillumtoggle 278)
(defconstant key.kbdillumdown 279)
(defconstant key.kbdillumup 280)
(defconstant key.eject 281)
(defconstant key.sleep 282)
| null | https://raw.githubusercontent.com/cbaggers/skitter/620772ae6146d510a8d58d07cae055c06e5c8620/sdl2/keys.lisp | lisp | (in-package skitter.sdl2.keys)
(defun key.id (name/event)
(etypecase name/event
(keyword
(or (position name/event skitter.sdl2::*key-button-names*)
(error "key.id: invalid name ~s" name/event)))
(t (error "key.id: Must be given a keyword name or an instance of the button event.~%Recieved ~s"
name/event))))
(defconstant key.a 4)
(defconstant key.b 5)
(defconstant key.c 6)
(defconstant key.d 7)
(defconstant key.e 8)
(defconstant key.f 9)
(defconstant key.g 10)
(defconstant key.h 11)
(defconstant key.i 12)
(defconstant key.j 13)
(defconstant key.k 14)
(defconstant key.l 15)
(defconstant key.m 16)
(defconstant key.n 17)
(defconstant key.o 18)
(defconstant key.p 19)
(defconstant key.q 20)
(defconstant key.r 21)
(defconstant key.s 22)
(defconstant key.t 23)
(defconstant key.u 24)
(defconstant key.v 25)
(defconstant key.w 26)
(defconstant key.x 27)
(defconstant key.y 28)
(defconstant key.z 29)
(defconstant key.1 30)
(defconstant key.2 31)
(defconstant key.3 32)
(defconstant key.4 33)
(defconstant key.5 34)
(defconstant key.6 35)
(defconstant key.7 36)
(defconstant key.8 37)
(defconstant key.9 38)
(defconstant key.0 39)
(defconstant key.return 40)
(defconstant key.escape 41)
(defconstant key.backspace 42)
(defconstant key.tab 43)
(defconstant key.space 44)
(defconstant key.minus 45)
(defconstant key.equals 46)
(defconstant key.leftbracket 47)
(defconstant key.rightbracket 48)
(defconstant key.backslash 49)
(defconstant key.nonushash 50)
(defconstant key.semicolon 51)
(defconstant key.apostrophe 52)
(defconstant key.grave 53)
(defconstant key.comma 54)
(defconstant key.period 55)
(defconstant key.slash 56)
(defconstant key.capslock 57)
(defconstant key.f1 58)
(defconstant key.f2 59)
(defconstant key.f3 60)
(defconstant key.f4 61)
(defconstant key.f5 62)
(defconstant key.f6 63)
(defconstant key.f7 64)
(defconstant key.f8 65)
(defconstant key.f9 66)
(defconstant key.f10 67)
(defconstant key.f11 68)
(defconstant key.f12 69)
(defconstant key.printscreen 70)
(defconstant key.scrolllock 71)
(defconstant key.pause 72)
(defconstant key.insert 73)
(defconstant key.home 74)
(defconstant key.pageup 75)
(defconstant key.delete 76)
(defconstant key.end 77)
(defconstant key.pagedown 78)
(defconstant key.right 79)
(defconstant key.left 80)
(defconstant key.down 81)
(defconstant key.up 82)
(defconstant key.numlockclear 83)
(defconstant key.kp_divide 84)
(defconstant key.kp_multiply 85)
(defconstant key.kp_minus 86)
(defconstant key.kp_plus 87)
(defconstant key.kp_enter 88)
(defconstant key.kp_1 89)
(defconstant key.kp_2 90)
(defconstant key.kp_3 91)
(defconstant key.kp_4 92)
(defconstant key.kp_5 93)
(defconstant key.kp_6 94)
(defconstant key.kp_7 95)
(defconstant key.kp_8 96)
(defconstant key.kp_9 97)
(defconstant key.kp_0 98)
(defconstant key.kp_period 99)
(defconstant key.nonusbackslash 100)
(defconstant key.application 101)
(defconstant key.power 102)
(defconstant key.kp_equals 103)
(defconstant key.f13 104)
(defconstant key.f14 105)
(defconstant key.f15 106)
(defconstant key.f16 107)
(defconstant key.f17 108)
(defconstant key.f18 109)
(defconstant key.f19 110)
(defconstant key.f20 111)
(defconstant key.f21 112)
(defconstant key.f22 113)
(defconstant key.f23 114)
(defconstant key.f24 115)
(defconstant key.execute 116)
(defconstant key.help 117)
(defconstant key.menu 118)
(defconstant key.select 119)
(defconstant key.stop 120)
(defconstant key.again 121)
(defconstant key.undo 122)
(defconstant key.cut 123)
(defconstant key.copy 124)
(defconstant key.paste 125)
(defconstant key.find 126)
(defconstant key.mute 127)
(defconstant key.volumeup 128)
(defconstant key.volumedown 129)
(defconstant key.lockingcapslock 130)
(defconstant key.lockingnumlock 131)
(defconstant key.lockingscrolllock 132)
(defconstant key.kp_comma 133)
(defconstant key.kp_equalsas400 134)
(defconstant key.international1 135)
(defconstant key.international2 136)
(defconstant key.international3 137)
(defconstant key.international4 138)
(defconstant key.international5 139)
(defconstant key.international6 140)
(defconstant key.international7 141)
(defconstant key.international8 142)
(defconstant key.international9 143)
(defconstant key.lang1 144)
(defconstant key.lang2 145)
(defconstant key.lang3 146)
(defconstant key.lang4 147)
(defconstant key.lang5 148)
(defconstant key.lang6 149)
(defconstant key.lang7 150)
(defconstant key.lang8 151)
(defconstant key.lang9 152)
(defconstant key.alterase 153)
(defconstant key.sysreq 154)
(defconstant key.cancel 155)
(defconstant key.clear 156)
(defconstant key.prior 157)
(defconstant key.return2 158)
(defconstant key.separator 159)
(defconstant key.out 160)
(defconstant key.oper 161)
(defconstant key.clearagain 162)
(defconstant key.crsel 163)
(defconstant key.exsel 164)
(defconstant key.kp_00 176)
(defconstant key.kp_000 177)
(defconstant key.thousandsseparator 178)
(defconstant key.decimalseparator 179)
(defconstant key.currencyunit 180)
(defconstant key.currencysubunit 181)
(defconstant key.kp_leftparen 182)
(defconstant key.kp_rightparen 183)
(defconstant key.kp_leftbrace 184)
(defconstant key.kp_rightbrace 185)
(defconstant key.kp_tab 186)
(defconstant key.kp_backspace 187)
(defconstant key.kp_a 188)
(defconstant key.kp_b 189)
(defconstant key.kp_c 190)
(defconstant key.kp_d 191)
(defconstant key.kp_e 192)
(defconstant key.kp_f 193)
(defconstant key.kp_xor 194)
(defconstant key.kp_power 195)
(defconstant key.kp_percent 196)
(defconstant key.kp_less 197)
(defconstant key.kp_greater 198)
(defconstant key.kp_ampersand 199)
(defconstant key.kp_dblampersand 200)
(defconstant key.kp_verticalbar 201)
(defconstant key.kp_dblverticalbar 202)
(defconstant key.kp_colon 203)
(defconstant key.kp_hash 204)
(defconstant key.kp_space 205)
(defconstant key.kp_at 206)
(defconstant key.kp_exclam 207)
(defconstant key.kp_memstore 208)
(defconstant key.kp_memrecall 209)
(defconstant key.kp_memclear 210)
(defconstant key.kp_memadd 211)
(defconstant key.kp_memsubtract 212)
(defconstant key.kp_memmultiply 213)
(defconstant key.kp_memdivide 214)
(defconstant key.kp_plusminus 215)
(defconstant key.kp_clear 216)
(defconstant key.kp_clearentry 217)
(defconstant key.kp_binary 218)
(defconstant key.kp_octal 219)
(defconstant key.kp_decimal 220)
(defconstant key.kp_hexadecimal 221)
(defconstant key.lctrl 224)
(defconstant key.lshift 225)
(defconstant key.lalt 226)
(defconstant key.lgui 227)
(defconstant key.rctrl 228)
(defconstant key.rshift 229)
(defconstant key.ralt 230)
(defconstant key.rgui 231)
(defconstant key.mode 257)
(defconstant key.audionext 258)
(defconstant key.audioprev 259)
(defconstant key.audiostop 260)
(defconstant key.audioplay 261)
(defconstant key.audiomute 262)
(defconstant key.mediaselect 263)
(defconstant key.www 264)
(defconstant key.mail 265)
(defconstant key.calculator 266)
(defconstant key.computer 267)
(defconstant key.ac_search 268)
(defconstant key.ac_home 269)
(defconstant key.ac_back 270)
(defconstant key.ac_forward 271)
(defconstant key.ac_stop 272)
(defconstant key.ac_refresh 273)
(defconstant key.ac_bookmarks 274)
(defconstant key.brightnessdown 275)
(defconstant key.brightnessup 276)
(defconstant key.displayswitch 277)
(defconstant key.kbdillumtoggle 278)
(defconstant key.kbdillumdown 279)
(defconstant key.kbdillumup 280)
(defconstant key.eject 281)
(defconstant key.sleep 282)
|
|
01ae6c56227405acae4b7874d736f00fb307d01e11bc005692d35424051af84a | artyom-poptsov/guile-smc | guile.scm | ;;; guile.scm -- Guile-SMC state machine compiler procedures.
Copyright ( C ) 2021 - 2022 Artyom V. Poptsov < >
;;
;; 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 3 of the License , or
;; (at your option) any later version.
;;
;; The 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 the program. If not, see </>.
;;; Commentary:
The procedures in this module produce a Scheme code for GNU .
;;; Code:
(define-module (smc compiler guile)
#:use-module (oop goops)
#:use-module (ice-9 pretty-print)
#:use-module (ice-9 regex)
#:use-module (ice-9 rdelim)
#:use-module (smc compiler guile-common)
#:use-module (smc core common)
#:use-module (smc core state)
#:use-module (smc core log)
#:use-module (smc version)
#:use-module (smc fsm)
#:use-module (smc puml)
#:use-module (smc config)
#:re-export (form-feed
write-header
write-parent-fsm-info)
#:export (write-module
write-use-modules
write-transition-table
write-define-class
write-initialize
copy-dependencies))
(define* (write-module module
#:key
extra-modules
class-name
port
(standalone-mode? #f))
"Write a @code{define-module} part to a @var{port}. @var{class-name} is used
to export a FSM class in the @code{#:export} part. @var{extra-modules} allow
to specify a list of extra modules that required for the output FSM to work."
(let loop ((lst `(define-module ,module
#:use-module (oop goops)
#:use-module ,(if standalone-mode?
(append module '(smc fsm))
'(smc fsm))))
(em extra-modules))
(if (or (not em) (null? em))
(begin
(pretty-print (append lst `(#:re-export (fsm-run!)
#:export (,class-name)))
port)
(newline port))
(loop (append lst `(#:use-module ,(car em)))
(cdr em)))))
(define (write-use-modules extra-modules port)
"Write 'use-modules' section to the @var{port}."
(let loop ((lst `(use-modules (smc fsm) (oop goops)))
(em extra-modules))
(if (or (not em) (null? em))
(begin
(display lst port)
(newline port))
(loop (append lst (list (car em)))
(cdr em)))))
(define-method-with-docs (write-transition-table (fsm <fsm>) (port <port>))
"Write a @var{fsm} transition table to a @var{port}."
(let ((table (fsm-transition-table fsm)))
(pretty-print
`(define %transition-table
,(list 'quasiquote
(map state->list/serialized
(hash-table->transition-list table))))
port)))
(define (write-define-class class-name port)
"Write @code{define-class} for a @var{class-name} to a @var{port}."
(pretty-print `(define-class ,class-name (<fsm>))
port))
(define (write-initialize fsm class-name port)
"Write the class constructor for @var{class-name} to the @var{port}."
(pretty-print
`(define-method (initialize (self ,class-name) initargs)
(next-method)
(fsm-description-set! self ,(fsm-description fsm))
(fsm-event-source-set! self ,(and (fsm-event-source fsm)
(procedure-name (fsm-event-source fsm))))
(fsm-transition-table-set!
self
(transition-list->hash-table self %transition-table))
(fsm-current-state-set! self
(fsm-state self
(quote ,(state-name (fsm-current-state fsm))))))
port))
(define (copy-file/substitute source destination substitutes)
(let ((src (open-input-file source))
(dst (open-output-file destination)))
(let loop ((line (read-line src)))
(if (eof-object? line)
(begin
(close-port src)
(close-port dst))
(let ((ln (let matcher-loop ((subs substitutes)
(ln line))
(if (null? subs)
ln
(let ((s (car subs)))
(matcher-loop (cdr subs)
(regexp-substitute/global #f
(car s)
ln
'pre
(cdr s)
'post)))))))
(write-line ln dst)
(loop (read-line src)))))))
(define (mkdir* path)
"Create directories from a PATH recursively."
(let loop ((dirparts (string-split path #\/))
(dir ""))
(unless (null? dirparts)
(let ((d (string-append dir (car dirparts) "/")))
(unless (file-exists? d)
(mkdir d))
(loop (cdr dirparts) d)))))
(define (modules->paths load-path modules)
"Locate each module from a MODULES list in the directories from a LOAD-PATH
list. Return a list of pairs (module-file full-path)."
(let mod-loop ((mods modules)
(result '()))
(if (null? mods)
result
(let* ((mod (car mods))
(mod-file (string-append (string-join (map symbol->string mod)
"/")
".scm"))
(full-path (let path-loop ((paths load-path))
(if (null? paths)
#f
(let ((path (string-append (car paths)
"/"
mod-file)))
(if (file-exists? path)
path
(path-loop (cdr paths))))))))
(if full-path
(mod-loop (cdr mods)
(cons (cons mod-file full-path) result))
(mod-loop (cdr mods)
result))))))
(define (copy-dependencies output-directory root-module-name extra-modules)
"Copy dependencies to a sub-directory with ROOT-MODULE-NAME of an
OUTPUT-DIRECTORY."
(define (copy src dst substitutes)
(let ((dir (dirname dst)))
(unless (file-exists? dir)
(log-debug " creating \"~a\" ..." dir)
(mkdir* (dirname dst))
(log-debug " creating \"~a\" ... done" dir))
(log-debug " copying: ~a -> ~a ..." src dst)
(copy-file/substitute src dst substitutes)
(log-debug " copying: ~a -> ~a ... done" src dst)))
(let* ((target-dir (format #f
"~a/~a"
output-directory
(string-join (map symbol->string root-module-name)
"/")))
(files (list "/fsm.scm"
"/core/common.scm"
"/core/config.scm"
"/core/log.scm"
"/core/state.scm"
"/core/stack.scm"
"/core/transition.scm"
"/context/char-context.scm"
"/context/context.scm"))
(substitutes (list (cons "\\(smc "
(format #f
"(~a smc "
(string-join (map symbol->string
root-module-name)
" ")))))
(substitutes-smc (cons (cons ";;; Commentary:"
(string-append
";;; Commentary:\n\n"
(format #f ";; Copied from Guile-SMC ~a~%"
(smc-version/string))))
substitutes))
(substitutes-extra (cons (cons "\\(define-module \\("
(format #f
"(define-module (~a "
(string-join (map symbol->string
root-module-name)
" ")))
substitutes)))
(log-debug "Copying core modules ...")
(for-each (lambda (file)
(let* ((src (string-append %guile-smc-modules-directory file))
(dst (string-append target-dir "/smc/" file)))
(copy src dst substitutes-smc)))
files)
(log-debug "Copying core modules ... done")
(log-debug "Copying extra modules ...")
(for-each (lambda (mod)
(let* ((src (cdr mod))
(dst (string-append target-dir "/" (car mod))))
(copy src dst substitutes-extra)))
(modules->paths %load-path extra-modules))
(log-debug "Copying extra modules ... done")))
;;; guile.scm ends here.
| null | https://raw.githubusercontent.com/artyom-poptsov/guile-smc/a29c7f01ad175c19210bd5815ce387be08268735/modules/smc/compiler/guile.scm | scheme | guile.scm -- Guile-SMC state machine compiler procedures.
This program is free software: you can redistribute it and/or modify
(at your option) any later version.
The 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 the program. If not, see </>.
Commentary:
Code:
guile.scm ends here. |
Copyright ( C ) 2021 - 2022 Artyom V. Poptsov < >
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
The procedures in this module produce a Scheme code for GNU .
(define-module (smc compiler guile)
#:use-module (oop goops)
#:use-module (ice-9 pretty-print)
#:use-module (ice-9 regex)
#:use-module (ice-9 rdelim)
#:use-module (smc compiler guile-common)
#:use-module (smc core common)
#:use-module (smc core state)
#:use-module (smc core log)
#:use-module (smc version)
#:use-module (smc fsm)
#:use-module (smc puml)
#:use-module (smc config)
#:re-export (form-feed
write-header
write-parent-fsm-info)
#:export (write-module
write-use-modules
write-transition-table
write-define-class
write-initialize
copy-dependencies))
(define* (write-module module
#:key
extra-modules
class-name
port
(standalone-mode? #f))
"Write a @code{define-module} part to a @var{port}. @var{class-name} is used
to export a FSM class in the @code{#:export} part. @var{extra-modules} allow
to specify a list of extra modules that required for the output FSM to work."
(let loop ((lst `(define-module ,module
#:use-module (oop goops)
#:use-module ,(if standalone-mode?
(append module '(smc fsm))
'(smc fsm))))
(em extra-modules))
(if (or (not em) (null? em))
(begin
(pretty-print (append lst `(#:re-export (fsm-run!)
#:export (,class-name)))
port)
(newline port))
(loop (append lst `(#:use-module ,(car em)))
(cdr em)))))
(define (write-use-modules extra-modules port)
"Write 'use-modules' section to the @var{port}."
(let loop ((lst `(use-modules (smc fsm) (oop goops)))
(em extra-modules))
(if (or (not em) (null? em))
(begin
(display lst port)
(newline port))
(loop (append lst (list (car em)))
(cdr em)))))
(define-method-with-docs (write-transition-table (fsm <fsm>) (port <port>))
"Write a @var{fsm} transition table to a @var{port}."
(let ((table (fsm-transition-table fsm)))
(pretty-print
`(define %transition-table
,(list 'quasiquote
(map state->list/serialized
(hash-table->transition-list table))))
port)))
(define (write-define-class class-name port)
"Write @code{define-class} for a @var{class-name} to a @var{port}."
(pretty-print `(define-class ,class-name (<fsm>))
port))
(define (write-initialize fsm class-name port)
"Write the class constructor for @var{class-name} to the @var{port}."
(pretty-print
`(define-method (initialize (self ,class-name) initargs)
(next-method)
(fsm-description-set! self ,(fsm-description fsm))
(fsm-event-source-set! self ,(and (fsm-event-source fsm)
(procedure-name (fsm-event-source fsm))))
(fsm-transition-table-set!
self
(transition-list->hash-table self %transition-table))
(fsm-current-state-set! self
(fsm-state self
(quote ,(state-name (fsm-current-state fsm))))))
port))
(define (copy-file/substitute source destination substitutes)
(let ((src (open-input-file source))
(dst (open-output-file destination)))
(let loop ((line (read-line src)))
(if (eof-object? line)
(begin
(close-port src)
(close-port dst))
(let ((ln (let matcher-loop ((subs substitutes)
(ln line))
(if (null? subs)
ln
(let ((s (car subs)))
(matcher-loop (cdr subs)
(regexp-substitute/global #f
(car s)
ln
'pre
(cdr s)
'post)))))))
(write-line ln dst)
(loop (read-line src)))))))
(define (mkdir* path)
"Create directories from a PATH recursively."
(let loop ((dirparts (string-split path #\/))
(dir ""))
(unless (null? dirparts)
(let ((d (string-append dir (car dirparts) "/")))
(unless (file-exists? d)
(mkdir d))
(loop (cdr dirparts) d)))))
(define (modules->paths load-path modules)
"Locate each module from a MODULES list in the directories from a LOAD-PATH
list. Return a list of pairs (module-file full-path)."
(let mod-loop ((mods modules)
(result '()))
(if (null? mods)
result
(let* ((mod (car mods))
(mod-file (string-append (string-join (map symbol->string mod)
"/")
".scm"))
(full-path (let path-loop ((paths load-path))
(if (null? paths)
#f
(let ((path (string-append (car paths)
"/"
mod-file)))
(if (file-exists? path)
path
(path-loop (cdr paths))))))))
(if full-path
(mod-loop (cdr mods)
(cons (cons mod-file full-path) result))
(mod-loop (cdr mods)
result))))))
(define (copy-dependencies output-directory root-module-name extra-modules)
"Copy dependencies to a sub-directory with ROOT-MODULE-NAME of an
OUTPUT-DIRECTORY."
(define (copy src dst substitutes)
(let ((dir (dirname dst)))
(unless (file-exists? dir)
(log-debug " creating \"~a\" ..." dir)
(mkdir* (dirname dst))
(log-debug " creating \"~a\" ... done" dir))
(log-debug " copying: ~a -> ~a ..." src dst)
(copy-file/substitute src dst substitutes)
(log-debug " copying: ~a -> ~a ... done" src dst)))
(let* ((target-dir (format #f
"~a/~a"
output-directory
(string-join (map symbol->string root-module-name)
"/")))
(files (list "/fsm.scm"
"/core/common.scm"
"/core/config.scm"
"/core/log.scm"
"/core/state.scm"
"/core/stack.scm"
"/core/transition.scm"
"/context/char-context.scm"
"/context/context.scm"))
(substitutes (list (cons "\\(smc "
(format #f
"(~a smc "
(string-join (map symbol->string
root-module-name)
" ")))))
(substitutes-smc (cons (cons ";;; Commentary:"
(string-append
";;; Commentary:\n\n"
(format #f ";; Copied from Guile-SMC ~a~%"
(smc-version/string))))
substitutes))
(substitutes-extra (cons (cons "\\(define-module \\("
(format #f
"(define-module (~a "
(string-join (map symbol->string
root-module-name)
" ")))
substitutes)))
(log-debug "Copying core modules ...")
(for-each (lambda (file)
(let* ((src (string-append %guile-smc-modules-directory file))
(dst (string-append target-dir "/smc/" file)))
(copy src dst substitutes-smc)))
files)
(log-debug "Copying core modules ... done")
(log-debug "Copying extra modules ...")
(for-each (lambda (mod)
(let* ((src (cdr mod))
(dst (string-append target-dir "/" (car mod))))
(copy src dst substitutes-extra)))
(modules->paths %load-path extra-modules))
(log-debug "Copying extra modules ... done")))
|
caaa2ce90f41444142f1f04bd8ca45d376f576fda0d5f8350dc0872fa1dceaeb | mauricioszabo/repl-tooling | cljs-blob.cljs | (extend-protocol IPrintWithWriter
js/Error
(-pr-writer [ex writer _]
(-write writer "#error ")
(-write writer {:type (.-name ex)
:message (.-message ex)
:trace (->> ex
.-stack
clojure.string/split-lines)}))
cljs.core/ExceptionInfo
(-pr-writer [ex writer _]
(-write writer "#error ")
(-write writer {:type "cljs.core.ExceptionInfo"
:data (.-data ex)
:message (.-message ex)
:trace (->> ex
.-stack
clojure.string/split-lines)})))
| null | https://raw.githubusercontent.com/mauricioszabo/repl-tooling/a340895ebaf79791decb8354903958fd186b586c/resources/cljs-blob.cljs | clojure | (extend-protocol IPrintWithWriter
js/Error
(-pr-writer [ex writer _]
(-write writer "#error ")
(-write writer {:type (.-name ex)
:message (.-message ex)
:trace (->> ex
.-stack
clojure.string/split-lines)}))
cljs.core/ExceptionInfo
(-pr-writer [ex writer _]
(-write writer "#error ")
(-write writer {:type "cljs.core.ExceptionInfo"
:data (.-data ex)
:message (.-message ex)
:trace (->> ex
.-stack
clojure.string/split-lines)})))
|
|
129fc4655989baf1024f26f800ced05b7adc635a55dc2212b5c361c066493438 | LeapYear/github-rest | Query.hs | # LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module Query (tests) where
import Data.Aeson (Value)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.Text.Lazy.Encoding as Text
import Network.HTTP.Types (status404)
import Test.Tasty (TestName, TestTree)
import Test.Tasty.Golden (goldenVsString)
import GitHub.REST
tests :: [TestTree]
tests =
[ goldens "Query Gist #1" "gists-gist_id-sha.golden" $ do
gist <- queryGitHub $ getGist 1 "8afc134bf14f8f56ed2e7234128490d9946e8c16"
return $ Text.encodeUtf8 $ gist .: "files" .: "gistfile1.txt" .: "content"
, goldens "Query non-existent Gist commit" "gists-gist_id-sha-422.golden" $ do
showResult . githubTry . queryGitHub $
getGist 1 "d00770679ba293a327156b9e7031c47c6d269157"
, goldens "Query non-existent Gist" "gists-gist_id-sha-404.golden" $ do
showResult . githubTry' status404 . queryGitHub $
getGist 0 "d00770679ba293a327156b9e7031c47c6d269157"
]
goldens :: TestName -> String -> GitHubT IO ByteString -> TestTree
goldens name fp action = goldenVsString name ("test/goldens/" ++ fp) $ runGitHubT state action
where
state =
GitHubSettings
{ token = Nothing
, userAgent = "github-rest"
, apiVersion = "v3"
}
showResult :: Monad m => m (Either Value Value) -> m ByteString
showResult m =
m >>= \case
Right v -> error $ "Got back invalid result: " ++ show v
Left e -> return $ Char8.pack $ show e
getGist :: Int -> String -> GHEndpoint
getGist gistId gistSha =
GHEndpoint
{ method = GET
, endpoint = "/gists/:gist_id/:sha"
, endpointVals =
[ "gist_id" := gistId
, "sha" := gistSha
]
, ghData = []
}
| null | https://raw.githubusercontent.com/LeapYear/github-rest/520e6c09f0cc494c89b696aad97c6c77c2551900/test/Query.hs | haskell | # LANGUAGE OverloadedStrings # | # LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
module Query (tests) where
import Data.Aeson (Value)
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy.Char8 as Char8
import qualified Data.Text.Lazy.Encoding as Text
import Network.HTTP.Types (status404)
import Test.Tasty (TestName, TestTree)
import Test.Tasty.Golden (goldenVsString)
import GitHub.REST
tests :: [TestTree]
tests =
[ goldens "Query Gist #1" "gists-gist_id-sha.golden" $ do
gist <- queryGitHub $ getGist 1 "8afc134bf14f8f56ed2e7234128490d9946e8c16"
return $ Text.encodeUtf8 $ gist .: "files" .: "gistfile1.txt" .: "content"
, goldens "Query non-existent Gist commit" "gists-gist_id-sha-422.golden" $ do
showResult . githubTry . queryGitHub $
getGist 1 "d00770679ba293a327156b9e7031c47c6d269157"
, goldens "Query non-existent Gist" "gists-gist_id-sha-404.golden" $ do
showResult . githubTry' status404 . queryGitHub $
getGist 0 "d00770679ba293a327156b9e7031c47c6d269157"
]
goldens :: TestName -> String -> GitHubT IO ByteString -> TestTree
goldens name fp action = goldenVsString name ("test/goldens/" ++ fp) $ runGitHubT state action
where
state =
GitHubSettings
{ token = Nothing
, userAgent = "github-rest"
, apiVersion = "v3"
}
showResult :: Monad m => m (Either Value Value) -> m ByteString
showResult m =
m >>= \case
Right v -> error $ "Got back invalid result: " ++ show v
Left e -> return $ Char8.pack $ show e
getGist :: Int -> String -> GHEndpoint
getGist gistId gistSha =
GHEndpoint
{ method = GET
, endpoint = "/gists/:gist_id/:sha"
, endpointVals =
[ "gist_id" := gistId
, "sha" := gistSha
]
, ghData = []
}
|
28ca2ee8ff9647e53ea75d3af077bea4db52cefa653cd3051d9487c49ac2ef61 | voidlizard/emufat | EncodeVM.hs | Copyright ( c ) 2014 ,
-- All rights reserved.
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
-- * Neither the name of emufat nor the names of its
-- contributors may be used to endorse or promote products derived from
-- this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
module EncodeVM where
import Prelude hiding (EQ)
import Data.Word
import Data.Maybe
import qualified Data.Map as M
import Data.Functor.Identity
import Text.Printf
import Data.Binary.Put
import Control.Monad.State
import Control.Monad.Writer
import qualified Data.ByteString.Lazy as BS
class OpcodeCL a where
isRLE :: a -> Bool
arity0 :: a -> Bool
arity1 :: a -> Bool
arity2 :: a -> Bool
arity3 :: a -> Bool
firstCode :: a
lastCode :: a
data Opcode = DUP | DROP
| CONST | CRNG
| JNZ | JZ | JGQ | JNE | JMP | CALLT | CALL | RET
| NOT | EQ | NEQ | GT | LE | GQ | LQ | RNG
| LOADS2 | LOADS3 | LOADS4 | LOADS5 | LOADS6 | LOADS7
| LOADS8 | LOADS9 | LOADS10 | LOADSN
| SER | NSER | NSER128
| RLE1 | RLE2 | RLE3 | RLE4 | RLE5 | RLE6 | RLE7 | RLE8
| RLE16 | RLE32 | RLE64 | RLE128 | RLE256 | RLE512 | RLEN
| OUTLE | OUTBE | OUTB
| NOP
| CALLN
| DEBUG
| EXIT
deriving (Eq, Ord, Enum, Show)
instance OpcodeCL Opcode where
isRLE x = x `elem` [RLE1 .. RLEN]
arity0 x =
x `elem` ([DUP, DROP] ++ [NOT .. RNG] ++ [CALLT, RET, NOP, DEBUG, EXIT] ++ [LOADS2 .. LOADS10] ++ [OUTLE .. OUTB])
arity1 x = x `elem` ([CONST] ++ [JNZ .. JMP] ++ [LOADSN] ++ [RLE1 .. RLEN] ++ [CALL] ++ [CALLN])
arity2 x = x `elem` ([SER, NSER128, CRNG])
arity3 x = x `elem` ([NSER])
firstCode = DUP
lastCode = EXIT
data CmdArg = W32 Word32 | W16 Word16 | W8 Word8 | ADDR Addr
data Addr = ALabel Label | AOffset Int
data Cmd = Cmd0 Opcode
| CmdConst Word32
| Cmd1 Opcode CmdArg
| Cmd2 Opcode CmdArg CmdArg
| Cmd3 Opcode CmdArg CmdArg CmdArg
| CmdJmp Opcode Addr
| CmdCondJmp Opcode Addr
| CmdLabel Label
| RawByte Word8
type Label = Int
type Block = (Label, [Cmd])
labelOf :: Block -> Label
labelOf = fst
instance Show CmdArg where
show (W32 x) = printf "%08X" x
show (W16 x) = printf "%04X" x
show (W8 x) = printf "%02X" x
show (ADDR a) = (show a)
instance Show Addr where
show (ALabel l) = "L" ++ show l
show (AOffset o) = printf "%04X" o
instance Show Cmd where
show (Cmd0 code) = ind 1 $ show code
show (CmdConst w) = ind 1 $ printf "CONST %d" w
show (Cmd1 code a) = ind 1 $ show code ++ " " ++ show a
show (Cmd2 code a b) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b
show (Cmd3 code a b c) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c
show (CmdJmp code a) = ind 1 $ show code ++ " " ++ show a
show (CmdCondJmp code a) = ind 1 $ show code ++ " " ++ show a
show (RawByte m) = ind 1 $ "BYTE " ++ printf "%02X" m
show (CmdLabel lbl) = "L" ++ show lbl ++ ":"
unArg (W8 a) = fromIntegral a
unArg (W16 a) = fromIntegral a
unArg (W32 a) = fromIntegral a
unArg (ADDR (ALabel a)) = a
unArg (ADDR (AOffset a)) = a
ind x s = concat (replicate x " ") ++ s
toBinary :: [(Label, [Cmd])] -> BS.ByteString
toBinary cmds = encodeM (pass3 (pass2 (pass1 cmds)))
where
pass3 m = execWriter $ forM_ cmds $ \(l, cs) -> mapM_ (repl m) cs
pass2 :: [(Label, Int)] -> M.Map Label Int
pass2 xs = M.fromList (execWriter (foldM_ blockOff 0 xs))
pass1 = map (\(l,c) -> (l, fromIntegral $ BS.length $ encodeM c))
encodeM :: [Cmd] -> BS.ByteString
encodeM c = runPut (mapM_ encode c)
encode (Cmd0 x) = putOpcode x
encode (CmdConst x) = putOpcode CONST >> putWord32be x
encode (Cmd1 CALLN a) = putOpcode CALLN >> putArg8 a
encode (Cmd1 LOADSN a) | (unArg a) < 256 = putOpcode LOADSN >> putArg8 a
| otherwise = error $ "BAD LOADSN ARG" ++ show a
encode (Cmd1 x a) | isRLE x = putOpcode x >> putArg8 a
| otherwise = putOpcode x >> putArg32 a
encode (RawByte b) = putWord8 b
encode (CmdLabel _) = return ()
encode (CmdJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (CmdCondJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (Cmd2 SER a b) = putOpcode SER >> putArg32 a >> putArg32 b
encode (Cmd2 NSER128 a b) = putOpcode NSER128 >> putArg32 a >> putArg32 b
encode (Cmd2 CRNG a b) = putOpcode CRNG >> putArg32 a >> putArg32 b
encode (Cmd3 NSER a b c) = putOpcode NSER >> putArg32 a >> putArg32 b >> putArg32 c
encode x = error $ "BAD COMMAND " ++ show x
putOpcode = putWord8 . op
putArg8 (W32 a) = putWord8 (fromIntegral a)
putArg8 (W16 a) = putWord8 (fromIntegral a)
putArg8 (W8 a) = putWord8 (fromIntegral a)
putArg8 (ADDR _ ) = error "BAD W8 (ADDRESS)"
putArg32 (W32 a) = putWord32be (fromIntegral a)
putArg32 (W16 a) = putWord32be (fromIntegral a)
putArg32 (W8 a) = putWord8 (fromIntegral a)
putArg32 (ADDR (ALabel a)) = putWord32be (fromIntegral 0)
putArg32 (ADDR (AOffset a)) = putWord32be (fromIntegral a)
op :: Opcode -> Word8
op = fromIntegral . fromEnum
blockOff sz (l', c) = tell [(l', sz)] >> return (sz + c)
repl m x@(Cmd1 CALL (ADDR (ALabel n))) = repl' (M.lookup n m) x
repl m x@(CmdJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x@(CmdCondJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x = tell [x]
repl' (Just n) (Cmd1 CALL x) = tell [Cmd1 CALL (ADDR (AOffset n))]
repl' (Just n) (CmdJmp op x) = tell [CmdJmp op (AOffset n)]
repl' (Just n) (CmdCondJmp op x) = tell [CmdCondJmp op (AOffset n)]
repl' Nothing x = error $ "BAD LABEL " ++ show x
| null | https://raw.githubusercontent.com/voidlizard/emufat/e1cdbebfd7c26f1362cd59273d856d5e13db36b5/src/EncodeVM.hs | haskell | All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of emufat nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | Copyright ( c ) 2014 ,
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS "
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
module EncodeVM where
import Prelude hiding (EQ)
import Data.Word
import Data.Maybe
import qualified Data.Map as M
import Data.Functor.Identity
import Text.Printf
import Data.Binary.Put
import Control.Monad.State
import Control.Monad.Writer
import qualified Data.ByteString.Lazy as BS
class OpcodeCL a where
isRLE :: a -> Bool
arity0 :: a -> Bool
arity1 :: a -> Bool
arity2 :: a -> Bool
arity3 :: a -> Bool
firstCode :: a
lastCode :: a
data Opcode = DUP | DROP
| CONST | CRNG
| JNZ | JZ | JGQ | JNE | JMP | CALLT | CALL | RET
| NOT | EQ | NEQ | GT | LE | GQ | LQ | RNG
| LOADS2 | LOADS3 | LOADS4 | LOADS5 | LOADS6 | LOADS7
| LOADS8 | LOADS9 | LOADS10 | LOADSN
| SER | NSER | NSER128
| RLE1 | RLE2 | RLE3 | RLE4 | RLE5 | RLE6 | RLE7 | RLE8
| RLE16 | RLE32 | RLE64 | RLE128 | RLE256 | RLE512 | RLEN
| OUTLE | OUTBE | OUTB
| NOP
| CALLN
| DEBUG
| EXIT
deriving (Eq, Ord, Enum, Show)
instance OpcodeCL Opcode where
isRLE x = x `elem` [RLE1 .. RLEN]
arity0 x =
x `elem` ([DUP, DROP] ++ [NOT .. RNG] ++ [CALLT, RET, NOP, DEBUG, EXIT] ++ [LOADS2 .. LOADS10] ++ [OUTLE .. OUTB])
arity1 x = x `elem` ([CONST] ++ [JNZ .. JMP] ++ [LOADSN] ++ [RLE1 .. RLEN] ++ [CALL] ++ [CALLN])
arity2 x = x `elem` ([SER, NSER128, CRNG])
arity3 x = x `elem` ([NSER])
firstCode = DUP
lastCode = EXIT
data CmdArg = W32 Word32 | W16 Word16 | W8 Word8 | ADDR Addr
data Addr = ALabel Label | AOffset Int
data Cmd = Cmd0 Opcode
| CmdConst Word32
| Cmd1 Opcode CmdArg
| Cmd2 Opcode CmdArg CmdArg
| Cmd3 Opcode CmdArg CmdArg CmdArg
| CmdJmp Opcode Addr
| CmdCondJmp Opcode Addr
| CmdLabel Label
| RawByte Word8
type Label = Int
type Block = (Label, [Cmd])
labelOf :: Block -> Label
labelOf = fst
instance Show CmdArg where
show (W32 x) = printf "%08X" x
show (W16 x) = printf "%04X" x
show (W8 x) = printf "%02X" x
show (ADDR a) = (show a)
instance Show Addr where
show (ALabel l) = "L" ++ show l
show (AOffset o) = printf "%04X" o
instance Show Cmd where
show (Cmd0 code) = ind 1 $ show code
show (CmdConst w) = ind 1 $ printf "CONST %d" w
show (Cmd1 code a) = ind 1 $ show code ++ " " ++ show a
show (Cmd2 code a b) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b
show (Cmd3 code a b c) = ind 1 $ show code ++ " " ++ show a ++ " " ++ show b ++ " " ++ show c
show (CmdJmp code a) = ind 1 $ show code ++ " " ++ show a
show (CmdCondJmp code a) = ind 1 $ show code ++ " " ++ show a
show (RawByte m) = ind 1 $ "BYTE " ++ printf "%02X" m
show (CmdLabel lbl) = "L" ++ show lbl ++ ":"
unArg (W8 a) = fromIntegral a
unArg (W16 a) = fromIntegral a
unArg (W32 a) = fromIntegral a
unArg (ADDR (ALabel a)) = a
unArg (ADDR (AOffset a)) = a
ind x s = concat (replicate x " ") ++ s
toBinary :: [(Label, [Cmd])] -> BS.ByteString
toBinary cmds = encodeM (pass3 (pass2 (pass1 cmds)))
where
pass3 m = execWriter $ forM_ cmds $ \(l, cs) -> mapM_ (repl m) cs
pass2 :: [(Label, Int)] -> M.Map Label Int
pass2 xs = M.fromList (execWriter (foldM_ blockOff 0 xs))
pass1 = map (\(l,c) -> (l, fromIntegral $ BS.length $ encodeM c))
encodeM :: [Cmd] -> BS.ByteString
encodeM c = runPut (mapM_ encode c)
encode (Cmd0 x) = putOpcode x
encode (CmdConst x) = putOpcode CONST >> putWord32be x
encode (Cmd1 CALLN a) = putOpcode CALLN >> putArg8 a
encode (Cmd1 LOADSN a) | (unArg a) < 256 = putOpcode LOADSN >> putArg8 a
| otherwise = error $ "BAD LOADSN ARG" ++ show a
encode (Cmd1 x a) | isRLE x = putOpcode x >> putArg8 a
| otherwise = putOpcode x >> putArg32 a
encode (RawByte b) = putWord8 b
encode (CmdLabel _) = return ()
encode (CmdJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (CmdCondJmp x a) = putOpcode x >> putArg32 (ADDR a)
encode (Cmd2 SER a b) = putOpcode SER >> putArg32 a >> putArg32 b
encode (Cmd2 NSER128 a b) = putOpcode NSER128 >> putArg32 a >> putArg32 b
encode (Cmd2 CRNG a b) = putOpcode CRNG >> putArg32 a >> putArg32 b
encode (Cmd3 NSER a b c) = putOpcode NSER >> putArg32 a >> putArg32 b >> putArg32 c
encode x = error $ "BAD COMMAND " ++ show x
putOpcode = putWord8 . op
putArg8 (W32 a) = putWord8 (fromIntegral a)
putArg8 (W16 a) = putWord8 (fromIntegral a)
putArg8 (W8 a) = putWord8 (fromIntegral a)
putArg8 (ADDR _ ) = error "BAD W8 (ADDRESS)"
putArg32 (W32 a) = putWord32be (fromIntegral a)
putArg32 (W16 a) = putWord32be (fromIntegral a)
putArg32 (W8 a) = putWord8 (fromIntegral a)
putArg32 (ADDR (ALabel a)) = putWord32be (fromIntegral 0)
putArg32 (ADDR (AOffset a)) = putWord32be (fromIntegral a)
op :: Opcode -> Word8
op = fromIntegral . fromEnum
blockOff sz (l', c) = tell [(l', sz)] >> return (sz + c)
repl m x@(Cmd1 CALL (ADDR (ALabel n))) = repl' (M.lookup n m) x
repl m x@(CmdJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x@(CmdCondJmp a (ALabel n)) = repl' (M.lookup n m) x
repl m x = tell [x]
repl' (Just n) (Cmd1 CALL x) = tell [Cmd1 CALL (ADDR (AOffset n))]
repl' (Just n) (CmdJmp op x) = tell [CmdJmp op (AOffset n)]
repl' (Just n) (CmdCondJmp op x) = tell [CmdCondJmp op (AOffset n)]
repl' Nothing x = error $ "BAD LABEL " ++ show x
|
4dd5c128710af8c9f027422a60dccdf76e010faa34116de2b868c58443880231 | Zulu-Inuoe/clution | do-enumerable.lisp | enumerable - enumerable implementation for CL , using cl - cont
Written in 2018 by < >
;;;
;;;To the extent possible under law, the author(s) have dedicated all copyright
;;;and related and neighboring rights to this software to the public domain
;;;worldwide. This software is distributed without any warranty.
You should have received a copy of the CC0 Public Domain Dedication along
;;;with this software. If not, see
;;;</>.
(in-package #:enumerable)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %derived-fun-type (function)
#+sbcl
(sb-impl::%fun-type function))
(defun %expression-type (exp env)
(setf exp (macroexpand exp env))
(cond
((constantp exp)
;;Constant expression, just get its type
(type-of exp))
((symbolp exp)
(multiple-value-bind (bind-type local decl-info)
(cltl2:variable-information exp env)
(declare (ignore bind-type local))
;;Try and find its declared type
(cdr (assoc 'type decl-info))))
((listp exp)
(destructuring-bind (fn &rest args) exp
(declare (ignore args))
(cond
((symbolp fn)
;;fn
(multiple-value-bind (bind-type local decl-info)
(cltl2:function-information fn env)
(case bind-type
(nil)
(:function
(when-let ((ftype (cond
(local
;;If it's local, try and get decl info
(cdr (assoc 'ftype decl-info)))
(t
;;Otherwise, try and get the decl info or the derived
(or (cdr (assoc 'ftype decl-info))
(and (fboundp fn)
(%derived-fun-type (symbol-function fn))))))))
;;ftype definition is
(destructuring-bind (function params return-values)
ftype
(declare (ignore function params))
(cond
((listp return-values)
;;(values ...)
(cadr return-values))
((eq return-values '*)
nil)
(t
return-values)))))
(:macro)
(:special-form
;;We could code walk..
))))
(t
;;(lambda ...)
;;We can't derive anything
))))
(t nil)))
(defun %do-enumerable-expand (default-expander var enumerable result body env)
(let* ((exp-type (%expression-type enumerable env))
(expander (or (%get-expander exp-type) default-expander)))
(funcall expander exp-type var enumerable result body env))))
(defmacro do-enumerable ((var enumerable &optional result)
&body body
&environment env)
(%do-enumerable-expand #'%typecase-map-expander var enumerable result body env))
| null | https://raw.githubusercontent.com/Zulu-Inuoe/clution/b72f7afe5f770ff68a066184a389c23551863f7f/cl-clution/qlfile-libs/enumerable-master/src/do-enumerable.lisp | lisp |
To the extent possible under law, the author(s) have dedicated all copyright
and related and neighboring rights to this software to the public domain
worldwide. This software is distributed without any warranty.
with this software. If not, see
</>.
Constant expression, just get its type
Try and find its declared type
fn
If it's local, try and get decl info
Otherwise, try and get the decl info or the derived
ftype definition is
(values ...)
We could code walk..
(lambda ...)
We can't derive anything
| enumerable - enumerable implementation for CL , using cl - cont
Written in 2018 by < >
You should have received a copy of the CC0 Public Domain Dedication along
(in-package #:enumerable)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %derived-fun-type (function)
#+sbcl
(sb-impl::%fun-type function))
(defun %expression-type (exp env)
(setf exp (macroexpand exp env))
(cond
((constantp exp)
(type-of exp))
((symbolp exp)
(multiple-value-bind (bind-type local decl-info)
(cltl2:variable-information exp env)
(declare (ignore bind-type local))
(cdr (assoc 'type decl-info))))
((listp exp)
(destructuring-bind (fn &rest args) exp
(declare (ignore args))
(cond
((symbolp fn)
(multiple-value-bind (bind-type local decl-info)
(cltl2:function-information fn env)
(case bind-type
(nil)
(:function
(when-let ((ftype (cond
(local
(cdr (assoc 'ftype decl-info)))
(t
(or (cdr (assoc 'ftype decl-info))
(and (fboundp fn)
(%derived-fun-type (symbol-function fn))))))))
(destructuring-bind (function params return-values)
ftype
(declare (ignore function params))
(cond
((listp return-values)
(cadr return-values))
((eq return-values '*)
nil)
(t
return-values)))))
(:macro)
(:special-form
))))
(t
))))
(t nil)))
(defun %do-enumerable-expand (default-expander var enumerable result body env)
(let* ((exp-type (%expression-type enumerable env))
(expander (or (%get-expander exp-type) default-expander)))
(funcall expander exp-type var enumerable result body env))))
(defmacro do-enumerable ((var enumerable &optional result)
&body body
&environment env)
(%do-enumerable-expand #'%typecase-map-expander var enumerable result body env))
|
adc4d464f949377af9f476a0138469a71de4559ac26f96fec5794db410359f07 | RoadRunnr/dtlsex | dtlsex_ssl2.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2007 - 2011 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
%%----------------------------------------------------------------------
Purpose : Handles sslv2 hello as clients supporting sslv2 and higher
will send an sslv2 hello .
%%----------------------------------------------------------------------
-module(dtlsex_ssl2).
-export([client_random/2]).
client_random(ChallengeData, 32) ->
ChallengeData;
client_random(ChallengeData, N) when N > 32 ->
<<NewChallengeData:32/binary, _/binary>> = ChallengeData,
NewChallengeData;
client_random(ChallengeData, N) ->
Pad = list_to_binary(lists:duplicate(N, 0)),
<<Pad/binary, ChallengeData/binary>>.
| null | https://raw.githubusercontent.com/RoadRunnr/dtlsex/6cb9e52ff00ab0e5f33e0c4b54bf46eacddeb8e7/src/dtlsex_ssl2.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
----------------------------------------------------------------------
---------------------------------------------------------------------- | Copyright Ericsson AB 2007 - 2011 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
Purpose : Handles sslv2 hello as clients supporting sslv2 and higher
will send an sslv2 hello .
-module(dtlsex_ssl2).
-export([client_random/2]).
client_random(ChallengeData, 32) ->
ChallengeData;
client_random(ChallengeData, N) when N > 32 ->
<<NewChallengeData:32/binary, _/binary>> = ChallengeData,
NewChallengeData;
client_random(ChallengeData, N) ->
Pad = list_to_binary(lists:duplicate(N, 0)),
<<Pad/binary, ChallengeData/binary>>.
|
a7672eb055e656547002b0a0803645467b5d058cbb61f83b26b9f61bdd4508e0 | input-output-hk/plutus-apps | Server.hs | # LANGUAGE FlexibleContexts #
{-# LANGUAGE NamedFieldPuns #-}
# LANGUAGE NumericUnderscores #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE TypeApplications #
module Cardano.Node.Server
( main
) where
import Cardano.BM.Data.Trace (Trace)
import Cardano.Node.API (API)
import Cardano.Node.Emulator.Params (Params (..))
import Cardano.Node.Emulator.TimeSlot (SlotConfig (SlotConfig, scSlotLength, scSlotZeroTime))
import Cardano.Node.Mock
import Cardano.Node.Params qualified as Params
import Cardano.Node.Types
import Cardano.Protocol.Socket.Mock.Client qualified as Client
import Cardano.Protocol.Socket.Mock.Server qualified as Server
import Control.Concurrent (MVar, forkIO, newMVar)
import Control.Concurrent.Availability (Availability, available)
import Control.Monad (void)
import Control.Monad.Freer.Delay (delayThread, handleDelayEffect)
import Control.Monad.Freer.Extras.Log (logInfo)
import Control.Monad.IO.Class (liftIO)
import Data.Function ((&))
import Data.Map.Strict qualified as Map
import Data.Proxy (Proxy (Proxy))
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Time.Units (Millisecond, Second)
import Ledger.Value.CardanoAPI qualified as CardanoAPI
import Network.Wai.Handler.Warp qualified as Warp
import Plutus.PAB.Arbitrary ()
import Plutus.PAB.Monitoring.Monitoring qualified as LM
import Servant (Application, hoistServer, serve, (:<|>) ((:<|>)))
import Servant.Client (BaseUrl (baseUrlPort))
import Wallet.Emulator.Wallet (fromWalletNumber)
app ::
Trace IO PABServerLogMsg
-> Params
-> Client.TxSendHandle
-> MVar AppState
-> Application
app trace params clientHandler stateVar =
serve (Proxy @API) $
hoistServer
(Proxy @API)
(liftIO . processChainEffects trace params (Just clientHandler) stateVar)
(healthcheck :<|> consumeEventHistory stateVar)
data Ctx = Ctx { serverHandler :: Server.ServerHandler
, txSendHandle :: Client.TxSendHandle
, serverState :: MVar AppState
, mockTrace :: Trace IO PABServerLogMsg
}
main :: Trace IO PABServerLogMsg -> PABServerConfig -> Availability -> IO ()
main trace nodeServerConfig@PABServerConfig { pscBaseUrl
, pscSlotConfig
, pscKeptBlocks
, pscInitialTxWallets
, pscSocketPath } availability = LM.runLogEffects trace $ do
make initial distribution of 1 billion Ada to all configured wallets
let dist = Map.fromList $ zip (fromWalletNumber <$> pscInitialTxWallets) (repeat (CardanoAPI.adaValueOf 1_000_000_000))
initialState <- initialChainState dist
let appState = AppState
{ _chainState = initialState
, _eventHistory = mempty
}
params <- liftIO $ Params.fromPABServerConfig nodeServerConfig
serverHandler <- liftIO $ Server.runServerNode trace pscSocketPath pscKeptBlocks (_chainState appState) params
serverState <- liftIO $ newMVar appState
handleDelayEffect $ delayThread (2 :: Second)
clientHandler <- liftIO $ Client.runTxSender pscSocketPath
let ctx = Ctx { serverHandler = serverHandler
, txSendHandle = clientHandler
, serverState = serverState
, mockTrace = trace
}
runSlotCoordinator ctx
logInfo $ StartingPABServer $ baseUrlPort pscBaseUrl
liftIO $ Warp.runSettings warpSettings $ app trace params clientHandler serverState
where
warpSettings = Warp.defaultSettings & Warp.setPort (baseUrlPort pscBaseUrl) & Warp.setBeforeMainLoop (available availability)
runSlotCoordinator (Ctx serverHandler _ _ _) = do
let SlotConfig{scSlotZeroTime, scSlotLength} = pscSlotConfig
logInfo $ StartingSlotCoordination (posixSecondsToUTCTime $ realToFrac scSlotZeroTime / 1000)
(fromInteger scSlotLength :: Millisecond)
void $ liftIO $ forkIO $ slotCoordinator pscSlotConfig serverHandler
| null | https://raw.githubusercontent.com/input-output-hk/plutus-apps/e8688b8f86a92b285e7d93eb418ccc314ad41bf9/plutus-pab/src/Cardano/Node/Server.hs | haskell | # LANGUAGE NamedFieldPuns #
# LANGUAGE OverloadedStrings # | # LANGUAGE FlexibleContexts #
# LANGUAGE NumericUnderscores #
# LANGUAGE TypeApplications #
module Cardano.Node.Server
( main
) where
import Cardano.BM.Data.Trace (Trace)
import Cardano.Node.API (API)
import Cardano.Node.Emulator.Params (Params (..))
import Cardano.Node.Emulator.TimeSlot (SlotConfig (SlotConfig, scSlotLength, scSlotZeroTime))
import Cardano.Node.Mock
import Cardano.Node.Params qualified as Params
import Cardano.Node.Types
import Cardano.Protocol.Socket.Mock.Client qualified as Client
import Cardano.Protocol.Socket.Mock.Server qualified as Server
import Control.Concurrent (MVar, forkIO, newMVar)
import Control.Concurrent.Availability (Availability, available)
import Control.Monad (void)
import Control.Monad.Freer.Delay (delayThread, handleDelayEffect)
import Control.Monad.Freer.Extras.Log (logInfo)
import Control.Monad.IO.Class (liftIO)
import Data.Function ((&))
import Data.Map.Strict qualified as Map
import Data.Proxy (Proxy (Proxy))
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import Data.Time.Units (Millisecond, Second)
import Ledger.Value.CardanoAPI qualified as CardanoAPI
import Network.Wai.Handler.Warp qualified as Warp
import Plutus.PAB.Arbitrary ()
import Plutus.PAB.Monitoring.Monitoring qualified as LM
import Servant (Application, hoistServer, serve, (:<|>) ((:<|>)))
import Servant.Client (BaseUrl (baseUrlPort))
import Wallet.Emulator.Wallet (fromWalletNumber)
app ::
Trace IO PABServerLogMsg
-> Params
-> Client.TxSendHandle
-> MVar AppState
-> Application
app trace params clientHandler stateVar =
serve (Proxy @API) $
hoistServer
(Proxy @API)
(liftIO . processChainEffects trace params (Just clientHandler) stateVar)
(healthcheck :<|> consumeEventHistory stateVar)
data Ctx = Ctx { serverHandler :: Server.ServerHandler
, txSendHandle :: Client.TxSendHandle
, serverState :: MVar AppState
, mockTrace :: Trace IO PABServerLogMsg
}
main :: Trace IO PABServerLogMsg -> PABServerConfig -> Availability -> IO ()
main trace nodeServerConfig@PABServerConfig { pscBaseUrl
, pscSlotConfig
, pscKeptBlocks
, pscInitialTxWallets
, pscSocketPath } availability = LM.runLogEffects trace $ do
make initial distribution of 1 billion Ada to all configured wallets
let dist = Map.fromList $ zip (fromWalletNumber <$> pscInitialTxWallets) (repeat (CardanoAPI.adaValueOf 1_000_000_000))
initialState <- initialChainState dist
let appState = AppState
{ _chainState = initialState
, _eventHistory = mempty
}
params <- liftIO $ Params.fromPABServerConfig nodeServerConfig
serverHandler <- liftIO $ Server.runServerNode trace pscSocketPath pscKeptBlocks (_chainState appState) params
serverState <- liftIO $ newMVar appState
handleDelayEffect $ delayThread (2 :: Second)
clientHandler <- liftIO $ Client.runTxSender pscSocketPath
let ctx = Ctx { serverHandler = serverHandler
, txSendHandle = clientHandler
, serverState = serverState
, mockTrace = trace
}
runSlotCoordinator ctx
logInfo $ StartingPABServer $ baseUrlPort pscBaseUrl
liftIO $ Warp.runSettings warpSettings $ app trace params clientHandler serverState
where
warpSettings = Warp.defaultSettings & Warp.setPort (baseUrlPort pscBaseUrl) & Warp.setBeforeMainLoop (available availability)
runSlotCoordinator (Ctx serverHandler _ _ _) = do
let SlotConfig{scSlotZeroTime, scSlotLength} = pscSlotConfig
logInfo $ StartingSlotCoordination (posixSecondsToUTCTime $ realToFrac scSlotZeroTime / 1000)
(fromInteger scSlotLength :: Millisecond)
void $ liftIO $ forkIO $ slotCoordinator pscSlotConfig serverHandler
|
3463b52980dc396185db296e007cce9af9a552efb8a1920dd35db34e5e33f85c | bjorng/esdl | sdl_img.erl | Copyright ( c ) 2007
%%
%% See the file "license.terms" for information on usage and redistribution
%% of this file, and for a DISCLAIMER OF ALL WARRANTIES.
%%
%% $Id$
%%
%%%----------------------------------------------------------------------
%%% File : sdl_img.erl
Author : < at users.sourceforge.net >
Purpose : Provide access to SDL 's image functions ( tested with
%%% SDL_image 1.2.4)
Created : 18 Feb 2007 by < at users.sourceforge.net >
%%%----------------------------------------------------------------------
-module(sdl_img).
-include("sdl_img_funcs.hrl").
-include("sdl_util.hrl").
-include("sdl_video.hrl").
%%% ERL_SDL functions
-export([]).
%%% SDL_Functions
-export([linkedVersion/0]).
-export([loadTypedRW/0]).
-export([load/1]).
-export([loadRW/0]).
-export([invertAlpha/0]).
-export([isBMP/0]).
-export([isPNM/0]).
-export([isXPM/0]).
-export([isXCF/0]).
-export([isPCX/0]).
-export([isGIF/0]).
-export([isJPG/0]).
-export([isTIF/0]).
-export([isPNG/0]).
-export([isLBM/0]).
-export([loadBMPRW/0]).
-export([loadPNMRW/0]).
-export([loadXPMRW/0]).
-export([loadXCFRW/0]).
-export([loadPCXRW/0]).
-export([loadGIFRW/0]).
-export([loadJPGRW/0]).
-export([loadTIFRW/0]).
-export([loadPNGRW/0]).
-export([loadTGARW/0]).
-export([loadLBMRW/0]).
-export([readXPMFromArray/0]).
-export([setError/1]).
-export([getError/0]).
%% Imports
-import(sdl, [call/2, cast/2]).
%% Defines
-define(INT, 16/signed).
-define(LONG, 32/signed).
-define(UINT8, 8/unsigned).
-define(UINT16, 16/unsigned).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% ERL_SDL API
%% Func: linkedVersion
: -
Returns : { Major , , Patch }
%% C-API func: const SDL_version * IMG_Linked_Version(void);
Desc : This function gets the version of the library .
linkedVersion() ->
<<Major:?UINT8, Minor:?UINT8, Patch:?UINT8>> =
call(?SDL_IMG_LinkedVersion, []),
{Major, Minor, Patch}.
%% Func: loadTypedRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, char *type);
%% Desc: Not implemented.
loadTypedRW() ->
exit({not_implemented, loadTypedRW}).
%% Func: load
: File
%% Returns: Surface Ref
%% C-API func: SDL_Surface * IMG_Load(const char *file);
Desc : Load an image from an SDL data source .
load(File) ->
<<SurfacePtr:?_PTR>> = call(?SDL_IMG_Load, [[File,0]]),
case SurfacePtr of
0 -> exit({load, returned_null_pointer});
_ -> {surfacep, SurfacePtr}
end.
%% Func: loadRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_Load_RW(SDL_RWops *src, int freesrc);
%% Desc: Not implemented.
loadRW() ->
exit({not_implemented, loadRW}).
%% Func: invertAlpha
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_InvertAlpha(int on);
%% Desc: Not implemented.
invertAlpha() ->
exit({not_implemented, invertAlpha}).
%% Func: isBMP
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isBMP(SDL_RWops *src);
%% Desc: Not implemented.
isBMP() ->
exit({not_implemented, isBMP}).
%% Func: isPNM
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isPNM(SDL_RWops *src);
%% Desc: Not implemented.
isPNM() ->
exit({not_implemented, isPNM}).
%% Func: isXPM
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isXPM(SDL_RWops *src);
%% Desc: Not implemented.
isXPM() ->
exit({not_implemented, isXPM}).
Func :
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isXCF(SDL_RWops *src);
%% Desc: Not implemented.
isXCF() ->
exit({not_implemented, isXCF}).
Func :
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isPCX(SDL_RWops *src);
%% Desc: Not implemented.
isPCX() ->
exit({not_implemented, isPCX}).
%% Func: isGIF
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isGIF(SDL_RWops *src);
%% Desc: Not implemented.
isGIF() ->
exit({not_implemented, isGIF}).
%% Func: isJPG
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isJPG(SDL_RWops *src);
%% Desc: Not implemented.
isJPG() ->
exit({not_implemented, isJPG}).
Func : isTIF
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isTIF(SDL_RWops *src);
%% Desc: Not implemented.
isTIF() ->
exit({not_implemented, isTIF}).
%% Func: isPNG
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isPNG(SDL_RWops *src);
%% Desc: Not implemented.
isPNG() ->
exit({not_implemented, isPNG}).
%% Func: isLBM
%% Args: N/A
%% Returns: N/A
%% C-API func: int IMG_isLBM(SDL_RWops *src);
%% Desc: Not implemented.
isLBM() ->
exit({not_implemented, isLBM}).
%% Func: loadBMPRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadBMP_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadBMPRW() ->
exit({not_implemented, loadBMPRW}).
%% Func: loadPNMRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadPNM_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadPNMRW() ->
exit({not_implemented, loadPNMRW}).
%% Func: loadXPMRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadXPM_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadXPMRW() ->
exit({not_implemented, loadXPMRW}).
%% Func: loadXCFRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadXCF_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadXCFRW() ->
exit({not_implemented, loadXCFRW}).
%% Func: loadPCXRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadPCX_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadPCXRW() ->
exit({not_implemented, loadPCXRW}).
%% Func: loadGIFRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadGIF_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadGIFRW() ->
exit({not_implemented, loadGIFRW}).
Func : loadJPGRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadJPG_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadJPGRW() ->
exit({not_implemented, loadJPGRW}).
%% Func: loadTIFRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadTIF_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadTIFRW() ->
exit({not_implemented, loadTIFRW}).
%% Func: loadPNGRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadPNG_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadPNGRW() ->
exit({not_implemented, loadPNGRW}).
%% Func: loadTGARW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadTGA_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadTGARW() ->
exit({not_implemented, loadTGARW}).
%% Func: loadLBMRW
%% Args: N/A
%% Returns: N/A
%% C-API func: SDL_Surface * IMG_LoadLBM_RW(SDL_RWops *src);
%% Desc: Not implemented.
loadLBMRW() ->
exit({not_implemented, loadLBMRW}).
%% Func: readXPMFromArray
%% Args: N/A
%% Returns: N/A
C - API func : SDL_Surface * IMG_ReadXPMFromArray(char * * ) ;
%% Desc: Not implemented.
readXPMFromArray() ->
exit({not_implemented, readXPMFromArray}).
Func : setError
%% Args: N/A
%% Returns: N/A
%% C-API func: void IMG_SetError(const char *fmt, ...)
%% Desc: Not implemented.
setError(_Error) ->
exit({not_implemented, setError}).
%% Func: getError
: -
%% Returns: Error
%% C-API func: char * IMG_GetError()
%% Desc: Returns a (string) containing a human readable version or the
%% reason for the last error that occured.
getError() ->
Bin = call(?SDL_IMG_GetError, []),
binary_to_list(Bin).
Internal functions % % % % % % % % % % %
| null | https://raw.githubusercontent.com/bjorng/esdl/dbd8ce9228aa36828091df2e8706c364094a3e22/src/sdl_img.erl | erlang |
See the file "license.terms" for information on usage and redistribution
of this file, and for a DISCLAIMER OF ALL WARRANTIES.
$Id$
----------------------------------------------------------------------
File : sdl_img.erl
SDL_image 1.2.4)
----------------------------------------------------------------------
ERL_SDL functions
SDL_Functions
Imports
Defines
ERL_SDL API
Func: linkedVersion
C-API func: const SDL_version * IMG_Linked_Version(void);
Func: loadTypedRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, char *type);
Desc: Not implemented.
Func: load
Returns: Surface Ref
C-API func: SDL_Surface * IMG_Load(const char *file);
Func: loadRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_Load_RW(SDL_RWops *src, int freesrc);
Desc: Not implemented.
Func: invertAlpha
Args: N/A
Returns: N/A
C-API func: int IMG_InvertAlpha(int on);
Desc: Not implemented.
Func: isBMP
Args: N/A
Returns: N/A
C-API func: int IMG_isBMP(SDL_RWops *src);
Desc: Not implemented.
Func: isPNM
Args: N/A
Returns: N/A
C-API func: int IMG_isPNM(SDL_RWops *src);
Desc: Not implemented.
Func: isXPM
Args: N/A
Returns: N/A
C-API func: int IMG_isXPM(SDL_RWops *src);
Desc: Not implemented.
Args: N/A
Returns: N/A
C-API func: int IMG_isXCF(SDL_RWops *src);
Desc: Not implemented.
Args: N/A
Returns: N/A
C-API func: int IMG_isPCX(SDL_RWops *src);
Desc: Not implemented.
Func: isGIF
Args: N/A
Returns: N/A
C-API func: int IMG_isGIF(SDL_RWops *src);
Desc: Not implemented.
Func: isJPG
Args: N/A
Returns: N/A
C-API func: int IMG_isJPG(SDL_RWops *src);
Desc: Not implemented.
Args: N/A
Returns: N/A
C-API func: int IMG_isTIF(SDL_RWops *src);
Desc: Not implemented.
Func: isPNG
Args: N/A
Returns: N/A
C-API func: int IMG_isPNG(SDL_RWops *src);
Desc: Not implemented.
Func: isLBM
Args: N/A
Returns: N/A
C-API func: int IMG_isLBM(SDL_RWops *src);
Desc: Not implemented.
Func: loadBMPRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadBMP_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadPNMRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadPNM_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadXPMRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadXPM_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadXCFRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadXCF_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadPCXRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadPCX_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadGIFRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadGIF_RW(SDL_RWops *src);
Desc: Not implemented.
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadJPG_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadTIFRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadTIF_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadPNGRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadPNG_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadTGARW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadTGA_RW(SDL_RWops *src);
Desc: Not implemented.
Func: loadLBMRW
Args: N/A
Returns: N/A
C-API func: SDL_Surface * IMG_LoadLBM_RW(SDL_RWops *src);
Desc: Not implemented.
Func: readXPMFromArray
Args: N/A
Returns: N/A
Desc: Not implemented.
Args: N/A
Returns: N/A
C-API func: void IMG_SetError(const char *fmt, ...)
Desc: Not implemented.
Func: getError
Returns: Error
C-API func: char * IMG_GetError()
Desc: Returns a (string) containing a human readable version or the
reason for the last error that occured.
% % % % % % % % % % | Copyright ( c ) 2007
Author : < at users.sourceforge.net >
Purpose : Provide access to SDL 's image functions ( tested with
Created : 18 Feb 2007 by < at users.sourceforge.net >
-module(sdl_img).
-include("sdl_img_funcs.hrl").
-include("sdl_util.hrl").
-include("sdl_video.hrl").
-export([]).
-export([linkedVersion/0]).
-export([loadTypedRW/0]).
-export([load/1]).
-export([loadRW/0]).
-export([invertAlpha/0]).
-export([isBMP/0]).
-export([isPNM/0]).
-export([isXPM/0]).
-export([isXCF/0]).
-export([isPCX/0]).
-export([isGIF/0]).
-export([isJPG/0]).
-export([isTIF/0]).
-export([isPNG/0]).
-export([isLBM/0]).
-export([loadBMPRW/0]).
-export([loadPNMRW/0]).
-export([loadXPMRW/0]).
-export([loadXCFRW/0]).
-export([loadPCXRW/0]).
-export([loadGIFRW/0]).
-export([loadJPGRW/0]).
-export([loadTIFRW/0]).
-export([loadPNGRW/0]).
-export([loadTGARW/0]).
-export([loadLBMRW/0]).
-export([readXPMFromArray/0]).
-export([setError/1]).
-export([getError/0]).
-import(sdl, [call/2, cast/2]).
-define(INT, 16/signed).
-define(LONG, 32/signed).
-define(UINT8, 8/unsigned).
-define(UINT16, 16/unsigned).
: -
Returns : { Major , , Patch }
Desc : This function gets the version of the library .
linkedVersion() ->
<<Major:?UINT8, Minor:?UINT8, Patch:?UINT8>> =
call(?SDL_IMG_LinkedVersion, []),
{Major, Minor, Patch}.
loadTypedRW() ->
exit({not_implemented, loadTypedRW}).
: File
Desc : Load an image from an SDL data source .
load(File) ->
<<SurfacePtr:?_PTR>> = call(?SDL_IMG_Load, [[File,0]]),
case SurfacePtr of
0 -> exit({load, returned_null_pointer});
_ -> {surfacep, SurfacePtr}
end.
loadRW() ->
exit({not_implemented, loadRW}).
invertAlpha() ->
exit({not_implemented, invertAlpha}).
isBMP() ->
exit({not_implemented, isBMP}).
isPNM() ->
exit({not_implemented, isPNM}).
isXPM() ->
exit({not_implemented, isXPM}).
Func :
isXCF() ->
exit({not_implemented, isXCF}).
Func :
isPCX() ->
exit({not_implemented, isPCX}).
isGIF() ->
exit({not_implemented, isGIF}).
isJPG() ->
exit({not_implemented, isJPG}).
Func : isTIF
isTIF() ->
exit({not_implemented, isTIF}).
isPNG() ->
exit({not_implemented, isPNG}).
isLBM() ->
exit({not_implemented, isLBM}).
loadBMPRW() ->
exit({not_implemented, loadBMPRW}).
loadPNMRW() ->
exit({not_implemented, loadPNMRW}).
loadXPMRW() ->
exit({not_implemented, loadXPMRW}).
loadXCFRW() ->
exit({not_implemented, loadXCFRW}).
loadPCXRW() ->
exit({not_implemented, loadPCXRW}).
loadGIFRW() ->
exit({not_implemented, loadGIFRW}).
Func : loadJPGRW
loadJPGRW() ->
exit({not_implemented, loadJPGRW}).
loadTIFRW() ->
exit({not_implemented, loadTIFRW}).
loadPNGRW() ->
exit({not_implemented, loadPNGRW}).
loadTGARW() ->
exit({not_implemented, loadTGARW}).
loadLBMRW() ->
exit({not_implemented, loadLBMRW}).
C - API func : SDL_Surface * IMG_ReadXPMFromArray(char * * ) ;
readXPMFromArray() ->
exit({not_implemented, readXPMFromArray}).
Func : setError
setError(_Error) ->
exit({not_implemented, setError}).
: -
getError() ->
Bin = call(?SDL_IMG_GetError, []),
binary_to_list(Bin).
|
bd97897ac22452a15baf8b6b4d0701c0b9054ca36a38bc236484e934ceb459ab | ztellman/riddley | walk.clj | (ns riddley.walk
(:refer-clojure :exclude [macroexpand])
(:require
[riddley.compiler :as cmp]))
(defn macroexpand
"Expands both macros and inline functions. Optionally takes a `special-form?` predicate which
identifies first elements of expressions that shouldn't be macroexpanded, and honors local
bindings."
([x]
(macroexpand x nil))
([x special-form?]
(cmp/with-base-env
(if (seq? x)
(let [frst (first x)]
(if (or
(and special-form? (special-form? frst))
(contains? (cmp/locals) frst))
;; might look like a macro, but for our purposes it isn't
x
(let [x' (macroexpand-1 x)]
(if-not (identical? x x')
(macroexpand x' special-form?)
;; if we can't macroexpand any further, check if it's an inlined function
(if-let [inline-fn (and (seq? x')
(symbol? (first x'))
(-> x' meta ::transformed not)
(or
(-> x' first resolve meta :inline-arities not)
((-> x' first resolve meta :inline-arities)
(count (rest x'))))
(-> x' first resolve meta :inline))]
(let [x'' (with-meta (apply inline-fn (rest x')) (meta x'))]
(macroexpand
;; unfortunately, static function calls can look a lot like what we just
;; expanded, so prevent infinite expansion
(if (= '. (first x''))
(with-meta
(concat (butlast x'')
[(if (instance? clojure.lang.IObj (last x''))
(with-meta (last x'')
(merge
(meta (last x''))
{::transformed true}))
(last x''))])
(meta x''))
x'')
special-form?))
x')))))
x))))
;;;
(def ^:private special-forms
(into #{} (keys (. clojure.lang.Compiler specials))))
(defn- special-meta [[op & body]]
(list* (vary-meta op assoc ::special true) body))
(defn- do-handler [f [_ & body]]
(list* 'do
(doall
(map f body))))
(defn- fn-handler [f x]
(let [prelude (take-while (complement sequential?) x)
remainder (drop (count prelude) x)
remainder (if (vector? (first remainder))
(list remainder) remainder)
body-handler (fn [x]
(cmp/with-lexical-scoping
(doseq [arg (first x)]
(cmp/register-arg arg))
(doall
(list* (first x)
(map f (rest x))))))]
(cmp/with-lexical-scoping
;; register a local for the function, if it's named
(when-let [nm (second prelude)]
(cmp/register-local nm
(list* 'fn* nm
(map #(take 1 %) remainder))))
(concat
prelude
(if (seq? (first remainder))
(doall (map body-handler remainder))
[(body-handler remainder)])))))
(defn- def-handler [f x]
(let [[_ n & r] x]
(cmp/with-lexical-scoping
(cmp/register-local n '())
(list* 'def (f n) (doall (map f r))))))
(defn- let-bindings [f x recursive?]
(let [pairs (partition-all 2 x)]
(when recursive?
(doall (map (fn [[k v]] (cmp/register-local k nil)) pairs)))
(->> pairs
(mapcat
(fn [[k v]]
(let [[k v] [k (f v)]]
(cmp/register-local k v)
[k v])))
vec)))
(defn- reify-handler [f x]
(let [[_ classes & fns] x]
(list* 'reify* classes
(doall
(map
(fn [[nm args & body]]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* nm args (doall (map f body)))))
fns)))))
(defn- deftype-handler [f x]
(let [[_ type resolved-type args _ interfaces & fns] x]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* 'deftype* type resolved-type args :implements interfaces
(doall
(map
(fn [[nm args & body]]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* nm args (doall (map f body)))))
fns))))))
(defn- let-handler
([f x]
(let-handler f x nil))
([f x recursive?]
(cmp/with-lexical-scoping
(doall
(list*
(first x)
(let-bindings f (second x) recursive?)
(map f (drop 2 x)))))))
(defn- letfn-handler [f x]
(let-handler f x true))
(defn- case-handler [f [_ ge shift mask default imap switch-type check-type skip-check]]
(let [prefix ['case* ge shift mask]
suffix [switch-type check-type skip-check]]
(concat
prefix
[(f default)]
[(let [m (->> imap
(map
(fn [[k [idx form]]]
[k [idx (f form)]]))
(into {}))]
(if (every? number? (keys m))
(into (sorted-map) m)
m))]
suffix)))
(defn- catch-handler [f x]
(let [[_ type var & body] x]
(cmp/with-lexical-scoping
(when var
(cmp/register-arg (with-meta var (merge (meta var) {:tag type}))))
(list* 'catch type var
(doall (map f body))))))
(defn- try-handler [f x]
(let [[_ & body] x]
(list* 'try (doall (map #(f % :try-clause? true) body)))))
(defn- dot-handler [f x]
(let [[_ hostexpr mem-or-meth & remainder] x]
(list* '.
(f hostexpr)
(if (seq? mem-or-meth)
(list* (first mem-or-meth)
(doall (map f (rest mem-or-meth))))
(f mem-or-meth))
(doall (map f remainder)))))
(defn walk-exprs
"A walk function which only traverses valid Clojure expressions. The `predicate` describes
whether the sub-form should be transformed. If it returns true, `handler` is invoked, and
returns a transformed form.
Unlike `clojure.walk`, if the handler is called, the rest of the sub-form is not walked.
The handler function is responsible for recursively calling `walk-exprs` on the form it is
given.
Macroexpansion can be halted by defining a set of `special-form?` which will be left alone.
Including `fn`, `let`, or other binding forms can break local variable analysis, so use
with caution.
The :try-clause? option indicates that a `try` clause is being walked. The special forms
`catch` and `finally` are only special in `try` clauses."
([predicate handler x]
(walk-exprs predicate handler nil x))
([predicate handler special-form? x & {:keys [try-clause?]}]
(cmp/with-base-env
(let [x (try
(macroexpand x special-form?)
(catch ClassNotFoundException _
x))
walk-exprs' (partial walk-exprs predicate handler special-form?)
x' (cond
(and (seq? x) (= 'var (first x)) (predicate x))
(handler (eval x))
(and (seq? x) (= 'quote (first x)) (not (predicate x)))
x
(predicate x)
(handler x)
(seq? x)
(if (or (and (not try-clause?)
(#{'catch 'finally} (first x)))
(not (contains? special-forms (first x))))
(doall (map walk-exprs' x))
((condp = (first x)
'do do-handler
'def def-handler
'fn* fn-handler
'let* let-handler
'loop* let-handler
'letfn* letfn-handler
'case* case-handler
'try try-handler
'catch catch-handler
'reify* reify-handler
'deftype* deftype-handler
'. dot-handler
#(doall (map %1 %2)))
walk-exprs' (special-meta x)))
(instance? java.util.Map$Entry x)
(clojure.lang.MapEntry.
(walk-exprs' (key x))
(walk-exprs' (val x)))
(or
(set? x)
(vector? x))
(into (empty x) (map walk-exprs' x))
(instance? clojure.lang.IRecord x)
x
(map? x)
(into (empty x) (map walk-exprs' x))
;; special case to handle clojure.test
(and (symbol? x) (-> x meta :test))
(vary-meta x update-in [:test] walk-exprs')
:else
x)]
(if (instance? clojure.lang.IObj x')
(with-meta x' (merge (meta x) (meta x')))
x')))))
;;;
(defn macroexpand-all
"Recursively macroexpands all forms, preserving the &env special variables."
[x]
(walk-exprs (constantly false) nil x))
(defn special-form?
"Given sym, a symbol produced by walk-exprs, returns true if sym is a special form."
[x]
(when (symbol? x) (::special (meta x))))
| null | https://raw.githubusercontent.com/ztellman/riddley/b5fe7c63ac9eaf55a23a855796d9bb7ee5f24567/src/riddley/walk.clj | clojure | might look like a macro, but for our purposes it isn't
if we can't macroexpand any further, check if it's an inlined function
unfortunately, static function calls can look a lot like what we just
expanded, so prevent infinite expansion
register a local for the function, if it's named
special case to handle clojure.test
| (ns riddley.walk
(:refer-clojure :exclude [macroexpand])
(:require
[riddley.compiler :as cmp]))
(defn macroexpand
"Expands both macros and inline functions. Optionally takes a `special-form?` predicate which
identifies first elements of expressions that shouldn't be macroexpanded, and honors local
bindings."
([x]
(macroexpand x nil))
([x special-form?]
(cmp/with-base-env
(if (seq? x)
(let [frst (first x)]
(if (or
(and special-form? (special-form? frst))
(contains? (cmp/locals) frst))
x
(let [x' (macroexpand-1 x)]
(if-not (identical? x x')
(macroexpand x' special-form?)
(if-let [inline-fn (and (seq? x')
(symbol? (first x'))
(-> x' meta ::transformed not)
(or
(-> x' first resolve meta :inline-arities not)
((-> x' first resolve meta :inline-arities)
(count (rest x'))))
(-> x' first resolve meta :inline))]
(let [x'' (with-meta (apply inline-fn (rest x')) (meta x'))]
(macroexpand
(if (= '. (first x''))
(with-meta
(concat (butlast x'')
[(if (instance? clojure.lang.IObj (last x''))
(with-meta (last x'')
(merge
(meta (last x''))
{::transformed true}))
(last x''))])
(meta x''))
x'')
special-form?))
x')))))
x))))
(def ^:private special-forms
(into #{} (keys (. clojure.lang.Compiler specials))))
(defn- special-meta [[op & body]]
(list* (vary-meta op assoc ::special true) body))
(defn- do-handler [f [_ & body]]
(list* 'do
(doall
(map f body))))
(defn- fn-handler [f x]
(let [prelude (take-while (complement sequential?) x)
remainder (drop (count prelude) x)
remainder (if (vector? (first remainder))
(list remainder) remainder)
body-handler (fn [x]
(cmp/with-lexical-scoping
(doseq [arg (first x)]
(cmp/register-arg arg))
(doall
(list* (first x)
(map f (rest x))))))]
(cmp/with-lexical-scoping
(when-let [nm (second prelude)]
(cmp/register-local nm
(list* 'fn* nm
(map #(take 1 %) remainder))))
(concat
prelude
(if (seq? (first remainder))
(doall (map body-handler remainder))
[(body-handler remainder)])))))
(defn- def-handler [f x]
(let [[_ n & r] x]
(cmp/with-lexical-scoping
(cmp/register-local n '())
(list* 'def (f n) (doall (map f r))))))
(defn- let-bindings [f x recursive?]
(let [pairs (partition-all 2 x)]
(when recursive?
(doall (map (fn [[k v]] (cmp/register-local k nil)) pairs)))
(->> pairs
(mapcat
(fn [[k v]]
(let [[k v] [k (f v)]]
(cmp/register-local k v)
[k v])))
vec)))
(defn- reify-handler [f x]
(let [[_ classes & fns] x]
(list* 'reify* classes
(doall
(map
(fn [[nm args & body]]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* nm args (doall (map f body)))))
fns)))))
(defn- deftype-handler [f x]
(let [[_ type resolved-type args _ interfaces & fns] x]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* 'deftype* type resolved-type args :implements interfaces
(doall
(map
(fn [[nm args & body]]
(cmp/with-lexical-scoping
(doseq [arg args]
(cmp/register-arg arg))
(list* nm args (doall (map f body)))))
fns))))))
(defn- let-handler
([f x]
(let-handler f x nil))
([f x recursive?]
(cmp/with-lexical-scoping
(doall
(list*
(first x)
(let-bindings f (second x) recursive?)
(map f (drop 2 x)))))))
(defn- letfn-handler [f x]
(let-handler f x true))
(defn- case-handler [f [_ ge shift mask default imap switch-type check-type skip-check]]
(let [prefix ['case* ge shift mask]
suffix [switch-type check-type skip-check]]
(concat
prefix
[(f default)]
[(let [m (->> imap
(map
(fn [[k [idx form]]]
[k [idx (f form)]]))
(into {}))]
(if (every? number? (keys m))
(into (sorted-map) m)
m))]
suffix)))
(defn- catch-handler [f x]
(let [[_ type var & body] x]
(cmp/with-lexical-scoping
(when var
(cmp/register-arg (with-meta var (merge (meta var) {:tag type}))))
(list* 'catch type var
(doall (map f body))))))
(defn- try-handler [f x]
(let [[_ & body] x]
(list* 'try (doall (map #(f % :try-clause? true) body)))))
(defn- dot-handler [f x]
(let [[_ hostexpr mem-or-meth & remainder] x]
(list* '.
(f hostexpr)
(if (seq? mem-or-meth)
(list* (first mem-or-meth)
(doall (map f (rest mem-or-meth))))
(f mem-or-meth))
(doall (map f remainder)))))
(defn walk-exprs
"A walk function which only traverses valid Clojure expressions. The `predicate` describes
whether the sub-form should be transformed. If it returns true, `handler` is invoked, and
returns a transformed form.
Unlike `clojure.walk`, if the handler is called, the rest of the sub-form is not walked.
The handler function is responsible for recursively calling `walk-exprs` on the form it is
given.
Macroexpansion can be halted by defining a set of `special-form?` which will be left alone.
Including `fn`, `let`, or other binding forms can break local variable analysis, so use
with caution.
The :try-clause? option indicates that a `try` clause is being walked. The special forms
`catch` and `finally` are only special in `try` clauses."
([predicate handler x]
(walk-exprs predicate handler nil x))
([predicate handler special-form? x & {:keys [try-clause?]}]
(cmp/with-base-env
(let [x (try
(macroexpand x special-form?)
(catch ClassNotFoundException _
x))
walk-exprs' (partial walk-exprs predicate handler special-form?)
x' (cond
(and (seq? x) (= 'var (first x)) (predicate x))
(handler (eval x))
(and (seq? x) (= 'quote (first x)) (not (predicate x)))
x
(predicate x)
(handler x)
(seq? x)
(if (or (and (not try-clause?)
(#{'catch 'finally} (first x)))
(not (contains? special-forms (first x))))
(doall (map walk-exprs' x))
((condp = (first x)
'do do-handler
'def def-handler
'fn* fn-handler
'let* let-handler
'loop* let-handler
'letfn* letfn-handler
'case* case-handler
'try try-handler
'catch catch-handler
'reify* reify-handler
'deftype* deftype-handler
'. dot-handler
#(doall (map %1 %2)))
walk-exprs' (special-meta x)))
(instance? java.util.Map$Entry x)
(clojure.lang.MapEntry.
(walk-exprs' (key x))
(walk-exprs' (val x)))
(or
(set? x)
(vector? x))
(into (empty x) (map walk-exprs' x))
(instance? clojure.lang.IRecord x)
x
(map? x)
(into (empty x) (map walk-exprs' x))
(and (symbol? x) (-> x meta :test))
(vary-meta x update-in [:test] walk-exprs')
:else
x)]
(if (instance? clojure.lang.IObj x')
(with-meta x' (merge (meta x) (meta x')))
x')))))
(defn macroexpand-all
"Recursively macroexpands all forms, preserving the &env special variables."
[x]
(walk-exprs (constantly false) nil x))
(defn special-form?
"Given sym, a symbol produced by walk-exprs, returns true if sym is a special form."
[x]
(when (symbol? x) (::special (meta x))))
|
511c801e292f8a298d5399005d9f58b2bd35bc7a041e0314e2de1260238b328b | tmfg/mmtis-national-access-point | admin.cljs | (ns ote.style.admin
"Admin panel styles"
(:require [stylefy.core :as stylefy]
[garden.units :refer [pt px em]]))
(def modal-data-label {:font-size "1.1em"
:color "#323232"
:font-weight "400"
:text-align "right"
:padding-right "20px"})
(def detection-button-container {:display "flex"
:flex-wrap "wrap"
:justify-content "flex-end"})
(def detection-info-text {:margin "0 0 0.5em 0"})
(def detection-button-with-input {:margin "0 0 0 2em"})
| null | https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/cljs/ote/style/admin.cljs | clojure | (ns ote.style.admin
"Admin panel styles"
(:require [stylefy.core :as stylefy]
[garden.units :refer [pt px em]]))
(def modal-data-label {:font-size "1.1em"
:color "#323232"
:font-weight "400"
:text-align "right"
:padding-right "20px"})
(def detection-button-container {:display "flex"
:flex-wrap "wrap"
:justify-content "flex-end"})
(def detection-info-text {:margin "0 0 0.5em 0"})
(def detection-button-with-input {:margin "0 0 0 2em"})
|
|
7679e2d22689746ca0fca1ee4ec7bfcea147d734cd855f1705ae8322e7d996c4 | graninas/The-Amoeba-World | View.hs | module Amoeba.View.View where
import Amoeba.View.Language
import Amoeba.View.Output.Types
import Amoeba.View.Output.Runtime
import Amoeba.View.Output.Utils
modifyView _ (StartViewPointMoving scrPt) view = view {runtimeVirtualPlainShift = Just (toUserViewPoint scrPt, toUserViewPoint scrPt)}
modifyView _ (ViewPointMoving scrPt) view@(Runtime _ _ mbShift) = let
point' = toUserViewPoint scrPt
in maybe view (\(shiftStart,_) -> view {runtimeVirtualPlainShift = Just (shiftStart, point')}) mbShift
modifyView _ (StopViewPointMoving scrPt) view@(Runtime a vPlane mbShift) = let
point' = toUserViewPoint scrPt
in maybe view (\(p1, p2) -> (Runtime a (vPlane +! p2 -! p1) Nothing)) mbShift
TODO !
modifyView _ viewCommand _ = error $ "modifyView: view command missing: " ++ show viewCommand | null | https://raw.githubusercontent.com/graninas/The-Amoeba-World/a147cd4dabf860bec8a6ae1c45c02b030916ddf4/src/Amoeba/View/View.hs | haskell | module Amoeba.View.View where
import Amoeba.View.Language
import Amoeba.View.Output.Types
import Amoeba.View.Output.Runtime
import Amoeba.View.Output.Utils
modifyView _ (StartViewPointMoving scrPt) view = view {runtimeVirtualPlainShift = Just (toUserViewPoint scrPt, toUserViewPoint scrPt)}
modifyView _ (ViewPointMoving scrPt) view@(Runtime _ _ mbShift) = let
point' = toUserViewPoint scrPt
in maybe view (\(shiftStart,_) -> view {runtimeVirtualPlainShift = Just (shiftStart, point')}) mbShift
modifyView _ (StopViewPointMoving scrPt) view@(Runtime a vPlane mbShift) = let
point' = toUserViewPoint scrPt
in maybe view (\(p1, p2) -> (Runtime a (vPlane +! p2 -! p1) Nothing)) mbShift
TODO !
modifyView _ viewCommand _ = error $ "modifyView: view command missing: " ++ show viewCommand |
|
ece3930a78c2b4b452544587afae783068af91e3312ebc821eeb08cb4939c035 | openbadgefactory/salava | my_test.clj | (ns salava.badge.my-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request test-user-credentials login! logout!]]))
(def test-user 1)
(def user-with-no-badges 3)
(def badge-id 1)
(facts "about user's badges"
(fact "user must be logged in"
(:status (test-api-request :get (str "/badge"))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user has two badges"
(let [{:keys [status body]} (test-api-request :get (str "/badge"))]
status => 200
(count body) => 2))
(fact "badge can be accepted"
(let [{:keys [status body]} (test-api-request :post (str "/badge/set_status/" badge-id) {:status "accepted"})]
status => 200
body => 1)
(let [{:keys [status body]} (test-api-request :get (str "/badge/info/" badge-id))]
status => 200
(:status body) => "accepted"))
(logout!)
(apply login! (test-user-credentials user-with-no-badges))
(fact "another user has no badges"
(let [{:keys [status body]} (test-api-request :get (str "/badge"))]
status => 200
(count body) => 0))
(logout!))
(migrator/reset-seeds (migrator/test-config)) | null | https://raw.githubusercontent.com/openbadgefactory/salava/97f05992406e4dcbe3c4bff75c04378d19606b61/test_old/clj/salava/badge/my_test.clj | clojure | (ns salava.badge.my-test
(:require [midje.sweet :refer :all]
[salava.core.migrator :as migrator]
[salava.test-utils :refer [test-api-request test-user-credentials login! logout!]]))
(def test-user 1)
(def user-with-no-badges 3)
(def badge-id 1)
(facts "about user's badges"
(fact "user must be logged in"
(:status (test-api-request :get (str "/badge"))) => 401)
(apply login! (test-user-credentials test-user))
(fact "user has two badges"
(let [{:keys [status body]} (test-api-request :get (str "/badge"))]
status => 200
(count body) => 2))
(fact "badge can be accepted"
(let [{:keys [status body]} (test-api-request :post (str "/badge/set_status/" badge-id) {:status "accepted"})]
status => 200
body => 1)
(let [{:keys [status body]} (test-api-request :get (str "/badge/info/" badge-id))]
status => 200
(:status body) => "accepted"))
(logout!)
(apply login! (test-user-credentials user-with-no-badges))
(fact "another user has no badges"
(let [{:keys [status body]} (test-api-request :get (str "/badge"))]
status => 200
(count body) => 0))
(logout!))
(migrator/reset-seeds (migrator/test-config)) |
|
25e64fa057e781f96208bb3aae29c60121cec3c7e03b6d3c5b7baeb9bdfd9671 | mtravers/wuwei | heroku-setup.lisp | (in-package :cl-user)
(print ">>> Building system....")
( asdf : clear - system " " )
;(asdf:clear-system "wuwei-examples")
(load (make-pathname :directory *build-dir* :defaults "wuwei.asd"))
This is NOT WORKING , and the build gets from Quicklisp . But that 's better than what it was doing before , which was using a completely obsolete version ... no fucking idea what is going on here .
(push (make-pathname :directory *build-dir*) asdf:*central-registry*)
(ql:quickload :wuwei-examples)
(print ">>> Done building system")
| null | https://raw.githubusercontent.com/mtravers/wuwei/c0968cca10554fa12567d48be6f932bf4418dbe1/heroku-setup.lisp | lisp | (asdf:clear-system "wuwei-examples") | (in-package :cl-user)
(print ">>> Building system....")
( asdf : clear - system " " )
(load (make-pathname :directory *build-dir* :defaults "wuwei.asd"))
This is NOT WORKING , and the build gets from Quicklisp . But that 's better than what it was doing before , which was using a completely obsolete version ... no fucking idea what is going on here .
(push (make-pathname :directory *build-dir*) asdf:*central-registry*)
(ql:quickload :wuwei-examples)
(print ">>> Done building system")
|
d8cfbac2bf131b3cc845941cd299f62e73d205f529fb73cc75f60218f8183591 | 3b/learnopengl | triangle1.lisp | using 3bgl - shader for lisp - like shaders starting here , rather than
;;; storing c-like shaders in strings
;; types are keywords named like the glsl versions, :vec4, :float, etc.
;; built-in functions and variables have mixedCase names converted to
;; lisp-style names, like glPosition -> gl-position
' swizzles ' are written like ( .xxyz foo ) instead of 's " foo.xxyz "
;; Types for globals (in/out/uniform/constant) must be specified,
;; while most types within functions are inferred from the types of
;; built-in functions and the types of the globals. In particular, a
;; single user-defined function can be used with any combination of
;; input/outputs that make sense for the body, and variants for each
;; combination used will be included automatically in the generated
;; glsl.
3bgl - shader has an API for defining shaders mixed in with normal
;;; lisp code, but easier to put it in its own package
(defpackage triangle1/shaders
(:use #:3bgl-glsl/cl)
;; shadow POSITION so we don't conflict with the default definition
of CL : POSITION as ( input position : vec4 : location 0 )
(:shadow position))
(in-package triangle1/shaders)
;;; "in" variables are defined with (input name type &key location stage)
;; "layout (location = x)" is specified as :LOCATION X
(input position :vec3 :location 0)
;; "out" variables use (output ...)
(output color :vec4)
;; we give normal names to the "main" function, so can put a bunch in
;; same file without having any conflicts
(defun vertex ()
(setf gl-position (vec4 position 1)))
(defun fragment ()
(setf color (vec4 1 0.5 0.2 1)))
;;;; back to normal lisp code
(in-package learning-opengl)
(defclass triangle1 (common1)
;; we need to track some state for the objects used to draw the
;; scene
((shader-program :initform nil :accessor shader-program)
(vao :initform nil :accessor vao)
(buffers :initform nil :accessor buffers)))
(defun triangle1-build-shader (stage entry-point &rest more-stages)
(let ((shader-program (gl:create-program)))
;;; build and compile our shader program
;; for each stage specified, create a shader, compile it and add
;; to SHADER-PROGRAM
(loop
for (stage entry-point) on (list* stage entry-point more-stages) by #'cddr
for shader = (gl:create-shader stage)
;; gl:shader-source accepts a string or list of strings. We use
3bgl - shader to compile lispy code into glsl in a string
do (gl:shader-source shader
(3bgl-shaders:generate-stage stage entry-point))
;;; try to compile the stage
(gl:compile-shader shader)
;; check for compile time errors. gl:get-shader returns a
;; boolean for :compile-status
(unless (gl:get-shader shader :compile-status)
;; and gl:get-shader-info-log returns a string directly
(format t "ERROR::SHADER::~:@(~a~)::COMPILATION_FAILED:~%~a~%"
stage (gl:get-shader-info-log shader)))
(gl:attach-shader shader-program shader)
we can tell GL to delete the shader once it is attached , GL
;; won't actually delete it until it is no longer attached to any
;; programs
(gl:delete-shader shader))
;;; link the shader program
(gl:link-program shader-program)
;; check for linking errors
(unless (gl:get-program shader-program :link-status)
(format t "ERROR::SHADER::PROGRAM::LINKING_FAILED:~%~a~%"
(gl:get-program-info-log shader-program)))
shader-program))
(defun triangle1-build-vao (w vertex-data)
cl - opengl has shortcuts to create 1 of most objects where the GL
;; API creates N at a time
(let ((vbo (gl:gen-buffer))
(vao (gl:gen-vertex-array)))
bind the Vertex Array Object first , then bind and set
;; vertex buffer(s) and attribute pointer(s)
(gl:bind-vertex-array vao)
(gl:bind-buffer :array-buffer vbo)
;; I usually use the low-level wrappers in %GL: for things like
;; vertex buffers. For that we need to pass the data as a
;; C-style pointer. The static-vectors library is an easy way to
;; get lisp data that can also be passed as a pointer to
non - lisp APIs like GL , so using that here . ( the other main
option is to manually manage the memory with CFFI 's api )
(static-vectors:with-static-vector (sv (length vertex-data)
;; for now assuming all floats
:element-type 'single-float)
(replace sv vertex-data)
(%gl:buffer-data :array-buffer
(* (length sv)
(cffi:foreign-type-size :float))
(static-vectors:static-vector-pointer sv)
:static-draw)
;; %gl since using the low-level API
(%gl:buffer-data :array-buffer
;; we do'nt have a convenient 'sizeof', so
;; need to calculate the number of octets we
are passing to GL manually
(* (length sv)
(cffi:foreign-type-size :float))
;; pass the pointer for the static-vector
array to GL
(static-vectors:static-vector-pointer sv)
:static-draw))
we pass / GL_FALSE as CL booleans
(gl:vertex-attrib-pointer 0 3 :float nil
(* 3 (cffi:foreign-type-size :float))
;; cl-opengl translates integers to
;; pointers for the functions like
;; this that accept either an
;; integer offset or a pointer
0)
(gl:enable-vertex-attrib-array 0)
;; Note that this is allowed, the call to
;; glVertexAttribPointer registered VBO as the currently bound
;; vertex buffer object so afterwards we can safely unbind
(gl:bind-buffer :array-buffer 0)
;; keep track of the VBO so we can delete it later
(push vbo (buffers w))
;; Unbind VAO (it's always a good thing to unbind any
;; buffer/array to prevent strange bugs)
(gl:bind-vertex-array 0)
return the vao
vao))
(defmethod init ((w triangle1))
(setf (shader-program w)
(triangle1-build-shader :vertex-shader 'triangle1/shaders::vertex
:fragment-shader 'triangle1/shaders::fragment))
(setf (vao w)
(triangle1-build-vao w '(-0.5 -0.5 0.0 ; Left
0.5 -0.5 0.0 ; Right
0.0 0.5 0.0) ; Top
)))
(defmethod cleanup ((w triangle1))
(gl:delete-buffers (buffers w))
(gl:delete-vertex-arrays (list (vao w)))
(gl:delete-program (shader-program w)))
(defmethod draw ((w triangle1))
draw our first triangle
(gl:use-program (shader-program w))
(gl:bind-vertex-array (vao w))
(gl:draw-arrays :triangles 0 3)
(gl:bind-vertex-array 0))
#++ (common 'triangle1)
| null | https://raw.githubusercontent.com/3b/learnopengl/30f910895ef336ac5ff0b4cc676af506413bb953/factored/triangle1.lisp | lisp | storing c-like shaders in strings
types are keywords named like the glsl versions, :vec4, :float, etc.
built-in functions and variables have mixedCase names converted to
lisp-style names, like glPosition -> gl-position
Types for globals (in/out/uniform/constant) must be specified,
while most types within functions are inferred from the types of
built-in functions and the types of the globals. In particular, a
single user-defined function can be used with any combination of
input/outputs that make sense for the body, and variants for each
combination used will be included automatically in the generated
glsl.
lisp code, but easier to put it in its own package
shadow POSITION so we don't conflict with the default definition
"in" variables are defined with (input name type &key location stage)
"layout (location = x)" is specified as :LOCATION X
"out" variables use (output ...)
we give normal names to the "main" function, so can put a bunch in
same file without having any conflicts
back to normal lisp code
we need to track some state for the objects used to draw the
scene
build and compile our shader program
for each stage specified, create a shader, compile it and add
to SHADER-PROGRAM
gl:shader-source accepts a string or list of strings. We use
try to compile the stage
check for compile time errors. gl:get-shader returns a
boolean for :compile-status
and gl:get-shader-info-log returns a string directly
won't actually delete it until it is no longer attached to any
programs
link the shader program
check for linking errors
API creates N at a time
vertex buffer(s) and attribute pointer(s)
I usually use the low-level wrappers in %GL: for things like
vertex buffers. For that we need to pass the data as a
C-style pointer. The static-vectors library is an easy way to
get lisp data that can also be passed as a pointer to
for now assuming all floats
%gl since using the low-level API
we do'nt have a convenient 'sizeof', so
need to calculate the number of octets we
pass the pointer for the static-vector
cl-opengl translates integers to
pointers for the functions like
this that accept either an
integer offset or a pointer
Note that this is allowed, the call to
glVertexAttribPointer registered VBO as the currently bound
vertex buffer object so afterwards we can safely unbind
keep track of the VBO so we can delete it later
Unbind VAO (it's always a good thing to unbind any
buffer/array to prevent strange bugs)
Left
Right
Top | using 3bgl - shader for lisp - like shaders starting here , rather than
' swizzles ' are written like ( .xxyz foo ) instead of 's " foo.xxyz "
3bgl - shader has an API for defining shaders mixed in with normal
(defpackage triangle1/shaders
(:use #:3bgl-glsl/cl)
of CL : POSITION as ( input position : vec4 : location 0 )
(:shadow position))
(in-package triangle1/shaders)
(input position :vec3 :location 0)
(output color :vec4)
(defun vertex ()
(setf gl-position (vec4 position 1)))
(defun fragment ()
(setf color (vec4 1 0.5 0.2 1)))
(in-package learning-opengl)
(defclass triangle1 (common1)
((shader-program :initform nil :accessor shader-program)
(vao :initform nil :accessor vao)
(buffers :initform nil :accessor buffers)))
(defun triangle1-build-shader (stage entry-point &rest more-stages)
(let ((shader-program (gl:create-program)))
(loop
for (stage entry-point) on (list* stage entry-point more-stages) by #'cddr
for shader = (gl:create-shader stage)
3bgl - shader to compile lispy code into glsl in a string
do (gl:shader-source shader
(3bgl-shaders:generate-stage stage entry-point))
(gl:compile-shader shader)
(unless (gl:get-shader shader :compile-status)
(format t "ERROR::SHADER::~:@(~a~)::COMPILATION_FAILED:~%~a~%"
stage (gl:get-shader-info-log shader)))
(gl:attach-shader shader-program shader)
we can tell GL to delete the shader once it is attached , GL
(gl:delete-shader shader))
(gl:link-program shader-program)
(unless (gl:get-program shader-program :link-status)
(format t "ERROR::SHADER::PROGRAM::LINKING_FAILED:~%~a~%"
(gl:get-program-info-log shader-program)))
shader-program))
(defun triangle1-build-vao (w vertex-data)
cl - opengl has shortcuts to create 1 of most objects where the GL
(let ((vbo (gl:gen-buffer))
(vao (gl:gen-vertex-array)))
bind the Vertex Array Object first , then bind and set
(gl:bind-vertex-array vao)
(gl:bind-buffer :array-buffer vbo)
non - lisp APIs like GL , so using that here . ( the other main
option is to manually manage the memory with CFFI 's api )
(static-vectors:with-static-vector (sv (length vertex-data)
:element-type 'single-float)
(replace sv vertex-data)
(%gl:buffer-data :array-buffer
(* (length sv)
(cffi:foreign-type-size :float))
(static-vectors:static-vector-pointer sv)
:static-draw)
(%gl:buffer-data :array-buffer
are passing to GL manually
(* (length sv)
(cffi:foreign-type-size :float))
array to GL
(static-vectors:static-vector-pointer sv)
:static-draw))
we pass / GL_FALSE as CL booleans
(gl:vertex-attrib-pointer 0 3 :float nil
(* 3 (cffi:foreign-type-size :float))
0)
(gl:enable-vertex-attrib-array 0)
(gl:bind-buffer :array-buffer 0)
(push vbo (buffers w))
(gl:bind-vertex-array 0)
return the vao
vao))
(defmethod init ((w triangle1))
(setf (shader-program w)
(triangle1-build-shader :vertex-shader 'triangle1/shaders::vertex
:fragment-shader 'triangle1/shaders::fragment))
(setf (vao w)
)))
(defmethod cleanup ((w triangle1))
(gl:delete-buffers (buffers w))
(gl:delete-vertex-arrays (list (vao w)))
(gl:delete-program (shader-program w)))
(defmethod draw ((w triangle1))
draw our first triangle
(gl:use-program (shader-program w))
(gl:bind-vertex-array (vao w))
(gl:draw-arrays :triangles 0 3)
(gl:bind-vertex-array 0))
#++ (common 'triangle1)
|
833d85aab78b388147d7f12684e770036697ac55628da6db77a27638e55ba843 | jkrivine/tl_interpreter | ledger.ml | open Tools
(** Syntactic sugar *)
open Env.Imp.Program
module MP = MP
module SP = SP
module A = Address
type token = A.t
type pos = A.t
type amount = int
(*type t = {map : ((A.t * string * token),amount) MP.t ; zcrossings : int; zwrapping: bool}*)
type t = {map : (A.t,((string * token),amount) MP.t) MP.t ; zcrossings : int; zwrapping: bool}
let solvent hk =
let {zcrossings;_} = data_get hk in
return (zcrossings = 0)
let zwrap_start hk =
data_update hk (fun l -> {l with zwrapping = true})
let zwrap_end hk =
data_update hk (fun l -> {l with zwrapping = false}) ;
if solvent hk
then return ()
else error "ledger is not solvent"
let is_zwrapping hk =
let {zwrapping;_} = data_get hk in
return zwrapping
let find m (a,s,t) =
return Base.Option.((MP.find m a) >>= fun m -> MP.find m (s,t))
let set m (a,s,t) v =
MP.update m a (fun m ->
let m' = m |? MP.empty in
MP.set m' (s,t) v)
let find_exn hk k =
match find hk k with
| Some e -> return e
| None -> error "not found"
[@@ocaml.warning "-32"]
let balance hk (who:A.t) ?(index="") (tk:token) =
return (find (data_get hk).map (who,index,tk) |? 0)
let add hk (who:A.t) ?(index="") (tk:token) (a:amount) =
let v = balance hk who ~index tk in
data_update hk (fun l ->
let z = l.zcrossings in
let modifier = if (a+v<0 && v>=0) then 1 else if (a+v>=0 && v<0) then (-1) else 0 in
{l with map = set l.map (who,index,tk) (a+v);zcrossings = (z+modifier)}) ;
let {zwrapping;_} = data_get hk in
if zwrapping
then return ()
else zwrap_end hk
let transfer hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (a:amount) (taker:A.t) =
add hk giver ~index:i1 tk (-a) ; add hk taker ~index:i2 tk a
let transfer_up_to hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (a:amount) (taker:A.t) =
let b = balance hk giver ~index:i1 tk in
transfer hk giver ~indices:(i1,i2) tk (min a b) taker
let transfer_all hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (taker:A.t) =
let a = balance hk giver ~index:i1 tk in
transfer hk giver ~indices:(i1,i2) tk a taker
let pp_custom fmt l f =
let printer fmt addr m' =
let printer' fmt (index,tk) amount =
f fmt addr index tk amount in
MP.pp_i fmt printer' m' in
MP.pp_i fmt printer l.map
let pp fmt l =
F.p fmt "(%d zcrossings, zwrapping: %b)" l.zcrossings l.zwrapping;
pp_custom fmt l (fun fmt addr index tk amount ->
let index_str = if index = "" then "" else ("."^index) in
F.cr (); F.p fmt "%a%s has %d %a" A.pp addr index_str amount A.pp tk)
let empty = { map = MP.empty; zcrossings = 0; zwrapping = false}
module Offchain = struct
let iter_address_i hk (who:A.t) ?(index="") f =
let {map;_} = data_get hk in
match MP.find map who with
| None -> ()
| Some map' ->
MP.iteri map' (fun (index',token) amount ->
if index = index' then f token amount else ())
let restrict hk f =
let l = data_get hk in
let map = MP.filter l.map @@ fun o m' -> f o m' in
data_set hk {l with map}
let update hk f =
let l = data_get hk in
let map = MP.map l.map @@ fun owner m' ->
MP.map m' @@ fun (index,token) amount -> f (owner,index,token) amount
in data_set hk {l with map}
end
| null | https://raw.githubusercontent.com/jkrivine/tl_interpreter/c967c6578dd4491a6930c9842a0709fbc5939496/lib/tooling/ledger.ml | ocaml | * Syntactic sugar
type t = {map : ((A.t * string * token),amount) MP.t ; zcrossings : int; zwrapping: bool} | open Tools
open Env.Imp.Program
module MP = MP
module SP = SP
module A = Address
type token = A.t
type pos = A.t
type amount = int
type t = {map : (A.t,((string * token),amount) MP.t) MP.t ; zcrossings : int; zwrapping: bool}
let solvent hk =
let {zcrossings;_} = data_get hk in
return (zcrossings = 0)
let zwrap_start hk =
data_update hk (fun l -> {l with zwrapping = true})
let zwrap_end hk =
data_update hk (fun l -> {l with zwrapping = false}) ;
if solvent hk
then return ()
else error "ledger is not solvent"
let is_zwrapping hk =
let {zwrapping;_} = data_get hk in
return zwrapping
let find m (a,s,t) =
return Base.Option.((MP.find m a) >>= fun m -> MP.find m (s,t))
let set m (a,s,t) v =
MP.update m a (fun m ->
let m' = m |? MP.empty in
MP.set m' (s,t) v)
let find_exn hk k =
match find hk k with
| Some e -> return e
| None -> error "not found"
[@@ocaml.warning "-32"]
let balance hk (who:A.t) ?(index="") (tk:token) =
return (find (data_get hk).map (who,index,tk) |? 0)
let add hk (who:A.t) ?(index="") (tk:token) (a:amount) =
let v = balance hk who ~index tk in
data_update hk (fun l ->
let z = l.zcrossings in
let modifier = if (a+v<0 && v>=0) then 1 else if (a+v>=0 && v<0) then (-1) else 0 in
{l with map = set l.map (who,index,tk) (a+v);zcrossings = (z+modifier)}) ;
let {zwrapping;_} = data_get hk in
if zwrapping
then return ()
else zwrap_end hk
let transfer hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (a:amount) (taker:A.t) =
add hk giver ~index:i1 tk (-a) ; add hk taker ~index:i2 tk a
let transfer_up_to hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (a:amount) (taker:A.t) =
let b = balance hk giver ~index:i1 tk in
transfer hk giver ~indices:(i1,i2) tk (min a b) taker
let transfer_all hk (giver:A.t) ?indices:((i1,i2)=("","")) (tk:token) (taker:A.t) =
let a = balance hk giver ~index:i1 tk in
transfer hk giver ~indices:(i1,i2) tk a taker
let pp_custom fmt l f =
let printer fmt addr m' =
let printer' fmt (index,tk) amount =
f fmt addr index tk amount in
MP.pp_i fmt printer' m' in
MP.pp_i fmt printer l.map
let pp fmt l =
F.p fmt "(%d zcrossings, zwrapping: %b)" l.zcrossings l.zwrapping;
pp_custom fmt l (fun fmt addr index tk amount ->
let index_str = if index = "" then "" else ("."^index) in
F.cr (); F.p fmt "%a%s has %d %a" A.pp addr index_str amount A.pp tk)
let empty = { map = MP.empty; zcrossings = 0; zwrapping = false}
module Offchain = struct
let iter_address_i hk (who:A.t) ?(index="") f =
let {map;_} = data_get hk in
match MP.find map who with
| None -> ()
| Some map' ->
MP.iteri map' (fun (index',token) amount ->
if index = index' then f token amount else ())
let restrict hk f =
let l = data_get hk in
let map = MP.filter l.map @@ fun o m' -> f o m' in
data_set hk {l with map}
let update hk f =
let l = data_get hk in
let map = MP.map l.map @@ fun owner m' ->
MP.map m' @@ fun (index,token) amount -> f (owner,index,token) amount
in data_set hk {l with map}
end
|
7c1cc4462d817ba498ab9d426ea9270ec16a35d71bfce9e068f1e49ac345ad6f | zadean/xqerl | fn_parse_xml_SUITE.erl | -module('fn_parse_xml_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['parse-xml-001'/1]).
-export(['parse-xml-002'/1]).
-export(['parse-xml-003'/1]).
-export(['parse-xml-004'/1]).
-export(['parse-xml-005'/1]).
-export(['parse-xml-006'/1]).
-export(['parse-xml-007'/1]).
-export(['parse-xml-008'/1]).
-export(['parse-xml-009'/1]).
-export(['parse-xml-010'/1]).
-export(['parse-xml-011'/1]).
-export(['parse-xml-012'/1]).
-export(['parse-xml-013'/1]).
-export(['parse-xml-014'/1]).
-export(['parse-xml-015'/1]).
-export(['parse-xml-016'/1]).
-export(['parse-xml-017'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0}
].
groups() ->
[
{group_0, [parallel], [
'parse-xml-001',
'parse-xml-002',
'parse-xml-003',
'parse-xml-004',
'parse-xml-005',
'parse-xml-006',
'parse-xml-007',
'parse-xml-008',
'parse-xml-009',
'parse-xml-010',
'parse-xml-011',
'parse-xml-012',
'parse-xml-013',
'parse-xml-014',
'parse-xml-015',
'parse-xml-016',
'parse-xml-017'
]}
].
environment('empty', __BaseDir) ->
[
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'parse-xml-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"))",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-001.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_type(Res, "document-node(element(*,xs:untyped))") of
true -> {comment, "Correct type"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"),'###/atomic.xml')",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-002.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"),'file:/test/fots/../docs/atomic.xml')",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-003.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>Test123\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-004.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-005.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><!DOCTYPE a [<!ELEMENT a (#PCDATA)>]><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-006.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "base-uri(parse-xml(\"<a>foo</a>\")) eq static-base-uri()",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-007.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<!DOCTYPE a SYSTEM 'parse-xml/a.dtd'><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-008.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><!DOCTYPE a SYSTEM 'parse-xml/a.dtd'><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-009.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<!DOCTYPE a [<!ELEMENT a (#PCDATA)><!ENTITY foo SYSTEM 'parse-xml/foo.entity'>]><a>\" ||\n"
" codepoints-to-string(38) || \"foo;</a>\")\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-010.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a><bar>baz</bar></a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "document-uri(parse-xml(\"<a>foo</a>\"))",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-011.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>foo</a>\") is parse-xml(\"<a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-012.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<!DOCTYPE a [<!ELEMENT a (#PCDATA)>]><a><b/></a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-013.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_xml(Res, "<a><b/></a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-014.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_type(Res, "document-node()") of
true -> {comment, "Correct type"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<p:a/>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-015.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(())",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-016.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" parse-xml(\"<a/>\"[current-date() lt xs:date('1900-01-01')])\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-017.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
| null | https://raw.githubusercontent.com/zadean/xqerl/1a94833e996435495922346010ce918b4b0717f2/test/fn/fn_parse_xml_SUITE.erl | erlang | -module('fn_parse_xml_SUITE').
-include_lib("common_test/include/ct.hrl").
-export([
all/0,
groups/0,
suite/0
]).
-export([
init_per_suite/1,
init_per_group/2,
end_per_group/2,
end_per_suite/1
]).
-export(['parse-xml-001'/1]).
-export(['parse-xml-002'/1]).
-export(['parse-xml-003'/1]).
-export(['parse-xml-004'/1]).
-export(['parse-xml-005'/1]).
-export(['parse-xml-006'/1]).
-export(['parse-xml-007'/1]).
-export(['parse-xml-008'/1]).
-export(['parse-xml-009'/1]).
-export(['parse-xml-010'/1]).
-export(['parse-xml-011'/1]).
-export(['parse-xml-012'/1]).
-export(['parse-xml-013'/1]).
-export(['parse-xml-014'/1]).
-export(['parse-xml-015'/1]).
-export(['parse-xml-016'/1]).
-export(['parse-xml-017'/1]).
suite() -> [{timetrap, {seconds, 180}}].
init_per_group(_, Config) -> Config.
end_per_group(_, _Config) ->
xqerl_code_server:unload(all).
end_per_suite(_Config) ->
ct:timetrap({seconds, 60}),
xqerl_code_server:unload(all).
init_per_suite(Config) ->
{ok, _} = application:ensure_all_started(xqerl),
DD = filename:dirname(filename:dirname(filename:dirname(?config(data_dir, Config)))),
TD = filename:join(DD, "QT3-test-suite"),
__BaseDir = filename:join(TD, "fn"),
[{base_dir, __BaseDir} | Config].
all() ->
[
{group, group_0}
].
groups() ->
[
{group_0, [parallel], [
'parse-xml-001',
'parse-xml-002',
'parse-xml-003',
'parse-xml-004',
'parse-xml-005',
'parse-xml-006',
'parse-xml-007',
'parse-xml-008',
'parse-xml-009',
'parse-xml-010',
'parse-xml-011',
'parse-xml-012',
'parse-xml-013',
'parse-xml-014',
'parse-xml-015',
'parse-xml-016',
'parse-xml-017'
]}
].
environment('empty', __BaseDir) ->
[
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{params, []},
{vars, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
].
'parse-xml-001'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"))",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-001.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_type(Res, "document-node(element(*,xs:untyped))") of
true -> {comment, "Correct type"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-002'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"),'###/atomic.xml')",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-002.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-003'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(unparsed-text(\"../docs/atomic.xml\"),'file:/test/fots/../docs/atomic.xml')",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-003.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "XPST0017") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: XPST0017 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-004'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>Test123\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-004.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-005'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-005.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-006'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><!DOCTYPE a [<!ELEMENT a (#PCDATA)>]><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-006.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-007'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "base-uri(parse-xml(\"<a>foo</a>\")) eq static-base-uri()",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-007.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-008'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<!DOCTYPE a SYSTEM 'parse-xml/a.dtd'><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-008.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-009'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<?xml version='1.0' encoding='iso-8859-1'?><!DOCTYPE a SYSTEM 'parse-xml/a.dtd'><a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-009.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a>foo</a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-010'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"parse-xml(\"<!DOCTYPE a [<!ELEMENT a (#PCDATA)><!ENTITY foo SYSTEM 'parse-xml/foo.entity'>]><a>\" ||\n"
" codepoints-to-string(38) || \"foo;</a>\")\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-010.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_xml(Res, "<a><bar>baz</bar></a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-011'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "document-uri(parse-xml(\"<a>foo</a>\"))",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-011.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-012'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>foo</a>\") is parse-xml(\"<a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-012.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_true(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case xqerl_test:assert_false(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-013'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<!DOCTYPE a [<!ELEMENT a (#PCDATA)>]><a><b/></a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-013.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case
lists:any(
fun
({comment, _}) -> true;
(_) -> false
end,
[
case xqerl_test:assert_xml(Res, "<a><b/></a>") of
true -> {comment, "XML Deep equal"};
{false, F} -> F
end,
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end
]
)
of
true -> {comment, "any-of"};
_ -> false
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-014'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<a>foo</a>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-014.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_type(Res, "document-node()") of
true -> {comment, "Correct type"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-015'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(\"<p:a/>\")",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-015.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_error(Res, "FODC0006") of
true -> {comment, "Correct error"};
{true, F} -> {comment, "WE: FODC0006 " ++ binary_to_list(F)};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-016'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry = "parse-xml(())",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-016.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
'parse-xml-017'(Config) ->
__BaseDir = ?config(base_dir, Config),
Qry =
"\n"
" parse-xml(\"<a/>\"[current-date() lt xs:date('1900-01-01')])\n"
" ",
{Env, Opts} = xqerl_test:handle_environment([
{'decimal-formats', []},
{sources, []},
{collections, []},
{'static-base-uri', []},
{'context-item', [""]},
{vars, []},
{params, []},
{namespaces, []},
{schemas, []},
{resources, []},
{modules, []}
]),
Qry1 = lists:flatten(Env ++ Qry),
io:format("Qry1: ~p~n", [Qry1]),
Res =
try
Mod = xqerl_code_server:compile(filename:join(__BaseDir, "parse-xml-017.xq"), Qry1),
xqerl:run(Mod, Opts)
of
D -> D
catch
_:E -> E
end,
Out =
case xqerl_test:assert_empty(Res) of
true -> {comment, "Empty"};
{false, F} -> F
end,
case Out of
{comment, C} -> {comment, C};
Err -> ct:fail(Err)
end.
|
|
77d0efa7d65f60f8014a1e83ee0854cde7666e98a4121e3f6ecede95f6a5d552 | mpickering/apply-refact | Default46.hs | h a = flip f x $ y z | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default46.hs | haskell | h a = flip f x $ y z |
|
998d9b4183246fbf42570e74df869550cba59dfd339d7b45097ce92acae034a2 | input-output-hk/plutus | Hedgehog.hs | -- | Reexports from modules from the @PlutusCore.Generators.Internal@ folder.
module PlutusCore.Generators.Hedgehog
( module Export
) where
import PlutusCore.Generators.Hedgehog.Builtin as Export
import PlutusCore.Generators.Hedgehog.Denotation as Export
import PlutusCore.Generators.Hedgehog.Entity as Export
import PlutusCore.Generators.Hedgehog.TypedBuiltinGen as Export
import PlutusCore.Generators.Hedgehog.TypeEvalCheck as Export
import PlutusCore.Generators.Hedgehog.Utils as Export
| null | https://raw.githubusercontent.com/input-output-hk/plutus/867fd234301d28525404de839d9a3c8220cbea63/plutus-core/testlib/PlutusCore/Generators/Hedgehog.hs | haskell | | Reexports from modules from the @PlutusCore.Generators.Internal@ folder. |
module PlutusCore.Generators.Hedgehog
( module Export
) where
import PlutusCore.Generators.Hedgehog.Builtin as Export
import PlutusCore.Generators.Hedgehog.Denotation as Export
import PlutusCore.Generators.Hedgehog.Entity as Export
import PlutusCore.Generators.Hedgehog.TypedBuiltinGen as Export
import PlutusCore.Generators.Hedgehog.TypeEvalCheck as Export
import PlutusCore.Generators.Hedgehog.Utils as Export
|
3e96272a5b3a4f1932b3e96ee0a5e264d2f4f69f02546c593a87ce682d203ca0 | ocaml-ppx/ppx | ppx_driver_runner.ml | Ppx.Driver.standalone ()
| null | https://raw.githubusercontent.com/ocaml-ppx/ppx/40e5a35a4386d969effaf428078c900bd03b78ec/runner/ppx_driver_runner.ml | ocaml | Ppx.Driver.standalone ()
|
|
9d01190e9c5e12270a77b45892140a03dc8c421ea5bd7c053371fff7e212fcb4 | scrintal/heroicons-reagent | plus_small.cljs | (ns com.scrintal.heroicons.solid.plus-small)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M12 5.25a.75.75 0 01.75.75v5.25H18a.75.75 0 010 1.5h-5.25V18a.75.75 0 01-1.5 0v-5.25H6a.75.75 0 010-1.5h5.25V6a.75.75 0 01.75-.75z"
:clipRule "evenodd"}]]) | null | https://raw.githubusercontent.com/scrintal/heroicons-reagent/572f51d2466697ec4d38813663ee2588960365b6/src/com/scrintal/heroicons/solid/plus_small.cljs | clojure | (ns com.scrintal.heroicons.solid.plus-small)
(defn render []
[:svg {:xmlns ""
:viewBox "0 0 24 24"
:fill "currentColor"
:aria-hidden "true"}
[:path {:fillRule "evenodd"
:d "M12 5.25a.75.75 0 01.75.75v5.25H18a.75.75 0 010 1.5h-5.25V18a.75.75 0 01-1.5 0v-5.25H6a.75.75 0 010-1.5h5.25V6a.75.75 0 01.75-.75z"
:clipRule "evenodd"}]]) |
|
279858bdd1d4f5f50be94a8ce200c7834123d97afc72de90156c46a711f93ed2 | ml4tp/tcoq | okey.ml | (*********************************************************************************)
Cameleon
(* *)
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
(* en Automatique. All rights reserved. *)
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
(* License, or 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 Library General Public License for more details .
(* *)
You should have received a copy of the GNU Library 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
(* *)
(* Contact: *)
(* *)
(*********************************************************************************)
type modifier = Gdk.Tags.modifier
type handler = {
cond : (unit -> bool) ;
cback : (unit -> unit) ;
}
type handler_spec = int * int * Gdk.keysym
(** mods * mask * key *)
let int_of_modifier = function
`SHIFT -> 1
| `LOCK -> 2
| `CONTROL -> 4
| `MOD1 -> 8
| `MOD2 -> 16
| `MOD3 -> 32
| `MOD4 -> 64
| `MOD5 -> 128
| `BUTTON1 -> 256
| `BUTTON2 -> 512
| `BUTTON3 -> 1024
| `BUTTON4 -> 2048
| `BUTTON5 -> 4096
| `HYPER -> 1 lsl 22
| `META -> 1 lsl 20
| `RELEASE -> 1 lsl 30
| `SUPER -> 1 lsl 21
let int_of_modifiers l =
List.fold_left (fun acc -> fun m -> acc + (int_of_modifier m)) 0 l
module H =
struct
type t = handler_spec * handler
let equal (m,k) (mods, mask, key) =
(k = key) && ((m land mask) = mods)
let filter_with_mask mods mask key l =
List.filter (fun a -> (fst a) <> (mods, mask, key)) l
let find_handlers mods key l =
List.map snd
(List.filter
(fun ((m,ma,k),_) -> equal (mods,key) (m,ma,k))
l
)
end
let (table : (int, H.t list ref) Hashtbl.t) = Hashtbl.create 13
let key_press w ev =
let key = GdkEvent.Key.keyval ev in
let modifiers = GdkEvent.Key.state ev in
try
let (r : H.t list ref) = Hashtbl.find table (Oo.id w) in
let l = H.find_handlers (int_of_modifiers modifiers) key !r in
match l with
[] -> false
| _ ->
List.iter
(fun h ->
if h.cond () then
try h.cback ()
with e -> Minilib.log (Printexc.to_string e)
else ()
)
l;
true
with
Not_found ->
false
let associate_key_press w =
ignore ((w#event#connect#key_press ~callback: (key_press w)) : GtkSignal.id)
let default_modifiers = ref ([] : modifier list)
let default_mask = ref ([`MOD2 ; `MOD3 ; `MOD4 ; `MOD5 ; `LOCK] : modifier list)
let set_default_modifiers l = default_modifiers := l
let set_default_mask l = default_mask := l
let remove_widget (w : < event : GObj.event_ops ; ..>) () =
try
let r = Hashtbl.find table (Oo.id w) in
r := []
with
Not_found ->
()
let add1 ?(remove=false) w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
let r =
try Hashtbl.find table (Oo.id w)
with Not_found ->
let r = ref [] in
Hashtbl.add table (Oo.id w) r;
ignore (w#connect#destroy ~callback: (remove_widget w));
associate_key_press w;
r
in
let n_mods = int_of_modifiers mods in
let n_mask = lnot (int_of_modifiers mask) in
let new_h = { cond = cond ; cback = callback } in
if remove then
(
let l = H.filter_with_mask n_mods n_mask k !r in
r := ((n_mods, n_mask, k), new_h) :: l
)
else
r := ((n_mods, n_mask, k), new_h) :: !r
let add w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
add1 w ~cond ~mods ~mask k callback
let add_list w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k_list callback =
List.iter (fun k -> add w ~cond ~mods ~mask k callback) k_list
let set w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
add1 ~remove: true w ~cond ~mods ~mask k callback
let set_list w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k_list callback =
List.iter (fun k -> set w ~cond ~mods ~mask k callback) k_list
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/ide/utils/okey.ml | ocaml | *******************************************************************************
en Automatique. All rights reserved.
This program is free software; you can redistribute it and/or modify
License, or 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
Contact:
*******************************************************************************
* mods * mask * key | Cameleon
Copyright ( C ) 2005 Institut National de Recherche en Informatique et
it under the terms of the GNU Library General Public License as
published by the Free Software Foundation ; either version 2 of the
GNU Library General Public License for more details .
You should have received a copy of the GNU Library 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
type modifier = Gdk.Tags.modifier
type handler = {
cond : (unit -> bool) ;
cback : (unit -> unit) ;
}
type handler_spec = int * int * Gdk.keysym
let int_of_modifier = function
`SHIFT -> 1
| `LOCK -> 2
| `CONTROL -> 4
| `MOD1 -> 8
| `MOD2 -> 16
| `MOD3 -> 32
| `MOD4 -> 64
| `MOD5 -> 128
| `BUTTON1 -> 256
| `BUTTON2 -> 512
| `BUTTON3 -> 1024
| `BUTTON4 -> 2048
| `BUTTON5 -> 4096
| `HYPER -> 1 lsl 22
| `META -> 1 lsl 20
| `RELEASE -> 1 lsl 30
| `SUPER -> 1 lsl 21
let int_of_modifiers l =
List.fold_left (fun acc -> fun m -> acc + (int_of_modifier m)) 0 l
module H =
struct
type t = handler_spec * handler
let equal (m,k) (mods, mask, key) =
(k = key) && ((m land mask) = mods)
let filter_with_mask mods mask key l =
List.filter (fun a -> (fst a) <> (mods, mask, key)) l
let find_handlers mods key l =
List.map snd
(List.filter
(fun ((m,ma,k),_) -> equal (mods,key) (m,ma,k))
l
)
end
let (table : (int, H.t list ref) Hashtbl.t) = Hashtbl.create 13
let key_press w ev =
let key = GdkEvent.Key.keyval ev in
let modifiers = GdkEvent.Key.state ev in
try
let (r : H.t list ref) = Hashtbl.find table (Oo.id w) in
let l = H.find_handlers (int_of_modifiers modifiers) key !r in
match l with
[] -> false
| _ ->
List.iter
(fun h ->
if h.cond () then
try h.cback ()
with e -> Minilib.log (Printexc.to_string e)
else ()
)
l;
true
with
Not_found ->
false
let associate_key_press w =
ignore ((w#event#connect#key_press ~callback: (key_press w)) : GtkSignal.id)
let default_modifiers = ref ([] : modifier list)
let default_mask = ref ([`MOD2 ; `MOD3 ; `MOD4 ; `MOD5 ; `LOCK] : modifier list)
let set_default_modifiers l = default_modifiers := l
let set_default_mask l = default_mask := l
let remove_widget (w : < event : GObj.event_ops ; ..>) () =
try
let r = Hashtbl.find table (Oo.id w) in
r := []
with
Not_found ->
()
let add1 ?(remove=false) w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
let r =
try Hashtbl.find table (Oo.id w)
with Not_found ->
let r = ref [] in
Hashtbl.add table (Oo.id w) r;
ignore (w#connect#destroy ~callback: (remove_widget w));
associate_key_press w;
r
in
let n_mods = int_of_modifiers mods in
let n_mask = lnot (int_of_modifiers mask) in
let new_h = { cond = cond ; cback = callback } in
if remove then
(
let l = H.filter_with_mask n_mods n_mask k !r in
r := ((n_mods, n_mask, k), new_h) :: l
)
else
r := ((n_mods, n_mask, k), new_h) :: !r
let add w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
add1 w ~cond ~mods ~mask k callback
let add_list w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k_list callback =
List.iter (fun k -> add w ~cond ~mods ~mask k callback) k_list
let set w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k callback =
add1 ~remove: true w ~cond ~mods ~mask k callback
let set_list w
?(cond=(fun () -> true))
?(mods= !default_modifiers)
?(mask= !default_mask)
k_list callback =
List.iter (fun k -> set w ~cond ~mods ~mask k callback) k_list
|
b9e3ca248fdac9004fe991777316cf4bcddca7a0d39b3e6a6083bfd732cc733c | Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library | TreasuryTransactionsResourceBalanceImpact.hs | {-# LANGUAGE MultiWayIf #-}
CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
{-# LANGUAGE OverloadedStrings #-}
| Contains the types generated from the schema TreasuryTransactionsResourceBalanceImpact
module StripeAPI.Types.TreasuryTransactionsResourceBalanceImpact where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
-- | Defines the object schema located at @components.schemas.treasury_transactions_resource_balance_impact@ in the specification.
--
-- Change to a FinancialAccount\'s balance
data TreasuryTransactionsResourceBalanceImpact = TreasuryTransactionsResourceBalanceImpact
{ -- | cash: The change made to funds the user can spend right now.
treasuryTransactionsResourceBalanceImpactCash :: GHC.Types.Int,
-- | inbound_pending: The change made to funds that are not spendable yet, but will become available at a later time.
treasuryTransactionsResourceBalanceImpactInboundPending :: GHC.Types.Int,
-- | outbound_pending: The change made to funds in the account, but not spendable because they are being held for pending outbound flows.
treasuryTransactionsResourceBalanceImpactOutboundPending :: GHC.Types.Int
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON TreasuryTransactionsResourceBalanceImpact where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["cash" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactCash obj] : ["inbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactInboundPending obj] : ["outbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactOutboundPending obj] : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["cash" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactCash obj] : ["inbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactInboundPending obj] : ["outbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactOutboundPending obj] : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON TreasuryTransactionsResourceBalanceImpact where
parseJSON = Data.Aeson.Types.FromJSON.withObject "TreasuryTransactionsResourceBalanceImpact" (\obj -> ((GHC.Base.pure TreasuryTransactionsResourceBalanceImpact GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "cash")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "inbound_pending")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "outbound_pending"))
-- | Create a new 'TreasuryTransactionsResourceBalanceImpact' with all required fields.
mkTreasuryTransactionsResourceBalanceImpact ::
-- | 'treasuryTransactionsResourceBalanceImpactCash'
GHC.Types.Int ->
-- | 'treasuryTransactionsResourceBalanceImpactInboundPending'
GHC.Types.Int ->
-- | 'treasuryTransactionsResourceBalanceImpactOutboundPending'
GHC.Types.Int ->
TreasuryTransactionsResourceBalanceImpact
mkTreasuryTransactionsResourceBalanceImpact treasuryTransactionsResourceBalanceImpactCash treasuryTransactionsResourceBalanceImpactInboundPending treasuryTransactionsResourceBalanceImpactOutboundPending =
TreasuryTransactionsResourceBalanceImpact
{ treasuryTransactionsResourceBalanceImpactCash = treasuryTransactionsResourceBalanceImpactCash,
treasuryTransactionsResourceBalanceImpactInboundPending = treasuryTransactionsResourceBalanceImpactInboundPending,
treasuryTransactionsResourceBalanceImpactOutboundPending = treasuryTransactionsResourceBalanceImpactOutboundPending
}
| null | https://raw.githubusercontent.com/Haskell-OpenAPI-Code-Generator/Stripe-Haskell-Library/ba4401f083ff054f8da68c741f762407919de42f/src/StripeAPI/Types/TreasuryTransactionsResourceBalanceImpact.hs | haskell | # LANGUAGE MultiWayIf #
# LANGUAGE OverloadedStrings #
| Defines the object schema located at @components.schemas.treasury_transactions_resource_balance_impact@ in the specification.
Change to a FinancialAccount\'s balance
| cash: The change made to funds the user can spend right now.
| inbound_pending: The change made to funds that are not spendable yet, but will become available at a later time.
| outbound_pending: The change made to funds in the account, but not spendable because they are being held for pending outbound flows.
| Create a new 'TreasuryTransactionsResourceBalanceImpact' with all required fields.
| 'treasuryTransactionsResourceBalanceImpactCash'
| 'treasuryTransactionsResourceBalanceImpactInboundPending'
| 'treasuryTransactionsResourceBalanceImpactOutboundPending' | CHANGE WITH CAUTION : This is a generated code file generated by -OpenAPI-Code-Generator/Haskell-OpenAPI-Client-Code-Generator .
| Contains the types generated from the schema TreasuryTransactionsResourceBalanceImpact
module StripeAPI.Types.TreasuryTransactionsResourceBalanceImpact where
import qualified Control.Monad.Fail
import qualified Data.Aeson
import qualified Data.Aeson as Data.Aeson.Encoding.Internal
import qualified Data.Aeson as Data.Aeson.Types
import qualified Data.Aeson as Data.Aeson.Types.FromJSON
import qualified Data.Aeson as Data.Aeson.Types.Internal
import qualified Data.Aeson as Data.Aeson.Types.ToJSON
import qualified Data.ByteString.Char8
import qualified Data.ByteString.Char8 as Data.ByteString.Internal
import qualified Data.Foldable
import qualified Data.Functor
import qualified Data.Maybe
import qualified Data.Scientific
import qualified Data.Text
import qualified Data.Text.Internal
import qualified Data.Time.Calendar as Data.Time.Calendar.Days
import qualified Data.Time.LocalTime as Data.Time.LocalTime.Internal.ZonedTime
import qualified GHC.Base
import qualified GHC.Classes
import qualified GHC.Int
import qualified GHC.Show
import qualified GHC.Types
import qualified StripeAPI.Common
import StripeAPI.TypeAlias
import qualified Prelude as GHC.Integer.Type
import qualified Prelude as GHC.Maybe
data TreasuryTransactionsResourceBalanceImpact = TreasuryTransactionsResourceBalanceImpact
treasuryTransactionsResourceBalanceImpactCash :: GHC.Types.Int,
treasuryTransactionsResourceBalanceImpactInboundPending :: GHC.Types.Int,
treasuryTransactionsResourceBalanceImpactOutboundPending :: GHC.Types.Int
}
deriving
( GHC.Show.Show,
GHC.Classes.Eq
)
instance Data.Aeson.Types.ToJSON.ToJSON TreasuryTransactionsResourceBalanceImpact where
toJSON obj = Data.Aeson.Types.Internal.object (Data.Foldable.concat (["cash" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactCash obj] : ["inbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactInboundPending obj] : ["outbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactOutboundPending obj] : GHC.Base.mempty))
toEncoding obj = Data.Aeson.Encoding.Internal.pairs (GHC.Base.mconcat (Data.Foldable.concat (["cash" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactCash obj] : ["inbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactInboundPending obj] : ["outbound_pending" Data.Aeson.Types.ToJSON..= treasuryTransactionsResourceBalanceImpactOutboundPending obj] : GHC.Base.mempty)))
instance Data.Aeson.Types.FromJSON.FromJSON TreasuryTransactionsResourceBalanceImpact where
parseJSON = Data.Aeson.Types.FromJSON.withObject "TreasuryTransactionsResourceBalanceImpact" (\obj -> ((GHC.Base.pure TreasuryTransactionsResourceBalanceImpact GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "cash")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "inbound_pending")) GHC.Base.<*> (obj Data.Aeson.Types.FromJSON..: "outbound_pending"))
mkTreasuryTransactionsResourceBalanceImpact ::
GHC.Types.Int ->
GHC.Types.Int ->
GHC.Types.Int ->
TreasuryTransactionsResourceBalanceImpact
mkTreasuryTransactionsResourceBalanceImpact treasuryTransactionsResourceBalanceImpactCash treasuryTransactionsResourceBalanceImpactInboundPending treasuryTransactionsResourceBalanceImpactOutboundPending =
TreasuryTransactionsResourceBalanceImpact
{ treasuryTransactionsResourceBalanceImpactCash = treasuryTransactionsResourceBalanceImpactCash,
treasuryTransactionsResourceBalanceImpactInboundPending = treasuryTransactionsResourceBalanceImpactInboundPending,
treasuryTransactionsResourceBalanceImpactOutboundPending = treasuryTransactionsResourceBalanceImpactOutboundPending
}
|
d19ed6f76049c1d053731bc62f7a6c0e8c42fe458e87251d006f0f8a961a101e | inaka/elvis_core | pass_numeric_format_elvis_attr.erl | -module(pass_numeric_format_elvis_attr).
-export([for_test/0]).
-elvis([{elvis_style, numeric_format, #{regex => "^[^_]+$"}}]).
for_test() ->
{ 1
, 2
, 10
, 100
, 1000
, 2#1010101
, 16#FACE
, 1.1010101
, 0.34e12
, -1
, -10
, -1000
, -2#1010101
, -16#FACE
, -1.1010101
, -0.34e-123
}.
| null | https://raw.githubusercontent.com/inaka/elvis_core/468bd3498f1782fd74ef3d8eb1b36217b0b76c11/test/examples/pass_numeric_format_elvis_attr.erl | erlang | -module(pass_numeric_format_elvis_attr).
-export([for_test/0]).
-elvis([{elvis_style, numeric_format, #{regex => "^[^_]+$"}}]).
for_test() ->
{ 1
, 2
, 10
, 100
, 1000
, 2#1010101
, 16#FACE
, 1.1010101
, 0.34e12
, -1
, -10
, -1000
, -2#1010101
, -16#FACE
, -1.1010101
, -0.34e-123
}.
|
|
1c4285f84a2746e6c5e96e81b4351b9601708994c07956ceac019a56dbc727b3 | learningclojurescript/code-examples | core.cljs | (ns match-demo.core
(:require [cljs.core.match :refer-macros [match]]))
(defprotocol foo
(bar [this]))
(deftype baz []
Object
(bar [this] 5))
;; basic
(let [v [:a :a :b]]
(match v
[_ :a :a] 1
[:a :b _ ] 2
[_ _ :a] 3
[_ _ :b] 4
:else 5))
;; local bindings
(match [:x :y]
[:y a] a
[b :y] b
:else nil)
;; vectors
(match [[:a :b :c]]
[[:a :c _]] 1
[[:b _ :a]] 2
[[_ :b :c]] 3
:else nil)
;; maps
(let [v {:x 1 :y 1}]
(match [v]
[{:x _ :y 2}] 1
[{:x 1 :y 1 :z _}] 2
:else "no match found"))
(let [v {:x 1 :y 1}]
(match [v]
[({:x 1} :only [:x])] true
:else false))
(let [v {:x {:y :z}}]
(match [v]
[{:x {:y k}}] k
:else nil))
;; sequential types
(let [x [1 2 nil nil nil]]
(match [x]
[([1 2] :seq)] :a1
[([1 2 nil nil nil] :seq)] :a2
:else nil))
;; rest patterns
(let [x [1 2 nil nil nil]]
(match [x]
[([1 2] :seq)] :a1
[([1 2 & r] :seq)] :a2
:else nil))
;; or
(let [x ["a" "b" "c"]]
(match x
["a" "d" "c"] :a1
["z" "d" "c"] :a1
["x" "b" "c"] :a2
["a" _ "d"] :a3
["a" _ "c"] :a3
["z" _ "d"] :a3
["z" _ "c"] :a3
:else nil))
;; guards
(let [x [1 3]]
(match x
[(_ :guard odd?) _] :a1
[(_ :guard even?) (_ :guard even?)] :a2
:else nil))
;; general function application
(let [x [1 3]]
(match x
[(2 :<< println) 3] :a1
[1 (2 :<< dec)] :a2
:else nil))
(enable-console-print!)
(println "Edits to this text should show up in your developer console.")
;; define your app data so that it doesn't get over-written on reload
(defonce app-state (atom {:text "Hello world!"}))
(defn on-js-reload []
;; optionally touch your app-state to force rerendering depending on
;; your application
;; (swap! app-state update-in [:__figwheel_counter] inc)
)
| null | https://raw.githubusercontent.com/learningclojurescript/code-examples/fdbd0e35ae5a16d53f1f784a52c25bcd4e5a8097/chapter-7/match-demo/src/match_demo/core.cljs | clojure | basic
local bindings
vectors
maps
sequential types
rest patterns
or
guards
general function application
define your app data so that it doesn't get over-written on reload
optionally touch your app-state to force rerendering depending on
your application
(swap! app-state update-in [:__figwheel_counter] inc) | (ns match-demo.core
(:require [cljs.core.match :refer-macros [match]]))
(defprotocol foo
(bar [this]))
(deftype baz []
Object
(bar [this] 5))
(let [v [:a :a :b]]
(match v
[_ :a :a] 1
[:a :b _ ] 2
[_ _ :a] 3
[_ _ :b] 4
:else 5))
(match [:x :y]
[:y a] a
[b :y] b
:else nil)
(match [[:a :b :c]]
[[:a :c _]] 1
[[:b _ :a]] 2
[[_ :b :c]] 3
:else nil)
(let [v {:x 1 :y 1}]
(match [v]
[{:x _ :y 2}] 1
[{:x 1 :y 1 :z _}] 2
:else "no match found"))
(let [v {:x 1 :y 1}]
(match [v]
[({:x 1} :only [:x])] true
:else false))
(let [v {:x {:y :z}}]
(match [v]
[{:x {:y k}}] k
:else nil))
(let [x [1 2 nil nil nil]]
(match [x]
[([1 2] :seq)] :a1
[([1 2 nil nil nil] :seq)] :a2
:else nil))
(let [x [1 2 nil nil nil]]
(match [x]
[([1 2] :seq)] :a1
[([1 2 & r] :seq)] :a2
:else nil))
(let [x ["a" "b" "c"]]
(match x
["a" "d" "c"] :a1
["z" "d" "c"] :a1
["x" "b" "c"] :a2
["a" _ "d"] :a3
["a" _ "c"] :a3
["z" _ "d"] :a3
["z" _ "c"] :a3
:else nil))
(let [x [1 3]]
(match x
[(_ :guard odd?) _] :a1
[(_ :guard even?) (_ :guard even?)] :a2
:else nil))
(let [x [1 3]]
(match x
[(2 :<< println) 3] :a1
[1 (2 :<< dec)] :a2
:else nil))
(enable-console-print!)
(println "Edits to this text should show up in your developer console.")
(defonce app-state (atom {:text "Hello world!"}))
(defn on-js-reload []
)
|
54094c2deab271133b87e92d61723913f792fca593fdf9f163fedbed405c5ea1 | savonet/ocaml-posix | gen_constants_c.ml | module Constants = Posix_base.Generators.Types (struct
module Types = Posix_types_constants.Def
let defines =
String.concat "\n"
(List.map
(fun t ->
let name = String.uppercase_ascii t in
Printf.sprintf
"\n\
#define %s_SIZE sizeof(%s)\n\
#define IS_%s_FLOAT ((float)((%s)1.23) == 1.23)" name t name t)
Posix_types_constants.number_types
@ List.map
(fun t ->
let name = String.uppercase_ascii t in
Printf.sprintf
"\n\
#define %s_SIZE sizeof(%s)\n\
#define %s_ALIGNMENT offsetof(struct { char c; %s x; }, x)" name
t name t)
Posix_types_constants.abstract_types)
let c_headers =
Printf.sprintf
"\n\
#include <sys/types.h>\n\
#include <sys/time.h>\n\
#include <unistd.h>\n\n\
%s"
defines
end)
let () = Constants.gen ()
| null | https://raw.githubusercontent.com/savonet/ocaml-posix/729f49d572d24b749a26e73fce970f05c3fd60f2/posix-types/src/generator/gen_constants_c.ml | ocaml | module Constants = Posix_base.Generators.Types (struct
module Types = Posix_types_constants.Def
let defines =
String.concat "\n"
(List.map
(fun t ->
let name = String.uppercase_ascii t in
Printf.sprintf
"\n\
#define %s_SIZE sizeof(%s)\n\
#define IS_%s_FLOAT ((float)((%s)1.23) == 1.23)" name t name t)
Posix_types_constants.number_types
@ List.map
(fun t ->
let name = String.uppercase_ascii t in
Printf.sprintf
"\n\
#define %s_SIZE sizeof(%s)\n\
#define %s_ALIGNMENT offsetof(struct { char c; %s x; }, x)" name
t name t)
Posix_types_constants.abstract_types)
let c_headers =
Printf.sprintf
"\n\
#include <sys/types.h>\n\
#include <sys/time.h>\n\
#include <unistd.h>\n\n\
%s"
defines
end)
let () = Constants.gen ()
|
|
adc20572e515f017609ed8fbd4106065ea07a34bd9a5733bd5ea162adde7bd54 | semerdzhiev/fp-2020-21 | flatten.rkt | #lang racket
(require rackunit)
(require rackunit/text-ui)
; flatten
функция , влагане в списъци
за да я имплементираме , е хубаво да atom ? и / или list ?
хубаво е и да помислим дали не може да използваме някоя от map / filter / fold за проблема
(define (flatten xs)
(void)
)
(define tests
(test-suite "flatten"
(check-equal? (flatten '((1) 2 ((3 4 (5)) (((((6)))))))) '(1 2 3 4 5 6))
(check-equal? (flatten '(1 2 3 (4))) '(1 2 3 4))
(check-equal? (flatten '(() () 3 (2))) '(3 2))
)
)
(run-tests tests 'verbose)
| null | https://raw.githubusercontent.com/semerdzhiev/fp-2020-21/64fa00c4f940f75a28cc5980275b124ca21244bc/group-b/exercises/06.map-filter-fold/flatten.rkt | racket | flatten | #lang racket
(require rackunit)
(require rackunit/text-ui)
функция , влагане в списъци
за да я имплементираме , е хубаво да atom ? и / или list ?
хубаво е и да помислим дали не може да използваме някоя от map / filter / fold за проблема
(define (flatten xs)
(void)
)
(define tests
(test-suite "flatten"
(check-equal? (flatten '((1) 2 ((3 4 (5)) (((((6)))))))) '(1 2 3 4 5 6))
(check-equal? (flatten '(1 2 3 (4))) '(1 2 3 4))
(check-equal? (flatten '(() () 3 (2))) '(3 2))
)
)
(run-tests tests 'verbose)
|
ea4c58f78039b3be60cc415b56c6632c4c468951cd33f48a9d4f2f100f9d6e80 | fccm/glMLite | cylinder.ml |
* cylinder drawing demo
*
* FUNCTION :
* Basic demo illustrating how to write code to draw
* the most basic cylinder shape .
*
* HISTORY :
* Linas Vepstas March 1995
* Copyright ( c ) 1995 Linas Vepstas < >
* 2008 - OCaml version by
* cylinder drawing demo
*
* FUNCTION:
* Basic demo illustrating how to write code to draw
* the most basic cylinder shape.
*
* HISTORY:
* Linas Vepstas March 1995
* Copyright (c) 1995 Linas Vepstas <>
* 2008 - OCaml version by F. Monnier
*)
open GL
open Glut
open GLE
open Mainvar
(* the arrays which define the polyline *)
let points = ba2_glefloat_of_array [|
[| -6.0; 6.0; 0.0 |];
[| 6.0; 6.0; 0.0 |];
[| 6.0; -6.0; 0.0 |];
[| -6.0; -6.0; 0.0 |];
[| -6.0; 6.0; 0.0 |];
[| 6.0; 6.0; 0.0 |];
|]
let colors = ba2_float32_of_array [|
[| 0.0; 0.0; 0.0 |];
[| 0.0; 0.8; 0.3 |];
[| 0.8; 0.3; 0.0 |];
[| 0.2; 0.3; 0.9 |];
[| 0.2; 0.8; 0.5 |];
[| 0.0; 0.0; 0.0 |];
|]
* Initialize a bent shape with three segments .
* The data format is a polyline .
*
* NOTE that neither the first , nor the last segment are drawn .
* The first & last segment serve only to determine that angle
* at which the endcaps are drawn .
* Initialize a bent shape with three segments.
* The data format is a polyline.
*
* NOTE that neither the first, nor the last segment are drawn.
* The first & last segment serve only to determine that angle
* at which the endcaps are drawn.
*)
let init_stuff () =
(* initialize the join style here *)
gleSetJoinStyle [TUBE_NORM_EDGE; TUBE_JN_ANGLE; TUBE_JN_CAP];
;;
(* draw the cylinder shape *)
let draw_stuff () =
glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
(* set up some matrices so that the object spins with the mouse *)
glPushMatrix ();
glTranslate 0.0 0.0 (-80.0);
glRotate (float !lastx) 0.0 1.0 0.0;
glRotate (float !lasty) 1.0 0.0 0.0;
Phew . FINALLY , Draw the polycylinder --
glePolyCylinder points colors 2.3;
glPopMatrix ();
glutSwapBuffers ();
;;
(* ------------------------ end of file ------------------- *)
| null | https://raw.githubusercontent.com/fccm/glMLite/c52cd806909581e49d9b660195576c8a932f6d33/gle-examples/cylinder.ml | ocaml | the arrays which define the polyline
initialize the join style here
draw the cylinder shape
set up some matrices so that the object spins with the mouse
------------------------ end of file ------------------- |
* cylinder drawing demo
*
* FUNCTION :
* Basic demo illustrating how to write code to draw
* the most basic cylinder shape .
*
* HISTORY :
* Linas Vepstas March 1995
* Copyright ( c ) 1995 Linas Vepstas < >
* 2008 - OCaml version by
* cylinder drawing demo
*
* FUNCTION:
* Basic demo illustrating how to write code to draw
* the most basic cylinder shape.
*
* HISTORY:
* Linas Vepstas March 1995
* Copyright (c) 1995 Linas Vepstas <>
* 2008 - OCaml version by F. Monnier
*)
open GL
open Glut
open GLE
open Mainvar
let points = ba2_glefloat_of_array [|
[| -6.0; 6.0; 0.0 |];
[| 6.0; 6.0; 0.0 |];
[| 6.0; -6.0; 0.0 |];
[| -6.0; -6.0; 0.0 |];
[| -6.0; 6.0; 0.0 |];
[| 6.0; 6.0; 0.0 |];
|]
let colors = ba2_float32_of_array [|
[| 0.0; 0.0; 0.0 |];
[| 0.0; 0.8; 0.3 |];
[| 0.8; 0.3; 0.0 |];
[| 0.2; 0.3; 0.9 |];
[| 0.2; 0.8; 0.5 |];
[| 0.0; 0.0; 0.0 |];
|]
* Initialize a bent shape with three segments .
* The data format is a polyline .
*
* NOTE that neither the first , nor the last segment are drawn .
* The first & last segment serve only to determine that angle
* at which the endcaps are drawn .
* Initialize a bent shape with three segments.
* The data format is a polyline.
*
* NOTE that neither the first, nor the last segment are drawn.
* The first & last segment serve only to determine that angle
* at which the endcaps are drawn.
*)
let init_stuff () =
gleSetJoinStyle [TUBE_NORM_EDGE; TUBE_JN_ANGLE; TUBE_JN_CAP];
;;
let draw_stuff () =
glClear [GL_COLOR_BUFFER_BIT; GL_DEPTH_BUFFER_BIT];
glPushMatrix ();
glTranslate 0.0 0.0 (-80.0);
glRotate (float !lastx) 0.0 1.0 0.0;
glRotate (float !lasty) 1.0 0.0 0.0;
Phew . FINALLY , Draw the polycylinder --
glePolyCylinder points colors 2.3;
glPopMatrix ();
glutSwapBuffers ();
;;
|
42107a7dcf3a6473b685acea8c50903063445a816355f347adba1bb82a3b5455 | AngryLawyer/reactjs_of_ocaml | ReactJS.mli | class type react_element = object end
class type react_class = object end
class type react_props = object end
type tag_type =
| Tag_name of string
| React_class of react_class
type content_type =
| Dom_string of string
| React_element of react_element Js.t
| Element_list of content_type list
| No_content
val create_element : tag_type -> ?props : < .. > Js.t -> content_type list -> react_element Js.t
val set_state : < render : react_element Js.t Js.meth; .. > Js.t -> < .. > Js.t -> unit
val is_valid_element: react_element Js.t -> bool
module type ReactClassSpec = sig
type props_spec
type state_spec
end
module type RC = sig
type props_spec
type state_spec
val create_class : < render : react_element Js.t Js.meth; .. > Js.t -> react_class
val get_props : < render : react_element Js.t Js.meth; .. > Js.t -> props_spec
val get_state : < render : react_element Js.t Js.meth; .. > Js.t -> state_spec
end
module Make_ReactClass(ClassSpec: ReactClassSpec): RC with type props_spec = ClassSpec.props_spec and type state_spec = ClassSpec.state_spec
module Children : sig
type children
val get_children : < render : react_element Js.t Js.meth; .. > Js.t -> children Js.t
val as_react_element : children Js.t -> react_element Js.t
end
| null | https://raw.githubusercontent.com/AngryLawyer/reactjs_of_ocaml/e89b077cc5c43b09021234478a82e66f2bfe5c37/lib/ReactJS.mli | ocaml | class type react_element = object end
class type react_class = object end
class type react_props = object end
type tag_type =
| Tag_name of string
| React_class of react_class
type content_type =
| Dom_string of string
| React_element of react_element Js.t
| Element_list of content_type list
| No_content
val create_element : tag_type -> ?props : < .. > Js.t -> content_type list -> react_element Js.t
val set_state : < render : react_element Js.t Js.meth; .. > Js.t -> < .. > Js.t -> unit
val is_valid_element: react_element Js.t -> bool
module type ReactClassSpec = sig
type props_spec
type state_spec
end
module type RC = sig
type props_spec
type state_spec
val create_class : < render : react_element Js.t Js.meth; .. > Js.t -> react_class
val get_props : < render : react_element Js.t Js.meth; .. > Js.t -> props_spec
val get_state : < render : react_element Js.t Js.meth; .. > Js.t -> state_spec
end
module Make_ReactClass(ClassSpec: ReactClassSpec): RC with type props_spec = ClassSpec.props_spec and type state_spec = ClassSpec.state_spec
module Children : sig
type children
val get_children : < render : react_element Js.t Js.meth; .. > Js.t -> children Js.t
val as_react_element : children Js.t -> react_element Js.t
end
|
|
1cdd21997a62277ced971b661a9724fab5ddfa4d2f13e6e32457c58cd1efa57a | seryh/example-selenium-project | profile.clj | этот ns реализует логику по работе с профайлами
позволяющую использовать как chromedriver так и phantomjs драйвер
а также использовать проект windows и * nix
(ns example-selenium-project.profile
(:use [clj-webdriver.driver :only [init-driver]])
(:require [clojure.test :refer :all]
[utils.webdriver :refer :all]
[clj-webdriver.taxi :refer :all]
[environ.core :as environ]
[clojure.tools.namespace.find :as ns]
[clojure.tools.logging :as log]
[clojure.java.classpath :as cp]
[clojure.test :refer :all])
(:import (java.util.concurrent TimeUnit)
(org.openqa.selenium.remote DesiredCapabilities)))
используется макрос из за selenium - java
(defmacro webdriver-import []
(when-not (#{"selenium"} (environ/env :clj-env))
(import '(org.openqa.selenium.phantomjs PhantomJSDriver)
'(org.openqa.selenium.phantomjs PhantomJSDriverService)
'(org.openqa.selenium.remote DesiredCapabilities))))
(webdriver-import)
(def profile-name (environ/env :clj-env))
(defonce driver (atom nil))
(defonce tests-fail (atom 0))
(defonce tests-success (atom 0))
(defn tests-report []
(println {:tests-fail @tests-fail
:tests-success @tests-success}))
(defn tests-report-reset []
(reset! tests-fail 0)
(reset! tests-success 0))
если + windows профайл , web - driver ,
в корне проекта должны быть файлы chromedriver.exe и phantomjs.exe
(case (environ/env :clj-env-os)
"windows" (if (#{"selenium"} profile-name)
(System/setProperty "webdriver.chrome.driver" "chromedriver.exe")
(System/setProperty "phantomjs.binary.path" "phantomjs.exe")) nil)
(defmacro webdriver-select
"Определяет веб драйвер при компиляции по профайлу,
инициализирует selenium или Phantom Driver"
[url]
(let [profile-name (environ/env :clj-env)]
(if (#{"selenium"} profile-name)
`(reset! driver (set-driver! {:browser :chrome} ~url))
(do
(webdriver-import)
`(reset! driver
(set-driver! (init-driver
{:webdriver
(PhantomJSDriver.
(doto (DesiredCapabilities.)
(.setCapability PhantomJSDriverService/PHANTOMJS_CLI_ARGS
(into-array String ["--webdriver-loglevel=NONE"
"--ignore-ssl-errors=yes"
"--ssl-protocol=any"]))))}) ~url))))))
(defmacro loading-my-tests
"Подключает все ns из каталога ns-dir с атрибутами :refer :all"
[ns-dir]
(let [all-ns (ns/find-namespaces (cp/classpath))
test-ns-list (filter #(re-matches (re-pattern (str ns-dir "(.*)")) (str %)) all-ns)
name-to-fn (fn [ns-name] `(require '[~ns-name :refer :all]))
fn-list (mapv name-to-fn test-ns-list)]
`(do ~@fn-list)))
(defmacro do-list
"Выполнит все переданные в векторе list функции без аргументов"
[list]
`(do ~@(mapv #(do `(~%)) (eval list))))
(defn open-browser
"Открывает браузер по переданному url"
[^String url]
(when @driver (quit))
(println (str "Open driver with profile:" profile-name " and url: " url))
(webdriver-select url)
(window-resize {:width 1024 :height 768})
(implicit-wait 6000))
(defmacro defwebtest [name url & forms]
`(deftest ~name
(open-browser ~url)
(try
~@forms
(swap! tests-success inc)
(log/info (var ~name) "test-->ok")
(is true)
(catch Throwable t#
(log/info (var ~name) "test-->fail" (.getMessage t#))
(swap! tests-fail inc)
(is false)))))
| null | https://raw.githubusercontent.com/seryh/example-selenium-project/5b14b187c0efb7d935a5f385d638257b5dba21d4/src/example_selenium_project/profile.clj | clojure | этот ns реализует логику по работе с профайлами
позволяющую использовать как chromedriver так и phantomjs драйвер
а также использовать проект windows и * nix
(ns example-selenium-project.profile
(:use [clj-webdriver.driver :only [init-driver]])
(:require [clojure.test :refer :all]
[utils.webdriver :refer :all]
[clj-webdriver.taxi :refer :all]
[environ.core :as environ]
[clojure.tools.namespace.find :as ns]
[clojure.tools.logging :as log]
[clojure.java.classpath :as cp]
[clojure.test :refer :all])
(:import (java.util.concurrent TimeUnit)
(org.openqa.selenium.remote DesiredCapabilities)))
используется макрос из за selenium - java
(defmacro webdriver-import []
(when-not (#{"selenium"} (environ/env :clj-env))
(import '(org.openqa.selenium.phantomjs PhantomJSDriver)
'(org.openqa.selenium.phantomjs PhantomJSDriverService)
'(org.openqa.selenium.remote DesiredCapabilities))))
(webdriver-import)
(def profile-name (environ/env :clj-env))
(defonce driver (atom nil))
(defonce tests-fail (atom 0))
(defonce tests-success (atom 0))
(defn tests-report []
(println {:tests-fail @tests-fail
:tests-success @tests-success}))
(defn tests-report-reset []
(reset! tests-fail 0)
(reset! tests-success 0))
если + windows профайл , web - driver ,
в корне проекта должны быть файлы chromedriver.exe и phantomjs.exe
(case (environ/env :clj-env-os)
"windows" (if (#{"selenium"} profile-name)
(System/setProperty "webdriver.chrome.driver" "chromedriver.exe")
(System/setProperty "phantomjs.binary.path" "phantomjs.exe")) nil)
(defmacro webdriver-select
"Определяет веб драйвер при компиляции по профайлу,
инициализирует selenium или Phantom Driver"
[url]
(let [profile-name (environ/env :clj-env)]
(if (#{"selenium"} profile-name)
`(reset! driver (set-driver! {:browser :chrome} ~url))
(do
(webdriver-import)
`(reset! driver
(set-driver! (init-driver
{:webdriver
(PhantomJSDriver.
(doto (DesiredCapabilities.)
(.setCapability PhantomJSDriverService/PHANTOMJS_CLI_ARGS
(into-array String ["--webdriver-loglevel=NONE"
"--ignore-ssl-errors=yes"
"--ssl-protocol=any"]))))}) ~url))))))
(defmacro loading-my-tests
"Подключает все ns из каталога ns-dir с атрибутами :refer :all"
[ns-dir]
(let [all-ns (ns/find-namespaces (cp/classpath))
test-ns-list (filter #(re-matches (re-pattern (str ns-dir "(.*)")) (str %)) all-ns)
name-to-fn (fn [ns-name] `(require '[~ns-name :refer :all]))
fn-list (mapv name-to-fn test-ns-list)]
`(do ~@fn-list)))
(defmacro do-list
"Выполнит все переданные в векторе list функции без аргументов"
[list]
`(do ~@(mapv #(do `(~%)) (eval list))))
(defn open-browser
"Открывает браузер по переданному url"
[^String url]
(when @driver (quit))
(println (str "Open driver with profile:" profile-name " and url: " url))
(webdriver-select url)
(window-resize {:width 1024 :height 768})
(implicit-wait 6000))
(defmacro defwebtest [name url & forms]
`(deftest ~name
(open-browser ~url)
(try
~@forms
(swap! tests-success inc)
(log/info (var ~name) "test-->ok")
(is true)
(catch Throwable t#
(log/info (var ~name) "test-->fail" (.getMessage t#))
(swap! tests-fail inc)
(is false)))))
|
|
e4bd8a52b08ea89ed3e6576101b8a62872726071ce6a422af862d33baed7a32c | sarabander/p2pu-sicp | 2.97.scm |
;; Added procedures to reduce fractions
(define (install-polynomial-package)
;; internal procedures
;; representation of poly
(define (make-poly variable term-list)
(cons variable term-list))
(define (variable p) (car p))
(define (term-list p) (cdr p)) ;
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
;; representation of terms and termlists
(define (adjoin-term term term-list)
(if (and (list? term) (=zero? (coeff term)))
term-list
(cons term term-list)))
(define (the-empty-termlist) '())
(define (first-term term-list) (car term-list))
(define (rest-terms term-list) (cdr term-list))
(define (empty-termlist? term-list)
(or (null? term-list) (list-of-zeros? term-list)))
(define (make-term type termorder termcoeff)
(if (eq? type 'dense)
termcoeff
(list termorder termcoeff)))
(define (termtype term)
(if (list? term) 'sparse 'dense))
(define (order term partial-termlist)
(if (list? term)
(car term)
(sub1 (length partial-termlist))))
(define (coeff term)
(if (list? term)
(cadr term)
term))
;; Greatest common divisor of polynomials
(define (gcd-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(gcd-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - GCD-POLY"
(list p1 p2))))
;; Original:
;; (define (gcd-terms a b)
;; (if (empty-termlist? b)
;; a
;; (gcd-terms b (remainder-terms a b))))
;; Uses pseudoremainder-terms and removes common factors from coefficients:
(define (gcd-terms a b)
(if (empty-termlist? b)
(let ((gcd-of-coeffs (apply gcd (map coeff a))))
(map (λ (term) (list (car term)
(/ (cadr term) gcd-of-coeffs)))
a))
(gcd-terms b (pseudoremainder-terms a b))))
(define (remainder-terms a b)
(cadr (div-terms a b)))
;; New concepts introduced to avoid fractional coefficients:
(define (pseudoquotient-terms P Q)
(pseudodivision-terms car P Q))
(define (pseudoremainder-terms P Q)
(pseudodivision-terms cadr P Q))
(define (pseudodivision-terms f P Q)
(let ((O1 (order (first-term P) P))
(O2 (order (first-term Q) Q))
(c (coeff (first-term Q))))
(let ((integerizer (list (list 0 (expt c (+ 1 O1 (- O2)))))))
(f (div-terms (mul-terms integerizer P) Q)))))
(define (reduce-poly n d)
(if (same-variable? (variable n) (variable d))
(let ((n-d-reduced (reduce-terms (term-list n)
(term-list d))))
(cons (make-poly (variable n) (car n-d-reduced))
(make-poly (variable n) (cadr n-d-reduced))))
(error "Polys not in same var - ADD-POLY"
(list p1 p2))))
;; Oh Lords of Lambda, I have sinned!
;; I've penetrated the abstraction barrier!
;; (Must repent and rewrite the procedure thrice.)
(define (reduce-terms n d)
(let ((g (gcd-terms n d)))
(let ((O1 (max (order (first-term n) n)
(order (first-term d) d)))
(O2 (order (first-term g) g))
(c (coeff (first-term g))))
(let ((integerizer (list (list 0 (expt c (+ 1 O1 (- O2)))))))
(let ((n-integerized (mul-terms integerizer n))
(d-integerized (mul-terms integerizer d)))
(let ((n/g (car (div-terms n-integerized g)))
(d/g (car (div-terms d-integerized g))))
(let ((gcd-of-coeffs
(apply gcd (map coeff (append n/g d/g)))))
(let ((divide-by-gcd
(λ (term) (list (car term) (/ (cadr term)
gcd-of-coeffs)))))
(let ((n-reduced (map divide-by-gcd n/g))
(d-reduced (map divide-by-gcd d/g)))
(list n-reduced d-reduced))))))))))
(define (reduce-integers n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(add-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - ADD-POLY"
(list p1 p2))))
(define (add-terms L1 L2)
(cond ((empty-termlist? L1) L2)
((empty-termlist? L2) L1)
(else
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(cond ((> (order t1 L1) (order t2 L2))
(adjoin-term
t1 (add-terms (rest-terms L1) L2)))
((< (order t1 L1) (order t2 L2))
(adjoin-term
t2 (add-terms L1 (rest-terms L2))))
(else
(adjoin-term
(make-term (termtype t1)
(order t1 L1)
(add (coeff t1) (coeff t2)))
(add-terms (rest-terms L1)
(rest-terms L2)))))))))
(define (mul-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(mul-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - MUL-POLY"
(list p1 p2))))
(define (mul-terms L1 L2)
(if (empty-termlist? L1)
(the-empty-termlist)
(add-terms (mul-term-by-all-terms (first-term L1)
(order (first-term L1) L1)
L2)
(mul-terms (rest-terms L1) L2))))
(define (mul-term-by-all-terms t1 t1-order L)
(if (empty-termlist? L)
(the-empty-termlist)
(let ((t2 (first-term L)))
(adjoin-term
(make-term (termtype t1)
(+ t1-order (order t2 L))
(mul (coeff t1) (coeff t2)))
(mul-term-by-all-terms t1
t1-order
(rest-terms L))))))
Division
(define (div-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(let ((divided-terms (div-terms (sort-termlist (term-list p1))
(sort-termlist (term-list p2)))))
(list
(make-poly (variable p1) (car divided-terms))
(make-poly (variable p1) (cadr divided-terms))))
(error "Polys not in same var - MUL-POLY"
(list p1 p2))))
(define (div-terms L1 L2)
(if (empty-termlist? L1)
(list (the-empty-termlist) (the-empty-termlist))
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(if (> (order t2 L2) (order t1 L1))
(list (the-empty-termlist) L1)
(let ((new-c (div (coeff t1) (coeff t2)))
(new-o (- (order t1 L1) (order t2 L2))))
(let* ((newterm (list (make-term 'sparse new-o new-c)))
(rest-of-result
(let* ((subtractor (mul-terms newterm L2))
(difference (sort-termlist
(add-terms L1
(negate-termlist
subtractor)))))
(if (empty? difference)
(list (the-empty-termlist)
(the-empty-termlist))
(div-terms difference L2)))))
(list
(sort-termlist (add-terms newterm
(car rest-of-result)))
(cadr rest-of-result))))))))
;; Sorts sparse termlist by term's order (descending)
(define (sort-termlist L)
(sort L #:key car >))
;; Converts dense termlist to sparse, leaves already sparse list intact
(define (convert-to-sparse termlist)
(if (empty? termlist)
empty
(let ((first-elem (car termlist)))
(if (and (number? first-elem) (zero? first-elem))
(convert-to-sparse (cdr termlist))
(cons (list (order first-elem termlist) (coeff first-elem))
(convert-to-sparse (cdr termlist)))))))
;; Converts dense polynomial to sparse
(define (to-sparse polynomial)
(cons (variable polynomial)
(convert-to-sparse (term-list polynomial))))
Negates all terms
(define (negate-termlist termlist)
(if (empty? termlist)
empty
(let ((negator (if (list? (car termlist))
(λ (elem) (list (car elem) (- (cadr elem))))
-)))
(map negator termlist))))
;; interface to rest of the system
(define (tag p) (attach-tag 'polynomial p))
(put 'add '(polynomial polynomial)
(lambda (p1 p2) (tag (add-poly p1 p2))))
(put 'sub '(polynomial polynomial)
(lambda (p1 p2) (tag (add-poly p1 (contents (neg (tag p2)))))))
(put 'mul '(polynomial polynomial)
(lambda (p1 p2) (tag (mul-poly (to-sparse p1)
(to-sparse p2)))))
(put 'div '(polynomial polynomial)
(lambda (p1 p2)
(let ((quotient+remainder (div-poly (to-sparse p1)
(to-sparse p2))))
(list (tag (car quotient+remainder))
(tag (cadr quotient+remainder))))))
(put 'neg '(polynomial)
(lambda (p)
(tag (cons (variable p)
(negate-termlist (contents p))))))
(put '=zero? '(polynomial)
(λ (p) (list-of-zeros? (contents p))))
(put 'gcd '(polynomial polynomial)
(λ (p1 p2) (tag (gcd-poly (to-sparse p1)
(to-sparse p2)))))
(put 'gcd '(scheme-number scheme-number) gcd)
(put 'make 'polynomial
(lambda (var terms) (tag (make-poly var terms))))
(put 'reduce '(scheme-number scheme-number) reduce-integers)
(put 'reduce '(polynomial polynomial)
(λ (n d)
(let ((reduced-p (reduce-poly n d)))
(cons (tag (car reduced-p))
(tag (cdr reduced-p))))))
'done)
(install-polynomial-package)
(define (install-rational-package)
;; internal procedures
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d) (reduce n d))
(define (add-rat x y)
(make-rat (add (mul (numer x) (denom y))
(mul (numer y) (denom x)))
(mul (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (sub (mul (numer x) (denom y))
(mul (numer y) (denom x)))
(mul (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (mul (numer x) (numer y))
(mul (denom x) (denom y))))
(define (div-rat x y)
(make-rat (div (numer x) (denom y))
(div (denom x) (numer y))))
;; interface to rest of the system
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'sub '(rational rational)
(lambda (x y) (tag (sub-rat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mul-rat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (div-rat x y))))
(put 'square '(rational)
(lambda (r) (sqr (/ (numer r) (denom r)))))
(put 'sine '(rational)
(lambda (r) (sin (/ (numer r) (denom r)))))
(put 'cosine '(rational)
(lambda (r) (cos (/ (numer r) (denom r)))))
(put 'atangent '(rational)
(lambda (r) (atan (/ (numer r) (denom r)))))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
(put 'numer '(rational)
(lambda (r) (numer r)))
(put 'denom '(rational)
(lambda (r) (denom r)))
'done)
(install-rational-package)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (numer r)
(apply-generic 'numer r))
(define (denom r)
(apply-generic 'denom r))
(define (reduce n d)
(apply-generic 'reduce n d))
;; Tests
' ( rational 4 . 27 )
(define p1 (make-polynomial 'x '((1 1) (0 1))))
(listpoly->mathpoly p1) ; "x + 1"
(define p2 (make-polynomial 'x '((3 1) (0 -1))))
(listpoly->mathpoly p2) ; "x³ - 1"
(define p3 (make-polynomial 'x '((1 1))))
(listpoly->mathpoly p3) ; "x"
(define p4 (make-polynomial 'x '((2 1) (0 -1))))
(listpoly->mathpoly p4) ; "x² - 1"
(define rf1 (make-rational p1 p2))
' ( rational ( polynomial x ( 1 -1 ) ( 0 -1 ) ) polynomial x ( 3 -1 ) ( 0 1 ) )
(listpoly->mathpoly (numer rf1)) ; "-x - 1"
(listpoly->mathpoly (denom rf1)) ; "-x³ + 1"
(define rf2 (make-rational p3 p4))
' ( rational ( polynomial x ( 1 1 ) ) polynomial x ( 2 1 ) ( 0 -1 ) )
(listpoly->mathpoly (numer rf2)) ; "x"
(listpoly->mathpoly (denom rf2)) ; "x² - 1"
(define rf1+rf2 (add rf1 rf2))
rf1+rf2
;; '(rational
( polynomial x ( 3 -1 ) ( 2 -2 ) ( 1 -3 ) ( 0 -1 ) )
;; polynomial
;; x
( 4 -1 )
( 3 -1 )
( 1 1 )
;; (0 1))
(listpoly->mathpoly (numer rf1+rf2)) ; "-x³ - 2x² - 3x - 1"
(listpoly->mathpoly (denom rf1+rf2)) ; "-x⁴ - x³ + x + 1"
;; Correct!
;; (Not to be picky, but we could multiply numerator and denominator by -1.)
| null | https://raw.githubusercontent.com/sarabander/p2pu-sicp/fbc49b67dac717da1487629fb2d7a7d86dfdbe32/2.5/2.97.scm | scheme | Added procedures to reduce fractions
internal procedures
representation of poly
representation of terms and termlists
Greatest common divisor of polynomials
Original:
(define (gcd-terms a b)
(if (empty-termlist? b)
a
(gcd-terms b (remainder-terms a b))))
Uses pseudoremainder-terms and removes common factors from coefficients:
New concepts introduced to avoid fractional coefficients:
Oh Lords of Lambda, I have sinned!
I've penetrated the abstraction barrier!
(Must repent and rewrite the procedure thrice.)
Sorts sparse termlist by term's order (descending)
Converts dense termlist to sparse, leaves already sparse list intact
Converts dense polynomial to sparse
interface to rest of the system
internal procedures
interface to rest of the system
Tests
"x + 1"
"x³ - 1"
"x"
"x² - 1"
"-x - 1"
"-x³ + 1"
"x"
"x² - 1"
'(rational
polynomial
x
(0 1))
"-x³ - 2x² - 3x - 1"
"-x⁴ - x³ + x + 1"
Correct!
(Not to be picky, but we could multiply numerator and denominator by -1.) |
(define (install-polynomial-package)
(define (make-poly variable term-list)
(cons variable term-list))
(define (variable p) (car p))
(define (variable? x) (symbol? x))
(define (same-variable? v1 v2)
(and (variable? v1) (variable? v2) (eq? v1 v2)))
(define (adjoin-term term term-list)
(if (and (list? term) (=zero? (coeff term)))
term-list
(cons term term-list)))
(define (the-empty-termlist) '())
(define (first-term term-list) (car term-list))
(define (rest-terms term-list) (cdr term-list))
(define (empty-termlist? term-list)
(or (null? term-list) (list-of-zeros? term-list)))
(define (make-term type termorder termcoeff)
(if (eq? type 'dense)
termcoeff
(list termorder termcoeff)))
(define (termtype term)
(if (list? term) 'sparse 'dense))
(define (order term partial-termlist)
(if (list? term)
(car term)
(sub1 (length partial-termlist))))
(define (coeff term)
(if (list? term)
(cadr term)
term))
(define (gcd-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(gcd-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - GCD-POLY"
(list p1 p2))))
(define (gcd-terms a b)
(if (empty-termlist? b)
(let ((gcd-of-coeffs (apply gcd (map coeff a))))
(map (λ (term) (list (car term)
(/ (cadr term) gcd-of-coeffs)))
a))
(gcd-terms b (pseudoremainder-terms a b))))
(define (remainder-terms a b)
(cadr (div-terms a b)))
(define (pseudoquotient-terms P Q)
(pseudodivision-terms car P Q))
(define (pseudoremainder-terms P Q)
(pseudodivision-terms cadr P Q))
(define (pseudodivision-terms f P Q)
(let ((O1 (order (first-term P) P))
(O2 (order (first-term Q) Q))
(c (coeff (first-term Q))))
(let ((integerizer (list (list 0 (expt c (+ 1 O1 (- O2)))))))
(f (div-terms (mul-terms integerizer P) Q)))))
(define (reduce-poly n d)
(if (same-variable? (variable n) (variable d))
(let ((n-d-reduced (reduce-terms (term-list n)
(term-list d))))
(cons (make-poly (variable n) (car n-d-reduced))
(make-poly (variable n) (cadr n-d-reduced))))
(error "Polys not in same var - ADD-POLY"
(list p1 p2))))
(define (reduce-terms n d)
(let ((g (gcd-terms n d)))
(let ((O1 (max (order (first-term n) n)
(order (first-term d) d)))
(O2 (order (first-term g) g))
(c (coeff (first-term g))))
(let ((integerizer (list (list 0 (expt c (+ 1 O1 (- O2)))))))
(let ((n-integerized (mul-terms integerizer n))
(d-integerized (mul-terms integerizer d)))
(let ((n/g (car (div-terms n-integerized g)))
(d/g (car (div-terms d-integerized g))))
(let ((gcd-of-coeffs
(apply gcd (map coeff (append n/g d/g)))))
(let ((divide-by-gcd
(λ (term) (list (car term) (/ (cadr term)
gcd-of-coeffs)))))
(let ((n-reduced (map divide-by-gcd n/g))
(d-reduced (map divide-by-gcd d/g)))
(list n-reduced d-reduced))))))))))
(define (reduce-integers n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
(define (add-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(add-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - ADD-POLY"
(list p1 p2))))
(define (add-terms L1 L2)
(cond ((empty-termlist? L1) L2)
((empty-termlist? L2) L1)
(else
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(cond ((> (order t1 L1) (order t2 L2))
(adjoin-term
t1 (add-terms (rest-terms L1) L2)))
((< (order t1 L1) (order t2 L2))
(adjoin-term
t2 (add-terms L1 (rest-terms L2))))
(else
(adjoin-term
(make-term (termtype t1)
(order t1 L1)
(add (coeff t1) (coeff t2)))
(add-terms (rest-terms L1)
(rest-terms L2)))))))))
(define (mul-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(make-poly (variable p1)
(mul-terms (term-list p1)
(term-list p2)))
(error "Polys not in same var - MUL-POLY"
(list p1 p2))))
(define (mul-terms L1 L2)
(if (empty-termlist? L1)
(the-empty-termlist)
(add-terms (mul-term-by-all-terms (first-term L1)
(order (first-term L1) L1)
L2)
(mul-terms (rest-terms L1) L2))))
(define (mul-term-by-all-terms t1 t1-order L)
(if (empty-termlist? L)
(the-empty-termlist)
(let ((t2 (first-term L)))
(adjoin-term
(make-term (termtype t1)
(+ t1-order (order t2 L))
(mul (coeff t1) (coeff t2)))
(mul-term-by-all-terms t1
t1-order
(rest-terms L))))))
Division
(define (div-poly p1 p2)
(if (same-variable? (variable p1) (variable p2))
(let ((divided-terms (div-terms (sort-termlist (term-list p1))
(sort-termlist (term-list p2)))))
(list
(make-poly (variable p1) (car divided-terms))
(make-poly (variable p1) (cadr divided-terms))))
(error "Polys not in same var - MUL-POLY"
(list p1 p2))))
(define (div-terms L1 L2)
(if (empty-termlist? L1)
(list (the-empty-termlist) (the-empty-termlist))
(let ((t1 (first-term L1))
(t2 (first-term L2)))
(if (> (order t2 L2) (order t1 L1))
(list (the-empty-termlist) L1)
(let ((new-c (div (coeff t1) (coeff t2)))
(new-o (- (order t1 L1) (order t2 L2))))
(let* ((newterm (list (make-term 'sparse new-o new-c)))
(rest-of-result
(let* ((subtractor (mul-terms newterm L2))
(difference (sort-termlist
(add-terms L1
(negate-termlist
subtractor)))))
(if (empty? difference)
(list (the-empty-termlist)
(the-empty-termlist))
(div-terms difference L2)))))
(list
(sort-termlist (add-terms newterm
(car rest-of-result)))
(cadr rest-of-result))))))))
(define (sort-termlist L)
(sort L #:key car >))
(define (convert-to-sparse termlist)
(if (empty? termlist)
empty
(let ((first-elem (car termlist)))
(if (and (number? first-elem) (zero? first-elem))
(convert-to-sparse (cdr termlist))
(cons (list (order first-elem termlist) (coeff first-elem))
(convert-to-sparse (cdr termlist)))))))
(define (to-sparse polynomial)
(cons (variable polynomial)
(convert-to-sparse (term-list polynomial))))
Negates all terms
(define (negate-termlist termlist)
(if (empty? termlist)
empty
(let ((negator (if (list? (car termlist))
(λ (elem) (list (car elem) (- (cadr elem))))
-)))
(map negator termlist))))
(define (tag p) (attach-tag 'polynomial p))
(put 'add '(polynomial polynomial)
(lambda (p1 p2) (tag (add-poly p1 p2))))
(put 'sub '(polynomial polynomial)
(lambda (p1 p2) (tag (add-poly p1 (contents (neg (tag p2)))))))
(put 'mul '(polynomial polynomial)
(lambda (p1 p2) (tag (mul-poly (to-sparse p1)
(to-sparse p2)))))
(put 'div '(polynomial polynomial)
(lambda (p1 p2)
(let ((quotient+remainder (div-poly (to-sparse p1)
(to-sparse p2))))
(list (tag (car quotient+remainder))
(tag (cadr quotient+remainder))))))
(put 'neg '(polynomial)
(lambda (p)
(tag (cons (variable p)
(negate-termlist (contents p))))))
(put '=zero? '(polynomial)
(λ (p) (list-of-zeros? (contents p))))
(put 'gcd '(polynomial polynomial)
(λ (p1 p2) (tag (gcd-poly (to-sparse p1)
(to-sparse p2)))))
(put 'gcd '(scheme-number scheme-number) gcd)
(put 'make 'polynomial
(lambda (var terms) (tag (make-poly var terms))))
(put 'reduce '(scheme-number scheme-number) reduce-integers)
(put 'reduce '(polynomial polynomial)
(λ (n d)
(let ((reduced-p (reduce-poly n d)))
(cons (tag (car reduced-p))
(tag (cdr reduced-p))))))
'done)
(install-polynomial-package)
(define (install-rational-package)
(define (numer x) (car x))
(define (denom x) (cdr x))
(define (make-rat n d) (reduce n d))
(define (add-rat x y)
(make-rat (add (mul (numer x) (denom y))
(mul (numer y) (denom x)))
(mul (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (sub (mul (numer x) (denom y))
(mul (numer y) (denom x)))
(mul (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (mul (numer x) (numer y))
(mul (denom x) (denom y))))
(define (div-rat x y)
(make-rat (div (numer x) (denom y))
(div (denom x) (numer y))))
(define (tag x) (attach-tag 'rational x))
(put 'add '(rational rational)
(lambda (x y) (tag (add-rat x y))))
(put 'sub '(rational rational)
(lambda (x y) (tag (sub-rat x y))))
(put 'mul '(rational rational)
(lambda (x y) (tag (mul-rat x y))))
(put 'div '(rational rational)
(lambda (x y) (tag (div-rat x y))))
(put 'square '(rational)
(lambda (r) (sqr (/ (numer r) (denom r)))))
(put 'sine '(rational)
(lambda (r) (sin (/ (numer r) (denom r)))))
(put 'cosine '(rational)
(lambda (r) (cos (/ (numer r) (denom r)))))
(put 'atangent '(rational)
(lambda (r) (atan (/ (numer r) (denom r)))))
(put 'make 'rational
(lambda (n d) (tag (make-rat n d))))
(put 'numer '(rational)
(lambda (r) (numer r)))
(put 'denom '(rational)
(lambda (r) (denom r)))
'done)
(install-rational-package)
(define (make-rational n d)
((get 'make 'rational) n d))
(define (numer r)
(apply-generic 'numer r))
(define (denom r)
(apply-generic 'denom r))
(define (reduce n d)
(apply-generic 'reduce n d))
' ( rational 4 . 27 )
(define p1 (make-polynomial 'x '((1 1) (0 1))))
(define p2 (make-polynomial 'x '((3 1) (0 -1))))
(define p3 (make-polynomial 'x '((1 1))))
(define p4 (make-polynomial 'x '((2 1) (0 -1))))
(define rf1 (make-rational p1 p2))
' ( rational ( polynomial x ( 1 -1 ) ( 0 -1 ) ) polynomial x ( 3 -1 ) ( 0 1 ) )
(define rf2 (make-rational p3 p4))
' ( rational ( polynomial x ( 1 1 ) ) polynomial x ( 2 1 ) ( 0 -1 ) )
(define rf1+rf2 (add rf1 rf2))
rf1+rf2
( polynomial x ( 3 -1 ) ( 2 -2 ) ( 1 -3 ) ( 0 -1 ) )
( 4 -1 )
( 3 -1 )
( 1 1 )
|
fc9052203fff363301545926a260ea8993fdae1599a024d4d52b1ec12216f270 | dmitryvk/sbcl-win32-threads | cross-misc.lisp | ;;;; cross-compile-time-only replacements for miscellaneous unportable
;;;; stuff
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB!IMPL")
In correct code , TRULY - THE has only a performance impact and can
;;; be safely degraded to ordinary THE.
(defmacro truly-the (type expr)
`(the ,type ,expr))
;;; MAYBE-INLINE and FREEZE-TYPE declarations can be safely ignored
;;; (possibly at some cost in efficiency).
(declaim (declaration freeze-type maybe-inline))
;;; INHIBIT-WARNINGS declarations can be safely ignored (although we
;;; may then have to wade through some irrelevant warnings).
(declaim (declaration inhibit-warnings))
;;; Interrupt control isn't an issue in the cross-compiler: we don't
use address - dependent ( and thus GC - dependent ) hashes , and we only
;;; have a single thread of control.
(defmacro without-interrupts (&rest forms)
`(macrolet ((allow-with-interrupts (&body body)
`(progn ,@body))
(with-local-interrupts (&body body)
`(progn ,@body)))
,@forms))
(defmacro with-locked-hash-table ((table) &body body)
(declare (ignore table))
`(progn ,@body))
(defmacro defglobal (name value &rest doc)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter ,name
(if (boundp ',name)
(symbol-value ',name)
,value)
,@doc)))
The GENESIS function works with fasl code which would , in the
target SBCL , work on ANSI - STREAMs ( streams which are n't extended
;;; Gray streams). In ANSI Common Lisp, an ANSI-STREAM is just a
CL : STREAM .
(deftype ansi-stream () 'stream)
(deftype sb!kernel:instance ()
'(or condition structure-object standard-object))
(deftype sb!kernel:funcallable-instance ()
(error "not clear how to represent FUNCALLABLE-INSTANCE type"))
In the target SBCL , the INSTANCE type refers to a base
;;; implementation for compound types with lowtag
;;; INSTANCE-POINTER-LOWTAG. There's no way to express exactly that
;;; concept portably, but we can get essentially the same effect by
;;; testing for any of the standard types which would, in the target
SBCL , be derived from INSTANCE :
(defun %instancep (x)
(typep x '(or condition structure-object standard-object)))
;;; There aren't any FUNCALLABLE-INSTANCEs in the cross-compilation
host .
(defun funcallable-instance-p (x)
(if (typep x 'generic-function)
In the target SBCL , FUNCALLABLE - INSTANCEs are used to implement
;; generic functions, so any case which tests for this might in
;; fact be trying to test for generic functions. My (WHN 19990313)
;; expectation is that this case won't arise in the
;; cross-compiler, but if it does, it deserves a little thought,
rather than reflexively returning NIL .
(error "not clear how to handle GENERIC-FUNCTION")
nil))
;;; This seems to be the portable Common Lisp type test which
corresponds to the effect of the target SBCL implementation test ...
(defun sb!kernel:array-header-p (x)
(and (typep x 'array)
(or (not (typep x 'simple-array))
(/= (array-rank x) 1))))
GENESIS needs these at cross - compile time . The target
;;; implementation of these is reasonably efficient by virtue of its
;;; ability to peek into the internals of the package implementation;
;;; this reimplementation is portable but slow.
(defun package-internal-symbol-count (package)
(let ((result 0))
(declare (type fixnum result))
(do-symbols (i package)
: The ANSI Common Lisp specification warns that
;; DO-SYMBOLS may execute its body more than once for symbols
;; that are inherited from multiple packages, and we currently
;; make no attempt to correct for that here. (The current uses
;; of this function at cross-compile time don't really care if
the count is a little too high . ) -- WHN 19990826
(multiple-value-bind (symbol status)
(find-symbol (symbol-name i) package)
(declare (ignore symbol))
(when (member status '(:internal :inherited))
(incf result))))
result))
(defun package-external-symbol-count (package)
(let ((result 0))
(declare (type fixnum result))
(do-external-symbols (i package)
(declare (ignorable i))
(incf result))
result))
;;; In the target Lisp, INTERN* is the primitive and INTERN is
;;; implemented in terms of it. This increases efficiency by letting
;;; us reuse a fixed-size buffer; the alternative would be
;;; particularly painful because we don't implement DYNAMIC-EXTENT. In
the host , this is only used at cold load time , and we do n't
;;; care as much about efficiency, so it's fine to treat the host
;;; Lisp's INTERN as primitive and implement INTERN* in terms of it.
(defun intern* (nameoid length package)
(intern (replace (make-string length) nameoid :end2 length) package))
;;; In the target Lisp this is implemented by reading a fixed slot in
;;; the symbol. In portable ANSI Common Lisp the same criteria can be
;;; met (more slowly, and with the extra property of repeatability
between runs ) by just calling SXHASH .
(defun symbol-hash (symbol)
(declare (type symbol symbol))
(sxhash symbol))
(defvar sb!xc:*gensym-counter* 0)
(defun sb!xc:gensym (&optional (thing "G"))
(declare (type string thing))
(let ((n sb!xc:*gensym-counter*))
(prog1
(make-symbol (concatenate 'string thing (write-to-string n :base 10 :radix nil :pretty nil)))
(incf sb!xc:*gensym-counter*))))
;;; These functions are needed for constant-folding.
(defun sb!kernel:simple-array-nil-p (object)
(when (typep object 'array)
(assert (not (eq (array-element-type object) nil))))
nil)
(defun sb!kernel:%negate (number)
(- number))
(defun sb!kernel:%single-float (number)
(coerce number 'single-float))
(defun sb!kernel:%double-float (number)
(coerce number 'double-float))
(defun sb!kernel:%ldb (size posn integer)
(ldb (byte size posn) integer))
(defun sb!kernel:%dpb (newbyte size posn integer)
(dpb newbyte (byte size posn) integer))
(defun sb!kernel:%with-array-data (array start end)
(assert (typep array '(simple-array * (*))))
(values array start end 0))
(defun sb!kernel:%with-array-data/fp (array start end)
(assert (typep array '(simple-array * (*))))
(values array start end 0))
(defun sb!kernel:signed-byte-32-p (number)
(typep number '(signed-byte 32)))
;;; package locking nops for the cross-compiler
(defmacro without-package-locks (&body body)
`(progn ,@body))
(defmacro with-single-package-locked-error ((&optional kind thing &rest format)
&body body)
(declare (ignore kind thing format))
`(progn ,@body))
(defun program-assert-symbol-home-package-unlocked (context symbol control)
(declare (ignore context control))
symbol)
(defun assert-package-unlocked (package &optional control &rest args)
(declare (ignore control args))
package)
(defun assert-symbol-home-package-unlocked (name format &key continuablep)
(declare (ignore format continuablep))
name)
(declaim (declaration enable-package-locks disable-package-locks))
| null | https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/src/code/cross-misc.lisp | lisp | cross-compile-time-only replacements for miscellaneous unportable
stuff
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
be safely degraded to ordinary THE.
MAYBE-INLINE and FREEZE-TYPE declarations can be safely ignored
(possibly at some cost in efficiency).
INHIBIT-WARNINGS declarations can be safely ignored (although we
may then have to wade through some irrelevant warnings).
Interrupt control isn't an issue in the cross-compiler: we don't
have a single thread of control.
Gray streams). In ANSI Common Lisp, an ANSI-STREAM is just a
implementation for compound types with lowtag
INSTANCE-POINTER-LOWTAG. There's no way to express exactly that
concept portably, but we can get essentially the same effect by
testing for any of the standard types which would, in the target
There aren't any FUNCALLABLE-INSTANCEs in the cross-compilation
generic functions, so any case which tests for this might in
fact be trying to test for generic functions. My (WHN 19990313)
expectation is that this case won't arise in the
cross-compiler, but if it does, it deserves a little thought,
This seems to be the portable Common Lisp type test which
implementation of these is reasonably efficient by virtue of its
ability to peek into the internals of the package implementation;
this reimplementation is portable but slow.
DO-SYMBOLS may execute its body more than once for symbols
that are inherited from multiple packages, and we currently
make no attempt to correct for that here. (The current uses
of this function at cross-compile time don't really care if
In the target Lisp, INTERN* is the primitive and INTERN is
implemented in terms of it. This increases efficiency by letting
us reuse a fixed-size buffer; the alternative would be
particularly painful because we don't implement DYNAMIC-EXTENT. In
care as much about efficiency, so it's fine to treat the host
Lisp's INTERN as primitive and implement INTERN* in terms of it.
In the target Lisp this is implemented by reading a fixed slot in
the symbol. In portable ANSI Common Lisp the same criteria can be
met (more slowly, and with the extra property of repeatability
These functions are needed for constant-folding.
package locking nops for the cross-compiler |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB!IMPL")
In correct code , TRULY - THE has only a performance impact and can
(defmacro truly-the (type expr)
`(the ,type ,expr))
(declaim (declaration freeze-type maybe-inline))
(declaim (declaration inhibit-warnings))
use address - dependent ( and thus GC - dependent ) hashes , and we only
(defmacro without-interrupts (&rest forms)
`(macrolet ((allow-with-interrupts (&body body)
`(progn ,@body))
(with-local-interrupts (&body body)
`(progn ,@body)))
,@forms))
(defmacro with-locked-hash-table ((table) &body body)
(declare (ignore table))
`(progn ,@body))
(defmacro defglobal (name value &rest doc)
`(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter ,name
(if (boundp ',name)
(symbol-value ',name)
,value)
,@doc)))
The GENESIS function works with fasl code which would , in the
target SBCL , work on ANSI - STREAMs ( streams which are n't extended
CL : STREAM .
(deftype ansi-stream () 'stream)
(deftype sb!kernel:instance ()
'(or condition structure-object standard-object))
(deftype sb!kernel:funcallable-instance ()
(error "not clear how to represent FUNCALLABLE-INSTANCE type"))
In the target SBCL , the INSTANCE type refers to a base
SBCL , be derived from INSTANCE :
(defun %instancep (x)
(typep x '(or condition structure-object standard-object)))
host .
(defun funcallable-instance-p (x)
(if (typep x 'generic-function)
In the target SBCL , FUNCALLABLE - INSTANCEs are used to implement
rather than reflexively returning NIL .
(error "not clear how to handle GENERIC-FUNCTION")
nil))
corresponds to the effect of the target SBCL implementation test ...
(defun sb!kernel:array-header-p (x)
(and (typep x 'array)
(or (not (typep x 'simple-array))
(/= (array-rank x) 1))))
GENESIS needs these at cross - compile time . The target
(defun package-internal-symbol-count (package)
(let ((result 0))
(declare (type fixnum result))
(do-symbols (i package)
: The ANSI Common Lisp specification warns that
the count is a little too high . ) -- WHN 19990826
(multiple-value-bind (symbol status)
(find-symbol (symbol-name i) package)
(declare (ignore symbol))
(when (member status '(:internal :inherited))
(incf result))))
result))
(defun package-external-symbol-count (package)
(let ((result 0))
(declare (type fixnum result))
(do-external-symbols (i package)
(declare (ignorable i))
(incf result))
result))
the host , this is only used at cold load time , and we do n't
(defun intern* (nameoid length package)
(intern (replace (make-string length) nameoid :end2 length) package))
between runs ) by just calling SXHASH .
(defun symbol-hash (symbol)
(declare (type symbol symbol))
(sxhash symbol))
(defvar sb!xc:*gensym-counter* 0)
(defun sb!xc:gensym (&optional (thing "G"))
(declare (type string thing))
(let ((n sb!xc:*gensym-counter*))
(prog1
(make-symbol (concatenate 'string thing (write-to-string n :base 10 :radix nil :pretty nil)))
(incf sb!xc:*gensym-counter*))))
(defun sb!kernel:simple-array-nil-p (object)
(when (typep object 'array)
(assert (not (eq (array-element-type object) nil))))
nil)
(defun sb!kernel:%negate (number)
(- number))
(defun sb!kernel:%single-float (number)
(coerce number 'single-float))
(defun sb!kernel:%double-float (number)
(coerce number 'double-float))
(defun sb!kernel:%ldb (size posn integer)
(ldb (byte size posn) integer))
(defun sb!kernel:%dpb (newbyte size posn integer)
(dpb newbyte (byte size posn) integer))
(defun sb!kernel:%with-array-data (array start end)
(assert (typep array '(simple-array * (*))))
(values array start end 0))
(defun sb!kernel:%with-array-data/fp (array start end)
(assert (typep array '(simple-array * (*))))
(values array start end 0))
(defun sb!kernel:signed-byte-32-p (number)
(typep number '(signed-byte 32)))
(defmacro without-package-locks (&body body)
`(progn ,@body))
(defmacro with-single-package-locked-error ((&optional kind thing &rest format)
&body body)
(declare (ignore kind thing format))
`(progn ,@body))
(defun program-assert-symbol-home-package-unlocked (context symbol control)
(declare (ignore context control))
symbol)
(defun assert-package-unlocked (package &optional control &rest args)
(declare (ignore control args))
package)
(defun assert-symbol-home-package-unlocked (name format &key continuablep)
(declare (ignore format continuablep))
name)
(declaim (declaration enable-package-locks disable-package-locks))
|
e99f52786408565e1252009b241b1bfbbfb24e837d5635f8b0c04697ced21afe | CodyReichert/qi | example.lisp | ;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
;;;
;;; This is example of Unix-opts, a minimalistic parser of command line
;;; options.
;;;
Copyright © 2015
;;;
;;; 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.
(asdf:load-system :unix-opts)
First of all , we need to define command line options . We do this with
;;; `define-opts' macro.
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help")
(:name :verbose
:description "verbose output"
:short #\v
:long "verbose")
(:name :level
:description "the program will run on LEVEL level"
:short #\l
:long "level"
:arg-parser #'parse-integer
:meta-var "LEVEL")
(:name :output
:description "redirect output to file FILE"
:short #\o
:long "output"
:arg-parser #'identity
:meta-var "FILE"))
;;; OK, since command line options can be malformed we should use a handy
;;; Common Lisp feature: restarts. Unix-opts gives us all we need to do so.
;;; Here we define function that will print a warning and ignore
;;; unknown-option. Several restarts (behaviors) are available for every
;;; exception that Unix-opts can throw. See documentation for `get-opts'
;;; function for more information.
(defun unknown-option (condition)
(format t "warning: ~s option is unknown!~%" (opts:option condition))
(invoke-restart 'opts:skip-option))
(defmacro when-option ((options opt) &body body)
`(let ((it (getf ,options ,opt)))
(when it
,@body)))
(multiple-value-bind (options free-args)
(handler-case
(handler-bind ((opts:unknown-option #'unknown-option))
(opts:get-opts))
(opts:missing-arg (condition)
(format t "fatal: option ~s needs an argument!~%"
(opts:option condition)))
(opts:arg-parser-failed (condition)
(format t "fatal: cannot parse ~s as argument of ~s~%"
(opts:raw-arg condition)
(opts:option condition))))
;; Here all options are checked independently, it's trivial to code any
;; logic to process them.
(when-option (options :help)
(opts:describe
:prefix "example — program to demonstrate unix-opts library"
:suffix "so that's how it works…"
:usage-of "example.sh"
:args "[FREE-ARGS]"))
(when-option (options :verbose)
(format t "OK, running in verbose mode…~%"))
(when-option (options :level)
(format t "I see you've supplied level option, you want ~a level!~%" it))
(when-option (options :output)
(format t "I see you want to output the stuff to ~s!~%"
(getf options :output)))
(format t "free args: ~{~a~^, ~}~%" free-args))
| null | https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/unix-opts-master/example/example.lisp | lisp | -*- Mode: Lisp; Syntax: ANSI-Common-Lisp -*-
This is example of Unix-opts, a minimalistic parser of command line
options.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
without limitation the rights to use, copy, modify, merge, publish,
the following conditions:
The above copyright notice and this permission notice shall be included
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
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
`define-opts' macro.
OK, since command line options can be malformed we should use a handy
Common Lisp feature: restarts. Unix-opts gives us all we need to do so.
Here we define function that will print a warning and ignore
unknown-option. Several restarts (behaviors) are available for every
exception that Unix-opts can throw. See documentation for `get-opts'
function for more information.
Here all options are checked independently, it's trivial to code any
logic to process them. | Copyright © 2015
" Software " ) , to deal in the Software without restriction , including
distribute , sublicense , and/or sell copies of the Software , and to
permit persons to whom the Software is furnished to do so , subject to
in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS
LIABLE FOR ANY CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION
(asdf:load-system :unix-opts)
First of all , we need to define command line options . We do this with
(opts:define-opts
(:name :help
:description "print this help text"
:short #\h
:long "help")
(:name :verbose
:description "verbose output"
:short #\v
:long "verbose")
(:name :level
:description "the program will run on LEVEL level"
:short #\l
:long "level"
:arg-parser #'parse-integer
:meta-var "LEVEL")
(:name :output
:description "redirect output to file FILE"
:short #\o
:long "output"
:arg-parser #'identity
:meta-var "FILE"))
(defun unknown-option (condition)
(format t "warning: ~s option is unknown!~%" (opts:option condition))
(invoke-restart 'opts:skip-option))
(defmacro when-option ((options opt) &body body)
`(let ((it (getf ,options ,opt)))
(when it
,@body)))
(multiple-value-bind (options free-args)
(handler-case
(handler-bind ((opts:unknown-option #'unknown-option))
(opts:get-opts))
(opts:missing-arg (condition)
(format t "fatal: option ~s needs an argument!~%"
(opts:option condition)))
(opts:arg-parser-failed (condition)
(format t "fatal: cannot parse ~s as argument of ~s~%"
(opts:raw-arg condition)
(opts:option condition))))
(when-option (options :help)
(opts:describe
:prefix "example — program to demonstrate unix-opts library"
:suffix "so that's how it works…"
:usage-of "example.sh"
:args "[FREE-ARGS]"))
(when-option (options :verbose)
(format t "OK, running in verbose mode…~%"))
(when-option (options :level)
(format t "I see you've supplied level option, you want ~a level!~%" it))
(when-option (options :output)
(format t "I see you want to output the stuff to ~s!~%"
(getf options :output)))
(format t "free args: ~{~a~^, ~}~%" free-args))
|
061a0e220c8e9a12e9e396c0529fc54623c9411844e1ffcda6c7ca8ee261f97d | 8c6794b6/guile-tjit | readline.scm | ;;;; readline.scm --- support functions for command-line editing
;;;;
Copyright ( C ) 1997 , 1999 , 2000 , 2001 , 2002 , 2006 , 2009 , 2010 , 2011 ,
2013 , 2014 Free Software Foundation , Inc.
;;;;
;;;; This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 , 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 software; see the file COPYING. If not, write to
the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor ,
Boston , USA
;;;;
Contributed by < > .
;;;; Extensions based upon code by
< > .
(define-module (ice-9 readline)
#:use-module (ice-9 session)
#:use-module (ice-9 regex)
#:use-module (ice-9 buffered-input)
#:no-backtrace
#:export (filename-completion-function
add-history
read-history
write-history
clear-history))
;;; Dynamically link the glue code for accessing the readline library,
;;; but only when it isn't already present.
(if (not (provided? 'readline))
(load-extension "guile-readline" "scm_init_readline"))
(if (not (provided? 'readline))
(scm-error 'misc-error
#f
"readline is not provided in this Guile installation"
'()
'()))
;;; Run-time options
(export
readline-options
readline-enable
readline-disable)
(export-syntax
readline-set!)
(define-option-interface
(readline-options-interface
(readline-options readline-enable readline-disable)
(readline-set!)))
;;; MDJ 980513 <>:
;;; There should probably be low-level support instead of this code.
: FIXME : : If the - readline - port , input - port or output - port are closed ,
;;; guile will enter an endless loop or crash.
(define-once new-input-prompt "")
(define-once continuation-prompt "")
(define-once input-port (current-input-port))
(define-once output-port (current-output-port))
(define-once read-hook #f)
(define (make-readline-port)
(let ((history-buffer #f))
(make-line-buffered-input-port (lambda (continuation?)
;; When starting a new read, add
;; the previously read expression
;; to the history.
(if (and (not continuation?)
history-buffer)
(begin
(add-history history-buffer)
(set! history-buffer #f)))
;; Set up prompts and read a line.
(let* ((prompt (if continuation?
continuation-prompt
new-input-prompt))
(str (%readline (if (string? prompt)
prompt
(prompt))
input-port
output-port
read-hook)))
(or (eof-object? str)
(string=? str "")
(set! history-buffer
(if history-buffer
(string-append history-buffer
"\n"
str)
str)))
str)))))
We only create one readline port . There 's no point in having
;;; more, since they would all share the tty and history ---
;;; everything except the prompt. And don't forget the
;;; compile/load/run phase distinctions. Also, the readline library
;;; isn't reentrant.
(define-once the-readline-port #f)
(define-once history-variable "GUILE_HISTORY")
(define-once history-file
(string-append (or (getenv "HOME") ".") "/.guile_history"))
(define-public readline-port
(let ((do (lambda (r/w)
(if (memq 'history-file (readline-options-interface))
(r/w (or (getenv history-variable)
history-file))))))
(lambda ()
(if (not the-readline-port)
(begin
(do read-history)
(set! the-readline-port (make-readline-port))
(add-hook! exit-hook (lambda ()
(do write-history)
(clear-history)))))
the-readline-port)))
;;; The user might try to use readline in his programs. It then
;;; becomes very uncomfortable that the current-input-port is the
;;; readline port...
;;;
;;; Here, we detect this situation and replace it with the
;;; underlying port.
;;;
;;; %readline is the low-level readline procedure.
(define-public (readline . args)
(let ((prompt new-input-prompt)
(inp input-port))
(cond ((not (null? args))
(set! prompt (car args))
(set! args (cdr args))
(cond ((not (null? args))
(set! inp (car args))
(set! args (cdr args))))))
(apply %readline
prompt
(if (eq? inp the-readline-port)
input-port
inp)
args)))
(define-public (set-readline-prompt! p . rest)
(set! new-input-prompt p)
(if (not (null? rest))
(set! continuation-prompt (car rest))))
(define-public (set-readline-input-port! p)
(cond ((or (not (file-port? p)) (not (input-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file input port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-input-port!"
"Port not open: ~S" (list p) #f))
(else
(set! input-port p))))
(define-public (set-readline-output-port! p)
(cond ((or (not (file-port? p)) (not (output-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file output port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-output-port!"
"Port not open: ~S" (list p) #f))
(else
(set! output-port p))))
(define-public (set-readline-read-hook! h)
(set! read-hook h))
(define-public apropos-completion-function
(let ((completions '()))
(lambda (text cont?)
(if (not cont?)
(set! completions
(map symbol->string
(apropos-internal
(string-append "^" (regexp-quote text))))))
(if (null? completions)
#f
(let ((retval (car completions)))
(begin (set! completions (cdr completions))
retval))))))
(if (provided? 'regex)
(set! *readline-completion-function* apropos-completion-function))
(define-public (with-readline-completion-function completer thunk)
"With @var{completer} as readline completion function, call @var{thunk}."
(let ((old-completer *readline-completion-function*))
(dynamic-wind
(lambda ()
(set! *readline-completion-function* completer))
thunk
(lambda ()
(set! *readline-completion-function* old-completer)))))
(define-once readline-repl-reader
(let ((boot-9-repl-reader repl-reader))
(lambda* (repl-prompt #:optional (reader (fluid-ref current-reader)))
(let ((port (current-input-port)))
(if (eq? port (readline-port))
(let ((outer-new-input-prompt new-input-prompt)
(outer-continuation-prompt continuation-prompt)
(outer-read-hook read-hook))
(dynamic-wind
(lambda ()
(set-buffered-input-continuation?! port #f)
(set-readline-prompt! repl-prompt "... ")
(set-readline-read-hook! (lambda ()
(run-hook before-read-hook))))
(lambda () ((or reader read) port))
(lambda ()
(set-readline-prompt! outer-new-input-prompt
outer-continuation-prompt)
(set-readline-read-hook! outer-read-hook))))
(boot-9-repl-reader repl-prompt reader))))))
(define-public (activate-readline)
(if (isatty? (current-input-port))
(begin
(set-current-input-port (readline-port))
(set! repl-reader readline-repl-reader)
(set! (using-readline?) #t))))
(define-public (make-completion-function strings)
"Construct and return a completion function for a list of strings.
The returned function is suitable for passing to
@code{with-readline-completion-function. The argument @var{strings}
should be a list of strings, where each string is one of the possible
completions."
(letrec ((strs '())
(regexp #f)
(completer (lambda (text continue?)
(if continue?
(if (null? strs)
#f
(let ((str (car strs)))
(set! strs (cdr strs))
(if (string-match regexp str)
str
(completer text #t))))
(begin
(set! strs strings)
(set! regexp
(string-append "^" (regexp-quote text)))
(completer text #t))))))
completer))
| null | https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/guile-readline/ice-9/readline.scm | scheme | readline.scm --- support functions for command-line editing
This program is free software; you can redistribute it and/or modify
either version 3 , 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.
along with this software; see the file COPYING. If not, write to
Extensions based upon code by
Dynamically link the glue code for accessing the readline library,
but only when it isn't already present.
Run-time options
MDJ 980513 <>:
There should probably be low-level support instead of this code.
guile will enter an endless loop or crash.
When starting a new read, add
the previously read expression
to the history.
Set up prompts and read a line.
more, since they would all share the tty and history ---
everything except the prompt. And don't forget the
compile/load/run phase distinctions. Also, the readline library
isn't reentrant.
The user might try to use readline in his programs. It then
becomes very uncomfortable that the current-input-port is the
readline port...
Here, we detect this situation and replace it with the
underlying port.
%readline is the low-level readline procedure. | Copyright ( C ) 1997 , 1999 , 2000 , 2001 , 2002 , 2006 , 2009 , 2010 , 2011 ,
2013 , 2014 Free Software Foundation , Inc.
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor ,
Boston , USA
Contributed by < > .
< > .
(define-module (ice-9 readline)
#:use-module (ice-9 session)
#:use-module (ice-9 regex)
#:use-module (ice-9 buffered-input)
#:no-backtrace
#:export (filename-completion-function
add-history
read-history
write-history
clear-history))
(if (not (provided? 'readline))
(load-extension "guile-readline" "scm_init_readline"))
(if (not (provided? 'readline))
(scm-error 'misc-error
#f
"readline is not provided in this Guile installation"
'()
'()))
(export
readline-options
readline-enable
readline-disable)
(export-syntax
readline-set!)
(define-option-interface
(readline-options-interface
(readline-options readline-enable readline-disable)
(readline-set!)))
: FIXME : : If the - readline - port , input - port or output - port are closed ,
(define-once new-input-prompt "")
(define-once continuation-prompt "")
(define-once input-port (current-input-port))
(define-once output-port (current-output-port))
(define-once read-hook #f)
(define (make-readline-port)
(let ((history-buffer #f))
(make-line-buffered-input-port (lambda (continuation?)
(if (and (not continuation?)
history-buffer)
(begin
(add-history history-buffer)
(set! history-buffer #f)))
(let* ((prompt (if continuation?
continuation-prompt
new-input-prompt))
(str (%readline (if (string? prompt)
prompt
(prompt))
input-port
output-port
read-hook)))
(or (eof-object? str)
(string=? str "")
(set! history-buffer
(if history-buffer
(string-append history-buffer
"\n"
str)
str)))
str)))))
We only create one readline port . There 's no point in having
(define-once the-readline-port #f)
(define-once history-variable "GUILE_HISTORY")
(define-once history-file
(string-append (or (getenv "HOME") ".") "/.guile_history"))
(define-public readline-port
(let ((do (lambda (r/w)
(if (memq 'history-file (readline-options-interface))
(r/w (or (getenv history-variable)
history-file))))))
(lambda ()
(if (not the-readline-port)
(begin
(do read-history)
(set! the-readline-port (make-readline-port))
(add-hook! exit-hook (lambda ()
(do write-history)
(clear-history)))))
the-readline-port)))
(define-public (readline . args)
(let ((prompt new-input-prompt)
(inp input-port))
(cond ((not (null? args))
(set! prompt (car args))
(set! args (cdr args))
(cond ((not (null? args))
(set! inp (car args))
(set! args (cdr args))))))
(apply %readline
prompt
(if (eq? inp the-readline-port)
input-port
inp)
args)))
(define-public (set-readline-prompt! p . rest)
(set! new-input-prompt p)
(if (not (null? rest))
(set! continuation-prompt (car rest))))
(define-public (set-readline-input-port! p)
(cond ((or (not (file-port? p)) (not (input-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file input port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-input-port!"
"Port not open: ~S" (list p) #f))
(else
(set! input-port p))))
(define-public (set-readline-output-port! p)
(cond ((or (not (file-port? p)) (not (output-port? p)))
(scm-error 'wrong-type-arg "set-readline-input-port!"
"Not a file output port: ~S" (list p) #f))
((port-closed? p)
(scm-error 'misc-error "set-readline-output-port!"
"Port not open: ~S" (list p) #f))
(else
(set! output-port p))))
(define-public (set-readline-read-hook! h)
(set! read-hook h))
(define-public apropos-completion-function
(let ((completions '()))
(lambda (text cont?)
(if (not cont?)
(set! completions
(map symbol->string
(apropos-internal
(string-append "^" (regexp-quote text))))))
(if (null? completions)
#f
(let ((retval (car completions)))
(begin (set! completions (cdr completions))
retval))))))
(if (provided? 'regex)
(set! *readline-completion-function* apropos-completion-function))
(define-public (with-readline-completion-function completer thunk)
"With @var{completer} as readline completion function, call @var{thunk}."
(let ((old-completer *readline-completion-function*))
(dynamic-wind
(lambda ()
(set! *readline-completion-function* completer))
thunk
(lambda ()
(set! *readline-completion-function* old-completer)))))
(define-once readline-repl-reader
(let ((boot-9-repl-reader repl-reader))
(lambda* (repl-prompt #:optional (reader (fluid-ref current-reader)))
(let ((port (current-input-port)))
(if (eq? port (readline-port))
(let ((outer-new-input-prompt new-input-prompt)
(outer-continuation-prompt continuation-prompt)
(outer-read-hook read-hook))
(dynamic-wind
(lambda ()
(set-buffered-input-continuation?! port #f)
(set-readline-prompt! repl-prompt "... ")
(set-readline-read-hook! (lambda ()
(run-hook before-read-hook))))
(lambda () ((or reader read) port))
(lambda ()
(set-readline-prompt! outer-new-input-prompt
outer-continuation-prompt)
(set-readline-read-hook! outer-read-hook))))
(boot-9-repl-reader repl-prompt reader))))))
(define-public (activate-readline)
(if (isatty? (current-input-port))
(begin
(set-current-input-port (readline-port))
(set! repl-reader readline-repl-reader)
(set! (using-readline?) #t))))
(define-public (make-completion-function strings)
"Construct and return a completion function for a list of strings.
The returned function is suitable for passing to
@code{with-readline-completion-function. The argument @var{strings}
should be a list of strings, where each string is one of the possible
completions."
(letrec ((strs '())
(regexp #f)
(completer (lambda (text continue?)
(if continue?
(if (null? strs)
#f
(let ((str (car strs)))
(set! strs (cdr strs))
(if (string-match regexp str)
str
(completer text #t))))
(begin
(set! strs strings)
(set! regexp
(string-append "^" (regexp-quote text)))
(completer text #t))))))
completer))
|
ff1a6e3da084487ce7f23f0dd38e1b732aae55cb8a8341df05dd2cb0a663ca12 | nallen05/logv | logv.lisp | ;
;
;
; todo: -log rotation script
; -different log levels
(in-package :logv)
; default logv environment
(defvar *default-log-env* :default-logv-env)
; global database of environments
(defvar *log-envs* nil) ;; (env-name . env-plist)
; log environment settings
(defun .verify-log-env-exists (log-env-name)
(if (assoc log-env-name *log-envs*)
t
(error "unknown log environment ~A. known loggers are: ~A" log-env-name (mapcar 'first *log-envs*))))
(defun .get-log-setting (key log-env-name)
(getf (rest (assoc log-env-name *log-envs*)) key))
(defun log-setting (key &optional (log-env-name *default-log-env*))
(.verify-log-env-exists log-env-name)
(.get-log-setting key log-env-name))
(defsetf log-setting (key (log-env-name *default-log-env*)) (new-value)
(let ((<log-env-name> (gensym "log-env-name-")))
`(let ((,<log-env-name> ,log-env-name))
(.verify-log-env-exists ,<log-env-name>)
(setf (getf (rest (assoc ,<log-env-name> *log-envs*))
,key)
,new-value))))
; writing to the log file
(defun .write-string-to-log (log-env-name string)
"
writes `STRING' to the LOG-ENV-NAME's log. exact behavior depends
on value of :LOG-OUTPUT log setting
"
(let ((log-output (log-setting :log-output log-env-name)))
(when log-output
(let ((string (concatenate 'string
(funcall (log-setting :log-prefix-string-factory log-env-name))
string))
(log-mutex (log-setting :log-mutex log-env-name)))
(with-lock-held (log-mutex)
(if (or (stringp log-output)
(pathnamep log-output))
(with-open-file (out log-output
:element-type '(unsigned-byte 8)
:direction :output
:if-exists :append
:if-does-not-exist :create)
(trivial-utf-8:write-utf-8-bytes string out))
(write-string string (if (eql log-output t)
*standard-output*
log-output)))))))
(values))
; creating new loggers
(defvar *.default-prefix-string-factory*
(lambda ()
(format nil
"~%; ~A [~A]: "
(rw-ut:write-time-string (get-universal-time)
"[YYYY/MM/DD] [hh:mm:ss]")
(thread-name (current-thread)))))
(defmacro def-log-env (env-name (&key logv-macro-name
logvs-macro-name
format-log-function-name)
&key (log-output t)
if : LOG - OUTPUT is
;; -T: then things that write to the log write to *STANDARD-OUTPUT*
;; -NIL: then things that normally write to the log don't do anything
;; -a stream: then things that write to the log write to the stream
;; -a pathname or a string [a pathname designator]: then things that write to the log
;; write to the file pointed to by the string/pathname. the file is created if it
;; doesn't already exist. if there are special characters then they are encoded in
UTF-8
(log-prefix-string-factory '*.default-prefix-string-factory*))
: LOG - PREFIX - STRING - FACTORY is a thunk that creates the string prepended to each log message
`(progn
(setf *log-envs*
(cons (list ',env-name
:log-output ,log-output
:log-prefix-string-factory ,log-prefix-string-factory
:log-mutex (make-lock (format nil "~A log mutex" ',env-name)))
_ _ LOG_MUTEX _ _ prevents multiple threads from writing to LOG - OUTPUT at the same time
(remove ',env-name *log-envs* :key 'first)))
,@(when logv-macro-name
`((defmacro ,logv-macro-name (form &rest more-forms)
(if more-forms
`(progn (logv ,form) (logv ,@more-forms))
(let ((% (gensym "value")))
`(let ((,% ,form))
(.write-string-to-log ',',env-name (format nil "~S -> ~S" ',form ,%))
,%))))))
,@(when logvs-macro-name
`((defmacro ,logvs-macro-name (form &rest more-forms)
(if more-forms
`(progn (logvs ,form) (logvs ,@more-forms))
(let ((%l (gensym "values")))
`(let ((,%l (multiple-value-list ,form)))
(.write-string-to-log ',',env-name (format nil "~S -> values list: ~S" ',form ,%l))
(apply 'values ,%l)))))))
,@(when format-log-function-name
`((defun ,format-log-function-name (fmt-string &rest fmt-args)
(.write-string-to-log ',env-name (apply 'format nil fmt-string fmt-args)))))))
(def-log-env :logv (:logv-macro-name logv
:logvs-macro-name logvs
:format-log-function-name format-log)) | null | https://raw.githubusercontent.com/nallen05/logv/2a6e76f60f4bd3ea2cb17554fe6a0a8665552e0e/logv.lisp | lisp |
todo: -log rotation script
-different log levels
default logv environment
global database of environments
(env-name . env-plist)
log environment settings
writing to the log file
creating new loggers
-T: then things that write to the log write to *STANDARD-OUTPUT*
-NIL: then things that normally write to the log don't do anything
-a stream: then things that write to the log write to the stream
-a pathname or a string [a pathname designator]: then things that write to the log
write to the file pointed to by the string/pathname. the file is created if it
doesn't already exist. if there are special characters then they are encoded in |
(in-package :logv)
(defvar *default-log-env* :default-logv-env)
(defun .verify-log-env-exists (log-env-name)
(if (assoc log-env-name *log-envs*)
t
(error "unknown log environment ~A. known loggers are: ~A" log-env-name (mapcar 'first *log-envs*))))
(defun .get-log-setting (key log-env-name)
(getf (rest (assoc log-env-name *log-envs*)) key))
(defun log-setting (key &optional (log-env-name *default-log-env*))
(.verify-log-env-exists log-env-name)
(.get-log-setting key log-env-name))
(defsetf log-setting (key (log-env-name *default-log-env*)) (new-value)
(let ((<log-env-name> (gensym "log-env-name-")))
`(let ((,<log-env-name> ,log-env-name))
(.verify-log-env-exists ,<log-env-name>)
(setf (getf (rest (assoc ,<log-env-name> *log-envs*))
,key)
,new-value))))
(defun .write-string-to-log (log-env-name string)
"
writes `STRING' to the LOG-ENV-NAME's log. exact behavior depends
on value of :LOG-OUTPUT log setting
"
(let ((log-output (log-setting :log-output log-env-name)))
(when log-output
(let ((string (concatenate 'string
(funcall (log-setting :log-prefix-string-factory log-env-name))
string))
(log-mutex (log-setting :log-mutex log-env-name)))
(with-lock-held (log-mutex)
(if (or (stringp log-output)
(pathnamep log-output))
(with-open-file (out log-output
:element-type '(unsigned-byte 8)
:direction :output
:if-exists :append
:if-does-not-exist :create)
(trivial-utf-8:write-utf-8-bytes string out))
(write-string string (if (eql log-output t)
*standard-output*
log-output)))))))
(values))
(defvar *.default-prefix-string-factory*
(lambda ()
(format nil
"~%; ~A [~A]: "
(rw-ut:write-time-string (get-universal-time)
"[YYYY/MM/DD] [hh:mm:ss]")
(thread-name (current-thread)))))
(defmacro def-log-env (env-name (&key logv-macro-name
logvs-macro-name
format-log-function-name)
&key (log-output t)
if : LOG - OUTPUT is
UTF-8
(log-prefix-string-factory '*.default-prefix-string-factory*))
: LOG - PREFIX - STRING - FACTORY is a thunk that creates the string prepended to each log message
`(progn
(setf *log-envs*
(cons (list ',env-name
:log-output ,log-output
:log-prefix-string-factory ,log-prefix-string-factory
:log-mutex (make-lock (format nil "~A log mutex" ',env-name)))
_ _ LOG_MUTEX _ _ prevents multiple threads from writing to LOG - OUTPUT at the same time
(remove ',env-name *log-envs* :key 'first)))
,@(when logv-macro-name
`((defmacro ,logv-macro-name (form &rest more-forms)
(if more-forms
`(progn (logv ,form) (logv ,@more-forms))
(let ((% (gensym "value")))
`(let ((,% ,form))
(.write-string-to-log ',',env-name (format nil "~S -> ~S" ',form ,%))
,%))))))
,@(when logvs-macro-name
`((defmacro ,logvs-macro-name (form &rest more-forms)
(if more-forms
`(progn (logvs ,form) (logvs ,@more-forms))
(let ((%l (gensym "values")))
`(let ((,%l (multiple-value-list ,form)))
(.write-string-to-log ',',env-name (format nil "~S -> values list: ~S" ',form ,%l))
(apply 'values ,%l)))))))
,@(when format-log-function-name
`((defun ,format-log-function-name (fmt-string &rest fmt-args)
(.write-string-to-log ',env-name (apply 'format nil fmt-string fmt-args)))))))
(def-log-env :logv (:logv-macro-name logv
:logvs-macro-name logvs
:format-log-function-name format-log)) |
58396ed1d997aaf7e558114220821c27cc11731295698342e93d179e98fb43eb | callum-oakley/advent-of-code | 01.clj | (ns aoc.2017.01
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(mapv #(- (int %) (int \0)) s))
(defn part-* [offset ds]
(->> (range (count ds))
(keep #(when (= (ds %) (ds (mod (+ offset %) (count ds))))
(ds %)))
(apply +)))
(defn part-1 [ds]
(part-* 1 ds))
(defn part-2 [ds]
(part-* (/ (count ds) 2) ds))
(deftest test-part-*
(is (= 3 (part-* 1 [1 1 2 2])))
(is (= 4 (part-* 1 [1 1 1 1])))
(is (= 0 (part-* 1 [1 2 3 4])))
(is (= 9 (part-* 1 [9 1 2 1 2 1 2 9])))
(is (= 6 (part-* 2 [1 2 1 2])))
(is (= 0 (part-* 2 [1 2 2 1])))
(is (= 4 (part-* 3 [1 2 3 4 2 5])))
(is (= 12 (part-* 3 [1 2 3 1 2 3])))
(is (= 4 (part-* 4 [1 2 1 3 1 4 1 5]))))
| null | https://raw.githubusercontent.com/callum-oakley/advent-of-code/da5233fc0fd3d3773d35ee747fd837c59c2b1c04/src/aoc/2017/01.clj | clojure | (ns aoc.2017.01
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(mapv #(- (int %) (int \0)) s))
(defn part-* [offset ds]
(->> (range (count ds))
(keep #(when (= (ds %) (ds (mod (+ offset %) (count ds))))
(ds %)))
(apply +)))
(defn part-1 [ds]
(part-* 1 ds))
(defn part-2 [ds]
(part-* (/ (count ds) 2) ds))
(deftest test-part-*
(is (= 3 (part-* 1 [1 1 2 2])))
(is (= 4 (part-* 1 [1 1 1 1])))
(is (= 0 (part-* 1 [1 2 3 4])))
(is (= 9 (part-* 1 [9 1 2 1 2 1 2 9])))
(is (= 6 (part-* 2 [1 2 1 2])))
(is (= 0 (part-* 2 [1 2 2 1])))
(is (= 4 (part-* 3 [1 2 3 4 2 5])))
(is (= 12 (part-* 3 [1 2 3 1 2 3])))
(is (= 4 (part-* 4 [1 2 1 3 1 4 1 5]))))
|
|
de3a15240e5478a324ac5cbad6d0463d55d17fd044c8610504d98833f40e39b5 | CSCfi/rems | attachment_types.cljc | (ns rems.common.attachment-types
(:require [clojure.string :as str]
[clojure.test :refer [deftest is]]))
(def allowed-extensions
[".pdf"
".txt"
".doc" ".docx" ".odt"
".ppt" ".pptx" ".odp"
".xls" ".xlsx" ".ods" ".csv" ".tsv"
".jpg" ".jpeg"
".png"
".gif"
".webp"
".tif" ".tiff"
".heif" ".heic"
".svg"])
(defn allowed-extension? [filename]
(some? (some #(str/ends-with? (str/lower-case filename) %) allowed-extensions)))
(deftest test-allowed-extension?
(is (allowed-extension? "a-simple-filename.docx"))
(is (allowed-extension? "must_ignore_capitals.PdF"))
(is (not (allowed-extension? "something.obviously.wrong"))))
(def allowed-extensions-string
(str/join ", " allowed-extensions))
| null | https://raw.githubusercontent.com/CSCfi/rems/644ef6df4518b8e382cdfeadd7719e29508a26f0/src/cljc/rems/common/attachment_types.cljc | clojure | (ns rems.common.attachment-types
(:require [clojure.string :as str]
[clojure.test :refer [deftest is]]))
(def allowed-extensions
[".pdf"
".txt"
".doc" ".docx" ".odt"
".ppt" ".pptx" ".odp"
".xls" ".xlsx" ".ods" ".csv" ".tsv"
".jpg" ".jpeg"
".png"
".gif"
".webp"
".tif" ".tiff"
".heif" ".heic"
".svg"])
(defn allowed-extension? [filename]
(some? (some #(str/ends-with? (str/lower-case filename) %) allowed-extensions)))
(deftest test-allowed-extension?
(is (allowed-extension? "a-simple-filename.docx"))
(is (allowed-extension? "must_ignore_capitals.PdF"))
(is (not (allowed-extension? "something.obviously.wrong"))))
(def allowed-extensions-string
(str/join ", " allowed-extensions))
|
|
d3a6d12b81e5afeed65ceb6e18054913e3942a31ff3237c30559d8c38f078e06 | progman1/genprintlib | checkpoints.mli | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
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. *)
(* *)
(**************************************************************************)
(***************************** Checkpoints *****************************)
open Primitives
open Debugcom
(*** A type for checkpoints. ***)
type checkpoint_state =
C_stopped
| C_running of int64
` c_valid ' is true if and only if the corresponding
* process is connected to the debugger .
* ` c_parent ' is the checkpoint whose process is parent
* of the checkpoint one ( ` root ' if no parent ) .
* c_pid = 2 for root pseudo - checkpoint .
* c_pid = 0 for ghost checkpoints .
* c_pid = -1 for kill checkpoints .
* process is connected to the debugger.
* `c_parent' is the checkpoint whose process is parent
* of the checkpoint one (`root' if no parent).
* c_pid = 2 for root pseudo-checkpoint.
* c_pid = 0 for ghost checkpoints.
* c_pid = -1 for kill checkpoints.
*)
type checkpoint =
{mutable c_time : int64;
mutable c_pid : int;
mutable c_fd : io_channel;
mutable c_valid : bool;
mutable c_report : report option;
mutable c_state : checkpoint_state;
mutable c_parent : checkpoint;
mutable c_breakpoint_version : int;
mutable c_breakpoints : (int * int ref) list;
mutable c_trap_barrier : int}
(*** Pseudo-checkpoint `root'. ***)
(* --- Parents of all checkpoints which have no parent. *)
val root : checkpoint
(*** Current state ***)
val checkpoints : checkpoint list ref
val current_checkpoint : checkpoint ref
val current_time : unit -> int64
val current_report : unit -> report option
val current_pc : unit -> int option
val current_pc_sp : unit -> (int * int) option
| null | https://raw.githubusercontent.com/progman1/genprintlib/acc1e5cc46b9ce6191d0306f51337581c93ffe94/debugger/4.07.1/checkpoints.mli | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
**************************** Checkpoints ****************************
** A type for checkpoints. **
** Pseudo-checkpoint `root'. **
--- Parents of all checkpoints which have no parent.
** Current state ** | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Primitives
open Debugcom
type checkpoint_state =
C_stopped
| C_running of int64
` c_valid ' is true if and only if the corresponding
* process is connected to the debugger .
* ` c_parent ' is the checkpoint whose process is parent
* of the checkpoint one ( ` root ' if no parent ) .
* c_pid = 2 for root pseudo - checkpoint .
* c_pid = 0 for ghost checkpoints .
* c_pid = -1 for kill checkpoints .
* process is connected to the debugger.
* `c_parent' is the checkpoint whose process is parent
* of the checkpoint one (`root' if no parent).
* c_pid = 2 for root pseudo-checkpoint.
* c_pid = 0 for ghost checkpoints.
* c_pid = -1 for kill checkpoints.
*)
type checkpoint =
{mutable c_time : int64;
mutable c_pid : int;
mutable c_fd : io_channel;
mutable c_valid : bool;
mutable c_report : report option;
mutable c_state : checkpoint_state;
mutable c_parent : checkpoint;
mutable c_breakpoint_version : int;
mutable c_breakpoints : (int * int ref) list;
mutable c_trap_barrier : int}
val root : checkpoint
val checkpoints : checkpoint list ref
val current_checkpoint : checkpoint ref
val current_time : unit -> int64
val current_report : unit -> report option
val current_pc : unit -> int option
val current_pc_sp : unit -> (int * int) option
|
6e5d96872d1aed15119243f16b15857ae9c5b35d9d19cc13d0b38ee99524c012 | rcherrueau/APE | stacker.rkt | #lang racket/base
(require racket/port
(for-syntax racket/base))
;; From
;; Reader
;;
;; Implementation of stacker reader. The reader is in charge of
;; parsing your program and producing an AST in return. To do so, the
;; reader implements a specific methods call `read-syntax' that takes
;; your program as an `input-port' and produces a s-exp `syntax'
object that represents your AST wrapped into a ` module ' . The module
;; then tells racket where to find the semantic of your program (the
;; expander).
;;
The reader of the ` stacker ' language produces an AST derived from the
;; following grammar:
;; Root ::= (handle x) Root | (handle x) with x an identifier
(provide read-syntax)
(define (read-syntax src-path in)
(define src-lines (port->lines in))
(define src-datums (map string->datum src-lines))
(define ast (map (λ (x) `(handle ,x)) src-datums))
(datum->syntax #f `(module stacker-module "stacker.rkt"
,@ast)))
(define (string->datum str)
(unless (equal? "" str)
(let ([result (read (open-input-string (format "(~a)" str)))])
(if (= (length result) 1)
(car result)
result))))
;; Expander
;;
;; Implementation of stacker expander. The expander is in charge of
;; defining the semantic of your program with real Racket expressions.
;; These expressions are then evaluated to produce a result.
;; Concretely, an expander for a specific language is provided by
implementing a function ` # % module - begin ' that returns a ` syntax '
;; object. This syntax object can be transformed thanks to macro and
;; are expanded until the most basic forms (fix point) that should
call ` # % module - begin ' of an underlining language ( e.g. , Racket ) .
;; The underlining language handles the final evaluation.
;;
;; - A name used in the code is called an /identifier/.
;; - A connection to an actual value or function is called a /binding/.
;; - The expander prepares the code for evaluation by ensuring that
;; /every identifier has a binding/.
;; - Once an identifier has a binding, it becomes a /variable/.
;;
;; Note: A syntax object defined by `#'' not only creates the datum,
;; but also captures the current /lexical context/, and attaches that
;; to the new syntax object. Lexical context is the list of available
;; variables which means that the syntax object made with `#'' will be
;; able to access all the variables defined at that point of the code.
;;
;; As a general methodology:
1 . Handle any language - specific processing of the code in the
` # % module - begin ' macro .
2 . Pass the result to an existing ` # % module - begin ' for the rest of
the heavy lifting ( note that all ` # % module - begin ' macro have the
;; same name. Some care is needed to keep them straight).
;;
;; The expander of the `stacker' language calls the `#%module-begin'
;; of Racket/base (cf. `#lang racket/base'). Then evaluates `handle'
;; expression that pushes and pops number on the stack. And finally
;; prints the top of the stack.
(provide (rename-out [stacker-module-begin #%module-begin])
#%top #%app #%datum #%top-interaction
handle + *)
(define-syntax (stacker-module-begin stx)
(syntax-case stx ()
[(_ HANDLE-EXP ...)
#'(#%module-begin
;; To debug, make it a symbol 'HANDLE-EXP ...
HANDLE-EXP ...
(displayln (car stack)))]))
;; The heavy lifting: Racket code that implements the semantics
(define stack '())
(define (pop-stack!)
(define hd (car stack))
(set! stack (cdr stack))
hd)
(define (push-stack! arg)
(set! stack (cons arg stack)))
(define (handle [arg #f])
(cond
[(number? arg)
(push-stack! arg)]
[(or (equal? * arg) (equal? + arg))
(define op-result (arg (pop-stack!) (pop-stack!)))
(push-stack! op-result)]))
| null | https://raw.githubusercontent.com/rcherrueau/APE/8b5302709000bd043b64d46d55642acb34ce5ba7/racket/beautifulracket/stacker.rkt | racket | From
Reader
Implementation of stacker reader. The reader is in charge of
parsing your program and producing an AST in return. To do so, the
reader implements a specific methods call `read-syntax' that takes
your program as an `input-port' and produces a s-exp `syntax'
then tells racket where to find the semantic of your program (the
expander).
following grammar:
Root ::= (handle x) Root | (handle x) with x an identifier
Expander
Implementation of stacker expander. The expander is in charge of
defining the semantic of your program with real Racket expressions.
These expressions are then evaluated to produce a result.
Concretely, an expander for a specific language is provided by
object. This syntax object can be transformed thanks to macro and
are expanded until the most basic forms (fix point) that should
The underlining language handles the final evaluation.
- A name used in the code is called an /identifier/.
- A connection to an actual value or function is called a /binding/.
- The expander prepares the code for evaluation by ensuring that
/every identifier has a binding/.
- Once an identifier has a binding, it becomes a /variable/.
Note: A syntax object defined by `#'' not only creates the datum,
but also captures the current /lexical context/, and attaches that
to the new syntax object. Lexical context is the list of available
variables which means that the syntax object made with `#'' will be
able to access all the variables defined at that point of the code.
As a general methodology:
same name. Some care is needed to keep them straight).
The expander of the `stacker' language calls the `#%module-begin'
of Racket/base (cf. `#lang racket/base'). Then evaluates `handle'
expression that pushes and pops number on the stack. And finally
prints the top of the stack.
To debug, make it a symbol 'HANDLE-EXP ...
The heavy lifting: Racket code that implements the semantics | #lang racket/base
(require racket/port
(for-syntax racket/base))
object that represents your AST wrapped into a ` module ' . The module
The reader of the ` stacker ' language produces an AST derived from the
(provide read-syntax)
(define (read-syntax src-path in)
(define src-lines (port->lines in))
(define src-datums (map string->datum src-lines))
(define ast (map (λ (x) `(handle ,x)) src-datums))
(datum->syntax #f `(module stacker-module "stacker.rkt"
,@ast)))
(define (string->datum str)
(unless (equal? "" str)
(let ([result (read (open-input-string (format "(~a)" str)))])
(if (= (length result) 1)
(car result)
result))))
implementing a function ` # % module - begin ' that returns a ` syntax '
call ` # % module - begin ' of an underlining language ( e.g. , Racket ) .
1 . Handle any language - specific processing of the code in the
` # % module - begin ' macro .
2 . Pass the result to an existing ` # % module - begin ' for the rest of
the heavy lifting ( note that all ` # % module - begin ' macro have the
(provide (rename-out [stacker-module-begin #%module-begin])
#%top #%app #%datum #%top-interaction
handle + *)
(define-syntax (stacker-module-begin stx)
(syntax-case stx ()
[(_ HANDLE-EXP ...)
#'(#%module-begin
HANDLE-EXP ...
(displayln (car stack)))]))
(define stack '())
(define (pop-stack!)
(define hd (car stack))
(set! stack (cdr stack))
hd)
(define (push-stack! arg)
(set! stack (cons arg stack)))
(define (handle [arg #f])
(cond
[(number? arg)
(push-stack! arg)]
[(or (equal? * arg) (equal? + arg))
(define op-result (arg (pop-stack!) (pop-stack!)))
(push-stack! op-result)]))
|
14b3f4bf11150ec46ec61c5943e1df9c8e3d0152a6088e2252ca505761f1500a | glguy/advent | 05.hs | {-# Language QuasiQuotes, ImportQualifiedPost #-}
|
Module : Main
Description : Day 5 solution
Copyright : ( c ) , 2022
License : ISC
Maintainer :
< >
> > > : {
: main +
" [ D ] \n\
\[N ] [ C ] \n\
\[Z ] [ M ] [ P]\n\
\ 1 2 3 \n\
\\n\
\move 1 from 2 to 1\n\
\move 3 from 1 to 3\n\
\move 2 from 2 to 1\n\
\move 1 from 1 to 2\n "
:}
CMZ
MCD
Module : Main
Description : Day 5 solution
Copyright : (c) Eric Mertens, 2022
License : ISC
Maintainer :
<>
>>> :{
:main +
" [D] \n\
\[N] [C] \n\
\[Z] [M] [P]\n\
\ 1 2 3 \n\
\\n\
\move 1 from 2 to 1\n\
\move 3 from 1 to 3\n\
\move 2 from 2 to 1\n\
\move 1 from 1 to 2\n"
:}
CMZ
MCD
-}
module Main where
import Data.List (transpose)
import Data.Maybe (catMaybes)
import Data.Map (Map)
import Data.Map qualified as Map
import Advent (format)
main :: IO ()
main =
do (toppart, labels, commands) <- [format|2022 5
(( |[%c])& %n)*
( %c )& %n
%n
(move %u from %c to %c%n)*|]
let stacks = Map.fromList (zip labels (map catMaybes (transpose toppart)))
let solve f = map head (Map.elems (foldl (apply f) stacks commands))
putStrLn (solve (flip (foldl (flip (:)))))
putStrLn (solve (++))
apply :: Ord k => ([a] -> [a] -> [a]) -> Map k [a] -> (Int, k, k) -> Map k [a]
apply f stacks (n, fr, to) =
case Map.alterF (traverse (splitAt n)) fr stacks of
(a, m) -> Map.adjust (f a) to m
| null | https://raw.githubusercontent.com/glguy/advent/d40b64f5789e4790b368855a942203ce5d86cef5/solutions/src/2022/05.hs | haskell | # Language QuasiQuotes, ImportQualifiedPost # | |
Module : Main
Description : Day 5 solution
Copyright : ( c ) , 2022
License : ISC
Maintainer :
< >
> > > : {
: main +
" [ D ] \n\
\[N ] [ C ] \n\
\[Z ] [ M ] [ P]\n\
\ 1 2 3 \n\
\\n\
\move 1 from 2 to 1\n\
\move 3 from 1 to 3\n\
\move 2 from 2 to 1\n\
\move 1 from 1 to 2\n "
:}
CMZ
MCD
Module : Main
Description : Day 5 solution
Copyright : (c) Eric Mertens, 2022
License : ISC
Maintainer :
<>
>>> :{
:main +
" [D] \n\
\[N] [C] \n\
\[Z] [M] [P]\n\
\ 1 2 3 \n\
\\n\
\move 1 from 2 to 1\n\
\move 3 from 1 to 3\n\
\move 2 from 2 to 1\n\
\move 1 from 1 to 2\n"
:}
CMZ
MCD
-}
module Main where
import Data.List (transpose)
import Data.Maybe (catMaybes)
import Data.Map (Map)
import Data.Map qualified as Map
import Advent (format)
main :: IO ()
main =
do (toppart, labels, commands) <- [format|2022 5
(( |[%c])& %n)*
( %c )& %n
%n
(move %u from %c to %c%n)*|]
let stacks = Map.fromList (zip labels (map catMaybes (transpose toppart)))
let solve f = map head (Map.elems (foldl (apply f) stacks commands))
putStrLn (solve (flip (foldl (flip (:)))))
putStrLn (solve (++))
apply :: Ord k => ([a] -> [a] -> [a]) -> Map k [a] -> (Int, k, k) -> Map k [a]
apply f stacks (n, fr, to) =
case Map.alterF (traverse (splitAt n)) fr stacks of
(a, m) -> Map.adjust (f a) to m
|
3c9a7419e4657abe08107603f359c45d48e45ff2373fb87642379aa1226ac68c | moss/haskell-roguelike-challenge | iatmwotk.hs | module IAmThatMerryWandererOfTheNight where
import Control.Monad
import System.Console.ANSI
import System.IO
type Position = (Int, Int)
data Command = MoveLeft
| MoveDown
| MoveUp
| MoveRight
| Quit
| Unknown
deriving (Eq)
initScreen = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetEcho stdin False
clearScreen
parseInput :: [Char] -> [Command]
parseInput chars = takeWhile (/= Quit) $ map parseCommand chars
parseCommand :: Char -> Command
parseCommand 'q' = Quit
parseCommand 'h' = MoveLeft
parseCommand 'j' = MoveDown
parseCommand 'k' = MoveUp
parseCommand 'l' = MoveRight
parseCommand _ = Unknown
draw (row, col) = do
setCursorPosition row col
putChar '@'
setCursorPosition 26 0
clear (row, col) = do
setCursorPosition row col
putChar ' '
setCursorPosition 26 0
advance MoveLeft (row, col) = (row, col - 1)
advance MoveUp (row, col) = (row - 1, col)
advance MoveDown (row, col) = (row + 1, col)
advance MoveRight (row, col) = (row, col + 1)
advance _ state = state
main :: IO ()
main = do
initScreen
draw (12, 40)
userInput <- getContents
foldM_ updateScreen (12, 40) (parseInput userInput) where
updateScreen curState command = do
let newState = advance command curState
clear curState
draw newState
return newState
| null | https://raw.githubusercontent.com/moss/haskell-roguelike-challenge/2163c3aa6f14051bc2360de0d7a1694b54ef73a3/2-i-am-that-merry-wanderer-of-the-night/iatmwotk.hs | haskell | module IAmThatMerryWandererOfTheNight where
import Control.Monad
import System.Console.ANSI
import System.IO
type Position = (Int, Int)
data Command = MoveLeft
| MoveDown
| MoveUp
| MoveRight
| Quit
| Unknown
deriving (Eq)
initScreen = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetEcho stdin False
clearScreen
parseInput :: [Char] -> [Command]
parseInput chars = takeWhile (/= Quit) $ map parseCommand chars
parseCommand :: Char -> Command
parseCommand 'q' = Quit
parseCommand 'h' = MoveLeft
parseCommand 'j' = MoveDown
parseCommand 'k' = MoveUp
parseCommand 'l' = MoveRight
parseCommand _ = Unknown
draw (row, col) = do
setCursorPosition row col
putChar '@'
setCursorPosition 26 0
clear (row, col) = do
setCursorPosition row col
putChar ' '
setCursorPosition 26 0
advance MoveLeft (row, col) = (row, col - 1)
advance MoveUp (row, col) = (row - 1, col)
advance MoveDown (row, col) = (row + 1, col)
advance MoveRight (row, col) = (row, col + 1)
advance _ state = state
main :: IO ()
main = do
initScreen
draw (12, 40)
userInput <- getContents
foldM_ updateScreen (12, 40) (parseInput userInput) where
updateScreen curState command = do
let newState = advance command curState
clear curState
draw newState
return newState
|
|
6f9bbba1b902e2f62e080fd5f71decf6a3b738cede8d178c925b555cb405fbb7 | Ptival/yugioh | DrawPhase.hs | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
-- | During the draw phase, players can draw a card. Eventually, they'll be
-- able to do some additional things, like activate specific effects.
module YuGiOh.DrawPhase
( drawPhase,
)
where
import Control.Monad (replicateM_)
import Polysemy
import qualified YuGiOh.Lenses as L
import YuGiOh.Move as Move
import YuGiOh.Operation
import YuGiOh.Phase
import YuGiOh.Victory
import Prelude hiding (log)
validMoves ::
Member Operation e =>
Sem e [Move 'DrawPhase]
validMoves =
getHasDrawnCard L.currentPlayer >>= \case
True -> return [Move.EndDrawPhase]
False -> return [DrawCard]
drawPhase ::
Member Operation e =>
Sem e (Maybe Victory)
drawPhase =
do
turnNumber <- getTurnNumber
if turnNumber == 1
then do
shs <- getStartingHandSize
replicateM_ shs $ drawCard L.currentPlayer
replicateM_ shs $ drawCard L.otherPlayer
enter MainPhase
return Nothing
else validMoves >>= chooseMove >>= \case
DrawCard ->
drawCard L.currentPlayer
Move.EndDrawPhase -> do
enter MainPhase
return Nothing
| null | https://raw.githubusercontent.com/Ptival/yugioh/855e8f22c3ff322c7ca1d0a1fa96c50a54724aeb/lib/YuGiOh/DrawPhase.hs | haskell | # LANGUAGE GADTs #
| During the draw phase, players can draw a card. Eventually, they'll be
able to do some additional things, like activate specific effects. | # LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
module YuGiOh.DrawPhase
( drawPhase,
)
where
import Control.Monad (replicateM_)
import Polysemy
import qualified YuGiOh.Lenses as L
import YuGiOh.Move as Move
import YuGiOh.Operation
import YuGiOh.Phase
import YuGiOh.Victory
import Prelude hiding (log)
validMoves ::
Member Operation e =>
Sem e [Move 'DrawPhase]
validMoves =
getHasDrawnCard L.currentPlayer >>= \case
True -> return [Move.EndDrawPhase]
False -> return [DrawCard]
drawPhase ::
Member Operation e =>
Sem e (Maybe Victory)
drawPhase =
do
turnNumber <- getTurnNumber
if turnNumber == 1
then do
shs <- getStartingHandSize
replicateM_ shs $ drawCard L.currentPlayer
replicateM_ shs $ drawCard L.otherPlayer
enter MainPhase
return Nothing
else validMoves >>= chooseMove >>= \case
DrawCard ->
drawCard L.currentPlayer
Move.EndDrawPhase -> do
enter MainPhase
return Nothing
|
d63e8d134318a32c121f7d5c4e75b8ffe4653a5df90df9b8bc27568e79e1c7c6 | coalton-lang/coalton | parse-form.lisp | (defpackage #:coalton-impl/ast/parse-form
(:use
#:cl
#:coalton-impl/algorithm
#:coalton-impl/ast/pattern
#:coalton-impl/ast/node
#:coalton-impl/ast/parse-error)
(:local-nicknames
(:util #:coalton-impl/util))
(:export
#:parse-form))
(in-package #:coalton-impl/ast/parse-form)
(defun parse-form (expr m package)
"Parse the value form FORM into a NODE structure. This also performs macro-expansion.
This does not attempt to do any sort of analysis whatsoever. It is suitable for parsing expressions irrespective of environment."
(declare (type immutable-map m)
(values node &optional)
(type package package))
(cond
((atom expr)
(etypecase expr
(null (error-parsing
expr
"The empty list literal (), also written as the symbol ~
COMMON-LISP:NIL, is not valid in Coalton.~&~%This error is ~
often triggered by expanding a buggy macro."))
(symbol (parse-variable expr m))
(util:literal-value
(parse-atom expr))))
((alexandria:proper-list-p expr)
(alexandria:destructuring-case expr
;; Abstraction
(((or coalton:fn coalton:λ) &rest args)
(unless (<= 2 (length args))
(error-parsing
expr
"Invalid anonymous function expression.~&~%~
Usage: (~S (VARS*) BODY)"
(car expr)))
(parse-abstraction expr (first args) (rest args) m package))
;; Let
((coalton:let &rest args)
(when (null args)
(error-parsing
expr
"Let forms must include a binding list"))
(parse-let expr (first args) (rest args) m package))
;; Lisp
((coalton:lisp &rest args)
(unless (<= 3 (length args))
(error-parsing expr "Invalid embedded Lisp expression."))
(parse-lisp expr (first args) (second args) (nthcdr 2 args) m))
;; Match
((coalton:match expr_ &rest patterns)
(parse-match expr expr_ patterns m package))
Seq
((coalton::seq &rest subnodes)
(parse-seq expr subnodes m package))
;; The
((coalton:the &rest args)
(unless (= 2 (length args))
(error-parsing expr "Invalid type assertion."))
(parse-the expr (first args) (second args) m package))
;; Return
((coalton:return form)
(parse-return expr form m package))
;; Bind
((coalton::bind &rest args)
(unless (= 3 (length args))
(error-parsing expr "Invalid bind expression"))
(parse-bind expr (first args) (second args) (third args) m package))
;; Application
((t &rest rands)
(cond
((and (symbolp (first expr)) (macro-function (first expr)))
(let ((expansion (funcall (macro-function (first expr)) expr nil)))
(parse-form expansion m package)))
((null rands)
(let ((unit (alexandria:ensure-symbol
"UNIT"
(find-package "COALTON-LIBRARY/CLASSES"))))
(parse-application expr (first expr) (list unit) m package)))
(t (parse-application expr (first expr) rands m package))))))
((listp expr) ;; EXPR already flunked PROPER-LIST-P, so it's a dotted list.
(error-parsing expr "Dotted lists are not valid Coalton syntax."))
(t
(util:unreachable))))
(defun invert-alist (alist)
(loop :for (key . value) :in alist
:collect (cons value key)))
(defun lookup-or-key (m key)
(declare (type immutable-map m)
(type symbol key))
(or (immutable-map-lookup m key)
key))
(defun parse-variable (var m)
(declare (type symbol var)
(type immutable-map m)
(values node-variable))
(make-node-variable
:unparsed var
:name (lookup-or-key m var)))
(defun make-local-vars (vars package)
(declare (type util:symbol-list vars)
(type package package))
(loop :for var :in vars
:collect
(cons
var
(gentemp (concatenate 'string (symbol-name var) "-") package))))
(defun parse-abstraction (unparsed vars subexprs m package)
(declare (type t unparsed)
(type util:symbol-list vars)
(type list subexprs)
(type immutable-map m)
(type package package))
(let ((nullary-fn nil)
(var nil))
(when (null vars)
(setf var (gentemp "G" package))
(setf vars (list var))
(setf nullary-fn t))
(let* ((binding-local-names (make-local-vars vars package))
(new-m (immutable-map-set-multiple m binding-local-names))
(subform (parse-form
(funcall (macro-function 'coalton:progn) (cons 'coalton:progn subexprs) nil)
new-m
package)))
(make-node-abstraction
:unparsed unparsed
:vars (mapcar #'cdr binding-local-names)
:subexpr (if nullary-fn
(make-node-seq
:unparsed unparsed
:subnodes (list
(make-node-the
:unparsed `(the Unit ,var)
:type `coalton:Unit
:subnode (make-node-variable
:unparsed var
:name (immutable-map-lookup new-m var)))
subform))
subform)
:name-map (invert-alist binding-local-names)))))
(defun parse-let (unparsed binding-forms subexpr m package)
(declare (type t unparsed)
(type list binding-forms)
(type t subexpr)
(type immutable-map m)
(type package package)
(values node-let))
(let ((bindings nil)
(declared-types nil))
;; Separate bindings from type declarations
(loop :for form :in binding-forms :do
(cond
((not (listp form))
(error-parsing form "Invalid let binding form"))
((= 2 (length form))
(unless (symbolp (first form))
(error-parsing form "Invalid let binding form"))
(push (cons (first form)
(second form))
bindings))
((= 3 (length form))
(unless (eql 'coalton:declare (first form))
(error-parsing form "Invalid let binding form"))
(unless (symbolp (second form))
(error-parsing form "Invalid let binding declaration form"))
(push (cons (second form)
(third form))
declared-types))
(t
(error-parsing form "Invalid let binding form"))))
;; Check that all declarations have a matching binding
(loop :for (bind-var . bind-type) :in declared-types :do
(unless (member bind-var bindings :key #'car)
(error-parsing unparsed "Orphan type declaration for variable ~S" bind-var)))
;; Perform variable renaming
(let* ((binding-names (mapcar #'car bindings))
(binding-local-names (make-local-vars binding-names package))
(new-m (immutable-map-set-multiple m binding-local-names)))
(make-node-let
:unparsed unparsed
:bindings (loop :for (bind-var . bind-val) :in bindings
:collect (cons
(lookup-or-key new-m bind-var)
(parse-form bind-val new-m package)))
:declared-types (loop :for (bind-var . bind-type) :in declared-types
:collect (cons
(lookup-or-key new-m bind-var)
bind-type))
:subexpr (parse-form (cons 'coalton:progn subexpr) new-m package)
:name-map (invert-alist binding-local-names)))))
(defun parse-lisp (unparsed type variables lisp-exprs m)
(declare (type immutable-map m))
(make-node-lisp
:unparsed unparsed
:type type
:variables (loop :for var :in variables
:collect (cons
var
(or (immutable-map-lookup m var)
(error-parsing unparsed "Unknown variable ~A in lisp node~%" var))))
;; Do *NOT* parse LISP-EXPRS!
:form lisp-exprs))
(defun parse-application (unparsed rator rands m package)
(declare (type immutable-map m)
(type package package))
(make-node-application
:unparsed unparsed
:rator (parse-form rator m package)
:rands (mapcar
(lambda (rand)
(parse-form rand m package))
rands)))
(defun parse-match-branch (branch m package)
(declare (type immutable-map m)
(type package package))
(assert (<= 2 (length branch))
() "Malformed match branch ~A" branch)
(let* ((parsed-pattern (parse-pattern (first branch)))
(pattern-vars (pattern-variables parsed-pattern))
(local-vars (make-local-vars pattern-vars package))
(new-m (immutable-map-set-multiple m local-vars))
(parsed-pattern (rewrite-pattern-vars parsed-pattern new-m))
(parsed-expr (parse-form (funcall (macro-function 'coalton:progn) (cons 'coalton:progn (cdr branch)) nil) new-m package)))
(make-match-branch
:unparsed branch
:pattern parsed-pattern
:subexpr parsed-expr
:name-map (invert-alist local-vars))))
(defun parse-match (unparsed expr branches m package)
(declare (type immutable-map m)
(type package package))
(let ((parsed-expr (parse-form expr m package))
(parsed-branches
(mapcar
(lambda (branch)
(parse-match-branch branch m package))
branches)))
(make-node-match
:unparsed unparsed
:expr parsed-expr
:branches parsed-branches)))
(defun parse-pattern (pattern)
(cond
((typep pattern 'util:literal-value)
(make-pattern-literal :value pattern))
((and (symbolp pattern)
(eql 'coalton:_ pattern))
(make-pattern-wildcard))
((symbolp pattern)
(make-pattern-var :id pattern))
((listp pattern)
(let ((ctor (first pattern))
(args (rest pattern)))
(make-pattern-constructor
:name ctor
:patterns (mapcar #'parse-pattern args))))))
(defun parse-atom (atom)
;; Convert integer literals into fromInt calls. This allows for
;; "overloaded" number literals. Other literals are left as is.
(let ((fromInt (alexandria:ensure-symbol "FROMINT" (find-package "COALTON-LIBRARY/CLASSES"))))
(etypecase atom
(integer (make-node-application
:unparsed atom
:rator (make-node-variable
:unparsed fromInt
:name fromInt)
:rands (list
(make-node-literal
:unparsed atom
:value atom))))
(t (make-node-literal
:unparsed atom
:value atom)))))
(defun parse-seq (expr subnodes m package)
(declare (type t expr)
(type list subnodes)
(type immutable-map m)
(type package package))
(assert (< 0 (length subnodes))
() "Seq form must have at least one node")
(make-node-seq
:unparsed expr
:subnodes (mapcar (lambda (node)
(parse-form node m package))
subnodes)))
(defun parse-the (expr type form m package)
(declare (type t expr)
(type t type)
(type t form)
(type immutable-map m)
(type package package))
(make-node-the
:unparsed expr
:type type
:subnode (parse-form form m package)))
(defun parse-return (expr form m package)
(declare (type t expr)
(type t form)
(type immutable-map m)
(type package package))
(make-node-return
:unparsed expr
:expr (parse-form form m package)))
(defun parse-bind (expr name node body m package)
(declare (type t expr)
(type symbol name)
(type t node)
(type t body)
(type immutable-map m)
(type package package))
(let* ((name (first (make-local-vars (list name) package)))
(new-m (immutable-map-set m (car name) (cdr name))))
(make-node-bind
:unparsed expr
:name (cdr name)
:expr (parse-form node m package)
:body (parse-form body new-m package))))
| null | https://raw.githubusercontent.com/coalton-lang/coalton/f7332d085211e63f114a63587eed3f63d0352f59/src/ast/parse-form.lisp | lisp | Abstraction
Let
Lisp
Match
The
Return
Bind
Application
EXPR already flunked PROPER-LIST-P, so it's a dotted list.
Separate bindings from type declarations
Check that all declarations have a matching binding
Perform variable renaming
Do *NOT* parse LISP-EXPRS!
Convert integer literals into fromInt calls. This allows for
"overloaded" number literals. Other literals are left as is. | (defpackage #:coalton-impl/ast/parse-form
(:use
#:cl
#:coalton-impl/algorithm
#:coalton-impl/ast/pattern
#:coalton-impl/ast/node
#:coalton-impl/ast/parse-error)
(:local-nicknames
(:util #:coalton-impl/util))
(:export
#:parse-form))
(in-package #:coalton-impl/ast/parse-form)
(defun parse-form (expr m package)
"Parse the value form FORM into a NODE structure. This also performs macro-expansion.
This does not attempt to do any sort of analysis whatsoever. It is suitable for parsing expressions irrespective of environment."
(declare (type immutable-map m)
(values node &optional)
(type package package))
(cond
((atom expr)
(etypecase expr
(null (error-parsing
expr
"The empty list literal (), also written as the symbol ~
COMMON-LISP:NIL, is not valid in Coalton.~&~%This error is ~
often triggered by expanding a buggy macro."))
(symbol (parse-variable expr m))
(util:literal-value
(parse-atom expr))))
((alexandria:proper-list-p expr)
(alexandria:destructuring-case expr
(((or coalton:fn coalton:λ) &rest args)
(unless (<= 2 (length args))
(error-parsing
expr
"Invalid anonymous function expression.~&~%~
Usage: (~S (VARS*) BODY)"
(car expr)))
(parse-abstraction expr (first args) (rest args) m package))
((coalton:let &rest args)
(when (null args)
(error-parsing
expr
"Let forms must include a binding list"))
(parse-let expr (first args) (rest args) m package))
((coalton:lisp &rest args)
(unless (<= 3 (length args))
(error-parsing expr "Invalid embedded Lisp expression."))
(parse-lisp expr (first args) (second args) (nthcdr 2 args) m))
((coalton:match expr_ &rest patterns)
(parse-match expr expr_ patterns m package))
Seq
((coalton::seq &rest subnodes)
(parse-seq expr subnodes m package))
((coalton:the &rest args)
(unless (= 2 (length args))
(error-parsing expr "Invalid type assertion."))
(parse-the expr (first args) (second args) m package))
((coalton:return form)
(parse-return expr form m package))
((coalton::bind &rest args)
(unless (= 3 (length args))
(error-parsing expr "Invalid bind expression"))
(parse-bind expr (first args) (second args) (third args) m package))
((t &rest rands)
(cond
((and (symbolp (first expr)) (macro-function (first expr)))
(let ((expansion (funcall (macro-function (first expr)) expr nil)))
(parse-form expansion m package)))
((null rands)
(let ((unit (alexandria:ensure-symbol
"UNIT"
(find-package "COALTON-LIBRARY/CLASSES"))))
(parse-application expr (first expr) (list unit) m package)))
(t (parse-application expr (first expr) rands m package))))))
(error-parsing expr "Dotted lists are not valid Coalton syntax."))
(t
(util:unreachable))))
(defun invert-alist (alist)
(loop :for (key . value) :in alist
:collect (cons value key)))
(defun lookup-or-key (m key)
(declare (type immutable-map m)
(type symbol key))
(or (immutable-map-lookup m key)
key))
(defun parse-variable (var m)
(declare (type symbol var)
(type immutable-map m)
(values node-variable))
(make-node-variable
:unparsed var
:name (lookup-or-key m var)))
(defun make-local-vars (vars package)
(declare (type util:symbol-list vars)
(type package package))
(loop :for var :in vars
:collect
(cons
var
(gentemp (concatenate 'string (symbol-name var) "-") package))))
(defun parse-abstraction (unparsed vars subexprs m package)
(declare (type t unparsed)
(type util:symbol-list vars)
(type list subexprs)
(type immutable-map m)
(type package package))
(let ((nullary-fn nil)
(var nil))
(when (null vars)
(setf var (gentemp "G" package))
(setf vars (list var))
(setf nullary-fn t))
(let* ((binding-local-names (make-local-vars vars package))
(new-m (immutable-map-set-multiple m binding-local-names))
(subform (parse-form
(funcall (macro-function 'coalton:progn) (cons 'coalton:progn subexprs) nil)
new-m
package)))
(make-node-abstraction
:unparsed unparsed
:vars (mapcar #'cdr binding-local-names)
:subexpr (if nullary-fn
(make-node-seq
:unparsed unparsed
:subnodes (list
(make-node-the
:unparsed `(the Unit ,var)
:type `coalton:Unit
:subnode (make-node-variable
:unparsed var
:name (immutable-map-lookup new-m var)))
subform))
subform)
:name-map (invert-alist binding-local-names)))))
(defun parse-let (unparsed binding-forms subexpr m package)
(declare (type t unparsed)
(type list binding-forms)
(type t subexpr)
(type immutable-map m)
(type package package)
(values node-let))
(let ((bindings nil)
(declared-types nil))
(loop :for form :in binding-forms :do
(cond
((not (listp form))
(error-parsing form "Invalid let binding form"))
((= 2 (length form))
(unless (symbolp (first form))
(error-parsing form "Invalid let binding form"))
(push (cons (first form)
(second form))
bindings))
((= 3 (length form))
(unless (eql 'coalton:declare (first form))
(error-parsing form "Invalid let binding form"))
(unless (symbolp (second form))
(error-parsing form "Invalid let binding declaration form"))
(push (cons (second form)
(third form))
declared-types))
(t
(error-parsing form "Invalid let binding form"))))
(loop :for (bind-var . bind-type) :in declared-types :do
(unless (member bind-var bindings :key #'car)
(error-parsing unparsed "Orphan type declaration for variable ~S" bind-var)))
(let* ((binding-names (mapcar #'car bindings))
(binding-local-names (make-local-vars binding-names package))
(new-m (immutable-map-set-multiple m binding-local-names)))
(make-node-let
:unparsed unparsed
:bindings (loop :for (bind-var . bind-val) :in bindings
:collect (cons
(lookup-or-key new-m bind-var)
(parse-form bind-val new-m package)))
:declared-types (loop :for (bind-var . bind-type) :in declared-types
:collect (cons
(lookup-or-key new-m bind-var)
bind-type))
:subexpr (parse-form (cons 'coalton:progn subexpr) new-m package)
:name-map (invert-alist binding-local-names)))))
(defun parse-lisp (unparsed type variables lisp-exprs m)
(declare (type immutable-map m))
(make-node-lisp
:unparsed unparsed
:type type
:variables (loop :for var :in variables
:collect (cons
var
(or (immutable-map-lookup m var)
(error-parsing unparsed "Unknown variable ~A in lisp node~%" var))))
:form lisp-exprs))
(defun parse-application (unparsed rator rands m package)
(declare (type immutable-map m)
(type package package))
(make-node-application
:unparsed unparsed
:rator (parse-form rator m package)
:rands (mapcar
(lambda (rand)
(parse-form rand m package))
rands)))
(defun parse-match-branch (branch m package)
(declare (type immutable-map m)
(type package package))
(assert (<= 2 (length branch))
() "Malformed match branch ~A" branch)
(let* ((parsed-pattern (parse-pattern (first branch)))
(pattern-vars (pattern-variables parsed-pattern))
(local-vars (make-local-vars pattern-vars package))
(new-m (immutable-map-set-multiple m local-vars))
(parsed-pattern (rewrite-pattern-vars parsed-pattern new-m))
(parsed-expr (parse-form (funcall (macro-function 'coalton:progn) (cons 'coalton:progn (cdr branch)) nil) new-m package)))
(make-match-branch
:unparsed branch
:pattern parsed-pattern
:subexpr parsed-expr
:name-map (invert-alist local-vars))))
(defun parse-match (unparsed expr branches m package)
(declare (type immutable-map m)
(type package package))
(let ((parsed-expr (parse-form expr m package))
(parsed-branches
(mapcar
(lambda (branch)
(parse-match-branch branch m package))
branches)))
(make-node-match
:unparsed unparsed
:expr parsed-expr
:branches parsed-branches)))
(defun parse-pattern (pattern)
(cond
((typep pattern 'util:literal-value)
(make-pattern-literal :value pattern))
((and (symbolp pattern)
(eql 'coalton:_ pattern))
(make-pattern-wildcard))
((symbolp pattern)
(make-pattern-var :id pattern))
((listp pattern)
(let ((ctor (first pattern))
(args (rest pattern)))
(make-pattern-constructor
:name ctor
:patterns (mapcar #'parse-pattern args))))))
(defun parse-atom (atom)
(let ((fromInt (alexandria:ensure-symbol "FROMINT" (find-package "COALTON-LIBRARY/CLASSES"))))
(etypecase atom
(integer (make-node-application
:unparsed atom
:rator (make-node-variable
:unparsed fromInt
:name fromInt)
:rands (list
(make-node-literal
:unparsed atom
:value atom))))
(t (make-node-literal
:unparsed atom
:value atom)))))
(defun parse-seq (expr subnodes m package)
(declare (type t expr)
(type list subnodes)
(type immutable-map m)
(type package package))
(assert (< 0 (length subnodes))
() "Seq form must have at least one node")
(make-node-seq
:unparsed expr
:subnodes (mapcar (lambda (node)
(parse-form node m package))
subnodes)))
(defun parse-the (expr type form m package)
(declare (type t expr)
(type t type)
(type t form)
(type immutable-map m)
(type package package))
(make-node-the
:unparsed expr
:type type
:subnode (parse-form form m package)))
(defun parse-return (expr form m package)
(declare (type t expr)
(type t form)
(type immutable-map m)
(type package package))
(make-node-return
:unparsed expr
:expr (parse-form form m package)))
(defun parse-bind (expr name node body m package)
(declare (type t expr)
(type symbol name)
(type t node)
(type t body)
(type immutable-map m)
(type package package))
(let* ((name (first (make-local-vars (list name) package)))
(new-m (immutable-map-set m (car name) (cdr name))))
(make-node-bind
:unparsed expr
:name (cdr name)
:expr (parse-form node m package)
:body (parse-form body new-m package))))
|
f65856c10caac2aa29b38e9dd2c916926df29f6d2dee98ec3dacb9acfcfde8a9 | niquola/reframe-template | routing.cljs | (ns frames.routing
(:require-macros [reagent.ratom :refer [reaction]])
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]
[clojure.set :as set]
[route-map.core :as route-map]))
(defn dispatch-routes [_]
(let [fragment (.. js/window -location -hash)]
(rf/dispatch [:fragment-changed fragment])))
(rf/reg-sub-raw
:route-map/breadcrumbs
(fn [db _] (reaction (:route-map/breadcrumbs @db))))
(rf/reg-sub-raw
:route-map/current-route
(fn [db _] (reaction (:route-map/current-route @db))))
(defn contexts-diff [old-contexts new-contexts params old-params]
(let [n-idx (into #{} new-contexts)
o-idx (into #{} old-contexts)
to-dispose (set/difference o-idx n-idx)]
(concat
(mapv (fn [x] [x :init params]) new-contexts)
(mapv (fn [x] [x :deinit old-params]) to-dispose))))
(defn mk-breadcrumbs [route]
(->> (:parents route)
(reduce (fn [acc v]
(let [prev (last acc)
uri (:uri prev)
p (last (for [[k route] prev :when (= (:. route) (:. v))] k))
p (or (get-in route [:params (first p)]) p) ]
(conj acc (assoc v :uri (str uri p "/")))))
[])
(filter :breadcrumb)
(mapv #(select-keys % [:uri :breadcrumb]))))
(rf/reg-event-fx
:fragment-changed
(fn [{db :db} [k fragment]]
(.error js/console
(route-map/match [:. "patients" "aabef205-1942-4de9-a9f2-bf7fcce93303" "dfdf"] (:route-map/routes db)))
(if-let [route (route-map/match [:. (str/replace fragment #"^#" "")] (:route-map/routes db))]
(let [contexts (->> (:parents route) (mapv :context) (filterv identity))
breadcrumbs (mk-breadcrumbs route)
dispose-context (or [])]
{:db (assoc db :fragment fragment
:route/context contexts
:route-map/breadcrumbs breadcrumbs
:route-map/current-route route)
:dispatch-n (contexts-diff (:route/context db)
contexts
(:params route)
(get-in db [:route-map/current-route :params]))})
{:db (assoc db :fragment fragment :route-map/current-route nil)})))
(rf/reg-event-fx
:route-map/init
(fn [cofx [_ routes]]
{:db (assoc (:db cofx) :route-map/routes routes)
:history {}}))
(rf/reg-fx
:history
(fn [_]
(aset js/window "onhashchange" dispatch-routes)
(dispatch-routes nil)))
(rf/reg-fx
:route-map/redirect
(fn [href]
(.log js/console "REDIRECT FX" href)
(aset (.-location js/window) "hash" href)))
| null | https://raw.githubusercontent.com/niquola/reframe-template/6482afabc1967d2b6cb39ddc3fc0158075535700/srcs/frames/routing.cljs | clojure | (ns frames.routing
(:require-macros [reagent.ratom :refer [reaction]])
(:require [reagent.core :as reagent]
[re-frame.core :as rf]
[clojure.string :as str]
[clojure.set :as set]
[route-map.core :as route-map]))
(defn dispatch-routes [_]
(let [fragment (.. js/window -location -hash)]
(rf/dispatch [:fragment-changed fragment])))
(rf/reg-sub-raw
:route-map/breadcrumbs
(fn [db _] (reaction (:route-map/breadcrumbs @db))))
(rf/reg-sub-raw
:route-map/current-route
(fn [db _] (reaction (:route-map/current-route @db))))
(defn contexts-diff [old-contexts new-contexts params old-params]
(let [n-idx (into #{} new-contexts)
o-idx (into #{} old-contexts)
to-dispose (set/difference o-idx n-idx)]
(concat
(mapv (fn [x] [x :init params]) new-contexts)
(mapv (fn [x] [x :deinit old-params]) to-dispose))))
(defn mk-breadcrumbs [route]
(->> (:parents route)
(reduce (fn [acc v]
(let [prev (last acc)
uri (:uri prev)
p (last (for [[k route] prev :when (= (:. route) (:. v))] k))
p (or (get-in route [:params (first p)]) p) ]
(conj acc (assoc v :uri (str uri p "/")))))
[])
(filter :breadcrumb)
(mapv #(select-keys % [:uri :breadcrumb]))))
(rf/reg-event-fx
:fragment-changed
(fn [{db :db} [k fragment]]
(.error js/console
(route-map/match [:. "patients" "aabef205-1942-4de9-a9f2-bf7fcce93303" "dfdf"] (:route-map/routes db)))
(if-let [route (route-map/match [:. (str/replace fragment #"^#" "")] (:route-map/routes db))]
(let [contexts (->> (:parents route) (mapv :context) (filterv identity))
breadcrumbs (mk-breadcrumbs route)
dispose-context (or [])]
{:db (assoc db :fragment fragment
:route/context contexts
:route-map/breadcrumbs breadcrumbs
:route-map/current-route route)
:dispatch-n (contexts-diff (:route/context db)
contexts
(:params route)
(get-in db [:route-map/current-route :params]))})
{:db (assoc db :fragment fragment :route-map/current-route nil)})))
(rf/reg-event-fx
:route-map/init
(fn [cofx [_ routes]]
{:db (assoc (:db cofx) :route-map/routes routes)
:history {}}))
(rf/reg-fx
:history
(fn [_]
(aset js/window "onhashchange" dispatch-routes)
(dispatch-routes nil)))
(rf/reg-fx
:route-map/redirect
(fn [href]
(.log js/console "REDIRECT FX" href)
(aset (.-location js/window) "hash" href)))
|
|
8614cadd2198b0a86c335fdfedc5eaeec02982cc406db43360b8a7eeb88192c0 | jacobobryant/eelchat | app.clj | (ns com.eelchat.feat.app
(:require [com.biffweb :as biff :refer [q]]
[com.eelchat.feat.subscriptions :as sub]
[com.eelchat.middleware :as mid]
[com.eelchat.ui :as ui]
[clojure.string :as str]
[ring.adapter.jetty9 :as jetty]
[rum.core :as rum]
[xtdb.api :as xt]))
(defn app [req]
(ui/app-page
req
[:p "Select a community, or create a new one."]))
(defn new-community [{:keys [session] :as req}]
(let [comm-id (random-uuid)]
(biff/submit-tx req
[{:db/doc-type :community
:xt/id comm-id
:comm/title (str "Community #" (rand-int 1000))}
{:db/doc-type :membership
:mem/user (:uid session)
:mem/comm comm-id
:mem/roles #{:admin}}])
{:status 303
:headers {"Location" (str "/community/" comm-id)}}))
(defn join-community [{:keys [user community] :as req}]
(biff/submit-tx req
[{:db/doc-type :membership
:db.op/upsert {:mem/user (:xt/id user)
:mem/comm (:xt/id community)}
:mem/roles [:db/default #{}]}])
{:status 303
:headers {"Location" (str "/community/" (:xt/id community))}})
(defn new-channel [{:keys [community roles] :as req}]
(if (and community (contains? roles :admin))
(let [chan-id (random-uuid)]
(biff/submit-tx req
[{:db/doc-type :channel
:xt/id chan-id
:chan/title (str "Channel #" (rand-int 1000))
:chan/comm (:xt/id community)}])
{:status 303
:headers {"Location" (str "/community/" (:xt/id community) "/channel/" chan-id)}})
{:status 403
:body "Forbidden."}))
(defn delete-channel [{:keys [biff/db channel roles] :as req}]
(when (contains? roles :admin)
(biff/submit-tx req
(for [id (conj (q db
'{:find msg
:in [channel]
:where [[msg :msg/channel channel]]}
(:xt/id channel))
(:xt/id channel))]
{:db/op :delete
:xt/id id})))
[:<>])
(defn community [{:keys [biff/db user community] :as req}]
(let [member (some (fn [mem]
(= (:xt/id community) (get-in mem [:mem/comm :xt/id])))
(:user/mems user))]
(ui/app-page
req
(if member
[:<>
[:.border.border-neutral-600.p-3.bg-white.grow
"Messages window"]
[:.h-3]
[:.border.border-neutral-600.p-3.h-28.bg-white
"Compose window"]]
[:<>
[:.grow]
[:h1.text-3xl.text-center (:comm/title community)]
[:.h-6]
(biff/form
{:action (str "/community/" (:xt/id community) "/join")
:class "flex justify-center"}
[:button.btn {:type "submit"} "Join this community"])
[:div {:class "grow-[1.75]"}]]))))
(defn message-view [{:msg/keys [mem text created-at]}]
(let [username (if (= :system mem)
"🎅🏻 System 🎅🏻"
(str "User " (subs (str mem) 0 4)))]
[:div
[:.text-sm
[:span.font-bold username]
[:span.w-2.inline-block]
[:span.text-gray-600 (biff/format-date created-at "d MMM h:mm aa")]]
[:p.whitespace-pre-wrap.mb-6 text]]))
(defn command-tx [{:keys [biff/db channel roles params]}]
(let [subscribe-url (second (re-find #"^/subscribe ([^\s]+)" (:text params)))
unsubscribe-url (second (re-find #"^/unsubscribe ([^\s]+)" (:text params)))
list-command (= (str/trimr (:text params)) "/list")
message (fn [text]
{:db/doc-type :message
:msg/mem :system
:msg/channel (:xt/id channel)
:msg/text text
;; Make sure this message comes after the user's message.
:msg/created-at (biff/add-seconds (java.util.Date.) 1)})]
(cond
(not (contains? roles :admin))
nil
subscribe-url
[{:db/doc-type :subscription
:db.op/upsert {:sub/url subscribe-url
:sub/chan (:xt/id channel)}}
(message (str "Subscribed to " subscribe-url))]
unsubscribe-url
[{:db/op :delete
:xt/id (biff/lookup-id db :sub/chan (:xt/id channel) :sub/url unsubscribe-url)}
(message (str "Unsubscribed from " unsubscribe-url))]
list-command
[(message (apply
str
"Subscriptions:"
(for [url (->> (q db
'{:find (pull sub [:sub/url])
:in [channel]
:where [[sub :sub/chan channel]]}
(:xt/id channel))
(map :sub/url)
sort)]
(str "\n - " url))))])))
(defn new-message [{:keys [channel mem params] :as req}]
(let [msg {:xt/id (random-uuid)
:msg/mem (:xt/id mem)
:msg/channel (:xt/id channel)
:msg/created-at (java.util.Date.)
:msg/text (:text params)}]
(biff/submit-tx (assoc req :biff.xtdb/retry false)
(concat [(assoc msg :db/doc-type :message)]
(command-tx req)))
(message-view msg)))
(defn channel-page [{:keys [biff/db community channel] :as req}]
(let [msgs (q db
'{:find (pull msg [*])
:in [channel]
:where [[msg :msg/channel channel]]}
(:xt/id channel))
href (str "/community/" (:xt/id community)
"/channel/" (:xt/id channel))]
(ui/app-page
req
[:.border.border-neutral-600.p-3.bg-white.grow.flex-1.overflow-y-auto#messages
{:hx-ext "ws"
:ws-connect (str href "/connect")
:_ "on load or newMessage set my scrollTop to my scrollHeight"}
(map message-view (sort-by :msg/created-at msgs))]
[:.h-3]
(biff/form
{:hx-post href
:hx-target "#messages"
:hx-swap "beforeend"
:_ (str "on htmx:afterRequest"
" set <textarea/>'s value to ''"
" then send newMessage to #messages")
:class "flex"}
[:textarea.w-full#text {:name "text"}]
[:.w-2]
[:button.btn {:type "submit"} "Send"]))))
(defn connect [{:keys [com.eelchat/chat-clients]
{chan-id :xt/id} :channel
{mem-id :xt/id} :mem
:as req}]
{:status 101
:headers {"upgrade" "websocket"
"connection" "upgrade"}
:ws {:on-connect (fn [ws]
(swap! chat-clients assoc-in [chan-id mem-id] ws))
:on-close (fn [ws status-code reason]
(swap! chat-clients
(fn [chat-clients]
(let [chat-clients (update chat-clients chan-id dissoc mem-id)]
(if (empty? (get chat-clients chan-id))
(dissoc chat-clients chan-id)
chat-clients)))))}})
(defn on-new-message [{:keys [biff.xtdb/node com.eelchat/chat-clients]} tx]
(let [db-before (xt/db node {::xt/tx-id (dec (::xt/tx-id tx))})]
(doseq [[op & args] (::xt/tx-ops tx)
:when (= op ::xt/put)
:let [[doc] args]
:when (and (contains? doc :msg/text)
(nil? (xt/entity db-before (:xt/id doc))))
:let [html (rum/render-static-markup
[:div#messages {:hx-swap-oob "beforeend"}
(message-view doc)
[:div {:_ "init send newMessage to #messages then remove me"}]])]
[mem-id client] (get @chat-clients (:msg/channel doc))
:when (not= mem-id (:msg/mem doc))]
(jetty/send! client html))))
(defn on-new-subscription [{:keys [biff.xtdb/node] :as sys} tx]
(let [db-before (xt/db node {::xt/tx-id (dec (::xt/tx-id tx))})]
(doseq [[op & args] (::xt/tx-ops tx)
:when (= op ::xt/put)
:let [[doc] args]
:when (and (contains? doc :sub/url)
(nil? (xt/entity db-before (:xt/id doc))))]
(biff/submit-job sys :fetch-rss (assoc doc :biff/priority 0)))))
(defn on-tx [sys tx]
(on-new-message sys tx)
(on-new-subscription sys tx))
(defn wrap-community [handler]
(fn [{:keys [biff/db user path-params] :as req}]
(if-some [community (xt/entity db (parse-uuid (:id path-params)))]
(let [mem (->> (:user/mems user)
(filter (fn [mem]
(= (:xt/id community) (get-in mem [:mem/comm :xt/id]))))
first)
roles (:mem/roles mem)]
(handler (assoc req :community community :roles roles :mem mem)))
{:status 303
:headers {"location" "/app"}})))
(defn wrap-channel [handler]
(fn [{:keys [biff/db user mem community path-params] :as req}]
(let [channel (xt/entity db (parse-uuid (:chan-id path-params)))]
(if (and (= (:chan/comm channel) (:xt/id community)) mem)
(handler (assoc req :channel channel))
{:status 303
:headers {"Location" (str "/community/" (:xt/id community))}}))))
(def features
{:routes ["" {:middleware [mid/wrap-signed-in]}
["/app" {:get app}]
["/community" {:post new-community}]
["/community/:id" {:middleware [wrap-community]}
["" {:get community}]
["/join" {:post join-community}]
["/channel" {:post new-channel}]
["/channel/:chan-id" {:middleware [wrap-channel]}
["" {:get channel-page
:post new-message
:delete delete-channel}]
["/connect" {:get connect}]]]]
:on-tx on-tx})
| null | https://raw.githubusercontent.com/jacobobryant/eelchat/8b7eb0776a6c121d75abe6a4088dd2ffd77c1024/src/com/eelchat/feat/app.clj | clojure | Make sure this message comes after the user's message. | (ns com.eelchat.feat.app
(:require [com.biffweb :as biff :refer [q]]
[com.eelchat.feat.subscriptions :as sub]
[com.eelchat.middleware :as mid]
[com.eelchat.ui :as ui]
[clojure.string :as str]
[ring.adapter.jetty9 :as jetty]
[rum.core :as rum]
[xtdb.api :as xt]))
(defn app [req]
(ui/app-page
req
[:p "Select a community, or create a new one."]))
(defn new-community [{:keys [session] :as req}]
(let [comm-id (random-uuid)]
(biff/submit-tx req
[{:db/doc-type :community
:xt/id comm-id
:comm/title (str "Community #" (rand-int 1000))}
{:db/doc-type :membership
:mem/user (:uid session)
:mem/comm comm-id
:mem/roles #{:admin}}])
{:status 303
:headers {"Location" (str "/community/" comm-id)}}))
(defn join-community [{:keys [user community] :as req}]
(biff/submit-tx req
[{:db/doc-type :membership
:db.op/upsert {:mem/user (:xt/id user)
:mem/comm (:xt/id community)}
:mem/roles [:db/default #{}]}])
{:status 303
:headers {"Location" (str "/community/" (:xt/id community))}})
(defn new-channel [{:keys [community roles] :as req}]
(if (and community (contains? roles :admin))
(let [chan-id (random-uuid)]
(biff/submit-tx req
[{:db/doc-type :channel
:xt/id chan-id
:chan/title (str "Channel #" (rand-int 1000))
:chan/comm (:xt/id community)}])
{:status 303
:headers {"Location" (str "/community/" (:xt/id community) "/channel/" chan-id)}})
{:status 403
:body "Forbidden."}))
(defn delete-channel [{:keys [biff/db channel roles] :as req}]
(when (contains? roles :admin)
(biff/submit-tx req
(for [id (conj (q db
'{:find msg
:in [channel]
:where [[msg :msg/channel channel]]}
(:xt/id channel))
(:xt/id channel))]
{:db/op :delete
:xt/id id})))
[:<>])
(defn community [{:keys [biff/db user community] :as req}]
(let [member (some (fn [mem]
(= (:xt/id community) (get-in mem [:mem/comm :xt/id])))
(:user/mems user))]
(ui/app-page
req
(if member
[:<>
[:.border.border-neutral-600.p-3.bg-white.grow
"Messages window"]
[:.h-3]
[:.border.border-neutral-600.p-3.h-28.bg-white
"Compose window"]]
[:<>
[:.grow]
[:h1.text-3xl.text-center (:comm/title community)]
[:.h-6]
(biff/form
{:action (str "/community/" (:xt/id community) "/join")
:class "flex justify-center"}
[:button.btn {:type "submit"} "Join this community"])
[:div {:class "grow-[1.75]"}]]))))
(defn message-view [{:msg/keys [mem text created-at]}]
(let [username (if (= :system mem)
"🎅🏻 System 🎅🏻"
(str "User " (subs (str mem) 0 4)))]
[:div
[:.text-sm
[:span.font-bold username]
[:span.w-2.inline-block]
[:span.text-gray-600 (biff/format-date created-at "d MMM h:mm aa")]]
[:p.whitespace-pre-wrap.mb-6 text]]))
(defn command-tx [{:keys [biff/db channel roles params]}]
(let [subscribe-url (second (re-find #"^/subscribe ([^\s]+)" (:text params)))
unsubscribe-url (second (re-find #"^/unsubscribe ([^\s]+)" (:text params)))
list-command (= (str/trimr (:text params)) "/list")
message (fn [text]
{:db/doc-type :message
:msg/mem :system
:msg/channel (:xt/id channel)
:msg/text text
:msg/created-at (biff/add-seconds (java.util.Date.) 1)})]
(cond
(not (contains? roles :admin))
nil
subscribe-url
[{:db/doc-type :subscription
:db.op/upsert {:sub/url subscribe-url
:sub/chan (:xt/id channel)}}
(message (str "Subscribed to " subscribe-url))]
unsubscribe-url
[{:db/op :delete
:xt/id (biff/lookup-id db :sub/chan (:xt/id channel) :sub/url unsubscribe-url)}
(message (str "Unsubscribed from " unsubscribe-url))]
list-command
[(message (apply
str
"Subscriptions:"
(for [url (->> (q db
'{:find (pull sub [:sub/url])
:in [channel]
:where [[sub :sub/chan channel]]}
(:xt/id channel))
(map :sub/url)
sort)]
(str "\n - " url))))])))
(defn new-message [{:keys [channel mem params] :as req}]
(let [msg {:xt/id (random-uuid)
:msg/mem (:xt/id mem)
:msg/channel (:xt/id channel)
:msg/created-at (java.util.Date.)
:msg/text (:text params)}]
(biff/submit-tx (assoc req :biff.xtdb/retry false)
(concat [(assoc msg :db/doc-type :message)]
(command-tx req)))
(message-view msg)))
(defn channel-page [{:keys [biff/db community channel] :as req}]
(let [msgs (q db
'{:find (pull msg [*])
:in [channel]
:where [[msg :msg/channel channel]]}
(:xt/id channel))
href (str "/community/" (:xt/id community)
"/channel/" (:xt/id channel))]
(ui/app-page
req
[:.border.border-neutral-600.p-3.bg-white.grow.flex-1.overflow-y-auto#messages
{:hx-ext "ws"
:ws-connect (str href "/connect")
:_ "on load or newMessage set my scrollTop to my scrollHeight"}
(map message-view (sort-by :msg/created-at msgs))]
[:.h-3]
(biff/form
{:hx-post href
:hx-target "#messages"
:hx-swap "beforeend"
:_ (str "on htmx:afterRequest"
" set <textarea/>'s value to ''"
" then send newMessage to #messages")
:class "flex"}
[:textarea.w-full#text {:name "text"}]
[:.w-2]
[:button.btn {:type "submit"} "Send"]))))
(defn connect [{:keys [com.eelchat/chat-clients]
{chan-id :xt/id} :channel
{mem-id :xt/id} :mem
:as req}]
{:status 101
:headers {"upgrade" "websocket"
"connection" "upgrade"}
:ws {:on-connect (fn [ws]
(swap! chat-clients assoc-in [chan-id mem-id] ws))
:on-close (fn [ws status-code reason]
(swap! chat-clients
(fn [chat-clients]
(let [chat-clients (update chat-clients chan-id dissoc mem-id)]
(if (empty? (get chat-clients chan-id))
(dissoc chat-clients chan-id)
chat-clients)))))}})
(defn on-new-message [{:keys [biff.xtdb/node com.eelchat/chat-clients]} tx]
(let [db-before (xt/db node {::xt/tx-id (dec (::xt/tx-id tx))})]
(doseq [[op & args] (::xt/tx-ops tx)
:when (= op ::xt/put)
:let [[doc] args]
:when (and (contains? doc :msg/text)
(nil? (xt/entity db-before (:xt/id doc))))
:let [html (rum/render-static-markup
[:div#messages {:hx-swap-oob "beforeend"}
(message-view doc)
[:div {:_ "init send newMessage to #messages then remove me"}]])]
[mem-id client] (get @chat-clients (:msg/channel doc))
:when (not= mem-id (:msg/mem doc))]
(jetty/send! client html))))
(defn on-new-subscription [{:keys [biff.xtdb/node] :as sys} tx]
(let [db-before (xt/db node {::xt/tx-id (dec (::xt/tx-id tx))})]
(doseq [[op & args] (::xt/tx-ops tx)
:when (= op ::xt/put)
:let [[doc] args]
:when (and (contains? doc :sub/url)
(nil? (xt/entity db-before (:xt/id doc))))]
(biff/submit-job sys :fetch-rss (assoc doc :biff/priority 0)))))
(defn on-tx [sys tx]
(on-new-message sys tx)
(on-new-subscription sys tx))
(defn wrap-community [handler]
(fn [{:keys [biff/db user path-params] :as req}]
(if-some [community (xt/entity db (parse-uuid (:id path-params)))]
(let [mem (->> (:user/mems user)
(filter (fn [mem]
(= (:xt/id community) (get-in mem [:mem/comm :xt/id]))))
first)
roles (:mem/roles mem)]
(handler (assoc req :community community :roles roles :mem mem)))
{:status 303
:headers {"location" "/app"}})))
(defn wrap-channel [handler]
(fn [{:keys [biff/db user mem community path-params] :as req}]
(let [channel (xt/entity db (parse-uuid (:chan-id path-params)))]
(if (and (= (:chan/comm channel) (:xt/id community)) mem)
(handler (assoc req :channel channel))
{:status 303
:headers {"Location" (str "/community/" (:xt/id community))}}))))
(def features
{:routes ["" {:middleware [mid/wrap-signed-in]}
["/app" {:get app}]
["/community" {:post new-community}]
["/community/:id" {:middleware [wrap-community]}
["" {:get community}]
["/join" {:post join-community}]
["/channel" {:post new-channel}]
["/channel/:chan-id" {:middleware [wrap-channel]}
["" {:get channel-page
:post new-message
:delete delete-channel}]
["/connect" {:get connect}]]]]
:on-tx on-tx})
|
fefabb22253b3ccad524f16a61153003b26e3878ee3908927e29e62f6f142a89 | erlang/otp | raw_file_io_inflate.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2017 - 2022 . 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(raw_file_io_inflate).
-behavior(gen_statem).
-export([init/1, callback_mode/0, terminate/3]).
-export([opening/3, opened_gzip/3, opened_passthrough/3]).
-include("file_int.hrl").
-define(INFLATE_CHUNK_SIZE, (8 bsl 10)).
-define(GZIP_WBITS, (16 + 15)).
callback_mode() -> state_functions.
init({Owner, Secret, [compressed]}) ->
%% 'reset mode', which resets the inflate state at the end of every stream,
%% allowing us to read concatenated gzip files.
init(Owner, Secret, reset);
init({Owner, Secret, [compressed_one]}) ->
' cut mode ' , which stops the inflate after one member
%% allowing us to read gzipped tar files
init(Owner, Secret, cut).
init(Owner, Secret, Mode) ->
Monitor = monitor(process, Owner),
%% We're using the undocumented inflateInit/3 to set the mode
Z = zlib:open(),
ok = zlib:inflateInit(Z, ?GZIP_WBITS, Mode),
Data =
#{ owner => Owner,
monitor => Monitor,
secret => Secret,
position => 0,
buffer => prim_buffer:new(),
zlib => Z },
{ok, opening, Data}.
%% The old driver fell back to plain reads if the file didn't start with the
magic .
choose_decompression_state(PrivateFd) ->
State =
case ?CALL_FD(PrivateFd, read, [2]) of
{ok, <<16#1F, 16#8B>>} -> opened_gzip;
_Other -> opened_passthrough
end,
{ok, 0} = ?CALL_FD(PrivateFd, position, [0]),
State.
opening({call, From}, {'$open', Secret, Filename, Modes}, #{ secret := Secret } = Data) ->
case raw_file_io:open(Filename, Modes) of
{ok, PrivateFd} ->
NextState = choose_decompression_state(PrivateFd),
NewData = Data#{ handle => PrivateFd },
{next_state, NextState, NewData, [{reply, From, ok}]};
Other ->
{stop_and_reply, normal, [{reply, From, Other}]}
end;
opening(_Event, _Contents, _Data) ->
{keep_state_and_data, [postpone]}.
internal_close(From, Data) ->
#{ handle := PrivateFd } = Data,
Response = ?CALL_FD(PrivateFd, close, []),
{stop_and_reply, normal, [{reply, From, Response}]}.
opened_passthrough(info, {'DOWN', Monitor, process, _Owner, _Reason}, #{ monitor := Monitor }) ->
{stop, shutdown};
opened_passthrough(info, _Message, _Data) ->
keep_state_and_data;
opened_passthrough({call, {Owner, _Tag} = From}, [close], #{ owner := Owner } = Data) ->
internal_close(From, Data);
opened_passthrough({call, {Owner, _Tag} = From}, [Method | Args], #{ owner := Owner } = Data) ->
#{ handle := PrivateFd } = Data,
Response = ?CALL_FD(PrivateFd, Method, Args),
{keep_state_and_data, [{reply, From, Response}]};
opened_passthrough({call, _From}, _Command, _Data) ->
%% The client functions filter this out, so we'll crash if the user does
%% anything stupid on purpose.
{shutdown, protocol_violation};
opened_passthrough(_Event, _Request, _Data) ->
keep_state_and_data.
%%
opened_gzip(info, {'DOWN', Monitor, process, _Owner, _Reason}, #{ monitor := Monitor }) ->
{stop, shutdown};
opened_gzip(info, _Message, _Data) ->
keep_state_and_data;
opened_gzip({call, {Owner, _Tag} = From}, [close], #{ owner := Owner } = Data) ->
internal_close(From, Data);
opened_gzip({call, {Owner, _Tag} = From}, [position, Mark], #{ owner := Owner } = Data) ->
case position(Data, Mark) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [read, Size], #{ owner := Owner } = Data) ->
case read(Data, Size) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [read_line], #{ owner := Owner } = Data) ->
case read_line(Data) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [write, _IOData], #{ owner := Owner }) ->
Response = {error, ebadf},
{keep_state_and_data, [{reply, From, Response}]};
opened_gzip({call, {Owner, _Tag} = From}, _Request, #{ owner := Owner }) ->
Response = {error, enotsup},
{keep_state_and_data, [{reply, From, Response}]};
opened_gzip({call, _From}, _Request, _Data) ->
%% The client functions filter this out, so we'll crash if the user does
%% anything stupid on purpose.
{shutdown, protocol_violation};
opened_gzip(_Event, _Request, _Data) ->
keep_state_and_data.
%%
read(#{ buffer := Buffer } = Data, Size) ->
try read_1(Data, Buffer, prim_buffer:size(Buffer), Size) of
Result -> Result
catch
error:badarg -> {error, badarg};
error:_ -> {error, eio}
end.
read_1(Data, Buffer, BufferSize, ReadSize) when BufferSize >= ReadSize ->
#{ position := Position } = Data,
Decompressed = prim_buffer:read(Buffer, ReadSize),
{ok, Data#{ position => (Position + ReadSize) }, Decompressed};
read_1(Data, Buffer, BufferSize, ReadSize) when BufferSize < ReadSize ->
#{ handle := PrivateFd } = Data,
case ?CALL_FD(PrivateFd, read, [?INFLATE_CHUNK_SIZE]) of
{ok, Compressed} ->
#{ zlib := Z } = Data,
Uncompressed = erlang:iolist_to_iovec(zlib:inflate(Z, Compressed)),
prim_buffer:write(Buffer, Uncompressed),
read_1(Data, Buffer, prim_buffer:size(Buffer), ReadSize);
eof when BufferSize > 0 ->
read_1(Data, Buffer, BufferSize, BufferSize);
Other ->
Other
end.
read_line(#{ buffer := Buffer } = Data) ->
try read_line_1(Data, Buffer, prim_buffer:find_byte_index(Buffer, $\n)) of
{ok, NewData, Decompressed} -> {ok, NewData, Decompressed};
Other -> Other
catch
error:badarg -> {error, badarg};
error:_ -> {error, eio}
end.
read_line_1(Data, Buffer, not_found) ->
#{ handle := PrivateFd, zlib := Z } = Data,
case ?CALL_FD(PrivateFd, read, [?INFLATE_CHUNK_SIZE]) of
{ok, Compressed} ->
Uncompressed = erlang:iolist_to_iovec(zlib:inflate(Z, Compressed)),
prim_buffer:write(Buffer, Uncompressed),
read_line_1(Data, Buffer, prim_buffer:find_byte_index(Buffer, $\n));
eof ->
case prim_buffer:size(Buffer) of
Size when Size > 0 -> {ok, prim_buffer:read(Buffer, Size)};
Size when Size =:= 0 -> eof
end;
Error ->
Error
end;
read_line_1(Data, Buffer, {ok, LFIndex}) ->
Translate CRLF into just LF , completely ignoring which encoding is used ,
but treat the file position as including CR .
#{ position := Position } = Data,
NewData = Data#{ position => (Position + LFIndex + 1) },
CRIndex = (LFIndex - 1),
TranslatedLine =
case prim_buffer:read(Buffer, LFIndex + 1) of
<<Line:CRIndex/binary, "\r\n">> -> <<Line/binary, "\n">>;
Line -> Line
end,
{ok, NewData, TranslatedLine}.
%%
We support seeking in both directions as long as it is n't relative to EOF .
%%
%% Seeking backwards is extremely inefficient since we have to seek to the very
%% beginning and then decompress up to the desired point.
%%
position(Data, Mark) when is_atom(Mark) ->
position(Data, {Mark, 0});
position(Data, Offset) when is_integer(Offset) ->
position(Data, {bof, Offset});
position(Data, {bof, Offset}) when is_integer(Offset) ->
position_1(Data, Offset);
position(Data, {cur, Offset}) when is_integer(Offset) ->
#{ position := Position } = Data,
position_1(Data, Position + Offset);
position(_Data, {eof, Offset}) when is_integer(Offset) ->
{error, einval};
position(_Data, _Other) ->
{error, badarg}.
position_1(_Data, Desired) when Desired < 0 ->
{error, einval};
position_1(#{ position := Desired } = Data, Desired) ->
{ok, Data, Desired};
position_1(#{ position := Current } = Data, Desired) when Current < Desired ->
case read(Data, min(Desired - Current, ?INFLATE_CHUNK_SIZE)) of
{ok, NewData, _Data} -> position_1(NewData, Desired);
eof -> {ok, Data, Current};
Other -> Other
end;
position_1(#{ position := Current } = Data, Desired) when Current > Desired ->
#{ handle := PrivateFd, buffer := Buffer, zlib := Z } = Data,
case ?CALL_FD(PrivateFd, position, [bof]) of
{ok, 0} ->
ok = zlib:inflateReset(Z),
prim_buffer:wipe(Buffer),
position_1(Data#{ position => 0 }, Desired);
Other ->
Other
end.
terminate(_Reason, _State, _Data) ->
ok.
| null | https://raw.githubusercontent.com/erlang/otp/daccb908c6d46bef5b1129fac66e1cdacb5e0568/lib/kernel/src/raw_file_io_inflate.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%
'reset mode', which resets the inflate state at the end of every stream,
allowing us to read concatenated gzip files.
allowing us to read gzipped tar files
We're using the undocumented inflateInit/3 to set the mode
The old driver fell back to plain reads if the file didn't start with the
The client functions filter this out, so we'll crash if the user does
anything stupid on purpose.
The client functions filter this out, so we'll crash if the user does
anything stupid on purpose.
Seeking backwards is extremely inefficient since we have to seek to the very
beginning and then decompress up to the desired point.
| Copyright Ericsson AB 2017 - 2022 . 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(raw_file_io_inflate).
-behavior(gen_statem).
-export([init/1, callback_mode/0, terminate/3]).
-export([opening/3, opened_gzip/3, opened_passthrough/3]).
-include("file_int.hrl").
-define(INFLATE_CHUNK_SIZE, (8 bsl 10)).
-define(GZIP_WBITS, (16 + 15)).
callback_mode() -> state_functions.
init({Owner, Secret, [compressed]}) ->
init(Owner, Secret, reset);
init({Owner, Secret, [compressed_one]}) ->
' cut mode ' , which stops the inflate after one member
init(Owner, Secret, cut).
init(Owner, Secret, Mode) ->
Monitor = monitor(process, Owner),
Z = zlib:open(),
ok = zlib:inflateInit(Z, ?GZIP_WBITS, Mode),
Data =
#{ owner => Owner,
monitor => Monitor,
secret => Secret,
position => 0,
buffer => prim_buffer:new(),
zlib => Z },
{ok, opening, Data}.
magic .
choose_decompression_state(PrivateFd) ->
State =
case ?CALL_FD(PrivateFd, read, [2]) of
{ok, <<16#1F, 16#8B>>} -> opened_gzip;
_Other -> opened_passthrough
end,
{ok, 0} = ?CALL_FD(PrivateFd, position, [0]),
State.
opening({call, From}, {'$open', Secret, Filename, Modes}, #{ secret := Secret } = Data) ->
case raw_file_io:open(Filename, Modes) of
{ok, PrivateFd} ->
NextState = choose_decompression_state(PrivateFd),
NewData = Data#{ handle => PrivateFd },
{next_state, NextState, NewData, [{reply, From, ok}]};
Other ->
{stop_and_reply, normal, [{reply, From, Other}]}
end;
opening(_Event, _Contents, _Data) ->
{keep_state_and_data, [postpone]}.
internal_close(From, Data) ->
#{ handle := PrivateFd } = Data,
Response = ?CALL_FD(PrivateFd, close, []),
{stop_and_reply, normal, [{reply, From, Response}]}.
opened_passthrough(info, {'DOWN', Monitor, process, _Owner, _Reason}, #{ monitor := Monitor }) ->
{stop, shutdown};
opened_passthrough(info, _Message, _Data) ->
keep_state_and_data;
opened_passthrough({call, {Owner, _Tag} = From}, [close], #{ owner := Owner } = Data) ->
internal_close(From, Data);
opened_passthrough({call, {Owner, _Tag} = From}, [Method | Args], #{ owner := Owner } = Data) ->
#{ handle := PrivateFd } = Data,
Response = ?CALL_FD(PrivateFd, Method, Args),
{keep_state_and_data, [{reply, From, Response}]};
opened_passthrough({call, _From}, _Command, _Data) ->
{shutdown, protocol_violation};
opened_passthrough(_Event, _Request, _Data) ->
keep_state_and_data.
opened_gzip(info, {'DOWN', Monitor, process, _Owner, _Reason}, #{ monitor := Monitor }) ->
{stop, shutdown};
opened_gzip(info, _Message, _Data) ->
keep_state_and_data;
opened_gzip({call, {Owner, _Tag} = From}, [close], #{ owner := Owner } = Data) ->
internal_close(From, Data);
opened_gzip({call, {Owner, _Tag} = From}, [position, Mark], #{ owner := Owner } = Data) ->
case position(Data, Mark) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [read, Size], #{ owner := Owner } = Data) ->
case read(Data, Size) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [read_line], #{ owner := Owner } = Data) ->
case read_line(Data) of
{ok, NewData, Result} ->
Response = {ok, Result},
{keep_state, NewData, [{reply, From, Response}]};
Other ->
{keep_state_and_data, [{reply, From, Other}]}
end;
opened_gzip({call, {Owner, _Tag} = From}, [write, _IOData], #{ owner := Owner }) ->
Response = {error, ebadf},
{keep_state_and_data, [{reply, From, Response}]};
opened_gzip({call, {Owner, _Tag} = From}, _Request, #{ owner := Owner }) ->
Response = {error, enotsup},
{keep_state_and_data, [{reply, From, Response}]};
opened_gzip({call, _From}, _Request, _Data) ->
{shutdown, protocol_violation};
opened_gzip(_Event, _Request, _Data) ->
keep_state_and_data.
read(#{ buffer := Buffer } = Data, Size) ->
try read_1(Data, Buffer, prim_buffer:size(Buffer), Size) of
Result -> Result
catch
error:badarg -> {error, badarg};
error:_ -> {error, eio}
end.
read_1(Data, Buffer, BufferSize, ReadSize) when BufferSize >= ReadSize ->
#{ position := Position } = Data,
Decompressed = prim_buffer:read(Buffer, ReadSize),
{ok, Data#{ position => (Position + ReadSize) }, Decompressed};
read_1(Data, Buffer, BufferSize, ReadSize) when BufferSize < ReadSize ->
#{ handle := PrivateFd } = Data,
case ?CALL_FD(PrivateFd, read, [?INFLATE_CHUNK_SIZE]) of
{ok, Compressed} ->
#{ zlib := Z } = Data,
Uncompressed = erlang:iolist_to_iovec(zlib:inflate(Z, Compressed)),
prim_buffer:write(Buffer, Uncompressed),
read_1(Data, Buffer, prim_buffer:size(Buffer), ReadSize);
eof when BufferSize > 0 ->
read_1(Data, Buffer, BufferSize, BufferSize);
Other ->
Other
end.
read_line(#{ buffer := Buffer } = Data) ->
try read_line_1(Data, Buffer, prim_buffer:find_byte_index(Buffer, $\n)) of
{ok, NewData, Decompressed} -> {ok, NewData, Decompressed};
Other -> Other
catch
error:badarg -> {error, badarg};
error:_ -> {error, eio}
end.
read_line_1(Data, Buffer, not_found) ->
#{ handle := PrivateFd, zlib := Z } = Data,
case ?CALL_FD(PrivateFd, read, [?INFLATE_CHUNK_SIZE]) of
{ok, Compressed} ->
Uncompressed = erlang:iolist_to_iovec(zlib:inflate(Z, Compressed)),
prim_buffer:write(Buffer, Uncompressed),
read_line_1(Data, Buffer, prim_buffer:find_byte_index(Buffer, $\n));
eof ->
case prim_buffer:size(Buffer) of
Size when Size > 0 -> {ok, prim_buffer:read(Buffer, Size)};
Size when Size =:= 0 -> eof
end;
Error ->
Error
end;
read_line_1(Data, Buffer, {ok, LFIndex}) ->
Translate CRLF into just LF , completely ignoring which encoding is used ,
but treat the file position as including CR .
#{ position := Position } = Data,
NewData = Data#{ position => (Position + LFIndex + 1) },
CRIndex = (LFIndex - 1),
TranslatedLine =
case prim_buffer:read(Buffer, LFIndex + 1) of
<<Line:CRIndex/binary, "\r\n">> -> <<Line/binary, "\n">>;
Line -> Line
end,
{ok, NewData, TranslatedLine}.
We support seeking in both directions as long as it is n't relative to EOF .
position(Data, Mark) when is_atom(Mark) ->
position(Data, {Mark, 0});
position(Data, Offset) when is_integer(Offset) ->
position(Data, {bof, Offset});
position(Data, {bof, Offset}) when is_integer(Offset) ->
position_1(Data, Offset);
position(Data, {cur, Offset}) when is_integer(Offset) ->
#{ position := Position } = Data,
position_1(Data, Position + Offset);
position(_Data, {eof, Offset}) when is_integer(Offset) ->
{error, einval};
position(_Data, _Other) ->
{error, badarg}.
position_1(_Data, Desired) when Desired < 0 ->
{error, einval};
position_1(#{ position := Desired } = Data, Desired) ->
{ok, Data, Desired};
position_1(#{ position := Current } = Data, Desired) when Current < Desired ->
case read(Data, min(Desired - Current, ?INFLATE_CHUNK_SIZE)) of
{ok, NewData, _Data} -> position_1(NewData, Desired);
eof -> {ok, Data, Current};
Other -> Other
end;
position_1(#{ position := Current } = Data, Desired) when Current > Desired ->
#{ handle := PrivateFd, buffer := Buffer, zlib := Z } = Data,
case ?CALL_FD(PrivateFd, position, [bof]) of
{ok, 0} ->
ok = zlib:inflateReset(Z),
prim_buffer:wipe(Buffer),
position_1(Data#{ position => 0 }, Desired);
Other ->
Other
end.
terminate(_Reason, _State, _Data) ->
ok.
|
a7986ced13eb771f44b211329e2161e60a2c7260f1a97caff801c94687c4e4ac | tlehman/sicp-exercises | ex-1.25.scm | Exercise 1.25 : complains that we went to a lot of
; extra work in writing expmod. After all, she says, since we already
; know how to compute exponentials, we could have simple written
(define (expmod base exp m)
(remainder (fast-expt base exp) m))
; Is she correct?
; Yes.
; Would this procedure serve as well for our fast prime tester? Explain.
; No, since it has to compute the whole exponentiation and then take
; the remainder, this is not as fast as expmod defined in helpers.scm
| null | https://raw.githubusercontent.com/tlehman/sicp-exercises/57151ec07d09a98318e91c83b6eacaa49361d156/ex-1.25.scm | scheme | extra work in writing expmod. After all, she says, since we already
know how to compute exponentials, we could have simple written
Is she correct?
Yes.
Would this procedure serve as well for our fast prime tester? Explain.
No, since it has to compute the whole exponentiation and then take
the remainder, this is not as fast as expmod defined in helpers.scm | Exercise 1.25 : complains that we went to a lot of
(define (expmod base exp m)
(remainder (fast-expt base exp) m))
|
c6c7d21d8f85a2f0036a49505841f2b914eaeb7af4a5efc1e304c28babdc1e24 | RefactoringTools/HaRe | D3.hs | module LiftOneLevel.D3 where
{-lift 'sq' to top level. This refactoring only affects the
current module. -}
sumSquares (x:xs) = sq x + sumSquares xs
where
sq x = x ^ pow
sumSquares [] = 0
pow = 2
| null | https://raw.githubusercontent.com/RefactoringTools/HaRe/ef5dee64c38fb104e6e5676095946279fbce381c/test/testdata/LiftOneLevel/D3.hs | haskell | lift 'sq' to top level. This refactoring only affects the
current module. | module LiftOneLevel.D3 where
sumSquares (x:xs) = sq x + sumSquares xs
where
sq x = x ^ pow
sumSquares [] = 0
pow = 2
|
46f8c1f1fc3c7643056e92931d115d0b75b9a15875014561f4d01ce8500f587e | ptal/AbSolute | bot.ml | Copyright 2014
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 .
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 .
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.
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. *)
(** Adds a bottom element to a data-type. *)
type 'a bot = Bot | Nb of 'a
let strict_bot f x =
match x with Bot -> Bot | Nb x -> f x
let lift_bot f x =
match x with Bot -> Bot | Nb x -> Nb (f x)
let merge_bot2 x y =
match x,y with
| Bot,_ -> Bot
| _,Bot -> Bot
| Nb a, Nb b -> Nb (a,b)
let join_bot2 f x y =
match x,y with Bot,a | a,Bot -> a | Nb a,Nb b -> Nb (f a b)
let meet_bot2 f x y =
match x,y with Bot, _ | _, Bot -> Bot | Nb a, Nb b -> Nb (f a b)
let meet_bot f x y =
match y with Bot -> Bot | Nb a -> f x a
let nobot =
function Nb x -> x | Bot -> failwith "unexpected bottom encountered"
exception Bot_found
let debot =
function Nb x -> x | Bot -> raise Bot_found
let rebot f x =
try Nb (f x) with Bot_found -> Bot
let bot_to_string f = function Bot -> "_|_" | Nb x -> f x
let is_Bot = function
| Bot -> true
| _ -> false
| null | https://raw.githubusercontent.com/ptal/AbSolute/469159d87e3a717499573c1e187e5cfa1b569829/src/core/bot.ml | ocaml | * Adds a bottom element to a data-type. | Copyright 2014
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 .
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 .
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.
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. *)
type 'a bot = Bot | Nb of 'a
let strict_bot f x =
match x with Bot -> Bot | Nb x -> f x
let lift_bot f x =
match x with Bot -> Bot | Nb x -> Nb (f x)
let merge_bot2 x y =
match x,y with
| Bot,_ -> Bot
| _,Bot -> Bot
| Nb a, Nb b -> Nb (a,b)
let join_bot2 f x y =
match x,y with Bot,a | a,Bot -> a | Nb a,Nb b -> Nb (f a b)
let meet_bot2 f x y =
match x,y with Bot, _ | _, Bot -> Bot | Nb a, Nb b -> Nb (f a b)
let meet_bot f x y =
match y with Bot -> Bot | Nb a -> f x a
let nobot =
function Nb x -> x | Bot -> failwith "unexpected bottom encountered"
exception Bot_found
let debot =
function Nb x -> x | Bot -> raise Bot_found
let rebot f x =
try Nb (f x) with Bot_found -> Bot
let bot_to_string f = function Bot -> "_|_" | Nb x -> f x
let is_Bot = function
| Bot -> true
| _ -> false
|
c2531195e62dcab4c86e65a0cfd14a5c0f8a989a0cc6bb9caa1182316c89bab5 | yetanalytics/dave | json.clj | (ns com.yetanalytics.dave.filter-scratch.json
(:require [clojure.spec.alpha :as s]))
(s/def ::any
(s/nilable
(s/or :scalar
(s/or :string
string?
:number
(s/or :double
(s/double-in :infinite? false :NaN? false
:max 1000.0 :min -1000.0)
:int
int?)
:boolean
boolean?)
:coll
(s/or :map
(s/map-of
string?
::any
:gen-max 4)
:vector
(s/coll-of
::any
:kind vector?
:into []
:gen-max 4)))))
;; Key paths, a subset of what clojure uses for get/assoc/update-in that applies
;; to JSON
(s/def ::key
(s/or :index (s/int-in 0 Integer/MAX_VALUE)
:key (s/or :string string?
:keyword keyword?)))
(s/def ::key-path
(s/every ::key))
(defn jassoc
"Like assoc, but if the first arg is nil it will dispatch on key to create the
value, placing val in a new vector if needed. Only has the one simple arity"
[coll k v]
(if (or coll (string? k))
(assoc coll k v)
(assoc [] k v)))
(defn jassoc-in
"like assoc-in, but for jassoc"
[m [k & ks] v]
(if ks
(jassoc m k (jassoc-in (get m k) ks v))
(jassoc m k v)))
| null | https://raw.githubusercontent.com/yetanalytics/dave/7a71c2017889862b2fb567edc8196b4382d01beb/scratch/filter-scratch/src/main/com/yetanalytics/dave/filter_scratch/json.clj | clojure | Key paths, a subset of what clojure uses for get/assoc/update-in that applies
to JSON | (ns com.yetanalytics.dave.filter-scratch.json
(:require [clojure.spec.alpha :as s]))
(s/def ::any
(s/nilable
(s/or :scalar
(s/or :string
string?
:number
(s/or :double
(s/double-in :infinite? false :NaN? false
:max 1000.0 :min -1000.0)
:int
int?)
:boolean
boolean?)
:coll
(s/or :map
(s/map-of
string?
::any
:gen-max 4)
:vector
(s/coll-of
::any
:kind vector?
:into []
:gen-max 4)))))
(s/def ::key
(s/or :index (s/int-in 0 Integer/MAX_VALUE)
:key (s/or :string string?
:keyword keyword?)))
(s/def ::key-path
(s/every ::key))
(defn jassoc
"Like assoc, but if the first arg is nil it will dispatch on key to create the
value, placing val in a new vector if needed. Only has the one simple arity"
[coll k v]
(if (or coll (string? k))
(assoc coll k v)
(assoc [] k v)))
(defn jassoc-in
"like assoc-in, but for jassoc"
[m [k & ks] v]
(if ks
(jassoc m k (jassoc-in (get m k) ks v))
(jassoc m k v)))
|
c36c42377f08e6b12437bc69960a209c3631b0cc3e8212ba89ba8c23a0ad4ceb | samply/blaze | common.clj | (ns blaze.db.impl.search-param.composite.common
(:require
[blaze.anomaly :as ba :refer [if-ok when-ok]]
[blaze.byte-string :as bs]
[blaze.coll.core :as coll]
[blaze.db.impl.protocols :as p]
[blaze.fhir-path :as fhir-path]
[clojure.string :as str])
(:import
[clojure.lang IReduceInit]))
(set! *warn-on-reflection* true)
(defn split-value [value]
(str/split value #"\$" 2))
(defn compile-component-value [{:keys [search-param]} value]
(p/-compile-value search-param nil value))
(defn- component-index-values
[resolver main-value {:keys [expression search-param]}]
(when-ok [values (fhir-path/eval resolver expression main-value)]
(coll/eduction
(comp
(p/-index-value-compiler search-param)
(filter (fn [[modifier]] (nil? modifier)))
(map (fn [[_ value]] value)))
values)))
(defn index-values [resolver c1 c2]
(comp
(map
(fn [main-value]
(when-ok [c1-values (component-index-values resolver main-value c1)]
(.reduce
^IReduceInit c1-values
(fn [res v1]
(if-ok [c2-values (component-index-values resolver main-value c2)]
(.reduce
^IReduceInit c2-values
(fn [res v2]
(conj res [nil (bs/concat v1 v2)]))
res)
reduced))
[]))))
(halt-when ba/anomaly?)
cat))
| null | https://raw.githubusercontent.com/samply/blaze/7afce7769059a68561b76fe756ff858b6d9813d7/modules/db/src/blaze/db/impl/search_param/composite/common.clj | clojure | (ns blaze.db.impl.search-param.composite.common
(:require
[blaze.anomaly :as ba :refer [if-ok when-ok]]
[blaze.byte-string :as bs]
[blaze.coll.core :as coll]
[blaze.db.impl.protocols :as p]
[blaze.fhir-path :as fhir-path]
[clojure.string :as str])
(:import
[clojure.lang IReduceInit]))
(set! *warn-on-reflection* true)
(defn split-value [value]
(str/split value #"\$" 2))
(defn compile-component-value [{:keys [search-param]} value]
(p/-compile-value search-param nil value))
(defn- component-index-values
[resolver main-value {:keys [expression search-param]}]
(when-ok [values (fhir-path/eval resolver expression main-value)]
(coll/eduction
(comp
(p/-index-value-compiler search-param)
(filter (fn [[modifier]] (nil? modifier)))
(map (fn [[_ value]] value)))
values)))
(defn index-values [resolver c1 c2]
(comp
(map
(fn [main-value]
(when-ok [c1-values (component-index-values resolver main-value c1)]
(.reduce
^IReduceInit c1-values
(fn [res v1]
(if-ok [c2-values (component-index-values resolver main-value c2)]
(.reduce
^IReduceInit c2-values
(fn [res v2]
(conj res [nil (bs/concat v1 v2)]))
res)
reduced))
[]))))
(halt-when ba/anomaly?)
cat))
|
|
d7020869becf31886af53b925b56009369ed15a4fe3457d06b98cc5c50e9eb0b | jfacorro/klarna-loves-erlang-meetup-2020 | bank_default_handler.erl | %% basic handler
-module(bank_default_handler).
%% Cowboy REST callbacks
-export([allowed_methods/2]).
-export([init/2]).
-export([allow_missing_post/2]).
-export([content_types_accepted/2]).
-export([content_types_provided/2]).
-export([delete_resource/2]).
-export([is_authorized/2]).
-export([known_content_type/2]).
-export([malformed_request/2]).
-export([valid_content_headers/2]).
-export([valid_entity_length/2]).
%% Handlers
-export([handle_request_json/2]).
-record(state, {
operation_id :: bank_api:operation_id(),
logic_handler :: atom(),
validator_state :: jesse_state:state(),
context=#{} :: #{}
}).
-type state() :: state().
-spec init(Req :: cowboy_req:req(), Opts :: bank_router:init_opts()) ->
{cowboy_rest, Req :: cowboy_req:req(), State :: state()}.
init(Req, {Operations, LogicHandler, ValidatorState}) ->
Method = cowboy_req:method(Req),
OperationID = maps:get(Method, Operations, undefined),
error_logger:info_msg("Attempt to process operation: ~p", [OperationID]),
State = #state{
operation_id = OperationID,
logic_handler = LogicHandler,
validator_state = ValidatorState
},
{cowboy_rest, Req, State}.
-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) ->
{Value :: [binary()], Req :: cowboy_req:req(), State :: state()}.
allowed_methods(
Req,
State = #state{
operation_id = 'CreateAccount'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'CreateAccountHolder'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'CreateTransfer'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetAccount'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetAccountHolder'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetTransfer'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'Healthcheck'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'Ping'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'UpdateTransfer'
}
) ->
{[<<"PATCH">>], Req, State};
allowed_methods(Req, State) ->
{[], Req, State}.
-spec is_authorized(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: true | {false, AuthHeader :: iodata()},
Req :: cowboy_req:req(),
State :: state()
}.
is_authorized(Req, State) ->
{true, Req, State}.
-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: [{binary(), AcceptResource :: atom()}],
Req :: cowboy_req:req(),
State :: state()
}.
content_types_accepted(Req, State) ->
{[
{<<"application/json">>, handle_request_json}
], Req, State}.
-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) ->
{Value :: boolean(), Req :: cowboy_req:req(), State :: state()}.
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateAccount'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateAccountHolder'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetAccount'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetAccountHolder'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'Healthcheck'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'Ping'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'UpdateTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(Req, State) ->
{false, Req, State}.
-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: [{binary(), ProvideResource :: atom()}],
Req :: cowboy_req:req(),
State :: state()
}.
content_types_provided(Req, State) ->
{[
{<<"application/json">>, handle_request_json}
], Req, State}.
-spec malformed_request(Req :: cowboy_req:req(), State :: state()) ->
{Value :: false, Req :: cowboy_req:req(), State :: state()}.
malformed_request(Req, State) ->
{false, Req, State}.
-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) ->
{Value :: false, Req :: cowboy_req:req(), State :: state()}.
allow_missing_post(Req, State) ->
{false, Req, State}.
-spec delete_resource(Req :: cowboy_req:req(), State :: state()) ->
processed_response().
delete_resource(Req, State) ->
handle_request_json(Req, State).
-spec known_content_type(Req :: cowboy_req:req(), State :: state()) ->
{Value :: true, Req :: cowboy_req:req(), State :: state()}.
known_content_type(Req, State) ->
{true, Req, State}.
-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) ->
{Value :: true, Req :: cowboy_req:req(), State :: state()}.
valid_entity_length(Req, State) ->
@TODO check the length
{true, Req, State}.
%%%%
-type result_ok() :: {
ok,
{Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()}
}.
-type result_error() :: {error, Reason :: any()}.
-type processed_response() :: {stop, cowboy_req:req(), state()}.
-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) ->
processed_response().
process_response(Response, Req0, State = #state{operation_id = OperationID}) ->
case Response of
{ok, {Code, Headers, Body}} ->
Req = cowboy_req:reply(Code, Headers, Body, Req0),
{stop, Req, State};
{error, Message} ->
error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]),
Req = cowboy_req:reply(400, Req0),
{stop, Req, State}
end.
-spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}.
handle_request_json(
Req0,
State = #state{
operation_id = OperationID,
logic_handler = LogicHandler,
validator_state = ValidatorState
}
) ->
case bank_api:populate_request(OperationID, Req0, ValidatorState) of
{ok, Populated, Req1} ->
{Code, Headers, Body} = bank_logic_handler:handle_request(
LogicHandler,
OperationID,
Req1,
maps:merge(State#state.context, Populated)
),
_ = bank_api:validate_response(
OperationID,
Code,
Body,
ValidatorState
),
PreparedBody = jsx:encode(Body),
Response = {ok, {Code, Headers, PreparedBody}},
process_response(Response, Req1, State);
{error, Reason, Req1} ->
process_response({error, Reason}, Req1, State)
end.
validate_headers(_, Req) -> {true, Req}.
| null | https://raw.githubusercontent.com/jfacorro/klarna-loves-erlang-meetup-2020/61795af0ac80ac7afa4a00a215342988e5aac45f/apps/bank/src/bank_default_handler.erl | erlang | basic handler
Cowboy REST callbacks
Handlers
| -module(bank_default_handler).
-export([allowed_methods/2]).
-export([init/2]).
-export([allow_missing_post/2]).
-export([content_types_accepted/2]).
-export([content_types_provided/2]).
-export([delete_resource/2]).
-export([is_authorized/2]).
-export([known_content_type/2]).
-export([malformed_request/2]).
-export([valid_content_headers/2]).
-export([valid_entity_length/2]).
-export([handle_request_json/2]).
-record(state, {
operation_id :: bank_api:operation_id(),
logic_handler :: atom(),
validator_state :: jesse_state:state(),
context=#{} :: #{}
}).
-type state() :: state().
-spec init(Req :: cowboy_req:req(), Opts :: bank_router:init_opts()) ->
{cowboy_rest, Req :: cowboy_req:req(), State :: state()}.
init(Req, {Operations, LogicHandler, ValidatorState}) ->
Method = cowboy_req:method(Req),
OperationID = maps:get(Method, Operations, undefined),
error_logger:info_msg("Attempt to process operation: ~p", [OperationID]),
State = #state{
operation_id = OperationID,
logic_handler = LogicHandler,
validator_state = ValidatorState
},
{cowboy_rest, Req, State}.
-spec allowed_methods(Req :: cowboy_req:req(), State :: state()) ->
{Value :: [binary()], Req :: cowboy_req:req(), State :: state()}.
allowed_methods(
Req,
State = #state{
operation_id = 'CreateAccount'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'CreateAccountHolder'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'CreateTransfer'
}
) ->
{[<<"POST">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetAccount'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetAccountHolder'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'GetTransfer'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'Healthcheck'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'Ping'
}
) ->
{[<<"GET">>], Req, State};
allowed_methods(
Req,
State = #state{
operation_id = 'UpdateTransfer'
}
) ->
{[<<"PATCH">>], Req, State};
allowed_methods(Req, State) ->
{[], Req, State}.
-spec is_authorized(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: true | {false, AuthHeader :: iodata()},
Req :: cowboy_req:req(),
State :: state()
}.
is_authorized(Req, State) ->
{true, Req, State}.
-spec content_types_accepted(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: [{binary(), AcceptResource :: atom()}],
Req :: cowboy_req:req(),
State :: state()
}.
content_types_accepted(Req, State) ->
{[
{<<"application/json">>, handle_request_json}
], Req, State}.
-spec valid_content_headers(Req :: cowboy_req:req(), State :: state()) ->
{Value :: boolean(), Req :: cowboy_req:req(), State :: state()}.
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateAccount'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateAccountHolder'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'CreateTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetAccount'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetAccountHolder'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'GetTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'Healthcheck'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'Ping'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(
Req0,
State = #state{
operation_id = 'UpdateTransfer'
}
) ->
Headers = [],
{Result, Req} = validate_headers(Headers, Req0),
{Result, Req, State};
valid_content_headers(Req, State) ->
{false, Req, State}.
-spec content_types_provided(Req :: cowboy_req:req(), State :: state()) ->
{
Value :: [{binary(), ProvideResource :: atom()}],
Req :: cowboy_req:req(),
State :: state()
}.
content_types_provided(Req, State) ->
{[
{<<"application/json">>, handle_request_json}
], Req, State}.
-spec malformed_request(Req :: cowboy_req:req(), State :: state()) ->
{Value :: false, Req :: cowboy_req:req(), State :: state()}.
malformed_request(Req, State) ->
{false, Req, State}.
-spec allow_missing_post(Req :: cowboy_req:req(), State :: state()) ->
{Value :: false, Req :: cowboy_req:req(), State :: state()}.
allow_missing_post(Req, State) ->
{false, Req, State}.
-spec delete_resource(Req :: cowboy_req:req(), State :: state()) ->
processed_response().
delete_resource(Req, State) ->
handle_request_json(Req, State).
-spec known_content_type(Req :: cowboy_req:req(), State :: state()) ->
{Value :: true, Req :: cowboy_req:req(), State :: state()}.
known_content_type(Req, State) ->
{true, Req, State}.
-spec valid_entity_length(Req :: cowboy_req:req(), State :: state()) ->
{Value :: true, Req :: cowboy_req:req(), State :: state()}.
valid_entity_length(Req, State) ->
@TODO check the length
{true, Req, State}.
-type result_ok() :: {
ok,
{Status :: cowboy:http_status(), Headers :: cowboy:http_headers(), Body :: iodata()}
}.
-type result_error() :: {error, Reason :: any()}.
-type processed_response() :: {stop, cowboy_req:req(), state()}.
-spec process_response(result_ok() | result_error(), cowboy_req:req(), state()) ->
processed_response().
process_response(Response, Req0, State = #state{operation_id = OperationID}) ->
case Response of
{ok, {Code, Headers, Body}} ->
Req = cowboy_req:reply(Code, Headers, Body, Req0),
{stop, Req, State};
{error, Message} ->
error_logger:error_msg("Unable to process request for ~p: ~p", [OperationID, Message]),
Req = cowboy_req:reply(400, Req0),
{stop, Req, State}
end.
-spec handle_request_json(cowboy_req:req(), state()) -> {cowboy_req:resp_body(), cowboy_req:req(), state()}.
handle_request_json(
Req0,
State = #state{
operation_id = OperationID,
logic_handler = LogicHandler,
validator_state = ValidatorState
}
) ->
case bank_api:populate_request(OperationID, Req0, ValidatorState) of
{ok, Populated, Req1} ->
{Code, Headers, Body} = bank_logic_handler:handle_request(
LogicHandler,
OperationID,
Req1,
maps:merge(State#state.context, Populated)
),
_ = bank_api:validate_response(
OperationID,
Code,
Body,
ValidatorState
),
PreparedBody = jsx:encode(Body),
Response = {ok, {Code, Headers, PreparedBody}},
process_response(Response, Req1, State);
{error, Reason, Req1} ->
process_response({error, Reason}, Req1, State)
end.
validate_headers(_, Req) -> {true, Req}.
|
a48ca8b377c1834a58b046c2b69e6add2b9075004635e6d3cc5b37aadbeca434 | asmala/clj-simple-form | util_test.clj | (ns clj-simple-form.util-test
(:use [clojure.test]
[clj-simple-form.util])
(:require [clj-simple-form.mock-html-ns]))
(deftest test-html-fns
(testing "set-html-fns! and html-fn"
(testing "Function map"
(set-html-fns! {:hello-world (fn [] "Hello World!")})
(is (= ((html-fn :hello-world)) "Hello World!"))
(is (thrown? Exception (html-fn :goodbye-world))))
(testing "Function namespace"
(set-html-fns! 'clj-simple-form.mock-html-ns)
(is (string? ((html-fn :hint) "My two cents")))
(is (thrown? Exception (html-fn :dirty-secret))))))
(deftest test-key-value-pair
(testing "key-value-paid"
(testing "Scalar values"
(is (= (key-value-pair "key") ["key" "key"])))
(testing "Tuples"
(is (= (key-value-pair ["key" "value"]) ["key" "value"]))))) | null | https://raw.githubusercontent.com/asmala/clj-simple-form/b1c566b1f0fe532639b15832b557f1608598a0a2/clj-simple-form-core/test/clj_simple_form/util_test.clj | clojure | (ns clj-simple-form.util-test
(:use [clojure.test]
[clj-simple-form.util])
(:require [clj-simple-form.mock-html-ns]))
(deftest test-html-fns
(testing "set-html-fns! and html-fn"
(testing "Function map"
(set-html-fns! {:hello-world (fn [] "Hello World!")})
(is (= ((html-fn :hello-world)) "Hello World!"))
(is (thrown? Exception (html-fn :goodbye-world))))
(testing "Function namespace"
(set-html-fns! 'clj-simple-form.mock-html-ns)
(is (string? ((html-fn :hint) "My two cents")))
(is (thrown? Exception (html-fn :dirty-secret))))))
(deftest test-key-value-pair
(testing "key-value-paid"
(testing "Scalar values"
(is (= (key-value-pair "key") ["key" "key"])))
(testing "Tuples"
(is (= (key-value-pair ["key" "value"]) ["key" "value"]))))) |
|
5d40a567b130b7ce4595d874fbb6266a745cb7eba6c92ed5934e084ea09018eb | racketscript/racketscript-playground | stub.rkt | #lang racket
;; Hack to compile all runtime files
(require racketscript/interop
racketscript/browser
racketscript/htdp/image
racketscript/htdp/universe)
;; interop
assoc->object
#%js-ffi
;; browser
window
;; image
square
;; universe
big-bang
;; list
foldr
make-list
;; boolean
true
false
;; math
pi
;; match
(match '(1 2)
[`(,a ,b) (+ a b)])
;; for
(for ([i '(1 2 3)])
(displayln i))
sort
displayln
print
write
;; racket/private/list-predicate.rkt
empty?
;; vector
vector-member
;; string
string-contains?
| null | https://raw.githubusercontent.com/racketscript/racketscript-playground/d594372e4c58a3c8ad1905f5500fe755d30ac720/stub.rkt | racket | Hack to compile all runtime files
interop
browser
image
universe
list
boolean
math
match
for
racket/private/list-predicate.rkt
vector
string | #lang racket
(require racketscript/interop
racketscript/browser
racketscript/htdp/image
racketscript/htdp/universe)
assoc->object
#%js-ffi
window
square
big-bang
foldr
make-list
true
false
pi
(match '(1 2)
[`(,a ,b) (+ a b)])
(for ([i '(1 2 3)])
(displayln i))
sort
displayln
print
write
empty?
vector-member
string-contains?
|
bbca3003e2f3e38bf213f58e41a043035125c78c60c949d7f830c038b71ca03b | tmattio/js-bindings | vscode_languageserver_protocol_messages.mli | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es5
import { RequestType , RequestType0 , NotificationType , ,
ProgressType , } from ' vscode - jsonrpc ' ;
ProgressType, EM.t } from 'vscode-jsonrpc'; *)
module RegistrationType : sig
type 'RO t
val t_to_js : ('RO -> Ojs.t) -> 'RO t -> Ojs.t
val t_of_js : (Ojs.t -> 'RO) -> Ojs.t -> 'RO t
val get_____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val get_method : 'RO t -> string [@@js.get "method"]
val create : method_:string -> 'RO t [@@js.create]
end
[@@js.scope "RegistrationType"]
module ProtocolRequestType0 : sig
type ('R, 'PR, 'E, 'RO) t
val t_to_js
: ('R -> Ojs.t)
-> ('PR -> Ojs.t)
-> ('E -> Ojs.t)
-> ('RO -> Ojs.t)
-> ('R, 'PR, 'E, 'RO) t
-> Ojs.t
val t_of_js
: (Ojs.t -> 'R)
-> (Ojs.t -> 'PR)
-> (Ojs.t -> 'E)
-> (Ojs.t -> 'RO)
-> Ojs.t
-> ('R, 'PR, 'E, 'RO) t
val get____ : ('R, 'PR, 'E, 'RO) t -> ('PR * 'RO * EM.t) or_undefined
[@@js.get "___"]
val get_____ : ('R, 'PR, 'E, 'RO) t -> ('RO * EM.t) or_undefined
[@@js.get "____"]
val get__pr : ('R, 'PR, 'E, 'RO) t -> 'PR or_undefined [@@js.get "_pr"]
val create : method_:string -> ('R, 'PR, 'E, 'RO) t [@@js.create]
val cast : ('R, 'PR, 'E, 'RO) t -> ('R, 'E) RequestType0.t [@@js.cast]
val cast' : ('R, 'PR, 'E, 'RO) t -> 'PR ProgressType.t [@@js.cast]
val cast'' : ('R, 'PR, 'E, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolRequestType0"]
module ProtocolRequestType : sig
type ('P, 'R, 'PR, 'E, 'RO) t = ('P, 'R, 'PR, 'E, 'RO) ProtocolRequestType.t
val t_to_js
: ('P -> Ojs.t)
-> ('R -> Ojs.t)
-> ('PR -> Ojs.t)
-> ('E -> Ojs.t)
-> ('RO -> Ojs.t)
-> ('P, 'R, 'PR, 'E, 'RO) t
-> Ojs.t
val t_of_js
: (Ojs.t -> 'P)
-> (Ojs.t -> 'R)
-> (Ojs.t -> 'PR)
-> (Ojs.t -> 'E)
-> (Ojs.t -> 'RO)
-> Ojs.t
-> ('P, 'R, 'PR, 'E, 'RO) t
val get____ : ('P, 'R, 'PR, 'E, 'RO) t -> ('PR * 'RO * EM.t) or_undefined
[@@js.get "___"]
val get_____ : ('P, 'R, 'PR, 'E, 'RO) t -> ('RO * EM.t) or_undefined
[@@js.get "____"]
val get__pr : ('P, 'R, 'PR, 'E, 'RO) t -> 'PR or_undefined [@@js.get "_pr"]
val create : method_:string -> ('P, 'R, 'PR, 'E, 'RO) t [@@js.create]
val cast : ('P, 'R, 'PR, 'E, 'RO) t -> ('P, 'R, 'E) RequestType.t [@@js.cast]
val cast' : ('P, 'R, 'PR, 'E, 'RO) t -> 'PR ProgressType.t [@@js.cast]
val cast'' : ('P, 'R, 'PR, 'E, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolRequestType"]
module ProtocolNotificationType0 : sig
type 'RO t = 'RO ProtocolNotificationType.t
val t_to_js : ('RO -> Ojs.t) -> 'RO t -> Ojs.t
val t_of_js : (Ojs.t -> 'RO) -> Ojs.t -> 'RO t
val get____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "___"]
val get_____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val create : method_:string -> 'RO t [@@js.create]
val cast : 'RO t -> NotificationType0.t [@@js.cast]
val cast' : 'RO t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolNotificationType0"]
module ProtocolNotificationType : sig
type ('P, 'RO) t
val t_to_js : ('P -> Ojs.t) -> ('RO -> Ojs.t) -> ('P, 'RO) t -> Ojs.t
val t_of_js : (Ojs.t -> 'P) -> (Ojs.t -> 'RO) -> Ojs.t -> ('P, 'RO) t
val get____ : ('P, 'RO) t -> ('RO * EM.t) or_undefined [@@js.get "___"]
val get_____ : ('P, 'RO) t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val create : method_:string -> ('P, 'RO) t [@@js.create]
val cast : ('P, 'RO) t -> 'P NotificationType.t [@@js.cast]
val cast' : ('P, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolNotificationType"]
| null | https://raw.githubusercontent.com/tmattio/js-bindings/f1d36bba378e4ecd5310542a0244dce9258b6496/lib/vscode-languageserver-protocol/vscode_languageserver_protocol_messages.mli | ocaml | [@@@ocaml.warning "-7-11-32-33-39"]
[@@@js.implem [@@@ocaml.warning "-7-11-32-33-39"]]
open Es5
import { RequestType , RequestType0 , NotificationType , ,
ProgressType , } from ' vscode - jsonrpc ' ;
ProgressType, EM.t } from 'vscode-jsonrpc'; *)
module RegistrationType : sig
type 'RO t
val t_to_js : ('RO -> Ojs.t) -> 'RO t -> Ojs.t
val t_of_js : (Ojs.t -> 'RO) -> Ojs.t -> 'RO t
val get_____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val get_method : 'RO t -> string [@@js.get "method"]
val create : method_:string -> 'RO t [@@js.create]
end
[@@js.scope "RegistrationType"]
module ProtocolRequestType0 : sig
type ('R, 'PR, 'E, 'RO) t
val t_to_js
: ('R -> Ojs.t)
-> ('PR -> Ojs.t)
-> ('E -> Ojs.t)
-> ('RO -> Ojs.t)
-> ('R, 'PR, 'E, 'RO) t
-> Ojs.t
val t_of_js
: (Ojs.t -> 'R)
-> (Ojs.t -> 'PR)
-> (Ojs.t -> 'E)
-> (Ojs.t -> 'RO)
-> Ojs.t
-> ('R, 'PR, 'E, 'RO) t
val get____ : ('R, 'PR, 'E, 'RO) t -> ('PR * 'RO * EM.t) or_undefined
[@@js.get "___"]
val get_____ : ('R, 'PR, 'E, 'RO) t -> ('RO * EM.t) or_undefined
[@@js.get "____"]
val get__pr : ('R, 'PR, 'E, 'RO) t -> 'PR or_undefined [@@js.get "_pr"]
val create : method_:string -> ('R, 'PR, 'E, 'RO) t [@@js.create]
val cast : ('R, 'PR, 'E, 'RO) t -> ('R, 'E) RequestType0.t [@@js.cast]
val cast' : ('R, 'PR, 'E, 'RO) t -> 'PR ProgressType.t [@@js.cast]
val cast'' : ('R, 'PR, 'E, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolRequestType0"]
module ProtocolRequestType : sig
type ('P, 'R, 'PR, 'E, 'RO) t = ('P, 'R, 'PR, 'E, 'RO) ProtocolRequestType.t
val t_to_js
: ('P -> Ojs.t)
-> ('R -> Ojs.t)
-> ('PR -> Ojs.t)
-> ('E -> Ojs.t)
-> ('RO -> Ojs.t)
-> ('P, 'R, 'PR, 'E, 'RO) t
-> Ojs.t
val t_of_js
: (Ojs.t -> 'P)
-> (Ojs.t -> 'R)
-> (Ojs.t -> 'PR)
-> (Ojs.t -> 'E)
-> (Ojs.t -> 'RO)
-> Ojs.t
-> ('P, 'R, 'PR, 'E, 'RO) t
val get____ : ('P, 'R, 'PR, 'E, 'RO) t -> ('PR * 'RO * EM.t) or_undefined
[@@js.get "___"]
val get_____ : ('P, 'R, 'PR, 'E, 'RO) t -> ('RO * EM.t) or_undefined
[@@js.get "____"]
val get__pr : ('P, 'R, 'PR, 'E, 'RO) t -> 'PR or_undefined [@@js.get "_pr"]
val create : method_:string -> ('P, 'R, 'PR, 'E, 'RO) t [@@js.create]
val cast : ('P, 'R, 'PR, 'E, 'RO) t -> ('P, 'R, 'E) RequestType.t [@@js.cast]
val cast' : ('P, 'R, 'PR, 'E, 'RO) t -> 'PR ProgressType.t [@@js.cast]
val cast'' : ('P, 'R, 'PR, 'E, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolRequestType"]
module ProtocolNotificationType0 : sig
type 'RO t = 'RO ProtocolNotificationType.t
val t_to_js : ('RO -> Ojs.t) -> 'RO t -> Ojs.t
val t_of_js : (Ojs.t -> 'RO) -> Ojs.t -> 'RO t
val get____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "___"]
val get_____ : 'RO t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val create : method_:string -> 'RO t [@@js.create]
val cast : 'RO t -> NotificationType0.t [@@js.cast]
val cast' : 'RO t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolNotificationType0"]
module ProtocolNotificationType : sig
type ('P, 'RO) t
val t_to_js : ('P -> Ojs.t) -> ('RO -> Ojs.t) -> ('P, 'RO) t -> Ojs.t
val t_of_js : (Ojs.t -> 'P) -> (Ojs.t -> 'RO) -> Ojs.t -> ('P, 'RO) t
val get____ : ('P, 'RO) t -> ('RO * EM.t) or_undefined [@@js.get "___"]
val get_____ : ('P, 'RO) t -> ('RO * EM.t) or_undefined [@@js.get "____"]
val create : method_:string -> ('P, 'RO) t [@@js.create]
val cast : ('P, 'RO) t -> 'P NotificationType.t [@@js.cast]
val cast' : ('P, 'RO) t -> 'RO RegistrationType.t [@@js.cast]
end
[@@js.scope "ProtocolNotificationType"]
|
|
bf83a11e92e88b58812ee7b5f6f96c6fb1fb0a6a8658fbf0235a71adccaad5ab | mirage/mirage | mirage_impl_udp.ml | open Functoria
open Mirage_impl_ip
open Mirage_impl_misc
open Mirage_impl_random
module Key = Mirage_key
type 'a udp = UDP
type udpv4v6 = v4v6 udp
let udp = Type.Type UDP
let udpv4v6 : udpv4v6 typ = udp
(* Value restriction ... *)
let udp_direct_func () =
let packages_v = right_tcpip_library ~sublibs:[ "udp" ] "tcpip" in
let connect _ modname = function
| [ ip; _random ] -> Fmt.str "%s.connect %s" modname ip
| _ -> failwith (connect_err "udp" 2)
in
impl ~packages_v ~connect "Udp.Make" (ip @-> random @-> udp)
let direct_udp ?(random = default_random) ip = udp_direct_func () $ ip $ random
let udpv4v6_socket_conf ~ipv4_only ~ipv6_only ipv4_key ipv6_key =
let keys =
[ Key.v ipv4_only; Key.v ipv6_only; Key.v ipv4_key; Key.v ipv6_key ]
in
let packages_v = right_tcpip_library ~sublibs:[ "udpv4v6-socket" ] "tcpip" in
let configure i =
match get_target i with
| `Unix | `MacOSX -> Action.ok ()
| _ -> Action.error "UDPv4v6 socket not supported on non-UNIX targets."
in
let connect _ modname _ =
Fmt.str "%s.connect ~ipv4_only:%a ~ipv6_only:%a %a %a" modname pp_key
ipv4_only pp_key ipv6_only pp_key ipv4_key pp_key ipv6_key
in
impl ~keys ~packages_v ~configure ~connect "Udpv4v6_socket" udpv4v6
let socket_udpv4v6 ?group ipv4 ipv6 =
let ipv4 =
match ipv4 with
| None -> Ipaddr.V4.Prefix.global
| Some ip -> Ipaddr.V4.Prefix.make 32 ip
and ipv6 =
match ipv6 with
| None -> None
| Some ip -> Some (Ipaddr.V6.Prefix.make 128 ip)
and ipv4_only = Key.ipv4_only ?group ()
and ipv6_only = Key.ipv6_only ?group () in
udpv4v6_socket_conf ~ipv4_only ~ipv6_only
(Key.V4.network ?group ipv4)
(Key.V6.network ?group ipv6)
| null | https://raw.githubusercontent.com/mirage/mirage/55bf856f61596c56710d42063234d2ab6082bfb6/lib/mirage/impl/mirage_impl_udp.ml | ocaml | Value restriction ... | open Functoria
open Mirage_impl_ip
open Mirage_impl_misc
open Mirage_impl_random
module Key = Mirage_key
type 'a udp = UDP
type udpv4v6 = v4v6 udp
let udp = Type.Type UDP
let udpv4v6 : udpv4v6 typ = udp
let udp_direct_func () =
let packages_v = right_tcpip_library ~sublibs:[ "udp" ] "tcpip" in
let connect _ modname = function
| [ ip; _random ] -> Fmt.str "%s.connect %s" modname ip
| _ -> failwith (connect_err "udp" 2)
in
impl ~packages_v ~connect "Udp.Make" (ip @-> random @-> udp)
let direct_udp ?(random = default_random) ip = udp_direct_func () $ ip $ random
let udpv4v6_socket_conf ~ipv4_only ~ipv6_only ipv4_key ipv6_key =
let keys =
[ Key.v ipv4_only; Key.v ipv6_only; Key.v ipv4_key; Key.v ipv6_key ]
in
let packages_v = right_tcpip_library ~sublibs:[ "udpv4v6-socket" ] "tcpip" in
let configure i =
match get_target i with
| `Unix | `MacOSX -> Action.ok ()
| _ -> Action.error "UDPv4v6 socket not supported on non-UNIX targets."
in
let connect _ modname _ =
Fmt.str "%s.connect ~ipv4_only:%a ~ipv6_only:%a %a %a" modname pp_key
ipv4_only pp_key ipv6_only pp_key ipv4_key pp_key ipv6_key
in
impl ~keys ~packages_v ~configure ~connect "Udpv4v6_socket" udpv4v6
let socket_udpv4v6 ?group ipv4 ipv6 =
let ipv4 =
match ipv4 with
| None -> Ipaddr.V4.Prefix.global
| Some ip -> Ipaddr.V4.Prefix.make 32 ip
and ipv6 =
match ipv6 with
| None -> None
| Some ip -> Some (Ipaddr.V6.Prefix.make 128 ip)
and ipv4_only = Key.ipv4_only ?group ()
and ipv6_only = Key.ipv6_only ?group () in
udpv4v6_socket_conf ~ipv4_only ~ipv6_only
(Key.V4.network ?group ipv4)
(Key.V6.network ?group ipv6)
|
2acb361bb075a239dc165e93bf85f4e2644da3694cc9c18db99fee49ab2c82c8 | clj-commons/rewrite-clj | uneval.cljc | (ns ^:no-doc rewrite-clj.node.uneval
(:require [rewrite-clj.node.protocols :as node]))
#?(:clj (set! *warn-on-reflection* true))
;; ## Node
(defrecord UnevalNode [children]
node/Node
(tag [_node] :uneval)
(node-type [_node] :uneval)
(printable-only? [_node] true)
(sexpr* [_node _opts]
(throw (ex-info "unsupported operation" {})))
(length [_node]
(+ 2 (node/sum-lengths children)))
(string [_node]
(str "#_" (node/concat-strings children)))
node/InnerNode
(inner? [_node] true)
(children [_node] children)
(replace-children [node children']
(node/assert-single-sexpr children')
(assoc node :children children'))
(leader-length [_node] 2)
Object
(toString [node]
(node/string node)))
(node/make-printable! UnevalNode)
# # Constructor
(defn uneval-node
"Create node representing an unevaled form with `children`.
```Clojure
(require '[rewrite-clj.node :as n])
(-> (n/uneval-node [(n/spaces 1)
(n/token-node 42)])
n/string)
= > \ " # _ 42\ "
```"
[children]
(if (sequential? children)
(do
(node/assert-single-sexpr children)
(->UnevalNode children))
(recur [children])))
| null | https://raw.githubusercontent.com/clj-commons/rewrite-clj/ced60309613a2672b4adc0532948d496a0778d77/src/rewrite_clj/node/uneval.cljc | clojure | ## Node | (ns ^:no-doc rewrite-clj.node.uneval
(:require [rewrite-clj.node.protocols :as node]))
#?(:clj (set! *warn-on-reflection* true))
(defrecord UnevalNode [children]
node/Node
(tag [_node] :uneval)
(node-type [_node] :uneval)
(printable-only? [_node] true)
(sexpr* [_node _opts]
(throw (ex-info "unsupported operation" {})))
(length [_node]
(+ 2 (node/sum-lengths children)))
(string [_node]
(str "#_" (node/concat-strings children)))
node/InnerNode
(inner? [_node] true)
(children [_node] children)
(replace-children [node children']
(node/assert-single-sexpr children')
(assoc node :children children'))
(leader-length [_node] 2)
Object
(toString [node]
(node/string node)))
(node/make-printable! UnevalNode)
# # Constructor
(defn uneval-node
"Create node representing an unevaled form with `children`.
```Clojure
(require '[rewrite-clj.node :as n])
(-> (n/uneval-node [(n/spaces 1)
(n/token-node 42)])
n/string)
= > \ " # _ 42\ "
```"
[children]
(if (sequential? children)
(do
(node/assert-single-sexpr children)
(->UnevalNode children))
(recur [children])))
|
44b8874ec598ea30097a6c87ce75f670796373d6ac4db8b985c372c1d904889d | Bogdanp/aoc2020 | day12-2.rkt | #lang racket/base
(require racket/match)
(struct instr (cmd n)
#:transparent)
(struct wp (dir x y)
#:transparent)
(struct state (wp x y)
#:transparent)
(define instr-re #rx"([NSEWLRF])(.+)")
(define instrs
(call-with-input-file "input12.txt"
(lambda (in)
(for/list ([line (in-lines in)])
(match (regexp-match instr-re line)
[(list _
(app string->symbol cmd)
(app string->number n))
(instr cmd n)])))))
(define (right-rotate w)
(match w
[(wp 'E x y) (wp 'S y (- x))]
[(wp 'S x y) (wp 'W y (- x))]
[(wp 'W x y) (wp 'N y (- x))]
[(wp 'N x y) (wp 'E y (- x))]))
(define (left-rotate w)
(match w
[(wp 'E x y) (wp 'N (- y) x)]
[(wp 'N x y) (wp 'W (- y) x)]
[(wp 'W x y) (wp 'S (- y) x)]
[(wp 'S x y) (wp 'E (- y) x)]))
(define (rotate s deg)
(define steps (quotient deg 90))
(define w (state-wp s))
(define-values (rot n)
(if (negative? steps)
(values left-rotate (abs steps))
(values right-rotate steps)))
(define new-w
(for/fold ([w w])
([_ (in-range n)])
(rot w)))
(state new-w (state-x s) (state-y s)))
(define (move s dir amt)
(match-define (state (wp wp-dir wp-x wp-y) ship-x ship-y) s)
(define-values (new-x new-y)
(case dir
[(N) (values wp-x (- wp-y amt))]
[(S) (values wp-x (+ wp-y amt))]
[(E) (values (- wp-x amt) wp-y)]
[(W) (values (+ wp-x amt) wp-y)]))
(state (wp wp-dir new-x new-y) ship-x ship-y))
(define (follow s amt)
(match-define (state (and (wp _ wp-x wp-y) w) ship-x ship-y) s)
(state w
(+ ship-x (* wp-x amt))
(+ ship-y (* wp-y amt))))
(define (step s i)
(match i
[(instr 'F amt) (follow s amt)]
[(instr 'L deg) (rotate s (- deg))]
[(instr 'R deg) (rotate s deg)]
[(instr d amt) (move s d amt)]))
(define (interp s instrs)
(for/fold ([s s])
([i (in-list instrs)])
(step s i)))
(define (distance s)
(+ (abs (state-x s))
(abs (state-y s))))
(define init (state (wp 'E -10 -1) 0 0))
(time (distance (interp init instrs)))
| null | https://raw.githubusercontent.com/Bogdanp/aoc2020/4021ed7a85eb58f655f38a9069656d64aaaa2ace/day12-2.rkt | racket | #lang racket/base
(require racket/match)
(struct instr (cmd n)
#:transparent)
(struct wp (dir x y)
#:transparent)
(struct state (wp x y)
#:transparent)
(define instr-re #rx"([NSEWLRF])(.+)")
(define instrs
(call-with-input-file "input12.txt"
(lambda (in)
(for/list ([line (in-lines in)])
(match (regexp-match instr-re line)
[(list _
(app string->symbol cmd)
(app string->number n))
(instr cmd n)])))))
(define (right-rotate w)
(match w
[(wp 'E x y) (wp 'S y (- x))]
[(wp 'S x y) (wp 'W y (- x))]
[(wp 'W x y) (wp 'N y (- x))]
[(wp 'N x y) (wp 'E y (- x))]))
(define (left-rotate w)
(match w
[(wp 'E x y) (wp 'N (- y) x)]
[(wp 'N x y) (wp 'W (- y) x)]
[(wp 'W x y) (wp 'S (- y) x)]
[(wp 'S x y) (wp 'E (- y) x)]))
(define (rotate s deg)
(define steps (quotient deg 90))
(define w (state-wp s))
(define-values (rot n)
(if (negative? steps)
(values left-rotate (abs steps))
(values right-rotate steps)))
(define new-w
(for/fold ([w w])
([_ (in-range n)])
(rot w)))
(state new-w (state-x s) (state-y s)))
(define (move s dir amt)
(match-define (state (wp wp-dir wp-x wp-y) ship-x ship-y) s)
(define-values (new-x new-y)
(case dir
[(N) (values wp-x (- wp-y amt))]
[(S) (values wp-x (+ wp-y amt))]
[(E) (values (- wp-x amt) wp-y)]
[(W) (values (+ wp-x amt) wp-y)]))
(state (wp wp-dir new-x new-y) ship-x ship-y))
(define (follow s amt)
(match-define (state (and (wp _ wp-x wp-y) w) ship-x ship-y) s)
(state w
(+ ship-x (* wp-x amt))
(+ ship-y (* wp-y amt))))
(define (step s i)
(match i
[(instr 'F amt) (follow s amt)]
[(instr 'L deg) (rotate s (- deg))]
[(instr 'R deg) (rotate s deg)]
[(instr d amt) (move s d amt)]))
(define (interp s instrs)
(for/fold ([s s])
([i (in-list instrs)])
(step s i)))
(define (distance s)
(+ (abs (state-x s))
(abs (state-y s))))
(define init (state (wp 'E -10 -1) 0 0))
(time (distance (interp init instrs)))
|
|
722e31a0e987340f7da6838d54ddc7ad7661c610e57cdd9345203ec9b46da58d | josefs/Gradualizer | lc_generator_not_none.erl | -module(lc_generator_not_none).
%% Compare with test/should_fail/lc_generator_not_none_fail.erl
-export([g/1,
h/1]).
-type t() :: {a, d}
| {a, [t()]}.
-spec g(t()) -> [t()].
g({a, d} = T) ->
[T];
g({a, Ts}) ->
[ T || T <- Ts ].
-spec h(t()) -> [t()].
h({a, Ts}) ->
[ T || T <- Ts ].
| null | https://raw.githubusercontent.com/josefs/Gradualizer/d2ea3201ee3c55695f50144ee4befcafa0756ccc/test/should_pass/lc_generator_not_none.erl | erlang | Compare with test/should_fail/lc_generator_not_none_fail.erl | -module(lc_generator_not_none).
-export([g/1,
h/1]).
-type t() :: {a, d}
| {a, [t()]}.
-spec g(t()) -> [t()].
g({a, d} = T) ->
[T];
g({a, Ts}) ->
[ T || T <- Ts ].
-spec h(t()) -> [t()].
h({a, Ts}) ->
[ T || T <- Ts ].
|
47f2792946b9439131fbe77b3d34e22e3809fd3e6d016af0bf494e0099601ea6 | rescript-lang/rescript-compiler | Runtime.mli | open GenTypeCommon
type recordGen
type recordValue
type moduleItem
type moduleAccessPath = Root of string | Dot of moduleAccessPath * moduleItem
val accessVariant : index:int -> string -> string
val checkMutableObjectField : previousName:string -> name:string -> bool
val default : string
val emitModuleAccessPath : config:Config.t -> moduleAccessPath -> string
val emitJSVariantGetLabel : polymorphic:bool -> string -> string
val emitJSVariantGetPayload : polymorphic:bool -> string -> string
val emitJSVariantWithPayload :
label:string -> polymorphic:bool -> string -> string
val emitVariantGetLabel : polymorphic:bool -> string -> string
val emitVariantGetPayload :
inlineRecord:bool -> numArgs:int -> polymorphic:bool -> string -> string
val emitVariantLabel : polymorphic:bool -> string -> string
val emitVariantWithPayload :
inlineRecord:bool -> label:string -> polymorphic:bool -> string list -> string
val isMutableObjectField : string -> bool
val mangleObjectField : string -> string
val newModuleItem : name:string -> moduleItem
val newRecordValue : unboxed:bool -> recordGen -> recordValue
val recordGen : unit -> recordGen
val recordValueToString : recordValue -> string
val jsVariantTag : polymorphic:bool -> string
val jsVariantValue : polymorphic:bool -> string
| null | https://raw.githubusercontent.com/rescript-lang/rescript-compiler/486c93306a96d85fcd38d5933ed5d361d518b25e/jscomp/gentype/Runtime.mli | ocaml | open GenTypeCommon
type recordGen
type recordValue
type moduleItem
type moduleAccessPath = Root of string | Dot of moduleAccessPath * moduleItem
val accessVariant : index:int -> string -> string
val checkMutableObjectField : previousName:string -> name:string -> bool
val default : string
val emitModuleAccessPath : config:Config.t -> moduleAccessPath -> string
val emitJSVariantGetLabel : polymorphic:bool -> string -> string
val emitJSVariantGetPayload : polymorphic:bool -> string -> string
val emitJSVariantWithPayload :
label:string -> polymorphic:bool -> string -> string
val emitVariantGetLabel : polymorphic:bool -> string -> string
val emitVariantGetPayload :
inlineRecord:bool -> numArgs:int -> polymorphic:bool -> string -> string
val emitVariantLabel : polymorphic:bool -> string -> string
val emitVariantWithPayload :
inlineRecord:bool -> label:string -> polymorphic:bool -> string list -> string
val isMutableObjectField : string -> bool
val mangleObjectField : string -> string
val newModuleItem : name:string -> moduleItem
val newRecordValue : unboxed:bool -> recordGen -> recordValue
val recordGen : unit -> recordGen
val recordValueToString : recordValue -> string
val jsVariantTag : polymorphic:bool -> string
val jsVariantValue : polymorphic:bool -> string
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.